> This page is for NeMo Relay, version v1.0.0.
> For other versions, use one of these documentation indexes:
> - Latest (v0.11.2) (default): https://docs.nvidia.com/nemo/relay/latest/llms.txt
> - dev: https://docs.nvidia.com/nemo/relay/dev/llms.txt
> - v1.0.0: https://docs.nvidia.com/nemo/relay/v1.0.0/llms.txt
> - v0.11.2: https://docs.nvidia.com/nemo/relay/v0.11.2/llms.txt
> - v0.10.4: https://docs.nvidia.com/nemo/relay/v0.10.4/llms.txt
> - v0.9.4: https://docs.nvidia.com/nemo/relay/v0.9.4/llms.txt
> - v0.8.4: https://docs.nvidia.com/nemo/relay/v0.8.4/llms.txt

> For clean Markdown of any page, append .md to the page URL. For a task-oriented documentation index, fetch https://docs.nvidia.com/nemo/relay/llms.txt. Use the documentation version matching the installed NeMo Relay package: latest follows the latest stable release, vX.Y.Z identifies a retained release snapshot, and dev documents development changes. Preserve the selected version when following links; do not mix examples or API contracts from different versions. Fetch the relevant section's /llms.txt before individual pages instead of loading a complete version index.

# About gRPC Worker Plugins

> Choose a Python, Rust, or custom gRPC worker implementation.

A worker plugin runs outside the Relay process. It implements
`nvidia.nemo.relay.worker.v1` and supports 17 subscriber and middleware callback
types. It can call the host's remaining execution chain through continuations,
use codecs during a callback, emit marks, and manage scope stacks.

The current contract is `nvidia.nemo.relay.worker.v1`, version `1.0.0`, introduced
in Relay 1.0. Upgrade the host and worker SDK together, regenerate custom bindings,
and set `compat.worker_protocol = "nvidia.nemo.relay.worker.v1"` in the manifest.
Set `compat.relay = ">=1.0.0,<2.0"` for the current SDK. Old `grpc-v1` workers
cannot use these services. Package versions continue to follow Relay releases.

Tool callbacks and `ToolNext` continuations preserve an application `result` and
optional opaque `annotation`; execution intercepts can add Relay-owned pending
marks. LLM execution callbacks receive `LlmExecutionContext`, which provides
request codecs and a response codec for non-streaming callbacks.

Workers can add a data schema, log severity, and semantic category to a mark, emit validated metric
measurements, and read the current host-level runtime diagnostics. These diagnostics are
ordered by code and are not attributed to a particular plugin. They are the legacy
report, not canonical snapshots. Rust and Python workers can also record internal
observations through the canonical diagnostics delivery API. Refer to
[Plugin Diagnostics](/nemo/relay/v1.0.0/build-plugins/diagnostics) for matching examples and delivery
limits. Worker recording does not grant canonical read access.

Choose a worker when a separate process or dependency environment is worth the
extra gRPC calls and data conversion. A worker crash does not crash the Relay
process, but the worker is still trusted code. It is not a security sandbox.
Relay uses a separate authentication token for each activation. That token lets
the worker request host operations for that activation.

## Choose the Implementation

Choose one of these implementation paths:

| Implementation | Development and Distribution Characteristics                                                                                                                                                                                                                                                 |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Python SDK     | Best fit for Python-only dependencies and rapid iteration. `plugins add` builds a Relay-managed environment from the package and records an attestation used at activation. Python workers cannot be activated by merely adding a manifest path to `plugins.toml`.                           |
| Rust SDK       | Best fit for a compiled, self-contained worker and Rust callback code. The executable is packaged directly and can be registered through a manifest reference or the CLI lifecycle.                                                                                                          |
| Custom command | Advanced path for another language or an existing service executable. It must implement every required `nvidia.nemo.relay.worker.v1` lifecycle, authentication, typed message validation, cancellation, continuation, codec, and shutdown rule itself. The SDK tutorials do not apply to it. |

Async Python and Rust callback work is cancelled cooperatively when the host caller times
out, a stream consumer disconnects, or shutdown begins. Dropping a future or cancelling an
`asyncio` task cannot preempt arbitrary blocking work or a separately spawned process.
Keep blocking work off the SDK event loop, propagate cancellation, and put external
cleanup in a guaranteed finalizer.

## Let the SDK Own the Transport

Implement `Plugin` and let the SDK run the protobuf server. `serve_plugin`
reads Relay's activation environment and opens the authenticated local endpoint.
It handles handshake, health, validation, registration, callbacks, cancellation,
and shutdown.

## Configure the Snapshot Location

Before starting a worker, Relay copies its package and runtime files into an
activation snapshot. This is a separate directory for that activation. Set
`NEMO_RELAY_PLUGIN_SNAPSHOT_DIR` in the environment that starts Relay to choose
where snapshots are stored. Relay creates the directory if needed. Keep it
outside plugin packages and all copied entrypoint and library directories. The following examples set the
snapshot location in PowerShell and Bash:

```powershell
$env:NEMO_RELAY_PLUGIN_SNAPSHOT_DIR = "C:\\nrs"
```

```bash
export NEMO_RELAY_PLUGIN_SNAPSHOT_DIR=/var/tmp/nrs
```

**`Python`**

```python title="Python"
import asyncio
from nemo_relay_plugin import ConfigDiagnostic, Json, PluginContext, WorkerPlugin, serve_plugin

class ExamplePythonWorker(WorkerPlugin):
    plugin_id = "examples.python_grpc_worker"
    allows_multiple_components = False

    def validate(self, config: Json) -> list[ConfigDiagnostic]:
        return validate_config(config)

    def register(self, context: PluginContext, config: Json) -> None:
        settings = normalized_config(config)
        if settings["observe"]["enabled"]:
            self._register_observation(
                context, settings["tag"], settings["observe"]
            )
        if settings["requests"]["enabled"]:
            self._register_requests(
                context,
                settings["tag"],
                settings["requests"],
                settings["execution"],
            )
        self._register_runtime(context, settings["tag"], settings["runtime"])
        if settings["execution"]["enabled"]:
            self._register_execution(context, settings["tag"], settings["execution"])

async def main() -> None:
    await serve_plugin(ExamplePythonWorker())

if __name__ == "__main__":
    asyncio.run(main())
```

**`Rust`**

```rust title="Rust"
use nemo_relay_worker::{
    ConfigDiagnostic, Json, Plugin, PluginContext, Result, WorkerSdkError, serve_plugin,
};

struct DocumentationWorker;

impl Plugin for DocumentationWorker {
    fn plugin_kind(&self) -> &str {
        "examples.rust_grpc_worker"
    }
    fn allows_multiple_components(&self) -> bool {
        false
    }
    fn validate(&self, config: &serde_json::Map<String, Json>) -> Vec<ConfigDiagnostic> {
        let config = &Json::Object(config.clone());
        validate_config(config)
    }

    fn register<'a>(
        &'a self,
        config: &'a serde_json::Map<String, Json>,
        context: &'a mut PluginContext,
    ) -> nemo_relay_worker::PluginFuture<'a, ()> {
        Box::pin(async move {
            let config = &Json::Object(config.clone());

            let settings = ExampleConfig::parse(config).map_err(WorkerSdkError::InvalidInput)?;
            if settings.observe.enabled {
                register_observation(context, &settings);
            }
            if settings.requests.enabled {
                register_requests(context, &settings);
            }
            register_execution(context, &settings);
            Ok(())
        })
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    serve_plugin(DocumentationWorker).await
}
```

Python supports synchronous or asynchronous registration. Rust registration returns
a future that the SDK awaits before sending the registration response. The installed callbacks can be asynchronous.

Rust `plugin_kind()` and Python `plugin_id` must match the manifest ID and handshake
identity. A mismatch
fails activation before any callback runs.

## Complete Path

Follow these pages in order to build, activate, exercise, and stop a worker plugin:

1. Use [Python Worker](/nemo/relay/v1.0.0/build-plugins/workers/python) when Relay should provision and own
   the Python environment, or [Rust Worker](/nemo/relay/v1.0.0/build-plugins/workers/rust) for the checked
   compiled counterpart.
2. Implement all callback families with [Middleware and Continuations](/nemo/relay/v1.0.0/build-plugins/workers/middleware-and-continuations),
   paying particular attention to repeated downstream calls and lazy streams.
3. Use [Runtime Events and Scopes](/nemo/relay/v1.0.0/build-plugins/workers/runtime-events-and-scopes) for
   marks, scope stacks, binding, restoration, and failure cleanup.
4. Use the [gRPC Protocol Reference](/nemo/relay/v1.0.0/build-plugins/workers/grpc-v1-protocol) to audit
   an SDK or implement a custom command.

The Rust lifecycle test builds the executable in an isolated target directory,
creates a manifest and checks its digest. It then activates the worker, runs a
managed tool call through `nvidia.nemo.relay.worker.v1`, checks a host-runtime mark,
and verifies shutdown. The Rust and Python callback-contract tests then isolate the sanitizer,
continuation, streaming, codec, cancellation, and scope-cleanup behavior. Merely
starting a process and registering one intercept is not enough evidence.