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

# Plugin Shape

> Understand plugin identity, lifecycle, ownership, rollback, and teardown.

A plugin is a configuration-driven installer for Relay behavior. It is not the
subscriber, guardrail, or intercept itself. The plugin gives a related set of runtime
registrations a stable identity, validates one component's JSON configuration, and
installs those registrations through a component-scoped context.

## The Shared Contract

| Part                         | Responsibility                                                                                                                                                                                                              |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Stable identity              | A language-binding plugin is registered under a kind; native and worker implementations report their plugin identity during loading or handshake. Configuration uses that identity in `components[].kind`.                  |
| `validate`                   | Examines component-local JSON and returns [structured diagnostics](/nemo/relay/v1.0.0/build-plugins/fundamentals/configuration-and-validation) without installing behavior or performing lasting side effects.                                |
| `register`                   | Receives the validated component configuration and a [`PluginContext`](/nemo/relay/v1.0.0/build-plugins/fundamentals/plugin-context), then installs the component's subscribers and middleware.                                               |
| `allows_multiple_components` | Declares whether one plugin implementation can back more than one configured component. Rust traits default to `true`. Return `false` for a plugin that allows only one component. Set or test this behavior in other SDKs. |
| Component ownership          | Every registration made through the context belongs to the component being activated. Relay qualifies registration names and tracks cleanup on that component's behalf.                                                     |

Rust plugin implementations must be `Send + Sync`. Their registration methods
take `&self`, the configuration first, and a mutable registration context. Each
returns a `PluginFuture`. This applies to built-in, native, and worker plugins.
The host waits for registration to finish before activating the component.
Python and Node.js registration hooks run synchronously. Installed middleware
callbacks can be asynchronous.

The lifecycle hooks use the same logical shape in every binding. These implementations
all validate `tag` and install one component-owned subscriber. The callback spelling is
different, but the identity, validation, and ownership rules are the same.

**`Python`**

```python title="Python"
from typing import Any

from nemo_relay.plugin import PluginContext

class AuditPlugin:
    def validate(self, config: dict[str, Any]) -> list[dict[str, str]]:
        tag = config.get("tag", "documentation")
        if isinstance(tag, str):
            return []
        return [{
            "level": "error",
            "code": "audit.invalid_tag",
            "component": "audit",
            "field": "tag",
            "message": "tag must be a string",
        }]

    def register(self, _config: dict[str, Any], context: PluginContext) -> None:
        context.register_subscriber("events", lambda event: print(event.name))
```

**`Node.js`**

```js title="Node.js"
const auditPlugin = {
  validate(config) {
    if (config.tag === undefined || typeof config.tag === 'string') return [];
    return [{
      level: 'error',
      code: 'audit.invalid_tag',
      component: 'audit',
      field: 'tag',
      message: 'tag must be a string',
    }];
  },

  register(_config, context) {
    context.registerSubscriber('events', (event) => console.log(event.name));
  },
};
```

**`Rust`**

```rust title="Rust"
use std::{future::Future, pin::Pin, sync::Arc};

use nemo_relay::plugin::{
    ConfigDiagnostic, DiagnosticLevel, Plugin, PluginRegistrationContext,
    Result as PluginResult,
};
use serde_json::{Map, Value as Json};

struct AuditPlugin;

impl Plugin for AuditPlugin {
    fn plugin_kind(&self) -> &str {
        "audit"
    }

    fn validate(&self, config: &Map<String, Json>) -> Vec<ConfigDiagnostic> {
        if config.get("tag").is_none_or(Json::is_string) {
            return Vec::new();
        }
        vec![ConfigDiagnostic {
            level: DiagnosticLevel::Error,
            code: "audit.invalid_tag".into(),
            component: Some("audit".into()),
            field: Some("tag".into()),
            message: "tag must be a string".into(),
        }]
    }

    fn register<'a>(
        &'a self,
        _config: &Map<String, Json>,
        context: &'a mut dyn PluginRegistrationContext,
    ) -> Pin<Box<dyn Future<Output = PluginResult<()>> + Send + 'a>> {
        Box::pin(async move {
            context.register_subscriber(
                "events",
                Arc::new(|event| println!("{}", event.name())),
            )?;
            Ok(())
        })
    }
}
```

Rust carries the kind on the `Plugin` implementation. Python and Node.js supply it when
the application calls `plugin.register("audit", implementation)`. In all three cases,
`events` is a local registration name. Relay qualifies that name with the component
owner, records it during activation, and removes it when the activation closes or rolls back.

One component can install several kinds of middleware when the configuration tells a
coherent story. For example, a policy component can observe calls, block configured
tools, and add an audit mark. A plugin that combines an unrelated exporter, routing
policy, and provider client is harder to validate, roll out, and remove safely; those
behaviors should normally become separate components.

## Activation Is Transactional

Activation begins with a complete plugin document, not an isolated callback. Relay
validates the document and every component, including disabled components, so a staged
configuration can be checked before it is enabled. An enabled component with error
diagnostics cannot activate.

For each valid, enabled component, Relay creates a registration context and calls the
plugin's registration hook. A successful hook commits the registrations as active
component state. If the hook fails after installing some behavior, Relay rolls back the
partial registrations. Native and worker components follow the same ownership
rules. Each component owns the callbacks and resources created during registration.

The runtime report is the observable record of that process. It identifies loaded
components and diagnostics, and it lets an application or deployment test distinguish
"configuration parsed" from "runtime behavior is active."

## Teardown Has an Owner

Registrations should be created only through the supplied context. Direct process-global
registration escapes component ownership and prevents reliable rollback. The same rule
applies to external resources: create clients, tasks, and file handles during
registration only when their lifetime is tied to the component and they can be stopped
when activation fails or the owning activation closes.

Language-binding applications close the owning activation to remove active plugin
configuration. They can deregister a plugin kind when the implementation itself
is no longer available. Dynamic hosts remove component registrations before
stopping executors or workers. Native libraries stay loaded until process exit.
Worker shutdown ends active callbacks, closes the authenticated endpoint, and
terminates the managed process.

## Verify the Lifecycle

Use the following sequence to verify validation, activation, ownership, and teardown:

1. Register or load the plugin implementation under its stable identity.
2. Validate one invalid component and confirm the report names the component, field,
   stable diagnostic code, and error level.
3. Validate a disabled invalid component and confirm the same error is still visible.
4. Validate and initialize a valid enabled component, then inspect the runtime report
   before sending application traffic.
5. Execute a representative managed call and observe the registration's effect rather
   than treating successful initialization as sufficient proof.
6. Close the activation and verify that the same call no longer observes the plugin.
7. For a native component, verify that its tasks stop. For a worker, verify
   that its process stops.

Success means invalid configuration never changes runtime behavior, valid configuration
produces an active report and an observable call-path effect, and teardown removes that
effect without leaving active component tasks, executors, or worker processes.