> 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.

# gRPC Worker Protocol Reference

> Reference the typed worker contract, lifecycle, authentication, capabilities, and delivery limits.

The Rust host, Rust worker SDK, and Python worker SDK use
`nvidia.nemo.relay.worker.v1`, with contract version `1.0.0`.
The canonical protobuf files live under
`crates/worker-proto/proto/nvidia/nemo/relay/worker/v1/`.
Crate and wheel release versions remain independent of this contract version.

Upgrade the host and workers together. Set
`compat.worker_protocol = "nvidia.nemo.relay.worker.v1"` and
`compat.relay = ">=1.0.0,<2.0"` in worker manifests. Regenerate custom bindings or
rebuild workers with the new SDK. Old `grpc-v1` workers cannot connect. The old
schema and generated bindings have been removed. Their definitions remain in
Git history.

SDK callbacks use shared domain types in Rust and authoring dictionaries and
dataclasses in Python. Private converters translate those values into typed
protobuf messages. Use `JsonValue` only for application or provider-owned data.

## Worker Service

The fully qualified service is
`nvidia.nemo.relay.worker.v1.PluginWorkerService`. Each RPC has its own
`<Method>Request` and `<Method>Response` message.

Each request contains `Credentials` with the activation ID and token. The server
checks credentials before validating the message or running a callback. Handshake
proposes a `ProtocolIdentity` with the exact name and contract version. Lifecycle
replies carry a typed `WorkerIdentity`. The following table describes each RPC:

| RPC                | Contract                                                                                                                                                                            |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Handshake`        | Verify the plugin and protocol identities; return identity, component multiplicity, and supported surfaces.                                                                         |
| `Health`           | Report a recognized readiness status and worker identity.                                                                                                                           |
| `Validate`         | Validate required application configuration; select typed `ConfigDiagnostics` or a callback error. Encode JSON null for no configuration.                                           |
| `Register`         | Return a typed `RegistrationPlan` or callback error. Concurrent requests with the same semantic configuration install once; changed configuration fails with `FAILED_PRECONDITION`. |
| `Invoke`           | Select exactly one surface-specific input. Return its corresponding typed result or callback error.                                                                                 |
| `InvokeStream`     | Accept a distinct `InvokeStreamRequest` containing an LLM request, continuation, and request codec context. Return ordered provider chunks or a terminal error.                     |
| `CancelInvocation` | Idempotently cancel an active invocation and wait for callback cleanup. Unknown or completed IDs return `accepted=false`.                                                           |
| `Shutdown`         | Stop admission, cancel active work, and drain bounded diagnostic delivery. Success is an empty `ShutdownResponse`.                                                                  |

The SDKs also expose standard `grpc.health.v1.Health` `Check` and `Watch` probes.
These are separate from the authenticated worker lifecycle `Health` RPC.

### Host Liveness

Relay launches a worker with a pipe on standard input and keeps the write end for
the life of the activation. A worker whose standard input is a pipe must stop when
it reads EOF, because EOF confirms that the Relay host closed or exited. On Unix,
Relay starts each worker as the leader of its own process group and terminates
that group when it stops the worker. A worker that leads its own process group
and stops because of EOF must terminate that group before it exits, so its child
processes do not outlive the host. The Rust and Python worker SDKs implement this
behavior.

Do not infer host death from a failed RPC or gRPC connectivity state. Local
transport failures can be transient. Older hosts give workers the null device
instead of a pipe. Those workers continue to rely on the authenticated `Shutdown`
RPC.

## Registration Surfaces

The `InvokeRequest.invocation` oneof selects the callback type. There is no
separate surface field that could conflict with the selected input. Registration
plans carry each callback's surface, local name, priority, and break-chain flag.
Each callback type accepts these success results:

| Surface                                                      | Successful Result                                                                                               |
| ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- |
| Subscriber                                                   | `completed`                                                                                                     |
| Event metadata injector                                      | `metadata_additions`, a `JsonObject`                                                                            |
| Mark, scope-start, or scope-end sanitizer                    | Typed `event_sanitize` fields                                                                                   |
| Tool request or response sanitizer; tool request interceptor | Application `tool_value`                                                                                        |
| Tool or LLM condition; conditional middleware callback       | `guardrail`, explicitly selecting allow or a nonempty block reason                                              |
| Tool execution interceptor                                   | Typed `tool_execution_outcome`, containing the canonical result, optional annotation, and ordered pending marks |
| LLM request sanitizer                                        | Typed `llm_request` or explicit `unchanged`                                                                     |
| LLM response sanitizer                                       | Provider `llm_response` or explicit `unchanged`                                                                 |
| LLM request interceptor                                      | Typed `llm_request_outcome`, including normalized annotation, pending marks, and optimization contributions     |
| LLM execution interceptor                                    | Provider `llm_response`                                                                                         |
| LLM stream execution interceptor                             | Ordered `InvokeStreamResponse` value items, then EOF or one terminal error                                      |

ATOF events retain UUIDs, timestamps, category profiles, and runtime propagation
fields. Scope sanitizer inputs must match their start or end lifecycle phase.
Closed LLM models represent message roles, multimodal parts, provider-specific
fields, tool choices, finish reasons, and optional empty collections explicitly.
Application and provider extensions use JSON. Rust conversions follow the
native SDK's number limits, as described below.

## Host Runtime Service

Workers call `nvidia.nemo.relay.worker.v1.RelayHostRuntimeService` on the host endpoint.
Requests contain credentials. Each scope or access handle belongs to the
activation or callback that created it. The service provides these RPCs:

| RPC                                        | Contract                                                                                                |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------- |
| `Log`                                      | Emit a typed severity and structured `JsonObject` attributes.                                           |
| `EmitMark`                                 | Submit a typed `PendingMarkSpec` under the supplied scope binding.                                      |
| `ListRuntimeRegistrations`                 | Return registration identities with an explicit core, global API, or plugin owner.                      |
| `RegisterConditionalMiddlewareGuardrail`   | Install a typed activation-owned gate declaration and return its handle.                                |
| `DeregisterConditionalMiddlewareGuardrail` | Remove an activation-owned gate and report whether it existed.                                          |
| `GetCurrentScopeStackSnapshot`             | Select a detached typed snapshot or explicit `no_context`. Inspection does not create a stack.          |
| `GetRuntimeDiagnostics`                    | Return bounded host diagnostic code, message, and count entries.                                        |
| `PushScope`                                | Open a scope and return its owned handle. Optional protobuf `Timestamp` supports historical start time. |
| `PopScope`                                 | Close the owned handle, optionally supplying output, metadata, and historical end time.                 |
| `CreateScopeStack`                         | Allocate an isolated activation-owned stack.                                                            |
| `DropScopeStack`                           | Release an isolated stack.                                                                              |
| `ToolNext`                                 | Continue tool execution and select the canonical typed result or original downstream error.             |
| `LlmNext`                                  | Continue unary LLM execution and select a provider response or original downstream error.               |
| `LlmStreamNext`                            | Continue streaming execution with a dedicated response item type.                                       |
| `DecodeLlmCodecRequest`                    | Decode through the live invocation's request codec capability.                                          |
| `EncodeLlmCodecRequest`                    | Apply a normalized annotation to the original typed request.                                            |
| `DecodeLlmCodecResponse`                   | Decode a completed provider response through its response codec capability.                             |

Request and response codecs have separate access handles. An explicit `none`
means that no codec is selected. A selected codec can carry a host-issued access
handle. Access ends when the callback finishes or is cancelled. For streaming
calls, it lasts until the stream finishes or closes. Streaming execution has a
request codec but no completed-response codec.

Continuation calls can repeat or overlap while the interceptor is active. Each
call uses an isolated copy of the scope stack. Finish this work before returning
from the interceptor. Return or re-raise the original downstream error to preserve
its source. A new error counts as a plugin failure.

### Codec References and Provider Data

Built-in, runtime-registered, and dynamic codecs use the same `LlmCodecReference`
fields: an open namespace (`kind`) and an optional stable `id`. These fields
describe the codec; they do not select a provider or codec implementation.
`LlmCodecContext` carries the access handle for the host's selected codec.

Shared annotated requests and responses use typed messages. Their `api_specific`
fields use the native SDK's JSON representation for every codec. Rust converters
preserve signed and unsigned 64-bit integers and finite 64-bit floating-point
values. They do not preserve decimal spelling or precision beyond those types.

Provider fields and custom codecs do not need protobuf changes. The transport
checks JSON syntax and required message fields. The codec interprets provider
data. The host checks who owns an access handle, its direction, and its lifetime.

### Scope Snapshot Extension

`GetCurrentScopeStackSnapshot` selects a typed snapshot or explicit `no_context`.
Snapshot entries contain validated scope UUIDs and recognized scope categories.
Inspection does not create a stack. Invalid or expired bindings fail with a gRPC
status. The historical `grpc-v1` extension cannot be used with the new services.

## Diagnostic Delivery

The optional `RelayDiagnosticsService` service shares the authenticated host endpoint.
It exposes six RPCs:

* `GetDiagnosticCapabilities`.
* `OpenDiagnosticSession`.
* `SubmitDiagnostic`.
* `ReadDiagnosticPage`.
* `GetDiagnosticDiscovery`.
* `InspectDiagnosticMemory`.

Its decode and admission limits are separate from `RelayHostRuntimeService`, logging,
and execution payload limits.

Older hosts return `UNIMPLEMENTED`. For unsupported hosts or disabled collection,
the SDK returns an inactive helper that skips lazy observation factories. Diagnostic
availability does not decide whether a plugin executes.

### Negotiate Settings and Authority

The host returns `DiagnosticCapabilities` before opening a session and again when
the session opens. Both values must agree. The SDK checks contract versions and
its local safety ceilings. It then uses the host's exact request and response
limits, queue capacity, retry count, and per-attempt timeout.

A mismatch, unsupported limit, or malformed session response produces an inactive
`unsupported` helper. This includes a session ID that is not 16 bytes long.
Plugin execution continues. The SDK does not negotiate different limits or use
local delivery defaults. Bootstrap calls have a separate local safety timeout.
Flush and shutdown drain also have local bounds. These are separate from the
host's per-attempt RPC timeout.

Recording uses activation credentials. Those credentials do not grant snapshot
read access: `can_read_context` is false, and canonical reads are denied. Query
filters do not grant permission. The read RPC reserves a separate access boundary.

Opening an already live session returns the same session. The host assigns its
UUID and ownership. Registration returns component and code handles. Code handles
are one-based positions in the registration's code list.

Workers can register common plugin failure codes, but not host-owned lifecycle
codes. Extensions can describe failure, success, or unspecified outcomes under a
host-assigned session namespace. Unknown authoring codes and failure classes are
rejected. Detail and correlation limits come from the core context.

### Submit and Retry Observations

`SubmitDiagnostic` uses one sequence, starting at one, for registration, recording,
component close, and session close. Positive counts of two and three add five
occurrences. The host commits a digest and receipt atomically with the record.

Receipts and sequence handling follow these rules:

* Retrying the last request with identical content returns its receipt without
  counting the observation again. Conflicts, gaps, and older sequences fail.
* Malformed requests do not consume a sequence. A valid request that passes
  admission but fails policy consumes a sequence and returns a terminal `Rejected`
  receipt.
* `Recorded` confirms in-memory counts. Evidence can be retained, truncated, or
  dropped. `Registered`, `Closed`, and `Disabled` add no occurrences.

The SDK freezes request bytes and sends one request at a time. Each retry uses
identical bytes, up to the host's attempt count and per-attempt deadline. If the
SDK cannot confirm acceptance, it stops delivery. Pending observations are never
replayed into a new session.

This release allows one session per activation. A closed session keeps its last
receipt until activation cleanup. Starting a new session requires a new activation.

### Delivery Limits

Delivery uses the following limits in addition to core storage limits:

| Resource                       | Diagnostic Limit                                                                                                                                                      |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Sessions                       | Up to 32 per host process, with one session per activation.                                                                                                           |
| Components                     | Eight registrations per session, including closed registrations.                                                                                                      |
| Extensions and codes           | Up to 16 extensions per session and 32 codes per component.                                                                                                           |
| Registration metadata          | 16 KiB per session, also subject to core capacity.                                                                                                                    |
| Protobuf frame                 | Host-advertised maximum. The SDK reserves 256 bytes for credentials, session identity, sequence, and framing, then checks the complete frame against the exact limit. |
| Extension name and description | 32 and 256 UTF-8 bytes, respectively.                                                                                                                                 |
| SDK queue                      | Host-advertised slots plus one in-flight request, within the SDK's safety ceiling.                                                                                    |
| Host decode admission          | Up to 16 concurrent diagnostic requests. There is no wait queue.                                                                                                      |
| Response ceiling               | Host-advertised maximum, within the SDK's safety ceiling.                                                                                                             |
| Replay storage                 | One digest and bounded receipt per session.                                                                                                                           |

The service takes a concurrency permit before decoding protobuf. A slow response
keeps that permit until its body reaches its delivery deadline or is dropped.
HTTP/2 buffers, channel state, allocator overhead, and core pools have separate
costs. These limits do not cap whole-process RSS.

### Handle Loss and Shutdown

`delivery_stats` reports local dropped, rejected, and uncertain totals separately
from host occurrence counts. An explicit `INVALID_ARGUMENT` response counts as
rejected, even when the host leaves its sequence available for a corrected request.

A host capacity rejection uses `RESOURCE_EXHAUSTED` with
`nemo-relay-diagnostic-not-consumed: 1` status metadata. The SDK counts a definite
rejection and preserves the sequence for later submissions. The metadata confirms
only that attempt. If an earlier attempt had an uncertain result, the SDK keeps
retrying the identical request within its policy. Without a receipt, delivery stays
uncertain and stops. A client-side or unmarked capacity error is also uncertain.
These decisions never depend on error-message text.

`flush` waits for earlier queued work. It returns an error for uncertain delivery.
Counters expose known losses. `close` drains and releases queued work within the
shutdown allowance. Activation teardown stops submissions and closes registrations.
The runtime context remains available.

Restricted evidence uses state-only recording. It never enters `Log`, `EmitMark`,
legacy reports, or exporters.

## Execution Protocol Compatibility

The active protocol is `nvidia.nemo.relay.worker.v1`, contract `1.0.0`.
Workers built for `grpc-v1` must rebuild with the updated SDK and update their
manifest's `worker_protocol`. There is no automatic adapter between namespaces.
Generate custom clients from the protobuf source in `crates/worker-proto/proto/`.

The worker implements `PluginWorkerService`. Relay implements
`RelayHostRuntimeService` and `RelayDiagnosticsService`. Each RPC has a dedicated
request and response message; streaming invocations use `InvokeStreamRequest`.
Empty responses acknowledge successful operations; failures use gRPC statuses.

## Authentication and Endpoints

Relay creates a fresh activation ID and high-entropy token, passes the worker and host
endpoints through the activation environment, and sends the same values in handshake.
Every later worker and host-runtime request includes the activation ID and token. SDKs
bind the endpoint locally, prefer Unix domain sockets where supported, constrain TCP
fallback to loopback, and reject mismatched credentials. Local authentication prevents
accidental cross-activation calls; it does not make untrusted worker code safe.

Relay supplies the following process environment to Rust, Python, and custom-command
workers:

| Variable                                      | Contract                                                                                                                                                                           |
| --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `NEMO_RELAY_WORKER_ID`                        | Opaque activation ID used in every authenticated request. It is not the manifest plugin ID.                                                                                        |
| `NEMO_RELAY_PLUGIN_ID`                        | Manifest plugin ID that the handshake response must match.                                                                                                                         |
| `NEMO_RELAY_WORKER_TOKEN`                     | High-entropy activation token used in every worker and host-runtime request. Do not log or persist it.                                                                             |
| `NEMO_RELAY_WORKER_SOCKET`                    | Worker listen endpoint. SDKs accept a Unix socket URI or a loopback TCP or HTTP endpoint; port zero requests an ephemeral TCP port.                                                |
| `NEMO_RELAY_HOST_SOCKET`                      | Relay host-runtime endpoint used for continuations, codecs, marks, and scopes.                                                                                                     |
| `NEMO_RELAY_WORKER_ENDPOINT_FILE`             | Optional path where a worker that binds an ephemeral port writes its resolved endpoint after it begins accepting requests.                                                         |
| `NEMO_RELAY_WORKER_MAX_MESSAGE_BYTES`         | Host fallback override, replacing plugin `default_bytes` and `by_name` limits. When unset: plugin `default_bytes`, then 4 MiB. Relay forwards the resolved fallback to the worker. |
| `NEMO_RELAY_WORKER_MAX_MESSAGE_BYTES_BY_NAME` | JSON map of exact callback registration names to byte limits. Relay forwards resolved per-callback overrides to the worker.                                                        |

Use [`load.forward_env`](/nemo/relay/v1.0.0/build-plugins/package-discoverable-plugins#forward-host-environment-variables)
to pass selected host environment variables to the worker. Forwarded values cannot
replace the settings that Relay supplies in the table.

### Configure Execution Message Size

Configure these tables in `relay-plugin.toml`, separate from the component
configuration in `plugins.toml`. For timeout settings and a combined example,
refer to [Worker Timeouts and Payload Limits](/nemo/relay/v1.0.0/configure-plugins/plugin-configuration-files#worker-timeouts-and-payload-limits).

Use exact callback registration names, as shown in the following example:

```toml title={"relay-plugin.toml"} showLineNumbers={false}
[load.max_message_bytes]
default_bytes = 4194304
[load.max_message_bytes.by_name]
input_guardrail = 16777216
output_guardrail = 8388608
```

Relay uses the following settings in order, from highest to lowest priority:

* Host `NEMO_RELAY_WORKER_MAX_MESSAGE_BYTES_BY_NAME`: JSON callback-to-bytes map, such as `{"input_guardrail":16777216}`.
* Host `NEMO_RELAY_WORKER_MAX_MESSAGE_BYTES`: decimal fallback for all RPCs.
* Plugin `load.max_message_bytes.by_name`: exact callback registration name.
* Plugin `load.max_message_bytes.default_bytes`, then 4 MiB.

Limits must be whole numbers from 1 through 2,147,483,647 bytes. They apply to
each sent or received message for that callback, including stream chunks and
calls to continuations. They do not limit the total stream size. Control RPCs
use the default limit. Zero is invalid. These limits do not change model
context limits or provide automatic compaction. Reactivate the plugin after changing the manifest or host
environment.

## Validation and Errors

The host and SDKs run Protovalidate checks before calling callbacks. They also
check JSON syntax, timestamps, and durations. Schema rules enforce required
alternatives, enum values, UUIDs, nonempty IDs, and relationships between fields.
Runtime code separately checks credentials, access rights, message sizes, and
operation order. Failures use the following error forms:

| Failure                                       | Representation                               |
| --------------------------------------------- | -------------------------------------------- |
| Invalid activation credentials                | `UNAUTHENTICATED`                            |
| Valid credentials without operation authority | `PERMISSION_DENIED`                          |
| Malformed request                             | `INVALID_ARGUMENT`                           |
| Incompatible protocol or lifecycle state      | `FAILED_PRECONDITION`                        |
| Frame or admission capacity exhausted         | `RESOURCE_EXHAUSTED`                         |
| Callback or downstream domain failure         | The dedicated response's `error` alternative |
| Runtime operation failure                     | Standard gRPC status                         |

`WorkerError` preserves a code, message, retryability, optional HTTP status, and
optional downstream continuation identity. Successful empty runtime operations
return empty dedicated response messages. Empty or contradictory result oneofs
are malformed; they do not mean allow, unchanged, or successful completion.

`JsonValue` contains UTF-8 JSON bytes and preserves JSON null and large integers.
`JsonObject` represents a JSON object. Closed Relay structures use typed protobuf
messages, not schema-tagged JSON envelopes. Handshake checks the contract identity.
Payloads do not repeat it.

## Cancellation and Shutdown

The SDK tracks active unary and streaming callbacks by invocation ID. Duplicate
active IDs are rejected. Cancellation aborts callback tasks, waits for their
owned resources to drop, and revokes scope, continuation, and codec access.
An accepted cancellation acknowledges callback cleanup; it does not prove that
arbitrary blocking work started by plugin code has stopped.

Stream setup, consumption, EOF, terminal error, consumer drop, and cancellation
all release invocation ownership. Stream items are ordered and bounded, with
backpressure and at most one terminal error. A transport failure does not make
execution safe to replay.

Shutdown stops new work and bounds callback and diagnostic cleanup. The host
retains responsibility for process termination and activation-owned resource
cleanup. Worker processes isolate dependencies and crashes; they are trusted
extensions and do not form a security sandbox.