<h2 align="center">
    <a href="https://nullplatform.com" target="blank_">
        <img height="100" alt="Nullplatform" src="https://nullplatform.com/favicon/android-chrome-192x192.png" />
    </a>
    <br>
    <br>
    @nullplatform/plugin
    <br>
</h2>

TypeScript SDK for nullplatform plugins: the worker the agent runs to answer what the platform asks (a service's or a scope's actions, an event, anything else), to describe what the plugin publishes, and to feed the catalog (a collector).

```bash
bun add @nullplatform/plugin
bun add @nullplatform/ingest   # a collector only: the optional peer it runs on
```

## What a plugin does

- **Answers a document.** The agent delivers one: exec'd with it in `NP_ACTION_CONTEXT`, or over its gRPC protocol (`np-agent-v1`). The first route whose `match` accepts the payload answers it, its middleware around its handler. The answer is stdout and the exit code (exec), or the gRPC result.
- **Describes itself.** `--describe` prints what `np package publish` reads: the package, its components (each API's body exactly as written), the package's agent channel, and the runs tooling offers.
- **Reports on the platform.** A kind's middleware does this, never the core. A service's or a scope's action is marked `in_progress`, each line logged at info and above is posted to it as a message, and it ends `success` with its results or `failed` with the error. The run is traced when tracing is on.

The layers:

| Layer | Where | What |
|---|---|---|
| The contract | [`contract/`](../contract) | what every language implements: the agent's proto, the settings, describe's schema, each kind's platform facts, fixtures and conformance cases |
| The core | `@nullplatform/plugin` | `definePlugin`, routes and middleware, the transports, `context.api`. It reads no payload |
| The kinds | `/service`, `/scope`, `/collector`, `event` | sugar: each builds its components, routes and middleware, and calls `definePlugin` |
| Testing | `/testing` | `run`, one payload in-process; `startPluginProcess`, the agent's side of a plugin process |

## The entry point

A plugin is a definition file and its entry points ([`examples/`](examples) has four). The agent runs `index.ts`:

```ts
import { main } from "@nullplatform/plugin";
import scope from "./scope";

await main(scope);
```

`main(plugin, ports?)` is the agent's command line:

- `--describe` prints the manifest.
- When the agent exec'd the worker, it answers that document: stdout is the answer, the exit code 0 or 1. It loads no gRPC to do so.
- Otherwise it serves until SIGTERM or SIGINT: the agent's gRPC protocol, the gRPC server loaded then, or the plugin's own serve (a collector's schedule). Stopping, a gRPC worker lets its address go, so a fresh connection is refused, and refuses every new call on a connection the agent holds `UNAVAILABLE`, so the agent sends it elsewhere; it ends once the answers in flight are delivered.
- It sets the exit code and never exits the process, so stdout is never cut short.

With no ports, each port is the real one (the platform API, the tracing API, catalog-ingest-api). A local run is its own entry file, and passes in-memory ports in code. No environment variable switches a run to local:

```ts
// local.ts: nothing reaches the platform or the tracing API; each request the platform would get is told on stderr.
import { main, noopTracing, recordingPlatform, stderrLogger } from "@nullplatform/plugin";
import scope from "./scope";

await main(scope, { fetch: recordingPlatform({ log: stderrLogger }).fetch, tracing: noopTracing });
```

```bash
bun index.ts --describe
NP_ACTION_CONTEXT="$(cat create-scope.json)" bun local.ts
```

The dev UI ([`dev-ui/`](../dev-ui/README.md)) starts a plugin's `src/local.ts` first, and says on stderr when the entry it starts runs the real ports.

`main` is optional. Any other client (a CLI of its own, a test) runs a plugin with `handle(plugin, text, ports?)`, which answers one document as `{ output, success }`, or with `serve(plugin, ports?)`. A plugin's own ports go beside the core's in `ports` (`context.ports`): when it needs one (`definePlugin<{ queue: Queue }>`), `main`, `handle`, `serve` and `run` take `ports` only with it, and the types refuse a call without it.

## A scope

```ts
import { ActionError } from "@nullplatform/plugin";
import { defineScope, ScopeActions } from "@nullplatform/plugin/scope";

export default defineScope({
  package: { name: "my-scope", version: "1.0.0" },
  specification: {
    // What a scope of this type holds: the platform copies an action's results into them.
    attributes: {
      schema: { type: "object", properties: { asset_url: { type: "string" }, domain: { type: "string" } } },
    },
  },
  actions: {
    [ScopeActions.CREATE_SCOPE]: async (input, context) => {
      const namespace = `scope-${input.parameters.scope_id}`;
      await context.trace.step("create-namespace", async () => {
        if (input.parameters.fail === true) {
          throw new ActionError("NAMESPACE_EXISTS", `${namespace} already exists`);
        }
      });
      context.log.info(`namespace ${namespace} ready`);
      return { domain: `${namespace}.example.com` };
    },
    [ScopeActions.START_INITIAL]: async (input, context) => {
      context.log.info(`deployment ${input.deployment.id} started on scope-${input.scope.id}`);
      return {};
    },
    [ScopeActions.LOG_READ]: async (input) => ({
      results: [{ message: `logs of scope-${input.scope.id}`, datetime: "2026-01-01T00:00:00.000Z" }],
    }),
  },
});
```

- `package` is the project's own, `{ name, version, description?, slug? }`, required on every define; its slug is the name's, slugified, unless given. The library reads no package.json.
- `specification` is the `service_specification` body, as the API takes it, named by the package's slug; the scope's defaults lie beneath it ([`contract/kinds/scope.json`](../contract/kinds/scope.json)).
- `ScopeActions` names the actions the platform sends a scope. A well-known one (`create-scope`, `start-initial`, …) is answered with its lifecycle on the platform. A telemetry one (`log:read`, `metric:list`, …) is answered raw, its output validated by the platform.
- Each action's handler takes `(input, context)` (What a handler gets). Its `input` is typed by its key and the scope's schemas, never by a type argument, and one `actions` record holds them all. `input.service.attributes` is the scope's attributes as stored, each optional; a well-known action returns `Partial` of them, which the platform copies into the scope's attributes.
  - A well-known key's `input.parameters` is its own row of the platform's table ([`contract/kinds/scope.json`](../contract/kinds/scope.json) `actions`): `scope_id`; a deployment action's `scope_id` and `deployment_id`; `switch-traffic` adds `desired_traffic`, `kill-instances` `instance_id`; `set-desired-instance-count` gets `desired_instances`; `pause-autoscaling`, `resume-autoscaling` and `restart-pods` declare none.
  - A deployment action (`start-initial`, `start-blue-green`, `switch-traffic`, `finalize-deployment`, `finalize-blue-green`, `rollback-deployment`, `delete-deployment`, `diagnose-deployment`, `kill-instances`) gets `DeploymentInput`: `input.deployment` is always there: a payload that names no deployment fails `MISSING_DEPLOYMENT` before the handler runs, and the deployment is checked again after `use`, right before the handler, so a middleware that passes on none fails the action the same.
  - Any other well-known key gets `ScopeInput`, its `input.deployment` there only when the payload names one. A well-known key's handler type is its own: one annotated with another input (a deployment's on `create-scope`) does not typecheck.
  - A telemetry key (any under `log:`, `metric:`, `parameter:` or `instance:`) gets `TelemetryInput`: the scope, the deployment, the service and the parameters, untyped, but no `action`, `managed` or `trace_context`, which a telemetry payload does not carry, so reading them does not typecheck; it returns what the payload's output schema says, `unknown` to the types. A handler written apart for `TelemetryInput` fits any key; one for `ScopeInput` fits no telemetry key.
  - A custom key, with its `specification`, gets its own `parameters` schema's values and returns its `results` schema's, as a service's custom action does.
  - A handler written apart is typed by its key and the specification: `ScopeActionInputOf<"create-scope", typeof specification>` (`DeploymentActionInputOf` for a deployment action) and `ScopeResultOf<"create-scope", typeof specification>`.
- `assetType` (`docker-image` unless given) and `scopeType` (the `scope_type` body it provides) are optional.
- A handler returns its results, or throws `ActionError(code, message, { retryable?, details?, cause? })` to fail the action. `retryable` and `details` are the trace's: neither the answer nor the action's lifecycle carries them.

## A service, with a link

```ts
import { defineService, ServiceActions } from "@nullplatform/plugin/service";

/** The ARN of the bucket the service `slug` is. */
function arnOf(slug: string): string {
  return `arn:aws:s3:::${slug}`;
}

export default defineService({
  package: { name: "example-bucket", version: "0.1.0" },
  specification: {
    selectors: { category: "storage", provider: "aws" },
    // What a bucket holds: the platform copies an action's results into them.
    attributes: {
      schema: { type: "object", properties: { region: { type: "string", default: "us-east-1" }, arn: { type: "string", visibleOn: ["read"] } } },
    },
  },
  actions: {
    // Every tracing option a handler has. index.ts traces it with the agent's key; local.ts passes noopTracing, so each call says nothing there.
    [ServiceActions.CREATE]: {
      // The console's timeline for the run: two steps, each titled, tag-bucket after create-bucket.
      plan: {
        steps: [
          { key: "create-bucket", title: "Create the bucket" },
          { key: "tag-bucket", title: "Tag the bucket", after: ["create-bucket"] },
        ],
      },
      handler: async (input, context) => {
        const region = input.parameters.region ?? "us-east-1";
        const slug = input.service.slug;
        // The step's node: one node however many attempts, up to 2 retries, each attempt bounded by 30 s.
        const { arn } = await context.trace.step("create-bucket", { retries: 2, timeoutMs: 30_000 }, async (step) => {
          // The step's headline, and why under it.
          step.explain({ what: `Bucket ${slug} created in ${region}`, why: "the application declared a bucket dependency" });
          // A fact the step's node keeps as data.
          step.output("arn", arnOf(slug));
          return { arn: arnOf(slug) };
        });
        await context.trace.step("tag-bucket", async (step) => {
          // The second step's headline.
          step.explain({ what: `Bucket ${slug} tagged with service ${input.service.id}` });
        });
        // The run's headline, and what it means for the reader.
        context.trace.explain({ what: `Bucket ${arn} ready in ${region}`, impact: "the application can read and write it now" });
        // A link out of the run's node.
        context.trace.link({ rel: "console", uri: `https://s3.console.aws.amazon.com/s3/buckets/${slug}`, label: "Open in the AWS console" });
        // A fact the run's node keeps as data.
        context.trace.output("region", region);
        // A log line, never tracing: the lifecycle posts it to the action as a message.
        context.log.info(`bucket ${arn} ready`);
        // The action's results, and the run's on the console.
        return { arn, region };
      },
    },
    [ServiceActions.UPDATE]: async () => ({}),
    [ServiceActions.DELETE]: async () => ({}),
    "empty-bucket": {
      specification: {
        type: "custom",
        parameters: { schema: { type: "object", required: ["prefix"], properties: { prefix: { type: "string" } } } },
        results: { schema: { type: "object", properties: { emptied: { type: "boolean" } } } },
      },
      handler: async (input, context) => {
        context.log.info(`bucket ${input.service.slug} emptied under ${input.parameters.prefix}`);
        return { emptied: true };
      },
    },
    // A return that is no object is the answer's data, and never the action's results.
    "bucket-arn": { specification: { type: "custom" }, handler: async (input) => arnOf(input.service.slug) },
  },
  links: {
    reader: {
      specification: { unique: false, attributes: { schema: { type: "object", properties: { policy: { type: "string" } } } } },
      actions: {
        [ServiceActions.CREATE]: async () => ({ policy: "read" }),
        [ServiceActions.UPDATE]: async () => ({}),
        [ServiceActions.DELETE]: async () => ({}),
      },
    },
  },
});
```

- A default action (`ServiceActions`: `create`, `update`, `delete`) is found by its type. A custom one is found by its key, and its `specification` is its `action_specification` body.
- Each action's handler takes `(input, context)` (What a handler gets). Its `input` is typed by the definition's schemas, never by a type argument (the definition is inferred as written, so write its schemas inline, or `as const`):

  | Action | `input.parameters` | What it returns (the action's results) |
  |---|---|---|
  | `create`, `update` | the attributes' values, each required that the schema requires and that has no `visibleOn` or is visible on that action | `Partial` of the attributes' values |
  | `delete` | the attributes' values, none required | `Partial` of the attributes' values |
  | a custom action | its `parameters` schema's values | its `results` schema's values |
  | a custom action with no schema | `Record<string, unknown>` | `unknown` |

  A link's default actions take the link's attributes. `input.service.attributes` is the service's attributes as stored, each optional, and `input.link.attributes` the link's. A key a schema does not declare is allowed, `unknown`, unless `additionalProperties` is `false`; a schema the mapper does not read (`oneOf`, `anyOf`, `allOf`, `$ref`, `patternProperties`) is `Record<string, unknown>`. A custom link action gets the open interface for now: TypeScript infers no link's custom action's specification, so its handler is annotated by hand (`async (input: LinkInput, context: Context) => …`). A handler written apart is typed by its key and the specification: `ActionInputOf<"create", typeof specification>` and `ActionResultOf<"create", typeof specification>` (a custom one's specification third), `LinkActionInputOf<"create", typeof link, typeof specification>` for a link's.
- A schema property the platform would rename is refused at definition, every one at once, naming what it would arrive as (`property "bucketName" arrives as "bucket_name": name it so`): the platform snake-cases every key of what it sends a plugin, at every depth (lodash's `snakeCase(camelCase(key))`, so digits split too: `ipv4_address` arrives as `ipv_4_address`). It holds for the attributes, a link's, a custom action's parameters and results, and a scope's attributes.
- An action is a handler, or `{ handler, plan?, title?, description?, specification? }`. `plan` declares the steps the console's timeline shows, and `context.trace.step` names them by key. The `create` above uses every tracing option a handler has: a plan, a step's retries and timeout, each step's narrative and the run's (What a handler gets), a log line the lifecycle posts, and its results.
- Each link is a `link_specification` under the service, and its actions report at `/link/{link.id}/action/{id}`. A link takes its own `use` (`{ specification?, actions, use? }`).
- `defineService` and `defineScope` also take `agent` (the channel's `selector`, `entrypoint`, `sources`, `pinVersion`, `manageChannel`), `use` and `routes` (routes of their own, after their actions, each with its own `use`, handed the payload).
- `use` is middleware around each action's handler, `(input, context, next)`, typed by the input its actions share: `input.parameters` untyped (each action's are its own), and `input.service.attributes` typed by the schema, so it reads `input.service`, `input.parameters`, `input.scope` or `input.deployment` with no cast, and an inline one needs no annotation. Each action's route builds its parameters again from the payload right before its handler, after `use`, so what a middleware passes on as parameters never reaches a handler typed by its schemas. A link's actions run their link's own `use` instead (`links.<key>.use`, of the link's input, `input.link` with its attributes), since a link's action is about the link; a scope's telemetry actions run none, their payload carrying no attributes. It runs inside each action's route, after the action is reported and its input built, so the platform hears what it throws; never on a specification's last route, which answers an unbound action `UNKNOWN_ACTION`, nor on a route of the definition's own. One typed for another kind's input does not typecheck:

```ts
import { ActionError } from "@nullplatform/plugin";
import { defineService, ServiceActions } from "@nullplatform/plugin/service";

/** The regions the organization runs buckets in: any other is refused before the bucket is created. */
const REGIONS: unknown[] = ["us-east-1", "eu-west-1"];

export default defineService({
  package: { name: "example-bucket", version: "0.1.0" },
  specification: { attributes: { schema: { type: "object", properties: { region: { type: "string", default: "us-east-1" } } } } },
  use: [
    async (input, context, next) => {
      const region = input.parameters.region ?? "us-east-1";
      if (!REGIONS.includes(region)) {
        throw new ActionError("REGION_NOT_ALLOWED", `region ${String(region)} is not one the organization runs buckets in`);
      }
      return next();
    },
  ],
  actions: {
    [ServiceActions.CREATE]: async (input) => ({ region: input.parameters.region ?? "us-east-1" }),
    [ServiceActions.UPDATE]: async () => ({}),
    [ServiceActions.DELETE]: async () => ({}),
  },
});
```

The core's `Middleware`, handed the payload, fits no kind's `use`: it may pass on a payload in place of the kind's input, which would reach a handler that reads the kind's fields. A middleware every kind's `use` takes, a service's, a link's and a scope's alike, is generic over the input it is handed, and passes on the one it is given:

```ts
import type { Context } from "@nullplatform/plugin";

const timed = async <Input>(input: Input, context: Context, next: () => Promise<unknown>): Promise<unknown> => {
  const started = Date.now();
  try {
    return await next();
  } finally {
    context.log.debug(`answered in ${Date.now() - started} ms`);
  }
};
```

## A plugin of no kind: an event and `execute`

```ts
import { definePlugin, event, execute } from "@nullplatform/plugin";

export default definePlugin({
  package: { name: "checklist-validator", version: "1.0.0" },
  routes: [event("checklist:item:validation_dispatched", async () => ({ valid: true })), execute(async (payload) => payload)],
});
```

Routes are tried in order, so `execute`, which matches anything, goes last. A route is `{ name, match, handler, use?, output?, describe?, guard?, channel?, sample? }`: `where({ "service.specification.slug": "bucket", link: null })` builds a `match` from dotted paths, each value JSON, copied when it is built (a Date, a Map or `undefined` is refused, naming its path). Middleware is one function around `next`, `(input, context, next) => next(input?, context?)`: `Middleware`, handed the payload, unless a kind types it: a plugin's `use` and a route's take it, a kind's `use` does not (above). Every function takes the same parameters, as Express's and Fastify's do: a handler `(input, context)`, a middleware `(input, context, next)`, built-in or yours, `context` the one `Context`. The first middleware is handed the payload, as a body parser is, and a kind's builds its typed input from it and passes that on. `next()` passes the input and the context on unchanged, `next(input)` replaces the input, `next(input, context)` both (a wrapped `log`, say). A route's `describe(payload)` says the run it is traced as, which the core opens before any middleware, so `context.trace` is that run for every one of them, and ends with the answer; its `guard(input, payload)` runs right before the handler, which gets what it returns. Both are a kind's own, and the core reads neither. A middleware sees what the handler returned or threw:

```ts
import { definePlugin, event, type Middleware } from "@nullplatform/plugin";

const timed: Middleware = async (input, context, next) => {
  const started = Date.now();
  try {
    return await next();
  } finally {
    context.log.debug(`answered in ${Date.now() - started} ms`);
  }
};

export default definePlugin({
  package: { name: "checklist-validator", version: "1.0.0" },
  use: [timed],
  routes: [
    event("checklist:item:validation_dispatched", async (input, context) => {
      const scope = await context.api.scope(String(input.event.context.scope_id)).get<{ status: string }>();
      return { valid: scope.status === "active" };
    }),
  ],
});
```

`definePlugin` also takes `components` (from `component(kind, name, body, { parent?, path?, list?, identity?, owner? })`; `ref(component)` is `{ ref: "<kind>/<name>" }`), `agent`, `serve` and `tooling`.

## A collector

```ts
import { DeletePolicy, Engine, type CollectorEvents } from "@nullplatform/ingest";
import { defineCollector } from "@nullplatform/plugin/collector";

/** Where the collector reads its inventory: what its entry point builds it with. */
export interface InventoryConfig {
  /** Where the inventory export lives; the collector's own inventory without it. */
  inventoryUrl?: string;
  /** Where the inventory streams its changes, one JSON line each; nothing to watch without it. */
  changesUrl?: string;
}

/** A service as the inventory lists it, with the team that owns it. */
interface InventoryRecord {
  id: string;
  name: string;
  owner: string;
  retired: boolean;
}

/** A team, as the collector sends it: the owner of a service. */
interface TeamRecord {
  name: string;
}

/** A change the inventory's feed streams: what happened to a record, and when. */
interface InventoryChange {
  change: "upsert" | "delete";
  record: InventoryRecord;
  at: string;
}

/** The inventory when no export is given. */
const OWN_INVENTORY: InventoryRecord[] = [
  { id: "svc-1", name: "checkout", owner: "payments", retired: false },
  { id: "svc-2", name: "legacy-cart", owner: "storefront", retired: true },
];

/** The records the export at `url` lists, read under `signal`, the collector's own inventory without one; an export that refuses fails the snapshot. */
async function inventoryOf(url: string | undefined, signal: AbortSignal): Promise<InventoryRecord[]> {
  if (url === undefined) {
    return OWN_INVENTORY;
  }
  const response = await fetch(url, { signal });
  if (!response.ok) {
    throw new Error(`the inventory export at ${url} answered ${response.status}`);
  }
  return (await response.json()) as InventoryRecord[];
}

/** The teams that own `services`, each once. */
function teamsOf(services: InventoryRecord[]): TeamRecord[] {
  return [...new Set(services.map((service) => service.owner))].map((name) => ({ name }));
}

/** The changes the feed at `url` streams, read under `signal`, in the batches they arrive in, one JSON line each; a feed that refuses throws. */
async function* changeBatchesOf(url: string, signal: AbortSignal): AsyncGenerator<InventoryChange[]> {
  const response = await fetch(url, { signal });
  if (!response.ok || response.body === null) {
    throw new Error(`the change feed at ${url} answered ${response.status}`);
  }
  const decoder = new TextDecoder();
  let partial = "";
  for await (const chunk of response.body) {
    const lines = (partial + decoder.decode(chunk, { stream: true })).split("\n");
    partial = lines.pop() ?? "";
    yield lines.filter((line) => line.trim() !== "").map((line) => JSON.parse(line) as InventoryChange);
  }
}

/** Emits `change` as the catalog takes it, observed when the feed says: a service retired or deleted is deleted; any other is upserted, with its team. */
function emitted(events: CollectorEvents, { change, record, at }: InventoryChange): void {
  if (change === "delete" || record.retired) {
    events.delete("service", record, { observedAt: at });
    return;
  }
  events.upsert("service", record, { observedAt: at });
  events.upsert("team", { name: record.owner } satisfies TeamRecord, { observedAt: at });
}

/** What resolves once `signal` aborts: at once if it already has. */
function untilAborted(signal: AbortSignal): Promise<void> {
  const aborted = Promise.withResolvers<void>();
  signal.addEventListener("abort", () => aborted.resolve(), { once: true });
  return signal.aborted ? Promise.resolve() : aborted.promise;
}

/** The collector of the inventory `config` names. */
export function inventoryCollector(config: InventoryConfig) {
  return defineCollector({
    // The slug is the name's unless given: given here as the name, it is also the source's slug unless the source port says another.
    package: { name: "example-inventory", slug: "example-inventory", version: "0.1.0", description: "Feeds the catalog with the services of an inventory export" },
    source: {
      // The source type's slug: what kind of system this is. Its mappings are the organization's.
      type: "inventory",
      name: "Inventory export",
      description: "The services an inventory export lists, and the teams that own them",
      // The organization's own data about the source, read by a mapping as `$source.attributes`.
      attributes: { region: "us-east-1" },
      runs: {
        // A snapshot not finished within an hour is aborted.
        ttlSeconds: 3600,
        // A finished snapshot deletes what it no longer saw: a retired service leaves the catalog.
        deletePolicy: DeletePolicy.SOFT_DELETE_STALE,
        // A snapshot that would delete half the entities or more is refused.
        maxDeleteRatio: 0.5,
        // A snapshot that listed nothing is refused: an empty export is a broken one.
        rejectEmpty: true,
      },
    },
    // A type the inventory source type's mappings map: the organization binds it to its endpoints once. Its source type's mappings' unless given; given, it must agree with them.
    recordTypes: ["team"],
    mappings: {
      // The organization's own type: its mapping is the collector's, evaluated by catalog-ingest-api.
      service: {
        engine: Engine.JSONATA,
        // Each service an entity of its id, in the region the source's attributes name.
        expression: '{ "id": id, "data": { "external_id": id, "name": name, "owner": owner, "region": $source.attributes.region } }',
        // Where the entities go: the catalog, and its endpoint, a specification's slug.
        target: "catalog",
        endpoint: "inventory-service",
        // Written while true: false stops writing the mapping's entities, the mapping kept.
        enabled: true,
      },
    },
    // What the records become in the catalog: the package defines everything they need. A relation's target goes before what points at it.
    entities: [
      // nullplatform's own: a client's publish finds it and pins it; nullplatform's writes it.
      { slug: "team", name: "Team", description: "A team that owns services", schema: { type: "object", properties: { name: { type: "string" } }, required: ["name"] }, platform: true },
      // The organization's own, the endpoint its own mapping writes to: its publish writes it.
      {
        slug: "inventory-service",
        name: "Inventory service",
        description: "A service the inventory export lists",
        schema: {
          type: "object",
          properties: { external_id: { type: "string" }, name: { type: "string" }, owner: { type: "string" }, region: { type: "string" } },
          required: ["external_id", "name"],
        },
      },
    ],
    // The source type, its slug the source's type.
    sourceType: {
      name: "Inventory export",
      description: "An inventory export's services and the teams that own them",
      // What every source of the type has unless it sets its own, in the API's own case.
      runs: { max_delete_ratio: 0.5 },
      // The mappings every source of the type shares, by slug: each maps the record type its slug names unless it gives its recordType.
      mappings: {
        team: { engine: Engine.JSONATA, expression: '{ "id": name, "data": { "name": name } }' },
      },
    },
    // With a watch, a resync: every six hours a snapshot catches what the watch missed while it was down.
    schedule: { intervalSeconds: 21_600 },
    async *snapshot(ctx) {
      const services = (await inventoryOf(config.inventoryUrl, ctx.signal)).filter((service) => !service.retired);
      // What the snapshot found, as of when it started: its records are observed then, unless one says otherwise.
      ctx.log.info(`${services.length} service(s) in source ${ctx.source.slug} as of ${ctx.observedAt.toISOString()}`);
      for (const service of services) {
        yield { type: "service", payload: service };
      }
      for (const team of teamsOf(services)) {
        yield { type: "team", payload: team };
      }
    },
    // The changes as they happen, until the collector stops; ingest restarts a watch that throws or returns, after a backoff.
    async watch(ctx) {
      const url = config.changesUrl;
      if (url === undefined) {
        // Nothing to watch: it waits for the stop, since a watch that returns at once is restarted.
        return untilAborted(ctx.signal);
      }
      for await (const batch of changeBatchesOf(url, ctx.signal)) {
        batch.forEach((change) => emitted(ctx.events, change));
        // Each batch sent as it arrives, not a second later.
        await ctx.events.flush();
      }
    },
  });
}

/** The collector of its own inventory, with nothing to watch: what a local run, and every language's conformance cases, run. */
export default inventoryCollector({});
```

- Everything that feeds catalog-ingest-api is `@nullplatform/ingest`'s: the definition is its `CollectorDefinition`, plus `package` and `schedule`. The example above uses every option:
  - a source with its `attributes` (which a mapping reads as `$source.attributes`) and its `runs` settings;
  - `recordTypes`, which the source type's mappings map, and which it could leave to them;
  - its own mapping, with its `target` and its `enabled` switch;
  - the definitions its records need, which describe publishes as components: its catalog `entities` and its `sourceType` (its slug `source.type`) with that type's `mappings`;
  - a `schedule`, which beside a watch is a resync;
  - a `snapshot`, which reads every field of its context.
- Its own configuration (where the inventory is) is its code's: `inventoryCollector(config)` builds the collector, and its handlers read `config`. The project's entry point builds it from what its deployment says (`index.ts` reads `INVENTORY_URL` and `INVENTORY_CHANGES_URL`; the library reads no environment), a local run with none (`local.ts`). Ingest's context carries no configuration.
- The example's watch:
  - It reads a change feed (`changesUrl`) under `ctx.signal` and emits each change with `ctx.events.upsert` or `ctx.events.delete`, observed when the feed says, flushing each batch as it arrives.
  - Without a feed, it waits until `ctx.signal` aborts: a watch that returns or throws is restarted, after a backoff.
- A package defines everything its records need: each entity is an `entity_specification`, the source type a `source_type` and each of its mappings a `mapping` under it, named `<type slug>/<mapping slug>`, its body the API's create body as written but `platform`. A mapping is keyed by its slug, unique in the type, and maps `recordType`, else its slug: an extension adds `pod-acme` mapping `pod` beside nullplatform's `pod`. Its `engine` is ingest's `Engine` or its name as text. `platform: true` marks one nullplatform's (`owner: "platform"`): a client's publish looks it up and pins it, never writes it, and nullplatform's own publish writes it. Entities are described in the order given, so give a relation's target first. With mappings, `recordTypes` is theirs unless given, each once in the order they first appear; given, it must agree with them. The SDK checks only what publishing needs (a slug, a name and an object schema per entity, each slug once; the source type's slug, when given, `source.type`; each mapping `{ recordType?, engine, expression }` of text; record types that agree with the mappings') and never writes them: the CLI, or a project's own script, publishes what describe says.
- An exec'd document is one snapshot: its options are `{ finalize? }`, and `{}` is a plain snapshot. Served, it snapshots every interval, and watches when it has a `watch`.
- Its own ports are given in code, beside the core's, and none is read from the environment:
  - `ingest`: catalog-ingest-api at `ingestUrl` (ingest's own URL under `apiUrl` unless given), authenticated by `ingestToken`, else by the run's `apiKey`;
  - `source`: `{ slug, nrn, name }`, the slug the package's unless given;
  - `intervalSeconds`: the schedule's unless given, else `DEFAULT_INTERVAL_SECONDS` (a day).
- A served collector with no credentials (no `apiKey`, no `ingestToken`) crashes at start: `main` exits 1 with what to set, before any snapshot or watch. An exec'd snapshot without them fails its answer.
- A local run passes `ingest: new InMemoryIngest({ log: stderrLogger })`, from `@nullplatform/ingest/testing`.
- A collector that needs ingest's client options (timeouts, retries, backpressure, batching) passes its own client as the `ingest` port: `ingest: ClientIngest.connect({ apiKey, timeoutMs: 60_000 })`, or `new ClientIngest(new IngestClient({ … }))`, `@nullplatform/ingest`'s. They are not ports of the collector's.
- A hot reload (`bun --hot`) of a served collector stops the running serve, its signal aborted and its end awaited, then serves the new definition: one runs at a time.

## What a handler gets

A handler takes `(input, context)`: its `input` is the payload's data, typed by its kind, and its `context` the SDK's tools, one type for every kind.

```ts
[ServiceActions.CREATE]: async (input, context) => {
  input.parameters.region; input.service.attributes; input.action; input.user; input.package; input.tags; input.entity_nrn; input.managed; input.trace_context;
  await context.trace.step("create-bucket", { retries: 2, timeoutMs: 30_000 }, async (step) => step.explain({ what: "created" }));
  context.trace.explain({ what: "ready" }); context.log.info("ready"); context.api; context.signal; context.credentials; context.ports;
  return {};
},
```

`context` is the core's `Context` type: `log`, `trace` (`step`, `explain`, `link`, `output`), `signal`, `api`, `credentials` (`apiUrl`, `apiKey`, frozen) and `ports` (the project's own), what every handler's context holds, as [contract/README.md](../contract/README.md#routes-and-middleware) lists it. `input` is its kind's:

| Handler | `input` |
|---|---|
| any route's (`definePlugin`, `execute`) | the payload as delivered: `execute(async (payload, context) => …)` |
| `event(name, …)` | `event`: `name`, `source`, `context` |
| a service's action | what the platform sends it: `parameters` (typed by its schemas), `action` (`id`, `slug`, `name`, `type`, `status`, `specification`), `service` (`id`, `slug`, its `attributes`, …), `link` (`id`, `slug`, its `attributes`, …) on a link's action, `user` (`id`, `email`), `package` (`id`, `slug`, `name`, `revision`), `tags`, `entity_nrn`, `managed` (whether the platform manages the action) and `trace_context` (the carrier of the trace it continues), as sent, when the payload carries them; no top-level `attributes`: `ServiceInput`, `LinkInput` |
| a scope's action | a service's, and `scope` (`id`, `slug`, …) and `deployment` (`id`), when the action is about one: `ScopeInput` |
| a scope's deployment action | a scope's, `deployment` always there: `DeploymentInput` |
| a scope's telemetry action | a scope's, but no `action`, `managed` or `trace_context`, its parameters untyped: `TelemetryInput` |

A collector's `snapshot` and `watch` are the one exception: they take `@nullplatform/ingest`'s own context, `ctx`, as ingest's API names it: `source` (`id`, `slug`), `log`, `signal`; `observedAt` on a snapshot, `events` on a watch. It carries no configuration: the collector's is its code's.

- `context.log` has `debug`, `info`, `warn` and `error`, and writes to stderr. On an action with a lifecycle, each line at info or above is posted to the action.
- `context.trace.step(name, options?, work)` is a unit of work with `retries` and `timeoutMs`, traced as a step of the run. Its work gets the step's narrative.
- `context.trace` is also the run's narrative: `explain({ what, why, … })`, `link({ rel, uri, label })`, `output(name, value)`. With tracing off it says nothing, and its step still runs its work with its retries and its timeout.
- A tool is never a field of `input`, nor a payload's field one of `context`: `input.log` and `context.parameters` do not typecheck. A middleware's context is the same `Context`: no `context.payload`, no `context.tracer`.
- A payload's fields pass through as the platform sends them: nothing converts their case.

## The platform API: `context.api`

A call reads like its URL:

| Call | Request |
|---|---|
| `context.api.service(id).action(actionId).patch(body)` | `PATCH /service/<id>/action/<actionId>` |
| `context.api.scope(id).get<Scope>()` | `GET /scope/<id>` |
| `context.api.service_specification(id).action_specification.post(body)` | `POST /service_specification/<id>/action_specification` |
| `context.api.notification.channel.list({ nrn, type: "agent" })` | `GET /notification/channel?nrn=…&type=agent`, every page |
| `context.api.scope(id).delete()` | `DELETE /scope/<id>` |

- A property adds a path segment as the API spells it (`service_specification`). A call adds an id, URL-encoded. Read as text (`String(resource)`, a template literal), a resource is its path: `/service/<id>/action/<actionId>`.
- Six verbs send: `get(query?)`, `delete()`, `post(body)`, `put(body)`, `patch(body)`, and `list(query?)`, an async iterable over every page. Nothing is sent without a verb, and the caller types the result.
- A refusal is an error naming the status, the call and the answer: `API 422: PATCH /service/svc-1/action/act-1 — {"message":"…"}`.
- A call that gets no whole answer, before it or while its body is read, is an error naming the call and why: `API: GET /scope/1 — fetch failed`, what kept it back its `cause`. A success with an empty or blank body answers `undefined`; one whose body is not JSON is an error naming the call.
- `context.api.fetch` is the raw platform port, `(request: Request) => Promise<Response>`, which every call goes through. The default port exchanges `apiKey` for a token, sends it as the bearer, and on a 401 lets the refused body go, exchanges again once (one exchange for every call refused that token) and sends the call once more. It times each attempt out at 30 s, and the call's signal stops it, and its wait for a token too. It sends the token only to the platform API's own origin: a request elsewhere goes as it is. A local run's `recordingPlatform().fetch` records each call instead.
- Outside a handler, `createApi({ fetch?, credentials?, signal? })` builds the same client.
- The library ships no API types. A project that wants them runs its own typed client over `context.api.fetch`.

## Settings

Settings are parameters, one string each, from [`contract/settings.json`](../contract/settings.json): `settings` on the ports of `main`, `handle` and `serve` (`Partial<Settings>`). A value given in code wins. `main` fills what the code leaves unset from the variables the agent sets on a worker, and each setting's default comes last. The library reads no other variable and no config file.

| Setting | The agent sets | Default | What |
|---|---|---|---|
| `apiUrl` | `NP_API_URL` | `https://api.nullplatform.com` | the platform API URL |
| `apiKey` | `NP_API_KEY` |  | the platform API key |
| `actionContext` | `NP_ACTION_CONTEXT` |  | the document the agent execs the worker with |
| `grpcListen` | `NP_GRPC_LISTEN` |  | the gRPC listen address |
| `agentPlugin` | `NP_AGENT_PLUGIN` |  | the agent's plugin protocol |
| `workerTlsCa` | `NP_WORKER_TLS_CA` |  | the worker's TLS CA, as PEM |
| `workerTlsCaFile` | `NP_WORKER_TLS_CA_FILE` |  | the worker's TLS CA file |
| `workerTlsCert` | `NP_WORKER_TLS_CERT` |  | the worker's TLS certificate, as PEM |
| `workerTlsCertFile` | `NP_WORKER_TLS_CERT_FILE` |  | the worker's TLS certificate file |
| `workerTlsKey` | `NP_WORKER_TLS_KEY` |  | the worker's TLS key, as PEM |
| `workerTlsKeyFile` | `NP_WORKER_TLS_KEY_FILE` |  | the worker's TLS key file |
| `tracingUrl` |  | `${apiUrl}/tracing` | the tracing API URL |

- With `grpcListen` set, the worker listens on that TCP address, with mTLS when the CA, the certificate and the key are all given (each as PEM or a file), insecure when none is; part of them is refused, naming each setting missing. To serve the agent's gRPC protocol without it, `agentPlugin` must be `np-agent-v1`, and the worker serves on a unix socket.
- Where a setting is used, a blank one is absent, as an empty one is.

```ts
import { main } from "@nullplatform/plugin";
import scope from "./scope";

await main(scope, { settings: { apiUrl: "https://api.example.test" } });
```

Tracing is off without an API key, or with an empty `tracingUrl` (a blank one is empty). Nothing is answered differently then, only not traced. When it is on, a tracing API that is slow or down holds an answer 5 s at most: past that, the run's end stops waiting, with a warning, and its events go on being sent for as long as the worker lives. `handle` stops the tracer it built once it has answered, and `serve` once it has ended; a backoff the tracing SDK is sleeping then ends, and what is still being sent is aborted and dropped, so tracing never holds the worker's exit: no request or timer of it outlives the answer, a run that continues a trace as any other. A tracer given as the `tracing` port is the caller's, never stopped. A blank `apiUrl` is its default; one that is not an `http` or `https` URL refuses every platform call, naming the setting. A handler gets only `context.credentials`: the listen address, the TLS material and the document stay the transport's.

## Testing

`run(plugin, request, options?)` answers one payload in-process, as exec would, and nothing leaves the process:

```ts
import { expect, test } from "bun:test";
import { run } from "@nullplatform/plugin/testing";
import scope from "./scope";

test("create-scope answers the scope's domain and reports the action", async () => {
  const result = await run(scope, "create-scope", { with: { parameters: { scope_id: "42" } } });
  expect(result.data).toEqual({ domain: "scope-42.example.com" });
  expect(result.requests.map((request) => request.body)).toEqual([
    { status: "in_progress" },
    { messages: [{ level: "info", message: "namespace scope-42 ready" }] },
    { status: "success", results: { domain: "scope-42.example.com" } },
  ]);
});
```

- `request` is a route's name, which runs the route's sample, or a payload. `with` is laid over it, however deep.
- `options` also takes `respond` (what answers each platform call, `200 {}` unless given), `settings`, `ports`, `signal` and `tracing`.
- It returns `{ success, data, failure, stdout, requests, logs, steps }`. `requests` holds each platform call as `{ method, path, body }`, in order.

`startPluginProcess(entrypoint, options?)` starts a plugin's entry point as the agent does and drives it over gRPC, for end-to-end tests and tooling (`dev-ui/` runs on it). It reads the plugin's handshake, its first whole line on stdout, and `executeStreaming(payload, onEvent)` forwards the plugin's own output to every streaming execute while it runs:

```ts
import { expect, test } from "bun:test";
import { startPluginProcess } from "@nullplatform/plugin/testing";
import scope from "./scope";

test("the plugin answers its first run over the agent's protocol", async () => {
  const plugin = await startPluginProcess("./local.ts");
  try {
    const response = await plugin.execute(scope.manifest().runs[0].document);
    expect(response.result?.success).toBe(true);
  } finally {
    plugin.stop();
  }
});
```

## Public paths

| Import | Exports |
|---|---|
| `@nullplatform/plugin` | `definePlugin`, `execute`, `event`, `where`, `component`, `ref`, `main`, `handle`, `serve`, `createApi`, `recordingPlatform`, `ActionError`, `stderrLogger`, `noopTracing`, and their types |
| `@nullplatform/plugin/service` | `defineService`, `ServiceActions` |
| `@nullplatform/plugin/scope` | `defineScope`, `ScopeActions` |
| `@nullplatform/plugin/collector` | `defineCollector`, `DEFAULT_INTERVAL_SECONDS`, and their types |
| `@nullplatform/plugin/testing` | `run`, `startPluginProcess` |

What changed from 0.1.11, and how to migrate: [CHANGELOG.md](CHANGELOG.md).
