> ## Documentation Index
> Fetch the complete documentation index at: https://iii.dev/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js SDK

> API reference for the iii SDK for Node.js / TypeScript.

## Installation

```bash theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
npm install iii-sdk
```

## Initialization

### registerWorker

Register the worker with a iii instance, returns a connected worker client.
The WebSocket connection is established automatically.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
registerWorker(address?: string, options?: InitOptions) => IIIClient
```

<Tabs>
  <Tab title="Parameters">
    <ParamField body="address" type="string">
      WebSocket URL of the III engine. Omit to resolve it from
      `process.env.III_URL`, falling back to DEFAULT\_ENGINE\_URL.
    </ParamField>

    <ParamField body="options" type="InitOptions">
      Optional InitOptions for worker name, timeouts, reconnection, and OTel.

      <Expandable title="`InitOptions` fields">
        <ParamField body="enableMetricsReporting" type="boolean">
          Enable worker metrics via OpenTelemetry. Defaults to `true`.
        </ParamField>

        <ParamField body="headers" type="Record<string, string>">
          Custom HTTP headers sent during the WebSocket handshake.
        </ParamField>

        <ParamField body="invocationTimeoutMs" type="number">
          Default timeout for `worker.trigger()` invocations in milliseconds. Defaults to `30000`.
        </ParamField>

        <ParamField body="namespace" type="string">
          Namespace this worker belongs to. Resolution order: `options.namespace` -> `process.env.III_NAMESPACE` -> undefined. When undefined the engine applies its `default` namespace. It scopes more than the registration. The worker and its functions register here, so identically-named entries coexist across namespaces, and everything the worker does afterwards follows it: a `trigger` resolves its target here, and a `registerTrigger` binds here, unless the call names another namespace. One declaration places the whole worker.
        </ParamField>

        <ParamField body="otel" type="Omit<OtelConfig, 'engineWsUrl'>">
          OpenTelemetry configuration. OTel is initialized automatically by default. Set `{ enabled: false }` or env `OTEL_ENABLED=false/0/no/off` to disable. The `engineWsUrl` is set automatically from the III address.
        </ParamField>

        <ParamField body="reconnectionConfig" type="Partial<IIIReconnectionConfig>">
          WebSocket reconnection behavior.
        </ParamField>

        <ParamField body="workerDescription" type="string">
          One-line, human/LLM-readable summary of what this worker does. Surfaces in `engine::workers::list` / `engine::workers::info`.
        </ParamField>

        <ParamField body="workerName" type="string">
          Display name for this worker. Defaults to `hostname:pid`.
        </ParamField>
      </Expandable>
    </ParamField>
  </Tab>

  <Tab title="Example">
    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
    import { registerWorker } from 'iii-sdk'

    // Address from III_URL, set by whatever supervisor spawned this worker.
    const worker = registerWorker()

    // Or explicitly, which always wins over the environment.
    const other = registerWorker('ws://localhost:49134', { workerName: 'my-worker' })
    ```
  </Tab>
</Tabs>

## Methods

### registerTrigger

Registers a new trigger. A trigger is a way to invoke a function when a certain event occurs.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
registerTrigger(trigger: RegisterTriggerInput) => Trigger
```

<Tabs>
  <Tab title="Parameters">
    <ParamField body="trigger" type="RegisterTriggerInput" required>
      The trigger to register.

      <Expandable title="`RegisterTriggerInput` fields" defaultOpen>
        <ParamField body="config" type="unknown" required>
          Trigger-type-specific configuration, matching the shape the trigger type expects.
        </ParamField>

        <ParamField body="function_id" type="string" required>
          ID of the function this trigger invokes when it fires.
        </ParamField>

        <ParamField body="metadata" type="Record<string, unknown>">
          Arbitrary user-specifiable metadata supplied to the triggered handler function on every invocation.
        </ParamField>

        <ParamField body="namespace" type="string">
          Namespace the trigger's target function resolves in. Omitting it does not bind in the engine's default: `registerTrigger` fills it from this worker's namespace, because the function a trigger names is one this worker registered, and that landed in the worker's namespace. Name another namespace, `default` included, to bind elsewhere.
        </ParamField>

        <ParamField body="trigger_namespace" type="string">
          Namespace to find the trigger type's provider in. Omitting it is not the same as `'default'`: it asks the engine to resolve, taking this worker's namespace first and the engine's own second. That is what lets a project ship its own provider for a type id the engine also provides, while a worker that has not been migrated keeps reaching the engine's without saying so. Naming one is strict.
        </ParamField>

        <ParamField body="type" type="string" required>
          Identifier of the registered trigger type this trigger uses (e.g. `storage::object-created`, `http`).
        </ParamField>
      </Expandable>
    </ParamField>
  </Tab>

  <Tab title="Example">
    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
    const trigger = worker.registerTrigger({
      type: 'cron',
      function_id: 'my-service::process-batch',
      config: { expression: '0 */5 * * * * *' },
    })

    // Later, remove the trigger
    trigger.unregister()
    ```
  </Tab>
</Tabs>

***

### registerFunction

Registers a new function with a local handler or an HTTP invocation config.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
registerFunction(functionId: string, handler: HttpInvocationConfig | RemoteFunctionHandler<any, any>, options?: RegisterFunctionOptions) => FunctionRef
```

<Tabs>
  <Tab title="Parameters">
    <ParamField body="functionId" type="string" required>
      Unique identifier for the function.
    </ParamField>

    <ParamField body="handler" type="HttpInvocationConfig | RemoteFunctionHandler<any, any>" required>
      Async handler for local execution, or an HTTP invocation config for external functions (Lambda, Cloudflare Workers, etc.).
    </ParamField>

    <ParamField body="options" type="RegisterFunctionOptions">
      Optional function registration options (description, request/response formats, metadata).

      <Expandable title="`RegisterFunctionOptions` fields">
        <ParamField body="description" type="string">
          The description of the function.
        </ParamField>

        <ParamField body="invocation" type="HttpInvocationConfig">
          HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.).
        </ParamField>

        <ParamField body="metadata" type="Record<string, unknown>">
          Arbitrary metadata attached to the function.
        </ParamField>

        <ParamField body="request_format" type="RegisterFunctionFormat">
          The request format of the function.
        </ParamField>

        <ParamField body="response_format" type="RegisterFunctionFormat">
          The response format of the function.
        </ParamField>
      </Expandable>
    </ParamField>
  </Tab>

  <Tab title="Example">
    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
    // Local handler
    const ref = worker.registerFunction(
      'greet',
      async (data: { name: string }) => ({ message: `Hello, ${data.name}!` }),
      { description: 'Returns a greeting' },
    )

    // HTTP invocation
    const lambdaRef = worker.registerFunction(
      'external::my-lambda',
      {
        url: 'https://abc123.lambda-url.us-east-1.on.aws',
        method: 'POST',
        timeout_ms: 30_000,
        auth: { type: 'bearer', token_key: 'LAMBDA_AUTH_TOKEN' },
      },
      { description: 'Proxied Lambda function' },
    )

    // Later, remove the function
    ref.unregister()
    ```
  </Tab>
</Tabs>

***

### trigger

Invokes a function using a request object.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
trigger(request: TriggerRequest<TInput>) => Promise<TOutput>
```

<Tabs>
  <Tab title="Parameters">
    <ParamField body="request" type="TriggerRequest<TInput>" required>
      The trigger request containing function\_id, payload, and optional action/timeout.

      <Expandable title="`TriggerRequest` fields" defaultOpen>
        <ParamField body="action" type="TriggerAction">
          Sets how the trigger is routed. Omit for a synchronous request/response. Specify for a specific routing scheme (e.g. `TriggerAction.Enqueue()`, `TriggerAction.Void()`).
        </ParamField>

        <ParamField body="function_id" type="string" required>
          ID of the function to invoke.
        </ParamField>

        <ParamField body="metadata" type="unknown">
          Arbitrary user-specifiable metadata supplied to the triggered handler function on every invocation.
        </ParamField>

        <ParamField body="namespace" type="string">
          Target namespace for routing. Omit to inherit this worker's; say `default` to reach the engine's from a namespaced worker. Serialized into the InvokeFunctionMessage `namespace` field.
        </ParamField>

        <ParamField body="payload" type="TInput" required>
          Input data passed to the function.
        </ParamField>

        <ParamField body="timeoutMs" type="number">
          Override the default invocation timeout, in milliseconds.
        </ParamField>
      </Expandable>
    </ParamField>
  </Tab>

  <Tab title="Example">
    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
    // Synchronous invocation
    const result = await worker.trigger<{ name: string }, { message: string }>({
      function_id: 'greet',
      payload: { name: 'World' },
      timeoutMs: 5000,
    })
    console.log(result.message) // "Hello, World!"

    // Fire-and-forget
    await worker.trigger({
      function_id: 'send-email',
      payload: { to: 'user@example.com' },
      action: TriggerAction.Void(),
    })

    // Enqueue for async processing (the queue must be declared in the
    // queue worker's queue_configs)
    const receipt = await worker.trigger({
      function_id: 'process-order',
      payload: { orderId: '123' },
      action: TriggerAction.Enqueue({ queue: 'orders' }),
    })
    ```
  </Tab>
</Tabs>

***

### registerTriggerType

Registers a new trigger type. A trigger type is a way to invoke a function when a certain event occurs.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
registerTriggerType(triggerType: RegisterTriggerTypeInput, handler: TriggerHandler<TConfig>) => TriggerTypeRef<TConfig>
```

<Tabs>
  <Tab title="Parameters">
    <ParamField body="triggerType" type="RegisterTriggerTypeInput" required>
      The trigger type to register.

      <Expandable title="`RegisterTriggerTypeInput` fields">
        <ParamField body="description" type="string" required>
          Human-readable description of what this trigger type does.
        </ParamField>

        <ParamField body="id" type="string" required>
          Unique identifier for the trigger type (e.g. `state`, `durable:subscriber`).
        </ParamField>

        <ParamField body="namespace" type="string">
          Namespace this provider serves. Omit to let the engine use this connection's own, which is what a worker providing a trigger type for its own project wants.
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="handler" type="TriggerHandler<TConfig>" required>
      The handler for the trigger type.

      <Expandable title="`TriggerHandler` fields">
        <ParamField body="registerTrigger" type="(config: TriggerConfig<TConfig>) => Promise<void>" required>
          Called when a trigger instance is registered.
        </ParamField>

        <ParamField body="unregisterTrigger" type="(config: TriggerConfig<TConfig>) => Promise<void>" required>
          Called when a trigger instance is unregistered.
        </ParamField>
      </Expandable>
    </ParamField>
  </Tab>

  <Tab title="Example">
    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
    type CronConfig = { expression: string }

    worker.registerTriggerType<CronConfig>(
      { id: 'cron', description: 'Fires on a cron schedule' },
      {
        async registerTrigger({ id, function_id, config }) {
          startCronJob(id, config.expression, () =>
            worker.trigger({ function_id, payload: {} }),
          )
        },
        async unregisterTrigger({ id }) {
          stopCronJob(id)
        },
      },
    )
    ```
  </Tab>
</Tabs>

***

### unregisterTriggerType

Unregisters a trigger type.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
unregisterTriggerType(triggerType: RegisterTriggerTypeInput) => void
```

<Tabs>
  <Tab title="Parameters">
    <ParamField body="triggerType" type="RegisterTriggerTypeInput" required>
      The trigger type to unregister.

      <Expandable title="`RegisterTriggerTypeInput` fields">
        <ParamField body="description" type="string" required>
          Human-readable description of what this trigger type does.
        </ParamField>

        <ParamField body="id" type="string" required>
          Unique identifier for the trigger type (e.g. `state`, `durable:subscriber`).
        </ParamField>

        <ParamField body="namespace" type="string">
          Namespace this provider serves. Omit to let the engine use this connection's own, which is what a worker providing a trigger type for its own project wants.
        </ParamField>
      </Expandable>
    </ParamField>
  </Tab>

  <Tab title="Example">
    ```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
    worker.unregisterTriggerType({ id: 'cron', description: 'Fires on a cron schedule' })
    ```
  </Tab>
</Tabs>

***

### getAddress

Engine address this worker resolved to: the explicit `registerWorker`
argument, else `III_URL`, else `ws://127.0.0.1:49134`.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
getAddress() => string
```

***

### getConnectionState

The current WebSocket connection state. `'failed'` is terminal: it follows
a fatal registration rejection (see getFatalError). Mirrors the
Python/Rust SDKs' `get_connection_state()`.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
getConnectionState() => IIIConnectionState
```

***

### getFatalError

The fatal registration rejection that terminated this connection, if any
(e.g. a `WORKER_NAMESPACE_CONFLICT`); `undefined` while healthy. Mirrors the
Python (`_fatal_error`) and Rust (`fatal_error()`) SDKs.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
getFatalError() => RegistrationRejectedError | undefined
```

***

### shutdown

Gracefully shutdown the iii, cleaning up all resources.

**Signature**

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
shutdown() => Promise<void>
```

#### Example

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
process.on('SIGTERM', async () => {
  await worker.shutdown()
  process.exit(0)
})
```

## Subpath Exports

The `iii-sdk` package provides additional entry points:

| Import path        | Contents                                                                                                                                                                                                                                                                                         |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `iii-sdk/channel`  | `Channel`, `ChannelReader`, `ChannelWriter`, `StreamChannelRef`                                                                                                                                                                                                                                  |
| `iii-sdk/engine`   | `EngineFunctions`, `EngineTriggers`, `RemoteFunctionHandler`                                                                                                                                                                                                                                     |
| `iii-sdk/errors`   | `InvocationError`, `InvocationErrorInit`, `RegistrationRejectedError`, `RegistrationRejectedInit`, `isErrorBody`                                                                                                                                                                                 |
| `iii-sdk/helpers`  | `ChannelDirection`, `ChannelItem`, `createChannel`, `createStream`, `extractChannelRefs`, `isChannelRef`                                                                                                                                                                                         |
| `iii-sdk`          | `DEFAULT_ENGINE_URL`, `EnqueueResult`, `IIIClient`, `IIIConnectionState`, `InitOptions`, `InvocationError`, `InvocationErrorInit`, `JsonValue`, `MiddlewareFunctionInput`, `RegistrationRejectedError`, `StreamRequest`, `StreamResponse`, `TelemetryOptions`, `TriggerAction`, `registerWorker` |
| `iii-sdk/protocol` | `ErrorBody`, `MessageType`, `RegisterFunctionFormat`, `RegisterFunctionInput`, `RegisterFunctionMessage`, `RegisterFunctionOptions`, `RegisterTriggerInput`, `RegisterTriggerMessage`, `RegisterTriggerTypeInput`, `RegisterTriggerTypeMessage`, `TriggerRequest`                                |
| `iii-sdk/runtime`  | `FunctionRef`, `IIIConnectionState`, `TriggerTypeRef`                                                                                                                                                                                                                                            |
| `iii-sdk/state`    | `IState`, `StateDeleteInput`, `StateDeleteResult`, `StateEventData`, `StateEventType`, `StateGetInput`, `StateListInput`, `StateSetInput`, `StateSetResult`, `StateUpdateInput`, `StateUpdateResult`                                                                                             |
| `iii-sdk/stream`   | `IStream`                                                                                                                                                                                                                                                                                        |
| `iii-sdk/trigger`  | `Trigger`, `TriggerConfig`, `TriggerHandler`                                                                                                                                                                                                                                                     |

## Types

### iii-sdk

[`EnqueueResult`](#enqueueresult) · [`InitOptions`](#initoptions) · [`JsonValue`](#jsonvalue) · [`MiddlewareFunctionInput`](#middlewarefunctioninput) · [`StreamRequest`](#streamrequest) · [`StreamResponse`](#streamresponse) · [`TelemetryOptions`](#telemetryoptions) · [`TriggerAction`](#triggeraction)

#### EnqueueResult

Result returned when a function is invoked with `TriggerAction.Enqueue`.

| Name               | Type     | Required | Description                                 |
| ------------------ | -------- | -------- | ------------------------------------------- |
| `messageReceiptId` | `string` | Yes      | Unique receipt ID for the enqueued message. |

***

#### InitOptions

Configuration options passed to registerWorker.

| Name                     | Type                              | Required | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| ------------------------ | --------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `enableMetricsReporting` | `boolean`                         | No       | Enable worker metrics via OpenTelemetry. Defaults to `true`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `headers`                | `Record<string, string>`          | No       | Custom HTTP headers sent during the WebSocket handshake.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `invocationTimeoutMs`    | `number`                          | No       | Default timeout for `worker.trigger()` invocations in milliseconds. Defaults to `30000`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `namespace`              | `string`                          | No       | Namespace this worker belongs to. Resolution order:<br />`options.namespace` -> `process.env.III_NAMESPACE` -> undefined. When<br />undefined the engine applies its `default` namespace.<br /><br />It scopes more than the registration. The worker and its functions<br />register here, so identically-named entries coexist across namespaces, and<br />everything the worker does afterwards follows it: a `trigger` resolves its<br />target here, and a `registerTrigger` binds here, unless the call names<br />another namespace. One declaration places the whole worker. |
| `otel`                   | `Omit<OtelConfig, "engineWsUrl">` | No       | OpenTelemetry configuration. OTel is initialized automatically by default.<br />Set `{ enabled: false }` or env `OTEL_ENABLED=false/0/no/off` to disable.<br />The `engineWsUrl` is set automatically from the III address.                                                                                                                                                                                                                                                                                                                                                          |
| `reconnectionConfig`     | `Partial<IIIReconnectionConfig>`  | No       | WebSocket reconnection behavior.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `workerDescription`      | `string`                          | No       | One-line, human/LLM-readable summary of what this worker does.<br />Surfaces in `engine::workers::list` / `engine::workers::info`.                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `workerName`             | `string`                          | No       | Display name for this worker. Defaults to `hostname:pid`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |

***

#### JsonValue

Any JSON value: the TypeScript equivalent of the engine's arbitrary-JSON
wire values (Rust `serde_json::Value`). Used where the wire contract is
"any JSON", e.g. per-invocation `metadata`.

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }
```

***

#### MiddlewareFunctionInput

Input passed to the RBAC middleware function on every function invocation
through the RBAC port. The middleware can inspect, modify, or reject the
call before it reaches the target function.

| Name          | Type                              | Required | Description                                                                                                                                   |
| ------------- | --------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `action`      | [`TriggerAction`](#triggeraction) | No       | Routing action, if any.                                                                                                                       |
| `context`     | `Record<string, unknown>`         | Yes      | Auth context returned by the auth function for this session.                                                                                  |
| `function_id` | `string`                          | Yes      | ID of the function being invoked.                                                                                                             |
| `namespace`   | `string`                          | No       | Target namespace the invoke addressed; forward the call here to stay in the<br />caller's namespace. Absent → the engine's default namespace. |
| `payload`     | `Record<string, unknown>`         | Yes      | Payload sent by the caller.                                                                                                                   |

***

#### StreamRequest

Incoming streaming request received by a function registered with a stream trigger.

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type StreamRequest = Omit<InternalHttpRequest<TBody>, "response">
```

***

#### StreamResponse

Response object passed to streaming function handlers. Use `status()` and
`headers()` to set response metadata, write to `stream` for streaming
responses, and call `close()` when done.

| Name      | Type                                        | Required | Description                            |
| --------- | ------------------------------------------- | -------- | -------------------------------------- |
| `close`   | `() => void`                                | Yes      | Close the response.                    |
| `headers` | `(headers: Record<string, string>) => void` | Yes      | Set response headers.                  |
| `status`  | `(statusCode: number) => void`              | Yes      | Set the HTTP status code.              |
| `stream`  | `NodeJS.WritableStream`                     | Yes      | Writable stream for the response body. |

***

#### TelemetryOptions

Worker metadata reported to the engine (language, framework, project).

| Name                | Type     | Required | Description                                 |
| ------------------- | -------- | -------- | ------------------------------------------- |
| `amplitude_api_key` | `string` | No       | Amplitude API key for product analytics.    |
| `framework`         | `string` | No       | Framework name, if applicable.              |
| `language`          | `string` | No       | Programming language of the worker.         |
| `project_name`      | `string` | No       | Name of the project this worker belongs to. |

***

#### TriggerAction

Factory object that constructs routing actions for IIIClient.trigger.

| Name      | Type                                                              | Required | Description                                                                                                                                                                                                                                                                                                              |
| --------- | ----------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Enqueue` | `(opts: { queue: string }) => { queue: string; type: "enqueue" }` | Yes      | Routes the invocation through a named queue. The engine enqueues the job,<br />acknowledges the caller with `{ messageReceiptId }`, and processes it<br />asynchronously.<br /><br />Requires the `queue` worker in `worker-compose.yaml`.<br />Without it the trigger rejects with `enqueue_error` (no queue provider). |
| `Void`    | `() => { type: "void" }`                                          | Yes      | Fire-and-forget routing. The engine forwards the invocation without<br />waiting for a response or queuing the job.                                                                                                                                                                                                      |

### iii-sdk/channel

[`Channel`](#channel) · [`ChannelReader`](#channelreader) · [`ChannelWriter`](#channelwriter) · [`StreamChannelRef`](#streamchannelref)

#### Channel

A streaming channel pair for worker-to-worker data transfer. Created via
the `createChannel` helper from `iii-sdk/helpers`.

| Name        | Type                                    | Required | Description                                                          |
| ----------- | --------------------------------------- | -------- | -------------------------------------------------------------------- |
| `reader`    | [`ChannelReader`](#channelreader)       | Yes      | Reader end of the channel.                                           |
| `readerRef` | [`StreamChannelRef`](#streamchannelref) | Yes      | Serializable reference to the reader (can be sent to other workers). |
| `writer`    | [`ChannelWriter`](#channelwriter)       | Yes      | Writer end of the channel.                                           |
| `writerRef` | [`StreamChannelRef`](#streamchannelref) | Yes      | Serializable reference to the writer (can be sent to other workers). |

***

#### ChannelReader

Read end of a streaming channel. Provides both a Node.js `Readable` stream
for binary data and an `onMessage` callback for structured text messages.

| Name     | Type       | Required | Description                              |
| -------- | ---------- | -------- | ---------------------------------------- |
| `stream` | `Readable` | Yes      | Node.js Readable stream for binary data. |

***

#### ChannelWriter

Write end of a streaming channel. Provides both a Node.js `Writable` stream
and a `sendMessage` method for sending structured text messages.

| Name     | Type       | Required | Description                              |
| -------- | ---------- | -------- | ---------------------------------------- |
| `stream` | `Writable` | Yes      | Node.js Writable stream for binary data. |

***

#### StreamChannelRef

Serializable reference to one end of a streaming channel. Can be included
in invocation payloads to pass channel endpoints between workers.

| Name         | Type                | Required | Description                                 |
| ------------ | ------------------- | -------- | ------------------------------------------- |
| `access_key` | `string`            | Yes      | Access key for authentication.              |
| `channel_id` | `string`            | Yes      | Unique channel identifier.                  |
| `direction`  | `"read" \| "write"` | Yes      | Whether this ref is for reading or writing. |

### iii-sdk/engine

[`EngineFunctions`](#enginefunctions) · [`EngineTriggers`](#enginetriggers) · [`RemoteFunctionHandler`](#remotefunctionhandler)

#### EngineFunctions

Engine function paths for internal operations.

Naming note: `LIST_TRIGGERS` / `INFO_TRIGGERS` cover trigger TYPES
(templates). `LIST_REGISTERED_TRIGGERS` / `INFO_REGISTERED_TRIGGERS`
cover trigger INSTANCES (subscriber rows). The old
`engine::trigger-types::list` builtin has been removed and is now
served by `engine::triggers::list`.

| Name                       | Type                                  | Required | Description |
| -------------------------- | ------------------------------------- | -------- | ----------- |
| `INFO_FUNCTIONS`           | `"engine::functions::info"`           | Yes      | -           |
| `INFO_REGISTERED_TRIGGERS` | `"engine::registered-triggers::info"` | Yes      | -           |
| `INFO_TRIGGERS`            | `"engine::triggers::info"`            | Yes      | -           |
| `INFO_WORKERS`             | `"engine::workers::info"`             | Yes      | -           |
| `LIST_FUNCTIONS`           | `"engine::functions::list"`           | Yes      | -           |
| `LIST_REGISTERED_TRIGGERS` | `"engine::registered-triggers::list"` | Yes      | -           |
| `LIST_TRIGGERS`            | `"engine::triggers::list"`            | Yes      | -           |
| `LIST_WORKERS`             | `"engine::workers::list"`             | Yes      | -           |
| `REGISTER_WORKER`          | `"engine::workers::register"`         | Yes      | -           |

***

#### EngineTriggers

Engine trigger types

| Name                  | Type                            | Required | Description |
| --------------------- | ------------------------------- | -------- | ----------- |
| `FUNCTIONS_AVAILABLE` | `"engine::functions-available"` | Yes      | -           |
| `LOG`                 | `"log"`                         | Yes      | -           |

***

#### RemoteFunctionHandler

Async function handler for a registered function. Receives the invocation
payload and an optional per-invocation `metadata` value, and returns the
result.

`metadata` is arbitrary JSON travelling on a separate channel from the
payload. It is `undefined` when the caller did not attach any. Existing
single-argument handlers keep working; they ignore the extra argument.

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type RemoteFunctionHandler = (data: TInput, metadata?: JsonValue) => Promise<TOutput>
```

### iii-sdk/errors

[`InvocationError`](#invocationerror) · [`InvocationErrorInit`](#invocationerrorinit) · [`RegistrationRejectedError`](#registrationrejectederror) · [`RegistrationRejectedInit`](#registrationrejectedinit)

#### InvocationError

| Name          | Type     | Required | Description |
| ------------- | -------- | -------- | ----------- |
| `code`        | `string` | Yes      | -           |
| `function_id` | `string` | No       | -           |
| `stacktrace`  | `string` | No       | -           |

***

#### InvocationErrorInit

Typed error surfaced when an invocation dispatched over the SDK fails, RBAC
rejection (FORBIDDEN), handler-level failure, or a timeout waiting for the
engine to respond. Wraps the wire `ErrorBody` shape plus the `function_id`
that was targeted, so callers get a single error type across all failure
modes and can disambiguate via `err.code`.

Before this existed, rejection values were plain `ErrorBody`-shaped objects,
which printed as `[object Object]` when stringified, leaving developers to
grep through SDK source to figure out what tripped. The class name, `code`
prefix in the message, and `function_id` field together make a rejection
self-describing.

| Name          | Type     | Required | Description |
| ------------- | -------- | -------- | ----------- |
| `code`        | `string` | Yes      | -           |
| `function_id` | `string` | No       | -           |
| `message`     | `string` | Yes      | -           |
| `stacktrace`  | `string` | No       | -           |

***

#### RegistrationRejectedError

Fatal error surfaced when the engine rejects this worker's identity because
another live worker owns the same `(namespace, worker_name)`, or when an
unknown rejection code is received. The SDK stops and does not reconnect.
A `FUNCTION_NAMESPACE_CONFLICT` is non-fatal and is logged instead of being
surfaced through this class. The wire fields identify the contested
registration and its current owner.

| Name              | Type     | Required | Description |
| ----------------- | -------- | -------- | ----------- |
| `code`            | `string` | Yes      | -           |
| `function_id`     | `string` | No       | -           |
| `namespace`       | `string` | Yes      | -           |
| `owner_worker_id` | `string` | Yes      | -           |
| `worker_name`     | `string` | No       | -           |

***

#### RegistrationRejectedInit

Fields used to construct a RegistrationRejectedError.

| Name              | Type     | Required | Description |
| ----------------- | -------- | -------- | ----------- |
| `code`            | `string` | Yes      | -           |
| `function_id`     | `string` | No       | -           |
| `namespace`       | `string` | Yes      | -           |
| `owner_worker_id` | `string` | Yes      | -           |
| `worker_name`     | `string` | No       | -           |

### iii-sdk/helpers

[`ChannelDirection`](#channeldirection) · [`ChannelItem`](#channelitem)

#### ChannelDirection

Direction of a streaming channel endpoint. Mirrors the Rust SDK's
`ChannelDirection` enum and matches the literal values used by
StreamChannelRef.direction.

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type ChannelDirection = typeof ChannelDirection[keyof typeof ChannelDirection]
```

***

#### ChannelItem

Discriminated runtime tag for an item observed on a streaming channel.
Mirrors the Rust SDK's `ChannelItem` enum (`Text` / `Binary`). Carrier for
factory + type-guard helpers so callers can construct and discriminate
channel items without depending on Rust-specific shape.

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type ChannelItem = { type: "text"; value: string } | { type: "binary"; value: Uint8Array }
```

### iii-sdk/protocol

[`ErrorBody`](#errorbody) · [`MessageType`](#messagetype) · [`RegisterFunctionFormat`](#registerfunctionformat) · [`RegisterFunctionInput`](#registerfunctioninput) · [`RegisterFunctionMessage`](#registerfunctionmessage) · [`RegisterFunctionOptions`](#registerfunctionoptions) · [`RegisterTriggerInput`](#registertriggerinput) · [`RegisterTriggerMessage`](#registertriggermessage) · [`RegisterTriggerTypeInput`](#registertriggertypeinput) · [`RegisterTriggerTypeMessage`](#registertriggertypemessage) · [`TriggerRequest`](#triggerrequest)

#### ErrorBody

| Name         | Type     | Required | Description |
| ------------ | -------- | -------- | ----------- |
| `code`       | `string` | Yes      | -           |
| `message`    | `string` | Yes      | -           |
| `stacktrace` | `string` | No       | -           |

***

#### MessageType

| Name                        | Type                          | Required | Description |
| --------------------------- | ----------------------------- | -------- | ----------- |
| `InvocationResult`          | `"invocationresult"`          | Yes      | -           |
| `InvokeFunction`            | `"invokefunction"`            | Yes      | -           |
| `Reattach`                  | `"reattach"`                  | Yes      | -           |
| `RegisterFunction`          | `"registerfunction"`          | Yes      | -           |
| `RegisterTrigger`           | `"registertrigger"`           | Yes      | -           |
| `RegisterTriggerType`       | `"registertriggertype"`       | Yes      | -           |
| `RegistrationRejected`      | `"registrationrejected"`      | Yes      | -           |
| `TriggerRegistrationResult` | `"triggerregistrationresult"` | Yes      | -           |
| `UnregisterFunction`        | `"unregisterfunction"`        | Yes      | -           |
| `UnregisterTrigger`         | `"unregistertrigger"`         | Yes      | -           |
| `UnregisterTriggerType`     | `"unregistertriggertype"`     | Yes      | -           |
| `WorkerRegistered`          | `"workerregistered"`          | Yes      | -           |

***

#### RegisterFunctionFormat

| Name            | Type                                                                                       | Required | Description                              |
| --------------- | ------------------------------------------------------------------------------------------ | -------- | ---------------------------------------- |
| `description`   | `string`                                                                                   | No       | The description of the parameter.        |
| `items`         | `unknown`                                                                                  | No       | The items of the parameter (for arrays). |
| `name`          | `string`                                                                                   | No       | The name of the parameter.               |
| `properties`    | `Record<string, unknown>`                                                                  | No       | The body of the parameter (for objects). |
| `required`      | `string[]`                                                                                 | No       | Whether the parameter is required.       |
| `type`          | `"string" \| "number" \| "boolean" \| "object" \| "array" \| "null" \| "map" \| "integer"` | No       | The type of the parameter.               |
| `[key: string]` | `unknown`                                                                                  | No       | -                                        |

***

#### RegisterFunctionInput

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type RegisterFunctionInput = Omit<RegisterFunctionMessage, "message_type">
```

| Name              | Type                                                | Required | Description                                                                            |
| ----------------- | --------------------------------------------------- | -------- | -------------------------------------------------------------------------------------- |
| `description`     | `string`                                            | No       | The description of the function.                                                       |
| `id`              | `string`                                            | Yes      | The path of the function (use :: for namespacing, e.g. external::my\_lambda).          |
| `invocation`      | `HttpInvocationConfig`                              | No       | HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.). |
| `metadata`        | `Record<string, unknown>`                           | No       | Arbitrary metadata attached to the function.                                           |
| `request_format`  | [`RegisterFunctionFormat`](#registerfunctionformat) | No       | The request format of the function.                                                    |
| `response_format` | [`RegisterFunctionFormat`](#registerfunctionformat) | No       | The response format of the function.                                                   |

***

#### RegisterFunctionMessage

| Name              | Type                                                | Required | Description                                                                            |
| ----------------- | --------------------------------------------------- | -------- | -------------------------------------------------------------------------------------- |
| `description`     | `string`                                            | No       | The description of the function.                                                       |
| `id`              | `string`                                            | Yes      | The path of the function (use :: for namespacing, e.g. external::my\_lambda).          |
| `invocation`      | `HttpInvocationConfig`                              | No       | HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.). |
| `message_type`    | [`MessageType`](#messagetype).RegisterFunction      | Yes      | -                                                                                      |
| `metadata`        | `Record<string, unknown>`                           | No       | Arbitrary metadata attached to the function.                                           |
| `request_format`  | [`RegisterFunctionFormat`](#registerfunctionformat) | No       | The request format of the function.                                                    |
| `response_format` | [`RegisterFunctionFormat`](#registerfunctionformat) | No       | The response format of the function.                                                   |

***

#### RegisterFunctionOptions

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type RegisterFunctionOptions = Omit<RegisterFunctionMessage, "message_type" | "id">
```

| Name              | Type                                                | Required | Description                                                                            |
| ----------------- | --------------------------------------------------- | -------- | -------------------------------------------------------------------------------------- |
| `description`     | `string`                                            | No       | The description of the function.                                                       |
| `invocation`      | `HttpInvocationConfig`                              | No       | HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.). |
| `metadata`        | `Record<string, unknown>`                           | No       | Arbitrary metadata attached to the function.                                           |
| `request_format`  | [`RegisterFunctionFormat`](#registerfunctionformat) | No       | The request format of the function.                                                    |
| `response_format` | [`RegisterFunctionFormat`](#registerfunctionformat) | No       | The response format of the function.                                                   |

***

#### RegisterTriggerInput

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type RegisterTriggerInput = Omit<RegisterTriggerMessage, "message_type" | "id">
```

| Name                | Type                      | Required | Description                                                                                                                                                                                                                                                                                                                                                                                                                            |
| ------------------- | ------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `config`            | `unknown`                 | Yes      | Trigger-type-specific configuration, matching the shape the trigger type expects.                                                                                                                                                                                                                                                                                                                                                      |
| `function_id`       | `string`                  | Yes      | ID of the function this trigger invokes when it fires.                                                                                                                                                                                                                                                                                                                                                                                 |
| `metadata`          | `Record<string, unknown>` | No       | Arbitrary user-specifiable metadata supplied to the triggered handler function on every invocation.                                                                                                                                                                                                                                                                                                                                    |
| `namespace`         | `string`                  | No       | Namespace the trigger's target function resolves in.<br /><br />Omitting it does not bind in the engine's default: `registerTrigger` fills<br />it from this worker's namespace, because the function a trigger names is<br />one this worker registered, and that landed in the worker's namespace. Name<br />another namespace, `default` included, to bind elsewhere.                                                               |
| `trigger_namespace` | `string`                  | No       | Namespace to find the trigger type's provider in.<br /><br />Omitting it is not the same as `'default'`: it asks the engine to resolve,<br />taking this worker's namespace first and the engine's own second. That is<br />what lets a project ship its own provider for a type id the engine also<br />provides, while a worker that has not been migrated keeps reaching the<br />engine's without saying so. Naming one is strict. |
| `type`              | `string`                  | Yes      | Identifier of the registered trigger type this trigger uses (e.g. `storage::object-created`, `http`).                                                                                                                                                                                                                                                                                                                                  |

***

#### RegisterTriggerMessage

| Name                | Type                                          | Required | Description                                                                                                                                                                                                                                                                                                                                                                                                                            |
| ------------------- | --------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `config`            | `unknown`                                     | Yes      | Trigger-type-specific configuration, matching the shape the trigger type expects.                                                                                                                                                                                                                                                                                                                                                      |
| `function_id`       | `string`                                      | Yes      | ID of the function this trigger invokes when it fires.                                                                                                                                                                                                                                                                                                                                                                                 |
| `id`                | `string`                                      | Yes      | Unique trigger identifier, generated by the SDK during registration.                                                                                                                                                                                                                                                                                                                                                                   |
| `message_type`      | [`MessageType`](#messagetype).RegisterTrigger | Yes      | Wire discriminator; always `MessageType.RegisterTrigger`.                                                                                                                                                                                                                                                                                                                                                                              |
| `metadata`          | `Record<string, unknown>`                     | No       | Arbitrary user-specifiable metadata supplied to the triggered handler function on every invocation.                                                                                                                                                                                                                                                                                                                                    |
| `namespace`         | `string`                                      | No       | Namespace the trigger's target function resolves in.<br /><br />Omitting it does not bind in the engine's default: `registerTrigger` fills<br />it from this worker's namespace, because the function a trigger names is<br />one this worker registered, and that landed in the worker's namespace. Name<br />another namespace, `default` included, to bind elsewhere.                                                               |
| `trigger_namespace` | `string`                                      | No       | Namespace to find the trigger type's provider in.<br /><br />Omitting it is not the same as `'default'`: it asks the engine to resolve,<br />taking this worker's namespace first and the engine's own second. That is<br />what lets a project ship its own provider for a type id the engine also<br />provides, while a worker that has not been migrated keeps reaching the<br />engine's without saying so. Naming one is strict. |
| `type`              | `string`                                      | Yes      | Identifier of the registered trigger type this trigger uses (e.g. `storage::object-created`, `http`).                                                                                                                                                                                                                                                                                                                                  |

***

#### RegisterTriggerTypeInput

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type RegisterTriggerTypeInput = Omit<RegisterTriggerTypeMessage, "message_type">
```

| Name          | Type     | Required | Description                                                                                                                                                            |
| ------------- | -------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `description` | `string` | Yes      | Human-readable description of what this trigger type does.                                                                                                             |
| `id`          | `string` | Yes      | Unique identifier for the trigger type (e.g. `state`, `durable:subscriber`).                                                                                           |
| `namespace`   | `string` | No       | Namespace this provider serves. Omit to let the engine use this<br />connection's own, which is what a worker providing a trigger type for its<br />own project wants. |

***

#### RegisterTriggerTypeMessage

| Name           | Type                                              | Required | Description                                                                                                                                                            |
| -------------- | ------------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `description`  | `string`                                          | Yes      | Human-readable description of what this trigger type does.                                                                                                             |
| `id`           | `string`                                          | Yes      | Unique identifier for the trigger type (e.g. `state`, `durable:subscriber`).                                                                                           |
| `message_type` | [`MessageType`](#messagetype).RegisterTriggerType | Yes      | -                                                                                                                                                                      |
| `namespace`    | `string`                                          | No       | Namespace this provider serves. Omit to let the engine use this<br />connection's own, which is what a worker providing a trigger type for its<br />own project wants. |

***

#### TriggerRequest

Request object passed to IIIClient.trigger.

| Name          | Type                              | Required | Description                                                                                                                                                                                       |
| ------------- | --------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `action`      | [`TriggerAction`](#triggeraction) | No       | Sets how the trigger is routed. Omit for a synchronous request/response. Specify for a specific routing scheme (e.g. `TriggerAction.Enqueue()`, `TriggerAction.Void()`).                          |
| `function_id` | `string`                          | Yes      | ID of the function to invoke.                                                                                                                                                                     |
| `metadata`    | `unknown`                         | No       | Arbitrary user-specifiable metadata supplied to the triggered handler function on every invocation.                                                                                               |
| `namespace`   | `string`                          | No       | Target namespace for routing. Omit to inherit this worker's; say `default`<br />to reach the engine's from a namespaced worker. Serialized into the<br />InvokeFunctionMessage `namespace` field. |
| `payload`     | `TInput`                          | Yes      | Input data passed to the function.                                                                                                                                                                |
| `timeoutMs`   | `number`                          | No       | Override the default invocation timeout, in milliseconds.                                                                                                                                         |

### iii-sdk/runtime

[`FunctionRef`](#functionref) · [`IIIConnectionState`](#iiiconnectionstate) · [`TriggerTypeRef`](#triggertyperef)

#### FunctionRef

Handle returned by IIIClient.registerFunction. Contains the function's
`id` and an `unregister()` method.

| Name         | Type         | Required | Description                            |
| ------------ | ------------ | -------- | -------------------------------------- |
| `id`         | `string`     | Yes      | The unique function identifier.        |
| `unregister` | `() => void` | Yes      | Removes this function from the engine. |

***

#### IIIConnectionState

Connection state for the III WebSocket

```typescript theme={"theme":{"light":"catppuccin-latte","dark":"dark-plus"}}
type IIIConnectionState = "disconnected" | "connecting" | "connected" | "reconnecting" | "failed"
```

***

#### TriggerTypeRef

Typed handle returned by IIIClient.registerTriggerType.

Provides convenience methods to register triggers and functions scoped
to this trigger type, so callers don't need to repeat the `type` field.

| Name               | Type                                                                                                                                                                    | Required | Description                                                       |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------------------------------------------------- |
| `id`               | `string`                                                                                                                                                                | Yes      | The trigger type identifier.                                      |
| `registerFunction` | (functionId: string, handler: [`RemoteFunctionHandler`](#remotefunctionhandler), config: TConfig, metadata?: Record\<string, unknown>) => [`FunctionRef`](#functionref) | Yes      | Register a function and immediately bind it to this trigger type. |
| `registerTrigger`  | (functionId: string, config: TConfig, metadata?: Record\<string, unknown>) => [`Trigger`](#trigger)                                                                     | Yes      | Register a trigger bound to this trigger type.                    |
| `unregister`       | `() => void`                                                                                                                                                            | Yes      | Unregister this trigger type from the engine.                     |

### iii-sdk/state

[`IState`](#istate) · [`StateDeleteInput`](#statedeleteinput) · [`StateDeleteResult`](#statedeleteresult) · [`StateEventData`](#stateeventdata) · [`StateEventType`](#stateeventtype) · [`StateGetInput`](#stategetinput) · [`StateListInput`](#statelistinput) · [`StateSetInput`](#statesetinput) · [`StateSetResult`](#statesetresult) · [`StateUpdateInput`](#stateupdateinput) · [`StateUpdateResult`](#stateupdateresult)

#### IState

Interface for state management operations. Available via the `iii-sdk/state`
subpath export.

| Name     | Type                                                                                                                    | Required | Description                                      |
| -------- | ----------------------------------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------ |
| `delete` | (input: [`StateDeleteInput`](#statedeleteinput)) => Promise\<[`StateDeleteResult`](#statedeleteresult)>                 | Yes      | Delete a state value.                            |
| `get`    | (input: [`StateGetInput`](#stategetinput)) => Promise\<TData \| null>                                                   | Yes      | Retrieve a value by scope and key.               |
| `list`   | (input: [`StateListInput`](#statelistinput)) => Promise\<TData\[]>                                                      | Yes      | List all values in a scope.                      |
| `set`    | (input: [`StateSetInput`](#statesetinput)) => Promise\<[`StateSetResult`](#statesetresult)\<TData> \| null>             | Yes      | Set (create or overwrite) a state value.         |
| `update` | (input: [`StateUpdateInput`](#stateupdateinput)) => Promise\<[`StateUpdateResult`](#stateupdateresult)\<TData> \| null> | Yes      | Apply atomic update operations to a state value. |

***

#### StateDeleteInput

Input for deleting a state value.

| Name    | Type     | Required | Description              |
| ------- | -------- | -------- | ------------------------ |
| `key`   | `string` | Yes      | Key within the scope.    |
| `scope` | `string` | Yes      | State scope (namespace). |

***

#### StateDeleteResult

Result of a state delete operation.

| Name        | Type  | Required | Description                     |
| ----------- | ----- | -------- | ------------------------------- |
| `old_value` | `any` | No       | Previous value (if it existed). |

***

#### StateEventData

Payload for state change events.

| Name         | Type                                | Required | Description                                |
| ------------ | ----------------------------------- | -------- | ------------------------------------------ |
| `event_type` | [`StateEventType`](#stateeventtype) | Yes      | Type of state change.                      |
| `key`        | `string`                            | Yes      | Key within the scope.                      |
| `new_value`  | `TData`                             | No       | New value (for create/update events).      |
| `old_value`  | `TData`                             | No       | Previous value (for update/delete events). |
| `scope`      | `string`                            | Yes      | State scope (namespace).                   |
| `type`       | `"state"`                           | Yes      | -                                          |

***

#### StateEventType

Types of state change events.

| Name      | Type              | Required | Description |
| --------- | ----------------- | -------- | ----------- |
| `Created` | `"state:created"` | Yes      | -           |
| `Deleted` | `"state:deleted"` | Yes      | -           |
| `Updated` | `"state:updated"` | Yes      | -           |

***

#### StateGetInput

Input for retrieving a state value.

| Name    | Type     | Required | Description              |
| ------- | -------- | -------- | ------------------------ |
| `key`   | `string` | Yes      | Key within the scope.    |
| `scope` | `string` | Yes      | State scope (namespace). |

***

#### StateListInput

Input for listing all values in a state scope.

| Name    | Type     | Required | Description              |
| ------- | -------- | -------- | ------------------------ |
| `scope` | `string` | Yes      | State scope (namespace). |

***

#### StateSetInput

Input for setting a state value.

| Name    | Type     | Required | Description              |
| ------- | -------- | -------- | ------------------------ |
| `key`   | `string` | Yes      | Key within the scope.    |
| `scope` | `string` | Yes      | State scope (namespace). |
| `value` | `any`    | Yes      | Value to store.          |

***

#### StateSetResult

Result of a state set operation.

| Name        | Type    | Required | Description                     |
| ----------- | ------- | -------- | ------------------------------- |
| `new_value` | `TData` | Yes      | New value that was stored.      |
| `old_value` | `TData` | No       | Previous value (if it existed). |

***

#### StateUpdateInput

Input for atomically updating a state value.

| Name    | Type         | Required | Description                                            |
| ------- | ------------ | -------- | ------------------------------------------------------ |
| `key`   | `string`     | Yes      | Key within the scope.                                  |
| `ops`   | `UpdateOp[]` | Yes      | Ordered list of update operations to apply atomically. |
| `scope` | `string`     | Yes      | State scope (namespace).                               |

***

#### StateUpdateResult

Result of a state update operation.

| Name        | Type              | Required | Description                                                                                                                                                                                                                                        |
| ----------- | ----------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `errors`    | `UpdateOpError[]` | No       | Per-op errors. Currently emitted only by the `merge` op when input<br />violates the validation bounds. See UpdateOpError and the<br />`UpdateMerge` JSDoc in `./stream` for the error codes. Field is<br />omitted from the JSON wire when empty. |
| `new_value` | `TData`           | Yes      | New value after the update.                                                                                                                                                                                                                        |
| `old_value` | `TData`           | No       | Previous value (if it existed).                                                                                                                                                                                                                    |

### iii-sdk/stream

[`IStream`](#istream)

#### IStream

Interface for custom stream implementations. Passed to `IIIClient.createStream`
to override the engine's built-in stream storage.

| Name         | Type                                                                       | Required | Description                                      |
| ------------ | -------------------------------------------------------------------------- | -------- | ------------------------------------------------ |
| `delete`     | `(input: StreamDeleteInput) => Promise<StreamDeleteResult>`                | Yes      | Delete a stream item.                            |
| `get`        | `(input: StreamGetInput) => Promise<TData \| null>`                        | Yes      | Retrieve a single item by group and item ID.     |
| `list`       | `(input: StreamListInput) => Promise<TData[]>`                             | Yes      | List all items in a group.                       |
| `listGroups` | `(input: StreamListGroupsInput) => Promise<string[]>`                      | Yes      | List all group IDs in a stream.                  |
| `set`        | `(input: StreamSetInput) => Promise<StreamSetResult<TData> \| null>`       | Yes      | Set (create or overwrite) a stream item.         |
| `update`     | `(input: StreamUpdateInput) => Promise<StreamUpdateResult<TData> \| null>` | Yes      | Apply atomic update operations to a stream item. |

### iii-sdk/trigger

[`Trigger`](#trigger) · [`TriggerConfig`](#triggerconfig) · [`TriggerHandler`](#triggerhandler)

#### Trigger

Handle returned by IIIClient.registerTrigger. Use `unregister()` to
remove the trigger from the engine.

| Name         | Type         | Required | Description                           |
| ------------ | ------------ | -------- | ------------------------------------- |
| `unregister` | `() => void` | Yes      | Removes this trigger from the engine. |

***

#### TriggerConfig

Configuration passed to a trigger handler when a trigger instance is
registered or unregistered.

| Name          | Type                      | Required | Description                                                                                                                                                                                                                       |
| ------------- | ------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `config`      | `TConfig`                 | Yes      | Trigger-specific configuration.                                                                                                                                                                                                   |
| `function_id` | `string`                  | Yes      | Function to invoke when the trigger fires.                                                                                                                                                                                        |
| `id`          | `string`                  | Yes      | Trigger instance ID.                                                                                                                                                                                                              |
| `metadata`    | `Record<string, unknown>` | No       | Arbitrary user-specifiable metadata supplied to the triggered handler function on every invocation.                                                                                                                               |
| `namespace`   | `string`                  | No       | Resolved namespace the trigger's target `function_id` uses. When the<br />registration omitted it, the registering SDK fills this from its worker's<br />namespace. A provider that later calls `trigger()` must pass it through. |

***

#### TriggerHandler

Handler interface for custom trigger types. Passed to
`IIIClient.registerTriggerType`.

| Name                | Type                                                                    | Required | Description                                     |
| ------------------- | ----------------------------------------------------------------------- | -------- | ----------------------------------------------- |
| `registerTrigger`   | (config: [`TriggerConfig`](#triggerconfig)\<TConfig>) => Promise\<void> | Yes      | Called when a trigger instance is registered.   |
| `unregisterTrigger` | (config: [`TriggerConfig`](#triggerconfig)\<TConfig>) => Promise\<void> | Yes      | Called when a trigger instance is unregistered. |
