{/* AUTO-GENERATED FILE. Do not edit. Regenerate with docs/next/scripts/generate-api-docs.mts. */} {/* AI: any skill-check (vale/AI) text fixes belong in the source doc-comments under sdk/packages/node/iii/src (prose) or docs/next/scripts/ (structure/formatting), then regenerate. Never edit this file directly. */}
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Reference?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/iii-hq-reference-e20d9557)
<!-- generated by iii-skill-render. DO NOT EDIT (changes here are overwritten on the next render). Edit docs/next/reference/sdk-node.mdx. -->
# Node.js SDK
{/* AUTO-GENERATED FILE. Do not edit. Regenerate with docs/next/scripts/generate-api-docs.mts. */}
{/* AI: any skill-check (vale/AI) text fixes belong in the source doc-comments under sdk/packages/node/iii/src (prose) or docs/next/scripts/ (structure/formatting), then regenerate. Never edit this file directly. */}
## Installation
```bash
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
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, on the main connection and on streaming channels. `Authorization: Bearer $III_TOKEN` is added unless you set `Authorization` here.
</ParamField>
<ParamField body="invocationTimeoutMs" type="number">
Default timeout for `worker.call()` 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 `call` resolves its target here, and an `observe` its source and target, unless the call names another namespace. One declaration places the whole worker.
</ParamField>
<ParamField body="otel" type="Omit<OtelConfig, 'engineWsUrl' | 'engineWsHeaders'>">
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, and `engineWsHeaders` from the handshake headers of the main connection.
</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. A non-empty `III_WORKER_NAME` overrides it. Defaults to `hostname:pid`.
</ParamField>
</Expandable>
</ParamField>
</Tab>
<Tab title="Example">
```typescript
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
### registerFunction
Registers a new function with a local handler or an HTTP invocation config.
The handler's return value is what the function's observers observe; an
event source's handler returns the event it is called with.
Every call of the function, local or routed, runs the handler and then
goes to the observers that want it (`onObservationMatch`; by default all of
them): the function's `onObservationDeliver` hook delivers it, or iii does,
to those whose capture and filters match. iii evaluates capture and filters
where the call is: the engine for a call it routes to this worker, and
the SDK for a call this worker makes to its own function in-process,
through an index of the filters' equality conditions. What the worker
does when the function is observed is set with the hooks (`onObserverAdded`,
`onObserverRemoved`, `onObservationMatch`, `onObservationDeliver`), by id or on
the returned FunctionRef. The SDK acks no observer before this
call returns, so a hook set by id before it, chained on its result, or
set later in the same synchronous block runs for every observer.
A function that sets `args_format`, `private: true`, `observable: false`,
an `onObservationMatch` hook or an `onObservationDeliver` hook needs an engine
with `observe.v2`: it is registered once the connection's engine
advertised it, and against an older engine it stays unregistered (logged
once, `UNSUPPORTED`).
**Signature**
```typescript
registerFunction(functionId: string, handler: HttpInvocationConfig | RemoteFunctionHandler<I, O>, options?: RegisterFunctionOptions) => FunctionRef<I, O>
```
<Tabs>
<Tab title="Parameters">
<ParamField body="functionId" type="string" required>
Unique identifier for the function.
</ParamField>
<ParamField body="handler" type="HttpInvocationConfig | RemoteFunctionHandler<I, O>" required>
Handler for local execution, or an HTTP invocation config for external functions (Lambda, Cloudflare Workers, etc.).
</ParamField>
<ParamField body="options" type="RegisterFunctionOptions">
Optional RegisterFunctionOptions: description, request/response formats, metadata, `args_format`, `private`, `observable`, `localDispatch`.
<Expandable title="`RegisterFunctionOptions` fields">
<ParamField body="args_format" type="RegisterFunctionFormat">
JSON Schema of the `args` an observer of this function passes. The engine validates every observer's args against it (`INVALID_ARGS`) before the added hooks run, and refuses a schema that is not valid (`INVALID_ARGS_FORMAT`). A function without it takes no args.
</ParamField>
<ParamField body="description" type="string">
Human-readable summary of the function, listed by discovery (`engine::functions::list`).
</ParamField>
<ParamField body="invocation" type="HttpInvocationConfig">
HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.).
</ParamField>
<ParamField body="localDispatch" type="boolean">
Calls this worker makes to its own function run in-process once the engine confirmed it (default `true`). Set `false` for a handler that must always run through the engine.
</ParamField>
<ParamField body="metadata" type="Record<string, unknown>">
Arbitrary metadata attached to the function, stored with it and listed by discovery (`engine::functions::list`). It is distinct from the per-call metadata a handler receives.
</ParamField>
<ParamField body="observable" type="boolean">
`false`: nobody may observe the function (`NOT_OBSERVABLE`), for one whose payloads carry credentials. Default `true`; sent only when `false`.
</ParamField>
<ParamField body="private" type="boolean">
Only this worker may call the function: the engine answers a call from any other connection with `FORBIDDEN`, and refuses the function as an observer's target. Any worker may observe it, and its observers receive every call this worker makes. For event sources, whose calls from anywhere else would be forged events. This worker's own calls pass the input and the result by reference: the handler and hooks treat both as read-only (frozen when `NODE_ENV` is `development`). Default `false`; sent only when `true`.
</ParamField>
<ParamField body="request_format" type="RegisterFunctionFormat">
JSON Schema of the call's input.
</ParamField>
<ParamField body="response_format" type="RegisterFunctionFormat">
JSON Schema of the handler's return value: what the function's observers observe.
</ParamField>
</Expandable>
</ParamField>
</Tab>
<Tab title="Example">
```typescript
// Local handler
const ref = worker.registerFunction(
'greet',
async (data: { name: string }) => ({ message: `Hello, ${data.name}!` }),
{ description: 'Returns a greeting' },
)
// An event source: observed by everyone, called only by this worker,
// set up for each observer by its args
worker
.registerFunction('cron::on-tick', (tick: CronTick) => tick, { args_format: CronArgs, private: true })
.onObserverAdded((obs) => scheduler.retain(obs.args.expression as string))
.onObserverRemoved((obs) => scheduler.release(obs.args.expression as string))
// 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>
---
### call
Invokes a function: by id, or the target of an observer of a function
this worker hosts (`{ observer, payload }`).
**Signature**
```typescript
call(request: CallRequest<TInput>) => Promise<TOutput>
```
<Tabs>
<Tab title="Parameters">
<ParamField body="request" type="CallRequest<TInput>" required>
The call request: `function_id` (or `observer`), `payload`, and optional action/timeout.
</ParamField>
</Tab>
<Tab title="Example">
```typescript
// Synchronous invocation
const result = await worker.call<{ name: string }, { message: string }>({
function_id: 'greet',
payload: { name: 'World' },
timeoutMs: 5000,
})
console.log(result.message) // "Hello, World!"
// Fire-and-forget
await worker.call({
function_id: 'send-email',
payload: { to: 'user@example.com' },
action: CallAction.Void(),
})
// Enqueue for async processing (the queue must be declared in the
// queue worker's queue_configs)
const receipt = await worker.call({
function_id: 'process-order',
payload: { orderId: '123' },
action: CallAction.Enqueue({ queue: 'orders' }),
})
// Through an observer, in the function's deliver hook: runs its target,
// with its policy and metadata
const response = await worker.call({ observer: route.obs, payload: request })
```
</Tab>
</Tabs>
---
### observe
Observes a function: every call of `source` that passes its `filters`
runs `target`, a registered function. Returns synchronously (also before
the connection is up); the observer is replayed with the same id on
reconnect. Errors show up as state `error` and reject `ready()`. An
`error` answer to its `observe` is the engine's refusal, the handle's
final answer: the engine holds no observer for it, it is not replayed,
and its `dispose()` sends nothing.
**Signature**
```typescript
observe(source: string | ObserveSource, target: Target, options?: ObserverOptions) => ObserverHandle
```
<Tabs>
<Tab title="Parameters">
<ParamField body="source" type="string | ObserveSource" required>
What is observed: a function id, or `function_id`, `args` (read by the worker that hosts the function), `filters`, `capture`.
<Expandable title="`ObserveSource` fields">
<ParamField body="args" type="Record<string, unknown>">
For the worker that hosts the function: what to set up and which calls to deliver (a table, a cron expression, a route). The engine validates them against the function's `args_format`.
</ParamField>
<ParamField body="capture" type="Capture[]">
What the target's payload carries, and with it which outcomes fire the target. Default `['input', 'output', 'caller']`. - `input` and `output` fire on success, `error` fires on error. - `caller` and `metadata` only add to the payload: a `capture` must name at least one of `input`, `output`, `error` (`INVALID_ARGS` otherwise). - `[]` fires on success, with the top-level fields only. So the default fires on success, `['error', 'caller']` on errors, and `['input', 'error']` on both. A success's payload never has `error`, an error's never has `output`.
</ParamField>
<ParamField body="filters" type="Filter">
Which calls reach the target, by `input`, `output`, `error`, `caller` and `metadata`; `{}` (or absent) = every call.
</ParamField>
<ParamField body="function_id" type="string" required>
The observed function.
</ParamField>
<ParamField body="namespace" type="string">
Defaults to this worker's namespace (`engine::*` and `configuration::*` resolve to `default`).
</ParamField>
</Expandable>
</ParamField>
<ParamField body="target" type="Target" required>
The function to invoke.
</ParamField>
<ParamField body="options" type="ObserverOptions">
`id`, `max_fires`, `expires_in_ms`, `max_in_flight`, `metadata`.
<Expandable title="`ObserverOptions` fields">
<ParamField body="expires_in_ms" type="number">
The observer is disposed this many milliseconds after it is created (`EXPIRED`). Default: never.
</ParamField>
<ParamField body="id" type="string">
Default: a random UUID, stable across replays. The handle holds it until it is disposed: an `observe` of an id a handle of this client holds throws an ObserveRejection with code `OBSERVER_ID_CONFLICT` and sends nothing.
</ParamField>
<ParamField body="max_fires" type="number">
The observer is disposed after this many activations (`MAX_FIRES`). Default: unlimited.
</ParamField>
<ParamField body="max_in_flight" type="number">
Activations running at once; further ones queue, then drop as `OVERFLOW`. Default: the engine's `observers.default_max_in_flight` (64).
</ParamField>
<ParamField body="metadata" type="Record<string, unknown>">
Delivered as the metadata sidecar of every activation.
</ParamField>
</Expandable>
</ParamField>
</Tab>
<Tab title="Example">
```typescript
// every successful call of orders::create runs alerts::big-order
worker.observe('orders::create', 'alerts::big-order')
// only large orders
worker.observe(
{ function_id: 'orders::create', filters: { 'input.total': { $gte: 500 } } },
'alerts::big-order',
)
// an event source with args for its worker: one tick every five minutes
const ticks = worker.observe(
{ function_id: 'cron::on-tick', args: { expression: '0 */5 * * * * *' } },
'reports::refresh',
)
await ticks.ready()
```
</Tab>
</Tabs>
---
### trigger
<Warning>
**Deprecated.** Use IIIClient.call, the same function.
</Warning>
Invokes a function using a request object.
**Signature**
```typescript
trigger(request: CallRequest<TInput>) => Promise<TOutput>
```
#### Parameters
<ParamField body="request" type="CallRequest<TInput>" required>
</ParamField>
---
### currentInvocation
The invocation the calling code runs in (remote or local handler, or the
function's deliver hook), or `undefined` outside any handler.
**Signature**
```typescript
currentInvocation() => InvocationContext | undefined
```
---
### getAddress
Engine address this worker resolved to: the explicit `registerWorker`
argument, else `III_URL`, else `ws://127.0.0.1:49134`.
**Signature**
```typescript
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
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
getFatalError() => RegistrationRejectedError | undefined
```
---
### isObserved
Whether a call of a function this worker hosts would reach anyone.
Without a call: any active observer. With a call, on a function matched
by keys: an observer filed under one of the call's keys. On any other
function the call is not read.
**Signature**
```typescript
isObserved(functionId: string, call?: Partial<Call<unknown, unknown>>) => boolean
```
#### Parameters
<ParamField body="functionId" type="string" required>
</ParamField>
<ParamField body="call" type="Partial<Call<unknown, unknown>>">
<Expandable title="`Call` fields">
<ParamField body="caller" type="Caller">
Who made the call; absent for a call made outside any handler.
</ParamField>
<ParamField body="error" type="{ code: string; message: string; stacktrace?: string }">
What the handler threw.
</ParamField>
<ParamField body="function_id" type="string" required>
</ParamField>
<ParamField body="input" type="I" required>
</ParamField>
<ParamField body="invocation_id" type="string" required>
</ParamField>
<ParamField body="metadata" type="Record<string, unknown>">
</ParamField>
<ParamField body="output" type="O">
The handler's return value: what observers observe.
</ParamField>
<ParamField body="status" type="'success' | 'error'" required>
</ParamField>
</Expandable>
</ParamField>
---
### observers
The active observers of a function this worker hosts (empty for any other).
**Signature**
```typescript
observers(functionId: string) => readonly Observer[]
```
#### Parameters
<ParamField body="functionId" type="string" required>
</ParamField>
---
### onObservationDeliver
Delivers each call of a function itself: `hook` receives the call and the
observers that matched it (a snapshot taken when the call started), and
what it returns (or throws) is what the caller gets back. iii delivers
nothing for that function: the hook calls through observers and applies
their filters with `obs.matches(call)`. Without it, iii delivers every
call to the matching observers whose capture and filters accept it, and the
caller gets the handler's result. `null` removes the hook.
A function with a deliver hook needs an engine with `observe.v2`: against
an older one it stays unregistered, and the SDK logs `UNSUPPORTED` once.
**Signature**
```typescript
onObservationDeliver(functionId: string, hook: DeliverHook<I, O, R> | null) => IIIClient
```
<Tabs>
<Tab title="Parameters">
<ParamField body="functionId" type="string" required>
</ParamField>
<ParamField body="hook" type="DeliverHook<I, O, R> | null" required>
</ParamField>
</Tab>
<Tab title="Example">
```typescript
worker.onObservationDeliver('http::on-request', async (call) => {
const route = routes.match(call.input)
if (!route) return { status_code: 404 }
if (!route.obs.matches(call)) return { status_code: 422 }
return worker.call({ observer: route.obs, payload: call.input })
})
```
</Tab>
</Tabs>
---
### onObservationMatch
Says which observers want each call of a function. By default every
observer wants every call. A predicate `(obs, call) => boolean` is asked
once per observation (for every call, once for each active observer);
`{ observer, call }` key functions are computed once per observer, when
it is accepted, and once per call, and an
observer wants a call when they share a key (the SDK keeps an index). The
observers' capture, filters and policy still apply. A hook set
while observers are active rebuilds the index from them. `null` removes
the hook, predicate or keys: every observer gets every call again.
A function with a match hook needs an engine with `observe.v2`: against
an older one it stays unregistered, and the SDK logs `UNSUPPORTED` once.
**Signature**
```typescript
onObservationMatch(functionId: string, hook: MatchPredicate<I, O> | null) => IIIClient
onObservationMatch(functionId: string, hook: MatchKeys<I, O>) => IIIClient
onObservationMatch(functionId: string, hook: MatchHook<I, O> | null) => IIIClient
```
<Tabs>
<Tab title="Parameters">
<ParamField body="functionId" type="string" required>
</ParamField>
<ParamField body="hook" type="MatchHook<I, O> | null" required>
</ParamField>
</Tab>
<Tab title="Example">
```typescript
// an observer of expression X gets the ticks of expression X
worker.onObservationMatch('cron::on-tick', (obs, call) => obs.args.expression === call.input.expression)
// many observers: keys, one lookup per key
worker.onObservationMatch('database::on-row-changed', {
observer: (obs) => `${obs.args.table}|${obs.args.op}`,
call: (call) => `${call.input.table}|${call.input.op}`,
})
```
</Tab>
</Tabs>
---
### onObserverAdded
Runs `hook` when an observer of any function this worker hosts is added,
before the SDK acks it; with a function id, for that function only. When
both are set, the worker's runs first. Throw to reject the observer.
`null` removes the hook. Hooks set by id stay in place across
`unregister()` and a later registration of the same id.
A hook set while the function already has active observers runs for each
of them at once (a throw late-rejects that observer), and the SDK logs a
warning.
**Signature**
```typescript
onObserverAdded(hook: AddedHook | null) => IIIClient
onObserverAdded(functionId: string, hook: AddedHook | null) => IIIClient
```
<Tabs>
<Tab title="Parameters">
<ParamField body="functionId" type="string">
</ParamField>
<ParamField body="hook" type="AddedHook | null" required>
</ParamField>
</Tab>
<Tab title="Example">
```typescript
// every function this worker hosts: keep the event stream open while anything is observed
worker.onObserverAdded(async () => { await events.retain() })
// one function, by id
worker.onObserverAdded('database::on-row-changed', async (obs) => {
await capture.install(obs.args.db, obs.args.table)
})
```
</Tab>
</Tabs>
---
### onObserverRemoved
Runs `hook` once for every accepted observer when it is removed (on
`unobserve`, disposal, unregister, late rejection); with a function id,
for that function only. When both are set, the function's runs first. An
error it throws is logged. `null` removes the hook.
**Signature**
```typescript
onObserverRemoved(hook: RemovedHook | null) => IIIClient
onObserverRemoved(functionId: string, hook: RemovedHook | null) => IIIClient
```
#### Parameters
<ParamField body="functionId" type="string">
</ParamField>
<ParamField body="hook" type="RemovedHook | null" required>
</ParamField>
---
### shutdown
Gracefully shutdown the iii, cleaning up all resources.
**Signature**
```typescript
shutdown() => Promise<void>
```
#### Example
```typescript
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`, `EngineSources`, `RemoteFunctionHandler` |
| `iii-sdk/errors` | `InvocationError`, `InvocationErrorInit`, `ObserveRejection`, `RegistrationRejectedError`, `RegistrationRejectedInit`, `isErrorBody` |
| `iii-sdk/helpers` | `ChannelDirection`, `ChannelItem`, `createChannel`, `createStream`, `extractChannelRefs`, `isChannelRef` |
| `iii-sdk` | `AddedHook`, `Call`, `CallAction`, `CallRequest`, `Caller`, `CallerInfo`, `Capture`, `DEFAULT_ENGINE_URL`, `DeliverHook`, `EngineSources`, `EnqueueResult`, `Filter`, `FunctionRef`, `IIIClient`, `IIIConnectionState`, `InitOptions`, `InvocationContext`, `InvocationError`, `InvocationErrorInit`, `JsonValue`, `Key`, `MatchHook`, `MatchKeys`, `MatchPredicate`, `MiddlewareFunctionInput`, `ObserveReason`, `ObserveRejection`, `ObserveSource`, `Observed`, `Observer`, `ObserverHandle`, `ObserverOptions`, `ObserverState`, `RegisterFunctionOptions`, `RegistrationRejectedError`, `RemovedHook`, `StreamRequest`, `StreamResponse`, `Target`, `TelemetryOptions`, `registerWorker` |
| `iii-sdk/protocol` | `ActivationWire`, `CallRequest`, `CallerWire`, `CaptureWire`, `DroppedReportStatsWire`, `ErrorBody`, `FEATURE_LARGE_MESSAGES_V1`, `FEATURE_LOCAL_DISPATCH_V1`, `FEATURE_OBSERVE_V1`, `FEATURE_OBSERVE_V2`, `FunctionRegisteredMessage`, `InvocationResultMessage`, `InvocationsObservedMessage`, `LocalFunctionStatsWire`, `LocalInvocationStatsMessage`, `MessageType`, `ObserveMessage`, `ObserveResultMessage`, `ObserveSourceWire`, `ObservedItemWire`, `ObserverAckMessage`, `ObserverAddedMessage`, `ObserverInfoWire`, `ObserverRemovedMessage`, `ObserverStateChangedMessage`, `RegisterFunctionFormat`, `RegisterFunctionInput`, `RegisterFunctionMessage`, `RegisterFunctionOptions`, `RegistrationRejectedMessage`, `SDK_FEATURES`, `TriggerRequest`, `UnobserveMessage` |
| `iii-sdk/runtime` | `FunctionRef`, `IIIConnectionState` |
| `iii-sdk/state` | `IState`, `StateDeleteInput`, `StateDeleteResult`, `StateEventData`, `StateEventType`, `StateGetInput`, `StateListInput`, `StateSetInput`, `StateSetResult`, `StateUpdateInput`, `StateUpdateResult` |
## Types
### iii-sdk
[`AddedHook`](#addedhook) · [`Call`](#call) · [`CallAction`](#callaction) · [`Caller`](#caller) · [`CallerInfo`](#callerinfo) · [`Capture`](#capture) · [`DeliverHook`](#deliverhook) · [`EnqueueResult`](#enqueueresult) · [`Filter`](#filter) · [`InitOptions`](#initoptions) · [`InvocationContext`](#invocationcontext) · [`JsonValue`](#jsonvalue) · [`Key`](#key) · [`MatchHook`](#matchhook) · [`MatchKeys`](#matchkeys) · [`MatchPredicate`](#matchpredicate) · [`MiddlewareFunctionInput`](#middlewarefunctioninput) · [`Observed`](#observed) · [`Observer`](#observer) · [`ObserveReason`](#observereason) · [`ObserverHandle`](#observerhandle) · [`ObserverOptions`](#observeroptions) · [`ObserverState`](#observerstate) · [`ObserveSource`](#observesource) · [`RemovedHook`](#removedhook) · [`StreamRequest`](#streamrequest) · [`StreamResponse`](#streamresponse) · [`Target`](#target) · [`TelemetryOptions`](#telemetryoptions)
#### AddedHook
Runs when an observer of a function is added, before the SDK acks it.
Throw to reject the observer: an ObserveRejection sets the code,
anything else is `OBSERVE_REJECTED`; after 30 s it is rejected with
`OWNER_TIMEOUT`.
```typescript
type AddedHook = (obs: Observer) => void | Promise<void>
```
---
#### Call
One call of a function, as its host delivers it: what the handler was
called with and what it returned (or threw). Observers observe `output`,
the handler's return value.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `caller` | [`Caller`](#caller) | No | Who made the call; absent for a call made outside any handler. |
| `error` | `{ code: string; message: string; stacktrace?: string }` | No | What the handler threw. |
| `function_id` | `string` | Yes | - |
| `input` | `I` | Yes | - |
| `invocation_id` | `string` | Yes | - |
| `metadata` | `Record<string, unknown>` | No | - |
| `output` | `O` | No | The handler's return value: what observers observe. |
| `status` | `"success" \| "error"` | Yes | - |
---
#### CallAction
Factory object that constructs routing actions for IIIClient.call.
| 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 call 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. |
---
#### Caller
Who started an invocation: the worker (`worker_id` / `worker_name`, stamped
by the engine), and the function and invocation the call was made from.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `function_id` | `string` | No | The handler the call was made from; absent for top-level calls. |
| `invocation_id` | `string` | No | - |
| `parent` | Omit<[`Caller`](#caller), "parent"> | No | The caller of that handler, one level only. |
| `worker_id` | `string` | No | Absent on activations, whose caller is the engine (`worker_name: 'iii-engine'`). |
| `worker_name` | `string` | No | - |
---
#### CallerInfo
A caller as the SDK knows it: every field may be missing (a top-level call
has no function; a call made before `WorkerRegistered` has no worker id).
```typescript
type CallerInfo = Partial<Omit<Caller, "parent">> & { parent?: Partial<Omit<Caller, "parent">> }
```
---
#### Capture
A field an observer captures. Default `['input', 'output', 'caller']`.
```typescript
type Capture = "input" | "output" | "error" | "caller" | "metadata"
```
---
#### DeliverHook
Delivers each call of a function itself (`onObservationDeliver`): it receives
the call and the observers that matched it (a snapshot taken when the call
started), and what it returns (or throws) is what the caller gets back. A
thrown ObserveRejection, or the error of a call it made, reaches the
caller with its code; any other error as `invocation_failed`. iii delivers
nothing for that function; the hook calls through observers
(`worker.call({ observer, payload })`) and applies their filters with
`obs.matches(call)`. It runs inside the function's invocation, so the calls
it makes have that invocation as their caller.
```typescript
type DeliverHook = (call: Call<I, O>, observers: readonly Observer[]) => R | Promise<R>
```
---
#### EnqueueResult
Result returned when a function is called with `CallAction.Enqueue`.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `messageReceiptId` | `string` | Yes | Unique receipt ID for the enqueued message. |
---
#### Filter
A declarative filter over `input`, `output`, `error`, `caller` and
`metadata`, with explicit operators only:
`{ 'input.amount': { $gte: 500 } }`. See the filter language reference.
```typescript
type Filter = Record<string, unknown>
```
---
#### 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, on the main connection and<br />on streaming channels. `Authorization: Bearer $III_TOKEN` is added unless you set<br />`Authorization` here. |
| `invocationTimeoutMs` | `number` | No | Default timeout for `worker.call()` 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 `call` resolves its<br />target here, and an `observe` its source and target, unless the call<br />names another namespace. One declaration places the whole worker. |
| `otel` | `Omit<OtelConfig, "engineWsUrl" \| "engineWsHeaders">` | 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, and `engineWsHeaders`<br />from the handshake headers of the main connection. |
| `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. A non-empty `III_WORKER_NAME` overrides it. Defaults to `hostname:pid`. |
---
#### InvocationContext
The invocation the current code runs in, in every handler, remote or
local (`iii.currentInvocation()`).
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `activation` | `{ activation_id?: string; observer_id: string }` | No | Set when this invocation is the activation of an observer's target. |
| `caller` | [`CallerInfo`](#callerinfo) | No | - |
| `function_id` | `string` | Yes | - |
| `invocation_id` | `string` | Yes | - |
| `observe_depth` | `number` | Yes | - |
---
#### 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
type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }
```
---
#### Key
A match key, or several: an observer wants a call when they share one.
```typescript
type Key = string | readonly string[]
```
---
#### MatchHook
Which observers want each call of a function (`onObservationMatch`). By
default every observer wants every call. A predicate is asked once per
observation: for every call, once for each active observer (a throw
counts as no match for that observer). Keys are computed
once per observer, when it is accepted, and once per call. The observers'
capture, filters and policy still apply. Setting it to `null`
removes it: every observer gets every call again.
```typescript
type MatchHook = MatchPredicate<I, O> | MatchKeys<I, O>
```
---
#### MatchKeys
`onObservationMatch` as keys: an observer wants a call when they share a key,
and the SDK keeps an index instead of asking every observer.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `call` | (call: [`Call`](#call)<I, O>) => [`Key`](#key) | Yes | What this call is. |
| `observer` | (obs: [`Observer`](#observer)) => [`Key`](#key) | Yes | What this observer listens for, computed once when it is accepted. |
---
#### MatchPredicate
`onObservationMatch` as a predicate: whether this observer wants this call.
```typescript
type MatchPredicate = (obs: Observer, call: Call<I, O>) => boolean
```
---
#### 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` | [`CallAction`](#callaction) | 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. |
---
#### Observed
What an observer's target receives when iii delivers: the top-level
fields, plus whichever of the observer's `capture` apply to the outcome.
Fields not captured, or that do not apply, are absent.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `activation_id` | `string` | Yes | - |
| `caller` | [`Caller`](#caller) | No | - |
| `duration_ms` | `number` | Yes | - |
| `error` | `{ code: string; message: string }` | No | - |
| `function_id` | `string` | Yes | - |
| `input` | `I` | No | - |
| `invocation_id` | `string` | Yes | - |
| `metadata` | `Record<string, unknown>` | No | - |
| `namespace` | `string` | Yes | - |
| `observer_id` | `string` | Yes | - |
| `output` | `O` | No | - |
| `started_at_ms` | `number` | Yes | - |
| `status` | `"success" \| "error"` | Yes | - |
---
#### Observer
An observer as the worker that hosts its function sees it (the hooks,
`FunctionRef.observers()`): its args, filters, target and capture.
Who observes, the observer's metadata and its policy stay with the engine.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `args` | `Record<string, unknown>` | Yes | The observer's args, validated against the function's `args_format` by the engine. |
| `capture` | [`Capture`](#capture)[] | Yes | - |
| `filters` | [`Filter`](#filter) | Yes | The observer's filters, normalized. |
| `function_id` | `string` | Yes | The observed function (one this worker hosts). |
| `id` | `string` | Yes | - |
| `target` | `string` | Yes | The target function id. |
| `accepted` | `() => Promise<void>` | Yes | Resolves once the SDK has acked the observer. A call made after it<br />resolves reaches an active observer, so a provider sends an observer its<br />initial state from here: a call through it<br />(`iii.call({ observer: obs, payload })`), which runs its target alone<br />with the payload as given. Rejects with an<br />ObserveRejection when the observer is rejected first. |
| `matches` | (call: Partial<[`Call`](#call)>) => boolean | Yes | Whether `call` reaches this observer: its `capture` fires on the call's<br />`status` (absent reads as `'success'`) and its filters match the call. |
| `reject` | `(code: string, message: string) => void` | Yes | Late rejection of an active observer (e.g. after a config reload). It<br />stops receiving calls at once, its `onObserverRemoved` hooks run, and it<br />stays rejected across reconnects until the engine adds it again. |
---
#### ObserveReason
A state reason or an error: a machine-readable code and a message.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `code` | `string` | Yes | - |
| `message` | `string` | Yes | - |
---
#### ObserverHandle
What `iii.observe` returns, synchronously.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `string` | Yes | - |
| `reason` | [`ObserveReason`](#observereason) | No | Why the observer is in its state (`error`, `suspended`, `disposed`). |
| `state` | [`ObserverState`](#observerstate) | Yes | - |
| `dispose` | `() => Promise<void>` | Yes | Removes the observer (`unobserve`). It is not replayed on reconnect.<br />After the engine refused the `observe`, it sends nothing. It resolves at<br />once in every case and awaits no answer from the engine, also when it is<br />called before the answer to the `observe` arrives. |
| `onStateChange` | (listener: (state: [`ObserverState`](#observerstate), reason?: [`ObserveReason`](#observereason)) => void) => () => void | Yes | Calls `listener` on every state change, in order; returns the<br />unsubscribe function. Listeners are called asynchronously (never on the<br />connection's read path), so they may call the client. |
| `ready` | `() => Promise<void>` | Yes | Resolves when the observer is `active`; rejects with an<br />ObserveRejection carrying the code when it turns `error` or<br />`disposed` first. |
---
#### ObserverOptions
The observer itself: its id, policy and metadata.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `expires_in_ms` | `number` | No | The observer is disposed this many milliseconds after it is created (`EXPIRED`). Default: never. |
| `id` | `string` | No | Default: a random UUID, stable across replays. The handle holds it until<br />it is disposed: an `observe` of an id a handle of this client holds<br />throws an ObserveRejection with code `OBSERVER_ID_CONFLICT` and<br />sends nothing. |
| `max_fires` | `number` | No | The observer is disposed after this many activations (`MAX_FIRES`). Default: unlimited. |
| `max_in_flight` | `number` | No | Activations running at once; further ones queue, then drop as `OVERFLOW`.<br />Default: the engine's `observers.default_max_in_flight` (64). |
| `metadata` | `Record<string, unknown>` | No | Delivered as the metadata sidecar of every activation. |
---
#### ObserverState
An observer's lifecycle: `pending` (no host yet, waiting for the host's
ack, or no target yet) → `active` or `error`; `suspended` while its worker
or target is away; `disposed` at the end.
```typescript
type ObserverState = "pending" | "active" | "suspended" | "error" | "disposed"
```
---
#### ObserveSource
The left side of `iii.observe`: what is observed.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `args` | `Record<string, unknown>` | No | For the worker that hosts the function: what to set up and which calls<br />to deliver (a table, a cron expression, a route). The engine validates<br />them against the function's `args_format`. |
| `capture` | [`Capture`](#capture)[] | No | What the target's payload carries, and with it which outcomes fire the<br />target. Default `['input', 'output', 'caller']`.<br /><br />- `input` and `output` fire on success, `error` fires on error.<br />- `caller` and `metadata` only add to the payload: a `capture` must name<br /> at least one of `input`, `output`, `error` (`INVALID_ARGS` otherwise).<br />- `[]` fires on success, with the top-level fields only.<br /><br />So the default fires on success, `['error', 'caller']` on errors, and<br />`['input', 'error']` on both. A success's payload never has `error`, an<br />error's never has `output`. |
| `filters` | [`Filter`](#filter) | No | Which calls reach the target, by `input`, `output`, `error`, `caller` and `metadata`; `{}` (or absent) = every call. |
| `function_id` | `string` | Yes | The observed function. |
| `namespace` | `string` | No | Defaults to this worker's namespace (`engine::*` and `configuration::*` resolve to `default`). |
---
#### RemovedHook
Runs once for every accepted observer when it is removed. An error it throws is logged.
```typescript
type RemovedHook = (obs: Observer) => void | Promise<void>
```
---
#### StreamRequest
Incoming streaming request received by a function that serves an HTTP route.
```typescript
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. |
---
#### Target
The right side of `iii.observe`: a registered function.
```typescript
type Target = string | { function_id: string; namespace?: string }
```
---
#### TelemetryOptions
Worker metadata reported to the engine (language, framework, project).
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `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. |
### 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) · [`EngineSources`](#enginesources) · [`RemoteFunctionHandler`](#remotefunctionhandler)
#### EngineFunctions
Engine function paths for internal operations.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `INFO_FUNCTIONS` | `"engine::functions::info"` | Yes | - |
| `INFO_WORKERS` | `"engine::workers::info"` | Yes | - |
| `LIST_FUNCTIONS` | `"engine::functions::list"` | Yes | - |
| `LIST_WORKERS` | `"engine::workers::list"` | Yes | - |
| `REGISTER_WORKER` | `"engine::workers::register"` | Yes | - |
---
#### EngineSources
The event sources the engine hosts: private functions whose handler
returns the event, observed with `iii.observe(EngineSources.X, target)`.
None takes args; filter on the event (`input`) instead.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `CONFIGURATION_UPDATED` | `"configuration::on-updated"` | Yes | The engine's configuration was reloaded. |
| `FUNCTIONS_CHANGED` | `"engine::on-functions-changed"` | Yes | A function was registered or unregistered; each row carries `observer_count`. |
| `LOG` | `"observability::on-log"` | Yes | A log record. |
| `OBSERVERS_CHANGED` | `"engine::on-observers-changed"` | Yes | An observer changed state: `{ observer_id, function_id, target, state, reason? }`. |
| `SPAN` | `"observability::on-span"` | Yes | A finished span. |
| `WORKERS_CHANGED` | `"engine::on-workers-changed"` | Yes | A worker connected or left. |
---
#### RemoteFunctionHandler
Handler of a registered function. Receives the invocation payload and an
optional per-invocation `metadata` value, and returns the result (or a
promise of it). The return value is what the function's observers observe.
`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
type RemoteFunctionHandler = (data: TInput, metadata?: JsonValue) => TOutput | Promise<TOutput>
```
### iii-sdk/errors
[`InvocationError`](#invocationerror) · [`InvocationErrorInit`](#invocationerrorinit) · [`ObserveRejection`](#observerejection) · [`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 | - |
---
#### ObserveRejection
Thrown by an `onObserverAdded` hook to reject an observer with a code of
its own (`HTTP_ROUTE_CONFLICT`, `INVALID_CRON_EXPRESSION`, ...); any other
error rejects it with `OBSERVE_REJECTED`. Also the error `ObserverHandle.ready()`
rejects with when the observer turns `error` or `disposed`.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `code` | `string` | Yes | - |
---
#### 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
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
type ChannelItem = { type: "text"; value: string } | { type: "binary"; value: Uint8Array }
```
### iii-sdk/protocol
[`ActivationWire`](#activationwire) · [`CallerWire`](#callerwire) · [`CallRequest`](#callrequest) · [`CaptureWire`](#capturewire) · [`DroppedReportStatsWire`](#droppedreportstatswire) · [`ErrorBody`](#errorbody) · [`FunctionRegisteredMessage`](#functionregisteredmessage) · [`InvocationResultMessage`](#invocationresultmessage) · [`InvocationsObservedMessage`](#invocationsobservedmessage) · [`LocalFunctionStatsWire`](#localfunctionstatswire) · [`LocalInvocationStatsMessage`](#localinvocationstatsmessage) · [`MessageType`](#messagetype) · [`ObservedItemWire`](#observeditemwire) · [`ObserveMessage`](#observemessage) · [`ObserverAckMessage`](#observerackmessage) · [`ObserverAddedMessage`](#observeraddedmessage) · [`ObserveResultMessage`](#observeresultmessage) · [`ObserverInfoWire`](#observerinfowire) · [`ObserverRemovedMessage`](#observerremovedmessage) · [`ObserverStateChangedMessage`](#observerstatechangedmessage) · [`ObserveSourceWire`](#observesourcewire) · [`RegisterFunctionFormat`](#registerfunctionformat) · [`RegisterFunctionInput`](#registerfunctioninput) · [`RegisterFunctionMessage`](#registerfunctionmessage) · [`RegisterFunctionOptions`](#registerfunctionoptions) · [`RegistrationRejectedMessage`](#registrationrejectedmessage) · [`UnobserveMessage`](#unobservemessage)
#### ActivationWire
`InvokeFunction.activation`: present on every activation of an observer's target.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `activation_id` | `string` | No | - |
| `observer_id` | `string` | Yes | - |
---
#### CallerWire
Who started an invocation. Engine → worker: `worker_id` / `worker_name`
are stamped by the engine from the calling connection. Worker → engine:
the SDK sends `function_id`, `invocation_id` and `parent` (the caller of the
handler the call was made from, one level only).
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `function_id` | `string` | No | - |
| `invocation_id` | `string` | No | - |
| `parent` | Omit<[`CallerWire`](#callerwire), "parent"> | No | - |
| `worker_id` | `string` | No | - |
| `worker_name` | `string` | No | - |
---
#### CallRequest
Request object passed to IIIClient.call: a function by id, or the
target of an observer.
```typescript
type CallRequest = { action?: CallAction; dispatch?: "auto" | "remote"; function_id: string; metadata?: unknown; namespace?: string; observer?: never; payload: TInput; timeoutMs?: number } | { action?: CallAction; function_id?: never; metadata?: never; observer: Observer; payload: TInput; timeoutMs?: number }
```
---
#### CaptureWire
What an observer captures (`capture`): the fields its target's payload
carries, and with them the outcomes that fire it.
```typescript
type CaptureWire = OpenEnum<"input" | "output" | "error" | "caller" | "metadata">
```
---
#### DroppedReportStatsWire
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `count` | `number` | Yes | - |
| `function_id` | `string` | Yes | - |
| `reason` | `string` | Yes | `BUFFER_FULL` \| `TOO_LARGE` \| `INACTIVE` (SDK-side drops). |
---
#### ErrorBody
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `code` | `string` | Yes | - |
| `message` | `string` | Yes | - |
| `stacktrace` | `string` | No | - |
---
#### FunctionRegisteredMessage
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `string` | Yes | - |
| `local_dispatch` | `boolean` | Yes | - |
| `message_type` | [`MessageType`](#messagetype).FunctionRegistered | Yes | - |
| `namespace` | `string` | Yes | - |
| `observers` | [`ObserverInfoWire`](#observerinfowire)[] | Yes | - |
| `revision` | `number` | Yes | - |
---
#### InvocationResultMessage
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `baggage` | `string` | No | W3C baggage header for cross-cutting context propagation |
| `delivered` | `boolean` | No | Host → engine (`observe.v2`): the function's deliver hook<br />(`onObservationDeliver`) delivered this routed call, and the engine<br />activates no observer for it. Sent only as `true`, and without<br />`matched`. |
| `error` | `unknown` | No | - |
| `function_id` | `string` | Yes | The path of the function. |
| `invocation_id` | `string` | Yes | The id of the invocation |
| `matched` | `string[]` | No | Host → engine (`observe.v2`): the observers the function's match hook<br />(`onObservationMatch`) matched for this routed call, before their capture and<br />filters, which the engine evaluates; `[]` when it matched none. Left out<br />by a function without a match hook: the engine then evaluates every<br />active observer of the function. |
| `message_type` | [`MessageType`](#messagetype).InvocationResult | Yes | - |
| `result` | `unknown` | No | - |
| `traceparent` | `string` | No | W3C trace-context traceparent header for distributed tracing |
---
#### InvocationsObservedMessage
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `items` | [`ObservedItemWire`](#observeditemwire)[] | Yes | - |
| `message_type` | [`MessageType`](#messagetype).InvocationsObserved | Yes | - |
---
#### LocalFunctionStatsWire
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `count` | `number` | Yes | - |
| `duration_ms_sum` | `number` | No | - |
| `errors` | `number` | No | - |
| `function_id` | `string` | Yes | - |
---
#### LocalInvocationStatsMessage
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `dropped_reports` | [`DroppedReportStatsWire`](#droppedreportstatswire)[] | Yes | - |
| `functions` | [`LocalFunctionStatsWire`](#localfunctionstatswire)[] | Yes | - |
| `message_type` | [`MessageType`](#messagetype).LocalInvocationStats | Yes | - |
| `window_ms` | `number` | Yes | - |
---
#### MessageType
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `FunctionRegistered` | `"functionregistered"` | Yes | Engine → host: the `registerfunction` ack, with the function's full observer set. |
| `InvocationResult` | `"invocationresult"` | Yes | - |
| `InvocationsObserved` | `"invocationsobserved"` | Yes | Host → engine: the calls of its functions that observers matched, batched. |
| `InvokeFunction` | `"invokefunction"` | Yes | - |
| `LocalInvocationStats` | `"localinvocationstats"` | Yes | Host → engine: periodic counts of local invocations and report drops. |
| `Observe` | `"observe"` | Yes | Observing worker → engine: create (or idempotently replay) an observer. |
| `ObserverAck` | `"observerack"` | Yes | Host → engine: accept (or reject) an added observer. |
| `ObserverAdded` | `"observeradded"` | Yes | Engine → host: one observer attached to a function this connection hosts. |
| `ObserveResult` | `"observeresult"` | Yes | Engine → observing worker: the reply to `observe` (also on replay). |
| `ObserverRemoved` | `"observerremoved"` | Yes | Engine → host: one observer detached. |
| `ObserverStateChanged` | `"observerstatechanged"` | Yes | Engine → observing worker: an observer's lifecycle transition. |
| `Reattach` | `"reattach"` | Yes | - |
| `RegisterFunction` | `"registerfunction"` | Yes | - |
| `RegistrationRejected` | `"registrationrejected"` | Yes | - |
| `Unobserve` | `"unobserve"` | Yes | Observing worker → engine: dispose an observer this connection owns. |
| `UnregisterFunction` | `"unregisterfunction"` | Yes | - |
| `WorkerRegistered` | `"workerregistered"` | Yes | - |
---
#### ObservedItemWire
One local call of a hosted function, with the observers its delivery selected.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `baggage` | `string` | No | - |
| `caller` | [`CallerWire`](#callerwire) | No | - |
| `duration_ms` | `number` | Yes | - |
| `error` | `unknown` | No | - |
| `function_id` | `string` | Yes | - |
| `input` | `unknown` | No | `null` is a value here: absent means not captured or does not exist. |
| `invocation_id` | `string` | Yes | - |
| `matched` | `string[]` | Yes | The observers delivered. |
| `metadata` | `unknown` | No | - |
| `namespace` | `string` | No | - |
| `observe_depth` | `number` | No | - |
| `output` | `unknown` | No | Absent with `output_is_input`: the engine fills it from `input`. |
| `output_is_input` | `boolean` | No | The handler returned its input; left out when `false`. |
| `started_at_ms` | `number` | Yes | - |
| `status` | `OpenEnum<"success" \| "error">` | Yes | - |
| `traceparent` | `string` | No | - |
---
#### ObserveMessage
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `expires_in_ms` | `number` | No | - |
| `id` | `string` | Yes | Client-generated UUID, stable across replays. |
| `max_fires` | `number` | No | - |
| `max_in_flight` | `number` | No | - |
| `message_type` | [`MessageType`](#messagetype).Observe | Yes | - |
| `metadata` | `Record<string, unknown>` | No | - |
| `source` | [`ObserveSourceWire`](#observesourcewire) | Yes | - |
| `target` | `{ function_id: string; namespace?: string }` | Yes | - |
---
#### ObserverAckMessage
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `error` | [`ErrorBody`](#errorbody) | No | Rejects the observer (also a late rejection of an active one). |
| `function_id` | `string` | Yes | - |
| `id` | `string` | Yes | - |
| `message_type` | [`MessageType`](#messagetype).ObserverAck | Yes | - |
| `namespace` | `string` | No | - |
| `revision` | `number` | Yes | - |
---
#### ObserverAddedMessage
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `function_id` | `string` | Yes | - |
| `message_type` | [`MessageType`](#messagetype).ObserverAdded | Yes | - |
| `namespace` | `string` | Yes | - |
| `observer` | [`ObserverInfoWire`](#observerinfowire) | Yes | - |
| `revision` | `number` | Yes | - |
---
#### ObserveResultMessage
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `error` | [`ErrorBody`](#errorbody) | No | - |
| `id` | `string` | Yes | - |
| `message_type` | [`MessageType`](#messagetype).ObserveResult | Yes | - |
| `state` | `ObserverStateWire` | Yes | - |
| `warnings` | `string[]` | No | - |
---
#### ObserverInfoWire
An observer as the host of its function sees it: never the observer's
metadata, policy or connection. `target` is the target function id.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `args` | `Record<string, unknown>` | Yes | - |
| `capture` | [`CaptureWire`](#capturewire)[] | Yes | - |
| `filters` | `Record<string, unknown>` | Yes | The observer's filters, normalized by the engine. `{}` matches every call. |
| `fires_on` | `FiresWire[]` | No | The outcomes that fire it, from an engine with `observe.capture`; absent from a 0.25 or rc engine. |
| `id` | `string` | Yes | - |
| `on` | `string` | No | - |
| `target` | `string` | Yes | - |
---
#### ObserverRemovedMessage
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `function_id` | `string` | Yes | - |
| `id` | `string` | Yes | - |
| `message_type` | [`MessageType`](#messagetype).ObserverRemoved | Yes | - |
| `namespace` | `string` | Yes | - |
| `revision` | `number` | Yes | - |
---
#### ObserverStateChangedMessage
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `fires` | `number` | Yes | - |
| `id` | `string` | Yes | - |
| `message_type` | [`MessageType`](#messagetype).ObserverStateChanged | Yes | - |
| `reason` | [`ErrorBody`](#errorbody) | No | - |
| `state` | `ObserverStateWire` | Yes | - |
---
#### ObserveSourceWire
`observe.source`: the left side of `iii.observe`.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `args` | `Record<string, unknown>` | No | - |
| `capture` | [`CaptureWire`](#capturewire)[] | No | - |
| `filters` | `Record<string, unknown>` | No | - |
| `function_id` | `string` | Yes | - |
| `namespace` | `string` | No | - |
---
#### 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
type RegisterFunctionInput = Omit<RegisterFunctionMessage, "message_type">
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `args_format` | [`RegisterFunctionFormat`](#registerfunctionformat) | No | JSON Schema of the `args` an observer of this function passes. The<br />engine validates every observer's args against it (`INVALID_ARGS`)<br />before the added hooks run, and refuses a schema that is not valid<br />(`INVALID_ARGS_FORMAT`). A function without it takes no args. |
| `description` | `string` | No | Human-readable summary of the function, listed by discovery<br />(`engine::functions::list`). |
| `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, stored with it and listed by<br />discovery (`engine::functions::list`). It is distinct from the per-call<br />metadata a handler receives. |
| `observable` | `boolean` | No | `false`: nobody may observe the function (`NOT_OBSERVABLE`), for one<br />whose payloads carry credentials. Default `true`; sent only when `false`. |
| `private` | `boolean` | No | Only this worker may call the function: the engine answers a call from<br />any other connection with `FORBIDDEN`, and refuses the function as an<br />observer's target. Any worker may observe it, and its observers receive<br />every call this worker makes. For event sources, whose calls from<br />anywhere else would be forged events. This worker's own calls pass the<br />input and the result by reference: the handler and hooks treat both as<br />read-only (frozen when `NODE_ENV` is `development`). Default `false`;<br />sent only when `true`. |
| `request_format` | [`RegisterFunctionFormat`](#registerfunctionformat) | No | JSON Schema of the call's input. |
| `response_format` | [`RegisterFunctionFormat`](#registerfunctionformat) | No | JSON Schema of the handler's return value: what the function's observers<br />observe. |
---
#### RegisterFunctionMessage
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `args_format` | [`RegisterFunctionFormat`](#registerfunctionformat) | No | JSON Schema of the `args` an observer of this function passes. The<br />engine validates every observer's args against it (`INVALID_ARGS`)<br />before the added hooks run, and refuses a schema that is not valid<br />(`INVALID_ARGS_FORMAT`). A function without it takes no args. |
| `description` | `string` | No | Human-readable summary of the function, listed by discovery<br />(`engine::functions::list`). |
| `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, stored with it and listed by<br />discovery (`engine::functions::list`). It is distinct from the per-call<br />metadata a handler receives. |
| `observable` | `boolean` | No | `false`: nobody may observe the function (`NOT_OBSERVABLE`), for one<br />whose payloads carry credentials. Default `true`; sent only when `false`. |
| `private` | `boolean` | No | Only this worker may call the function: the engine answers a call from<br />any other connection with `FORBIDDEN`, and refuses the function as an<br />observer's target. Any worker may observe it, and its observers receive<br />every call this worker makes. For event sources, whose calls from<br />anywhere else would be forged events. This worker's own calls pass the<br />input and the result by reference: the handler and hooks treat both as<br />read-only (frozen when `NODE_ENV` is `development`). Default `false`;<br />sent only when `true`. |
| `request_format` | [`RegisterFunctionFormat`](#registerfunctionformat) | No | JSON Schema of the call's input. |
| `response_format` | [`RegisterFunctionFormat`](#registerfunctionformat) | No | JSON Schema of the handler's return value: what the function's observers<br />observe. |
---
#### RegisterFunctionOptions
Options of IIIClient.registerFunction: what describes the function
to the engine (description, formats, metadata, `args_format`, `private`,
`observable`), and what the SDK does with it (`localDispatch`).
What the worker does when the function is observed is set with hooks.
```typescript
type RegisterFunctionOptions = Omit<RegisterFunctionMessage, "message_type" | "id"> & { localDispatch?: boolean }
```
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `args_format` | [`RegisterFunctionFormat`](#registerfunctionformat) | No | JSON Schema of the `args` an observer of this function passes. The<br />engine validates every observer's args against it (`INVALID_ARGS`)<br />before the added hooks run, and refuses a schema that is not valid<br />(`INVALID_ARGS_FORMAT`). A function without it takes no args. |
| `description` | `string` | No | Human-readable summary of the function, listed by discovery<br />(`engine::functions::list`). |
| `invocation` | `HttpInvocationConfig` | No | HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.). |
| `localDispatch` | `boolean` | No | Calls this worker makes to its own function run in-process once the<br />engine confirmed it (default `true`). Set `false` for a handler that must<br />always run through the engine. |
| `metadata` | `Record<string, unknown>` | No | Arbitrary metadata attached to the function, stored with it and listed by<br />discovery (`engine::functions::list`). It is distinct from the per-call<br />metadata a handler receives. |
| `observable` | `boolean` | No | `false`: nobody may observe the function (`NOT_OBSERVABLE`), for one<br />whose payloads carry credentials. Default `true`; sent only when `false`. |
| `private` | `boolean` | No | Only this worker may call the function: the engine answers a call from<br />any other connection with `FORBIDDEN`, and refuses the function as an<br />observer's target. Any worker may observe it, and its observers receive<br />every call this worker makes. For event sources, whose calls from<br />anywhere else would be forged events. This worker's own calls pass the<br />input and the result by reference: the handler and hooks treat both as<br />read-only (frozen when `NODE_ENV` is `development`). Default `false`;<br />sent only when `true`. |
| `request_format` | [`RegisterFunctionFormat`](#registerfunctionformat) | No | JSON Schema of the call's input. |
| `response_format` | [`RegisterFunctionFormat`](#registerfunctionformat) | No | JSON Schema of the handler's return value: what the function's observers<br />observe. |
---
#### RegistrationRejectedMessage
Sent by the engine when it refuses a registration. The `code` decides
severity:
- `WORKER_NAMESPACE_CONFLICT`: another worker already holds this
`(namespace, worker_name)`. The engine closes the connection -- fatal: the
SDK stops the worker and does not reconnect.
- `FUNCTION_NAMESPACE_CONFLICT`: another worker already exports this one
`function_id`. The engine keeps the connection
open -- non-fatal: only that registration is refused and the worker keeps
serving its other functions.
- `INVALID_ARGS_FORMAT` (the function's `args_format` is not a valid JSON
Schema) and `UNSUPPORTED`: only that function is refused, the connection
stays open.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `code` | `string` | Yes | Machine-readable rejection code. |
| `function_id` | `string` | No | The refused function. Present on every rejection of one function. |
| `message_type` | [`MessageType`](#messagetype).RegistrationRejected | Yes | - |
| `namespace` | `string` | Yes | Namespace of the refused registration. |
| `owner_worker_id` | `string` | Yes | ID of the live worker that already owns the contested identity; `""` on a rejection that is not a conflict. |
| `worker_name` | `string` | No | Contested worker name. Present only for `WORKER_NAMESPACE_CONFLICT`. |
---
#### UnobserveMessage
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `string` | Yes | - |
| `message_type` | [`MessageType`](#messagetype).Unobserve | Yes | - |
### iii-sdk/runtime
[`FunctionRef`](#functionref) · [`IIIConnectionState`](#iiiconnectionstate)
#### FunctionRef
Handle returned by IIIClient.registerFunction: the client's hook
methods with the function id filled in. Each method returns the handle, so
calls chain.
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `string` | Yes | The unique function identifier. |
| `isObserved` | (call?: Partial<[`Call`](#call)<I, unknown>>) => boolean | Yes | IIIClient.isObserved for this registration: skip building an event<br />nobody receives. Without a call it is one load of this registration's<br />active set. |
| `observers` | () => readonly [`Observer`](#observer)[] | Yes | The active observers of this registration, as this host sees them (none<br />once the function is unregistered, also after the id is registered again). |
| `onObservationDeliver` | (hook: [`DeliverHook`](#deliverhook)<I, O, R> \| null) => [`FunctionRef`](#functionref)<I, O> | Yes | IIIClient.onObservationDeliver for this function. |
| `onObservationMatch` | (hook: [`MatchHook`](#matchhook)<I, O> \| null) => [`FunctionRef`](#functionref)<I, O> | Yes | IIIClient.onObservationMatch for this function. |
| `onObserverAdded` | (hook: [`AddedHook`](#addedhook) \| null) => [`FunctionRef`](#functionref)<I, O> | Yes | IIIClient.onObserverAdded for this function. |
| `onObserverRemoved` | (hook: [`RemovedHook`](#removedhook) \| null) => [`FunctionRef`](#functionref)<I, O> | Yes | IIIClient.onObserverRemoved for this function. |
| `unregister` | `() => void` | Yes | Removes this function from the engine. Its hooks stay in place for a later registration of the id. |
---
#### IIIConnectionState
Connection state for the III WebSocket
```typescript
type IIIConnectionState = "disconnected" | "connecting" | "connected" | "reconnecting" | "failed"
```
### 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). |