Node.js SDK

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

Link to this sectionInstallation

Terminal
npm install iii-sdk

Link to this sectionInitialization

Link to this sectionregisterWorker

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

Signature

registerWorker(address?: string, options?: InitOptions) => IIIClient
addressstring

WebSocket URL of the III engine. Omit to resolve it from process.env.III_URL, falling back to DEFAULT_ENGINE_URL.

optionsInitOptions

Optional InitOptions for worker name, timeouts, reconnection, and OTel.

Show `InitOptions` fields
enableMetricsReportingboolean

Enable worker metrics via OpenTelemetry. Defaults to true.

headersRecord<string, string>

Custom HTTP headers sent during the WebSocket handshake, on the main connection and on the sockets of streams (InputStream, OutputStream). Authorization: Bearer $III_TOKEN is added unless you set Authorization here.

invocationTimeoutMsnumber

Default timeout for worker.call() invocations in milliseconds. Defaults to 30000.

namespacestring

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.

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

reconnectionConfigPartial<IIIReconnectionConfig>

WebSocket reconnection behavior.

workerDescriptionstring

One-line, human/LLM-readable summary of what this worker does. Surfaces in engine::workers::list / engine::workers::info.

workerNamestring

Display name for this worker. A non-empty III_WORKER_NAME overrides it. Defaults to hostname:pid.

Link to this sectionMethods

Link to this sectionregisterFunction

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.

HTTP-invoked functions (HttpInvocationConfig) are deprecated (iii-http-functions) and will be removed in an upcoming release: register a handler that makes the HTTP call instead. Migration guide: https://iii.dev/docs/upgrading/migrate-from-http-functions

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

registerFunction(functionId: string, handler: HttpInvocationConfig | RemoteFunctionHandler<I, O>, options?: RegisterFunctionOptions) => FunctionRef<I, O>
functionIdstringrequired

Unique identifier for the function.

handlerHttpInvocationConfig | RemoteFunctionHandler<I, O>required

Handler for local execution, or an HTTP invocation config for external functions (Lambda, Cloudflare Workers, etc.).

optionsRegisterFunctionOptions

Optional RegisterFunctionOptions: description, request/response formats, metadata, args_format, private, observable, localDispatch.

Show `RegisterFunctionOptions` fields
args_formatRegisterFunctionFormat

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.

descriptionstring

Human-readable summary of the function, listed by discovery (engine::functions::list).

invocationHttpInvocationConfig

HTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.).

localDispatchboolean

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.

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

observableboolean

false: nobody may observe the function (NOT_OBSERVABLE), for one whose payloads carry credentials. Default true; sent only when false.

privateboolean

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.

request_formatRegisterFunctionFormat

JSON Schema of the call's input.

response_formatRegisterFunctionFormat

JSON Schema of the handler's return value: what the function's observers observe.


Link to this sectioncall

Invokes a function: by id, or the target of an observer of a function this worker hosts ({ observer, payload }).

Signature

call(request: CallRequest<TInput>) => Promise<TOutput>
requestCallRequest<TInput>required

The call request: function_id (or observer), payload, and optional action/timeout.


Link to this sectionobserve

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

observe(source: string | ObserveSource, target: Target, options?: ObserverOptions) => ObserverHandle
sourcestring | ObserveSourcerequired

What is observed: a function id, or function_id, args (read by the worker that hosts the function), filters, capture.

Show `ObserveSource` fields
argsRecord<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.

captureCapture[]

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.

filtersFilter

Which calls reach the target, by input, output, error, caller and metadata; {} (or absent) = every call.

function_idstringrequired

The observed function.

namespacestring

Defaults to this worker's namespace (engine::* and configuration::* resolve to default).

targetTargetrequired

The function to invoke.

optionsObserverOptions

id, max_fires, expires_in_ms, max_in_flight, metadata.

Show `ObserverOptions` fields
expires_in_msnumber

The observer is disposed this many milliseconds after it is created (EXPIRED). Default: never.

idstring

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.

max_firesnumber

The observer is disposed after this many activations (MAX_FIRES). Default: unlimited.

max_in_flightnumber

Activations running at once; further ones queue, then drop as OVERFLOW. Default: the engine's observers.default_max_in_flight (64).

metadataRecord<string, unknown>

Delivered as the metadata sidecar of every activation.


Link to this sectiontrigger

Invokes a function using a request object.

Signature

trigger(request: CallRequest<TInput>) => Promise<TOutput>

Link to this sectionParameters

requestCallRequest<TInput>required

Link to this sectioncurrentInvocation

The invocation the calling code runs in (remote or local handler, or the function's deliver hook), or undefined outside any handler.

Signature

currentInvocation() => InvocationContext | undefined

Link to this sectiongetAddress

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

Signature

getAddress() => string

Link to this sectiongetConnectionState

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

getConnectionState() => IIIConnectionState

Link to this sectiongetFatalError

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

getFatalError() => RegistrationRejectedError | undefined

Link to this sectionisObserved

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

isObserved(functionId: string, call?: Partial<Call<unknown, unknown>>) => boolean

Link to this sectionParameters

functionIdstringrequired
callPartial<Call<unknown, unknown>>
Show `Call` fields
callerCaller

Who made the call; absent for a call made outside any handler.

error{ code: string; message: string; stacktrace?: string }

What the handler threw.

function_idstringrequired
inputIrequired
invocation_idstringrequired
metadataRecord<string, unknown>
outputO

The handler's return value: what observers observe.

status'success' | 'error'required

Link to this sectionobservers

The active observers of a function this worker hosts (empty for any other).

Signature

observers(functionId: string) => readonly Observer[]

Link to this sectionParameters

functionIdstringrequired

Link to this sectiononObservationDeliver

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

onObservationDeliver(functionId: string, hook: DeliverHook<I, O, R> | null) => IIIClient
functionIdstringrequired
hookDeliverHook<I, O, R> | nullrequired

Link to this sectiononObservationMatch

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

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
functionIdstringrequired
hookMatchHook<I, O> | nullrequired

Link to this sectiononObserverAdded

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

onObserverAdded(hook: AddedHook | null) => IIIClient
onObserverAdded(functionId: string, hook: AddedHook | null) => IIIClient
functionIdstring
hookAddedHook | nullrequired

Link to this sectiononObserverRemoved

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

onObserverRemoved(hook: RemovedHook | null) => IIIClient
onObserverRemoved(functionId: string, hook: RemovedHook | null) => IIIClient

Link to this sectionParameters

functionIdstring
hookRemovedHook | nullrequired

Link to this sectionpipe

Creates a pipe: an InputStream and an OutputStream joined through the engine; what is written into output is read from input. Put either end in a payload or a result for the other side to use: it travels as its ref. This worker owns the pipe and must stay connected until the other side attached.

A source or a sink placed in a payload gets its pipe from the SDK, so most code does not need this: use it for an end that must exist before its source does, a two-way session (two pipes), or a pipe handed to a call made later.

Signature

pipe(options?: PipeOptions) => Promise<Pipe>
optionsPipeOptions

bufferSize: frames the engine holds before the reader attached.

Show `PipeOptions` fields
bufferSizenumber

Frames the engine holds for the pipe before its reader attached (engine default when omitted).


Link to this sectionshutdown

Gracefully shutdown the iii, cleaning up all resources.

Signature

shutdown() => Promise<void>

Link to this sectionExample

process.on('SIGTERM', async () => {
  await worker.shutdown()
  process.exit(0)
})

Link to this sectionSubpath Exports

The iii-sdk package provides additional entry points:

Import pathContents
iii-sdk/engineEngineFunctions, EngineSources, RemoteFunctionHandler
iii-sdk/errorsInvocationError, InvocationErrorInit, ObserveRejection, RegistrationRejectedError, RegistrationRejectedInit, StreamAbortedError, isErrorBody
iii-sdk/helperscreateStream
iii-sdkAddedHook, Call, CallAction, CallRequest, Caller, CallerInfo, Capture, DEFAULT_ENGINE_URL, DeliverHook, EngineSources, EnqueueResult, Filter, FunctionRef, IIIClient, IIIConnectionState, InitOptions, InputStream, InputStreamSource, InvocationContext, InvocationError, InvocationErrorInit, JsonValue, Key, MatchHook, MatchKeys, MatchPredicate, MiddlewareFunctionInput, ObserveReason, ObserveRejection, ObserveSource, Observed, Observer, ObserverHandle, ObserverOptions, ObserverState, OutputStream, OutputStreamSink, Pipe, PipeOptions, RegisterFunctionOptions, RegistrationRejectedError, RemovedHook, StreamAbortedError, StreamFrame, StreamInfo, StreamRequest, StreamResponse, Target, TelemetryOptions, registerWorker
iii-sdk/protocolActivationWire, CallRequest, CallerWire, CaptureWire, ChannelDirection, ChannelItem, 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, StreamChannelRef, TriggerRequest, UnobserveMessage, extractChannelRefs, isChannelRef
iii-sdk/runtimeFunctionRef, IIIConnectionState
iii-sdk/stateIState, StateDeleteInput, StateDeleteResult, StateEventData, StateEventType, StateGetInput, StateListInput, StateSetInput, StateSetResult, StateUpdateInput, StateUpdateResult

Link to this sectionTypes

Link to this sectioniii-sdk

AddedHook · Call · CallAction · Caller · CallerInfo · Capture · DeliverHook · EnqueueResult · Filter · InitOptions · InputStream · InputStreamSource · InvocationContext · JsonValue · Key · MatchHook · MatchKeys · MatchPredicate · MiddlewareFunctionInput · Observed · Observer · ObserveReason · ObserverHandle · ObserverOptions · ObserverState · ObserveSource · OutputStream · OutputStreamSink · Pipe · PipeOptions · RemovedHook · StreamFrame · StreamInfo · StreamRequest · StreamResponse · Target · TelemetryOptions

Link to this sectionAddedHook

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.

type AddedHook = (obs: Observer) => void | Promise<void>

Link to this sectionCall

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.

NameTypeRequiredDescription
callerCallerNoWho made the call; absent for a call made outside any handler.
error{ code: string; message: string; stacktrace?: string }NoWhat the handler threw.
function_idstringYes-
inputIYes-
invocation_idstringYes-
metadataRecord<string, unknown>No-
outputONoThe handler's return value: what observers observe.
status"success" | "error"Yes-

Link to this sectionCallAction

Factory object that constructs routing actions for IIIClient.call.

NameTypeRequiredDescription
Enqueue(opts: { queue: string }) => { queue: string; type: "enqueue" }YesRoutes the invocation through a named queue. The engine enqueues the job,
acknowledges the caller with { messageReceiptId }, and processes it
asynchronously.

Requires the queue worker in worker-compose.yaml.
Without it the call rejects with enqueue_error (no queue provider).
Void() => { type: "void" }YesFire-and-forget routing. The engine forwards the invocation without
waiting for a response or queuing the job.

Link to this sectionCaller

Who started an invocation: the worker (worker_id / worker_name, stamped by the engine), and the function and invocation the call was made from.

NameTypeRequiredDescription
function_idstringNoThe handler the call was made from; absent for top-level calls.
invocation_idstringNo-
parentOmit<Caller, "parent">NoThe caller of that handler, one level only.
worker_idstringNoAbsent on activations, whose caller is the engine (worker_name: 'iii-engine').
worker_namestringNo-

Link to this sectionCallerInfo

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

type CallerInfo = Partial<Omit<Caller, "parent">> & { parent?: Partial<Omit<Caller, "parent">> }

Link to this sectionCapture

A field an observer captures. Default ['input', 'output', 'caller'].

type Capture = "input" | "output" | "error" | "caller" | "metadata"

Link to this sectionDeliverHook

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.

type DeliverHook = (call: Call<I, O>, observers: readonly Observer[]) => R | Promise<R>

Link to this sectionEnqueueResult

Result returned when a function is called with CallAction.Enqueue.

NameTypeRequiredDescription
messageReceiptIdstringYesUnique receipt ID for the enqueued message.

Link to this sectionFilter

A declarative filter over input, output, error, caller and metadata, with explicit operators only: { 'input.amount': { $gte: 500 } }. See the filter language reference.

type Filter = Record<string, unknown>

Link to this sectionInitOptions

Configuration options passed to registerWorker.

NameTypeRequiredDescription
enableMetricsReportingbooleanNoEnable worker metrics via OpenTelemetry. Defaults to true.
headersRecord<string, string>NoCustom HTTP headers sent during the WebSocket handshake, on the main connection and
on the sockets of streams (InputStream, OutputStream). Authorization: Bearer $III_TOKEN is added unless you set
Authorization here.
invocationTimeoutMsnumberNoDefault timeout for worker.call() invocations in milliseconds. Defaults to 30000.
namespacestringNoNamespace 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.
otelOmit<OtelConfig, "engineWsUrl" | "engineWsHeaders">NoOpenTelemetry 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.
reconnectionConfigPartial<IIIReconnectionConfig>NoWebSocket reconnection behavior.
workerDescriptionstringNoOne-line, human/LLM-readable summary of what this worker does.
Surfaces in engine::workers::list / engine::workers::info.
workerNamestringNoDisplay name for this worker. A non-empty III_WORKER_NAME overrides it. Defaults to hostname:pid.

Link to this sectionInputStream

The read side of a stream. A field of a handler's input or of a call's result arrives as one when the sender put a source there (a Node Readable, a Web ReadableStream, a Blob, an async generator, or an InputStream). Build one yourself with InputStream.from.

A stream has one reader: read it once, with one of for await, bytes, text, lines, messages, frames, toReadable or toWebStream. Call tee first for two. Pass it on unread in a payload or a result and its ref travels instead: no bytes go through this worker. Inside a handler, a stream the handler started reading and did not finish is cancelled when the handler returns.

A stream carries bytes (binary frames) and, separately, JSON messages (text frames): byte reads skip the messages, messages skips the bytes, and frames yields both in order. An abort surfaces as a StreamAbortedError from the read, after the data sent before it.


Link to this sectionInputStreamSource

What InputStream.from reads from.

type InputStreamSource = InputStream | Readable | ReadableStream<Uint8Array> | Blob | Uint8Array | ArrayBuffer | string | AsyncIterable<Uint8Array | string> | Iterable<Uint8Array | string>

Link to this sectionInvocationContext

The invocation the current code runs in, in every handler, remote or local (iii.currentInvocation()).

NameTypeRequiredDescription
activation{ activation_id?: string; observer_id: string }NoSet when this invocation is the activation of an observer's target.
callerCallerInfoNo-
function_idstringYes-
invocation_idstringYes-
observe_depthnumberYes-

Link to this sectionJsonValue

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.

type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }

Link to this sectionKey

A match key, or several: an observer wants a call when they share one.

type Key = string | readonly string[]

Link to this sectionMatchHook

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.

type MatchHook = MatchPredicate<I, O> | MatchKeys<I, O>

Link to this sectionMatchKeys

onObservationMatch as keys: an observer wants a call when they share a key, and the SDK keeps an index instead of asking every observer.

NameTypeRequiredDescription
call(call: Call<I, O>) => KeyYesWhat this call is.
observer(obs: Observer) => KeyYesWhat this observer listens for, computed once when it is accepted.

Link to this sectionMatchPredicate

onObservationMatch as a predicate: whether this observer wants this call.

type MatchPredicate = (obs: Observer, call: Call<I, O>) => boolean

Link to this sectionMiddlewareFunctionInput

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.

NameTypeRequiredDescription
actionCallActionNoRouting action, if any.
contextRecord<string, unknown>YesAuth context returned by the auth function for this session.
function_idstringYesID of the function being invoked.
namespacestringNoTarget namespace the invoke addressed; forward the call here to stay in the
caller's namespace. Absent → the engine's default namespace.
payloadRecord<string, unknown>YesPayload sent by the caller.

Link to this sectionObserved

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.

NameTypeRequiredDescription
activation_idstringYes-
callerCallerNo-
duration_msnumberYes-
error{ code: string; message: string }No-
function_idstringYes-
inputINo-
invocation_idstringYes-
metadataRecord<string, unknown>No-
namespacestringYes-
observer_idstringYes-
outputONo-
started_at_msnumberYes-
status"success" | "error"Yes-

Link to this sectionObserver

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.

NameTypeRequiredDescription
argsRecord<string, unknown>YesThe observer's args, validated against the function's args_format by the engine.
captureCapture[]Yes-
filtersFilterYesThe observer's filters, normalized.
function_idstringYesThe observed function (one this worker hosts).
idstringYes-
targetstringYesThe target function id.
accepted() => Promise<void>YesResolves once the SDK has acked the observer. A call made after it
resolves reaches an active observer, so a provider sends an observer its
initial state from here: a call through it
(iii.call({ observer: obs, payload })), which runs its target alone
with the payload as given. Rejects with an
ObserveRejection when the observer is rejected first.
matches(call: Partial<Call>) => booleanYesWhether call reaches this observer: its capture fires on the call's
status (absent reads as 'success') and its filters match the call.
reject(code: string, message: string) => voidYesLate rejection of an active observer (e.g. after a config reload). It
stops receiving calls at once, its onObserverRemoved hooks run, and it
stays rejected across reconnects until the engine adds it again.

Link to this sectionObserveReason

A state reason or an error: a machine-readable code and a message.

NameTypeRequiredDescription
codestringYes-
messagestringYes-

Link to this sectionObserverHandle

What iii.observe returns, synchronously.

NameTypeRequiredDescription
idstringYes-
reasonObserveReasonNoWhy the observer is in its state (error, suspended, disposed).
stateObserverStateYes-
dispose() => Promise<void>YesRemoves the observer (unobserve). It is not replayed on reconnect.
After the engine refused the observe, it sends nothing. It resolves at
once in every case and awaits no answer from the engine, also when it is
called before the answer to the observe arrives.
onStateChange(listener: (state: ObserverState, reason?: ObserveReason) => void) => () => voidYesCalls listener on every state change, in order; returns the
unsubscribe function. Listeners are called asynchronously (never on the
connection's read path), so they may call the client.
ready() => Promise<void>YesResolves when the observer is active; rejects with an
ObserveRejection carrying the code when it turns error or
disposed first.

Link to this sectionObserverOptions

The observer itself: its id, policy and metadata.

NameTypeRequiredDescription
expires_in_msnumberNoThe observer is disposed this many milliseconds after it is created (EXPIRED). Default: never.
idstringNoDefault: 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.
max_firesnumberNoThe observer is disposed after this many activations (MAX_FIRES). Default: unlimited.
max_in_flightnumberNoActivations running at once; further ones queue, then drop as OVERFLOW.
Default: the engine's observers.default_max_in_flight (64).
metadataRecord<string, unknown>NoDelivered as the metadata sidecar of every activation.

Link to this sectionObserverState

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.

type ObserverState = "pending" | "active" | "suspended" | "error" | "disposed"

Link to this sectionObserveSource

The left side of iii.observe: what is observed.

NameTypeRequiredDescription
argsRecord<string, unknown>NoFor 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.
captureCapture[]NoWhat 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.
filtersFilterNoWhich calls reach the target, by input, output, error, caller and metadata; {} (or absent) = every call.
function_idstringYesThe observed function.
namespacestringNoDefaults to this worker's namespace (engine::* and configuration::* resolve to default).

Link to this sectionOutputStream

The write side of a stream. A field of a handler's input arrives as one when the caller put a sink there (a Node Writable, a Web WritableStream, or an OutputStream); the call resolves once what the handler wrote reached the sink. Build one yourself with OutputStream.to.

Inside a handler, a stream the handler wrote to (or bridged) is closed when the handler returns and aborted when it throws, unless it was closed, aborted, sent on, or kept open with keepOpen. One the handler never touched is closed when it returns, whatever it returns. In an observer activation (an HTTP route target), it is closed only when the handler returns undefined or null, and left alone otherwise: the HTTP worker reads an untouched response and a value as a buffered response.


Link to this sectionOutputStreamSink

What OutputStream.to writes into.

type OutputStreamSink = Writable | WritableStream<Uint8Array>

Link to this sectionPipe

The two ends of a pipe made by IIIClient.pipe: what is written into output is read from input. Either end can be put in a payload or a result.

NameTypeRequiredDescription
inputInputStreamYesThe read end.
outputOutputStreamYesThe write end.

Link to this sectionPipeOptions

Options of IIIClient.pipe.

NameTypeRequiredDescription
bufferSizenumberNoFrames the engine holds for the pipe before its reader attached (engine default when omitted).

Link to this sectionRemovedHook

Runs once for every accepted observer when it is removed. An error it throws is logged.

type RemovedHook = (obs: Observer) => void | Promise<void>

Link to this sectionStreamFrame

One frame of InputStream.frames: bytes, or a text message.

type StreamFrame = { type: "binary"; value: Buffer } | { type: "text"; value: string }

Link to this sectionStreamInfo

What an observer's target sees in place of a stream that the observed call carried in its input or output: that a stream was there, its direction and its channel id, without the access key (a stream has one reader, and it is the observed function). The engine still sends the key on the wire; the SDK drops it.

NameTypeRequiredDescription
direction"read" | "write"Yes-
idstringYes-
streamtrueYes-

Link to this sectionStreamRequest

Incoming streaming request received by a function that serves an HTTP route.

type StreamRequest = Omit<InternalHttpRequest<TBody>, "response">

Link to this sectionStreamResponse

Response object passed to streaming function handlers (the http helper of @iii-dev/helpers/http). Use status() and headers() to set response metadata, write() or stream for the body, and close() when done.

NameTypeRequiredDescription
close() => Promise<void>YesClose the response.
headers(headers: Record<string, string>) => Promise<void>YesSet response headers (a set_headers message on the response stream).
status(statusCode: number) => Promise<void>YesSet the HTTP status code (a set_status message on the response stream).
streamNodeJS.WritableStreamYesWritable stream for the response body; ending it ends the response.
write(chunk: Uint8Array | string) => Promise<void>YesWrite a chunk of the body.

Link to this sectionTarget

The right side of iii.observe: a registered function.

type Target = string | { function_id: string; namespace?: string }

Link to this sectionTelemetryOptions

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

NameTypeRequiredDescription
frameworkstringNoFramework name, if applicable.
languagestringNoProgramming language of the worker.
project_namestringNoName of the project this worker belongs to.

Link to this sectioniii-sdk/engine

EngineFunctions · EngineSources · RemoteFunctionHandler

Link to this sectionEngineFunctions

Engine function paths for internal operations.

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

Link to this sectionEngineSources

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.

NameTypeRequiredDescription
CONFIGURATION_UPDATED"configuration::on-updated"YesThe engine's configuration was reloaded.
FUNCTIONS_CHANGED"engine::on-functions-changed"YesA function was registered or unregistered; each row carries observer_count.
LOG"observability::on-log"YesA log record.
OBSERVERS_CHANGED"engine::on-observers-changed"YesAn observer changed state: { observer_id, function_id, target, state, reason? }.
SPAN"observability::on-span"YesA finished span.
WORKERS_CHANGED"engine::on-workers-changed"YesA worker connected or left.

Link to this sectionRemoteFunctionHandler

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.

type RemoteFunctionHandler = (data: TInput, metadata?: JsonValue) => TOutput | Promise<TOutput>

Link to this sectioniii-sdk/errors

InvocationError · InvocationErrorInit · ObserveRejection · RegistrationRejectedError · RegistrationRejectedInit · StreamAbortedError

Link to this sectionInvocationError

NameTypeRequiredDescription
codestringYes-
function_idstringNo-
stacktracestringNo-

Link to this sectionInvocationErrorInit

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.

NameTypeRequiredDescription
codestringYes-
function_idstringNo-
messagestringYes-
stacktracestringNo-

Link to this sectionObserveRejection

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.

NameTypeRequiredDescription
codestringYes-

Link to this sectionRegistrationRejectedError

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.

NameTypeRequiredDescription
codestringYes-
function_idstringNo-
namespacestringYes-
owner_worker_idstringYes-
worker_namestringNo-

Link to this sectionRegistrationRejectedInit

Fields used to construct a RegistrationRejectedError.

NameTypeRequiredDescription
codestringYes-
function_idstringNo-
namespacestringYes-
owner_worker_idstringYes-
worker_namestringNo-

Link to this sectionStreamAbortedError

A stream failed instead of ending: its writer aborted it (a source that threw, a handler that threw while writing, out.abort()), or its socket was lost. Thrown by the reads of an InputStream after the data sent before the abort, and the error a call rejects with when a sink it passed was aborted (code is STREAM_ABORTED in both cases).

reason is what the reader was told. Across the engine that is the engine's text (channel writer aborted: closed with code 1011), not the writer's own reason: the engine does not relay it.

NameTypeRequiredDescription
codestringYes-
function_idstringNo-
reasonstringYesWhy the stream was aborted, as the reader learned it.
stacktracestringNo-

Link to this sectioniii-sdk/protocol

ActivationWire · CallerWire · CallRequest · CaptureWire · ChannelDirection · ChannelItem · DroppedReportStatsWire · ErrorBody · FunctionRegisteredMessage · InvocationResultMessage · InvocationsObservedMessage · LocalFunctionStatsWire · LocalInvocationStatsMessage · MessageType · ObservedItemWire · ObserveMessage · ObserverAckMessage · ObserverAddedMessage · ObserveResultMessage · ObserverInfoWire · ObserverRemovedMessage · ObserverStateChangedMessage · ObserveSourceWire · RegisterFunctionFormat · RegisterFunctionInput · RegisterFunctionMessage · RegisterFunctionOptions · RegistrationRejectedMessage · StreamChannelRef · UnobserveMessage

Link to this sectionActivationWire

InvokeFunction.activation: present on every activation of an observer's target.

NameTypeRequiredDescription
activation_idstringNo-
observer_idstringYes-

Link to this sectionCallerWire

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

NameTypeRequiredDescription
function_idstringNo-
invocation_idstringNo-
parentOmit<CallerWire, "parent">No-
worker_idstringNo-
worker_namestringNo-

Link to this sectionCallRequest

Request object passed to IIIClient.call: a function by id, or the target of an observer.

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 }

Link to this sectionCaptureWire

What an observer captures (capture): the fields its target's payload carries, and with them the outcomes that fire it.

type CaptureWire = OpenEnum<"input" | "output" | "error" | "caller" | "metadata">

Link to this sectionChannelDirection

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

type ChannelDirection = typeof ChannelDirection[keyof typeof ChannelDirection]

Link to this sectionChannelItem

One frame of a channel: a binary frame carries bytes, a text frame a message. Mirrors the Rust SDK's ChannelItem enum (Text / Binary); InputStream.frames() yields these.

type ChannelItem = { type: "text"; value: string } | { type: "binary"; value: Uint8Array }

Link to this sectionDroppedReportStatsWire

NameTypeRequiredDescription
countnumberYes-
function_idstringYes-
reasonstringYesBUFFER_FULL | TOO_LARGE | INACTIVE (SDK-side drops).

Link to this sectionErrorBody

NameTypeRequiredDescription
codestringYes-
messagestringYes-
stacktracestringNo-

Link to this sectionFunctionRegisteredMessage

NameTypeRequiredDescription
idstringYes-
local_dispatchbooleanYes-
message_typeMessageType.FunctionRegisteredYes-
namespacestringYes-
observersObserverInfoWire[]Yes-
revisionnumberYes-

Link to this sectionInvocationResultMessage

NameTypeRequiredDescription
baggagestringNoW3C baggage header for cross-cutting context propagation
deliveredbooleanNoHost → engine (observe.v2): the function's deliver hook
(onObservationDeliver) delivered this routed call, and the engine
activates no observer for it. Sent only as true, and without
matched.
errorunknownNo-
function_idstringYesThe path of the function.
invocation_idstringYesThe id of the invocation
matchedstring[]NoHost → engine (observe.v2): the observers the function's match hook
(onObservationMatch) matched for this routed call, before their capture and
filters, which the engine evaluates; [] when it matched none. Left out
by a function without a match hook: the engine then evaluates every
active observer of the function.
message_typeMessageType.InvocationResultYes-
resultunknownNo-
traceparentstringNoW3C trace-context traceparent header for distributed tracing

Link to this sectionInvocationsObservedMessage

NameTypeRequiredDescription
itemsObservedItemWire[]Yes-
message_typeMessageType.InvocationsObservedYes-

Link to this sectionLocalFunctionStatsWire

NameTypeRequiredDescription
countnumberYes-
duration_ms_sumnumberNo-
errorsnumberNo-
function_idstringYes-

Link to this sectionLocalInvocationStatsMessage

NameTypeRequiredDescription
dropped_reportsDroppedReportStatsWire[]Yes-
functionsLocalFunctionStatsWire[]Yes-
message_typeMessageType.LocalInvocationStatsYes-
window_msnumberYes-

Link to this sectionMessageType

NameTypeRequiredDescription
FunctionRegistered"functionregistered"YesEngine → host: the registerfunction ack, with the function's full observer set.
InvocationResult"invocationresult"Yes-
InvocationsObserved"invocationsobserved"YesHost → engine: the calls of its functions that observers matched, batched.
InvokeFunction"invokefunction"Yes-
LocalInvocationStats"localinvocationstats"YesHost → engine: periodic counts of local invocations and report drops.
Observe"observe"YesObserving worker → engine: create (or idempotently replay) an observer.
ObserverAck"observerack"YesHost → engine: accept (or reject) an added observer.
ObserverAdded"observeradded"YesEngine → host: one observer attached to a function this connection hosts.
ObserveResult"observeresult"YesEngine → observing worker: the reply to observe (also on replay).
ObserverRemoved"observerremoved"YesEngine → host: one observer detached.
ObserverStateChanged"observerstatechanged"YesEngine → observing worker: an observer's lifecycle transition.
Reattach"reattach"Yes-
RegisterFunction"registerfunction"Yes-
RegistrationRejected"registrationrejected"Yes-
Unobserve"unobserve"YesObserving worker → engine: dispose an observer this connection owns.
UnregisterFunction"unregisterfunction"Yes-
WorkerRegistered"workerregistered"Yes-

Link to this sectionObservedItemWire

One local call of a hosted function, with the observers its delivery selected.

NameTypeRequiredDescription
baggagestringNo-
callerCallerWireNo-
duration_msnumberYes-
errorunknownNo-
function_idstringYes-
inputunknownNonull is a value here: absent means not captured or does not exist.
invocation_idstringYes-
matchedstring[]YesThe observers delivered.
metadataunknownNo-
namespacestringNo-
observe_depthnumberNo-
outputunknownNoAbsent with output_is_input: the engine fills it from input.
output_is_inputbooleanNoThe handler returned its input; left out when false.
started_at_msnumberYes-
statusOpenEnum<"success" | "error">Yes-
traceparentstringNo-

Link to this sectionObserveMessage

NameTypeRequiredDescription
expires_in_msnumberNo-
idstringYesClient-generated UUID, stable across replays.
max_firesnumberNo-
max_in_flightnumberNo-
message_typeMessageType.ObserveYes-
metadataRecord<string, unknown>No-
sourceObserveSourceWireYes-
target{ function_id: string; namespace?: string }Yes-

Link to this sectionObserverAckMessage

NameTypeRequiredDescription
errorErrorBodyNoRejects the observer (also a late rejection of an active one).
function_idstringYes-
idstringYes-
message_typeMessageType.ObserverAckYes-
namespacestringNo-
revisionnumberYes-

Link to this sectionObserverAddedMessage

NameTypeRequiredDescription
function_idstringYes-
message_typeMessageType.ObserverAddedYes-
namespacestringYes-
observerObserverInfoWireYes-
revisionnumberYes-

Link to this sectionObserveResultMessage

NameTypeRequiredDescription
errorErrorBodyNo-
idstringYes-
message_typeMessageType.ObserveResultYes-
stateObserverStateWireYes-
warningsstring[]No-

Link to this sectionObserverInfoWire

An observer as the host of its function sees it: never the observer's metadata, policy or connection. target is the target function id.

NameTypeRequiredDescription
argsRecord<string, unknown>Yes-
captureCaptureWire[]Yes-
filtersRecord<string, unknown>YesThe observer's filters, normalized by the engine. {} matches every call.
fires_onFiresWire[]NoThe outcomes that fire it, from an engine with observe.capture; absent from a 0.25 or rc engine.
idstringYes-
onstringNo-
targetstringYes-

Link to this sectionObserverRemovedMessage

NameTypeRequiredDescription
function_idstringYes-
idstringYes-
message_typeMessageType.ObserverRemovedYes-
namespacestringYes-
revisionnumberYes-

Link to this sectionObserverStateChangedMessage

NameTypeRequiredDescription
firesnumberYes-
idstringYes-
message_typeMessageType.ObserverStateChangedYes-
reasonErrorBodyNo-
stateObserverStateWireYes-

Link to this sectionObserveSourceWire

observe.source: the left side of iii.observe.

NameTypeRequiredDescription
argsRecord<string, unknown>No-
captureCaptureWire[]No-
filtersRecord<string, unknown>No-
function_idstringYes-
namespacestringNo-

Link to this sectionRegisterFunctionFormat

NameTypeRequiredDescription
descriptionstringNoThe description of the parameter.
itemsunknownNoThe items of the parameter (for arrays).
namestringNoThe name of the parameter.
propertiesRecord<string, unknown>NoThe body of the parameter (for objects).
requiredstring[]NoWhether the parameter is required.
type"string" | "number" | "boolean" | "object" | "array" | "null" | "map" | "integer"NoThe type of the parameter.
[key: string]unknownNo-

Link to this sectionRegisterFunctionInput

type RegisterFunctionInput = Omit<RegisterFunctionMessage, "message_type">
NameTypeRequiredDescription
args_formatRegisterFunctionFormatNoJSON 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.
descriptionstringNoHuman-readable summary of the function, listed by discovery
(engine::functions::list).
idstringYesThe path of the function (use :: for namespacing, e.g. external::my_lambda).
invocationHttpInvocationConfigNoHTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.).
metadataRecord<string, unknown>NoArbitrary 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.
observablebooleanNofalse: nobody may observe the function (NOT_OBSERVABLE), for one
whose payloads carry credentials. Default true; sent only when false.
privatebooleanNoOnly 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.
request_formatRegisterFunctionFormatNoJSON Schema of the call's input.
response_formatRegisterFunctionFormatNoJSON Schema of the handler's return value: what the function's observers
observe.

Link to this sectionRegisterFunctionMessage

NameTypeRequiredDescription
args_formatRegisterFunctionFormatNoJSON 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.
descriptionstringNoHuman-readable summary of the function, listed by discovery
(engine::functions::list).
idstringYesThe path of the function (use :: for namespacing, e.g. external::my_lambda).
invocationHttpInvocationConfigNoHTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.).
message_typeMessageType.RegisterFunctionYes-
metadataRecord<string, unknown>NoArbitrary 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.
observablebooleanNofalse: nobody may observe the function (NOT_OBSERVABLE), for one
whose payloads carry credentials. Default true; sent only when false.
privatebooleanNoOnly 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.
request_formatRegisterFunctionFormatNoJSON Schema of the call's input.
response_formatRegisterFunctionFormatNoJSON Schema of the handler's return value: what the function's observers
observe.

Link to this sectionRegisterFunctionOptions

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.

type RegisterFunctionOptions = Omit<RegisterFunctionMessage, "message_type" | "id"> & { localDispatch?: boolean }
NameTypeRequiredDescription
args_formatRegisterFunctionFormatNoJSON 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.
descriptionstringNoHuman-readable summary of the function, listed by discovery
(engine::functions::list).
invocationHttpInvocationConfigNoHTTP invocation config for external HTTP functions (Lambda, Cloudflare Workers, etc.).
localDispatchbooleanNoCalls 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.
metadataRecord<string, unknown>NoArbitrary 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.
observablebooleanNofalse: nobody may observe the function (NOT_OBSERVABLE), for one
whose payloads carry credentials. Default true; sent only when false.
privatebooleanNoOnly 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.
request_formatRegisterFunctionFormatNoJSON Schema of the call's input.
response_formatRegisterFunctionFormatNoJSON Schema of the handler's return value: what the function's observers
observe.

Link to this sectionRegistrationRejectedMessage

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.
NameTypeRequiredDescription
codestringYesMachine-readable rejection code.
function_idstringNoThe refused function. Present on every rejection of one function.
message_typeMessageType.RegistrationRejectedYes-
namespacestringYesNamespace of the refused registration.
owner_worker_idstringYesID of the live worker that already owns the contested identity; "" on a rejection that is not a conflict.
worker_namestringNoContested worker name. Present only for WORKER_NAMESPACE_CONFLICT.

Link to this sectionStreamChannelRef

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

NameTypeRequiredDescription
access_keystringYesAccess key for authentication.
channel_idstringYesUnique channel identifier.
direction"read" | "write"YesWhether this ref is for reading or writing.

Link to this sectionUnobserveMessage

NameTypeRequiredDescription
idstringYes-
message_typeMessageType.UnobserveYes-

Link to this sectioniii-sdk/runtime

FunctionRef · IIIConnectionState

Link to this sectionFunctionRef

Handle returned by IIIClient.registerFunction: the client's hook methods with the function id filled in. Each method returns the handle, so calls chain.

NameTypeRequiredDescription
idstringYesThe unique function identifier.
isObserved(call?: Partial<Call<I, unknown>>) => booleanYesIIIClient.isObserved for this registration: skip building an event
nobody receives. Without a call it is one load of this registration's
active set.
observers() => readonly Observer[]YesThe active observers of this registration, as this host sees them (none
once the function is unregistered, also after the id is registered again).
onObservationDeliver(hook: DeliverHook<I, O, R> | null) => FunctionRef<I, O>YesIIIClient.onObservationDeliver for this function.
onObservationMatch(hook: MatchHook<I, O> | null) => FunctionRef<I, O>YesIIIClient.onObservationMatch for this function.
onObserverAdded(hook: AddedHook | null) => FunctionRef<I, O>YesIIIClient.onObserverAdded for this function.
onObserverRemoved(hook: RemovedHook | null) => FunctionRef<I, O>YesIIIClient.onObserverRemoved for this function.
unregister() => voidYesRemoves this function from the engine. Its hooks stay in place for a later registration of the id.

Link to this sectionIIIConnectionState

Connection state for the III WebSocket

type IIIConnectionState = "disconnected" | "connecting" | "connected" | "reconnecting" | "failed"

Link to this sectioniii-sdk/state

IState · StateDeleteInput · StateDeleteResult · StateEventData · StateEventType · StateGetInput · StateListInput · StateSetInput · StateSetResult · StateUpdateInput · StateUpdateResult

Link to this sectionIState

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

NameTypeRequiredDescription
delete(input: StateDeleteInput) => Promise<StateDeleteResult>YesDelete a state value.
get(input: StateGetInput) => Promise<TData | null>YesRetrieve a value by scope and key.
list(input: StateListInput) => Promise<TData[]>YesList all values in a scope.
set(input: StateSetInput) => Promise<StateSetResult<TData> | null>YesSet (create or overwrite) a state value.
update(input: StateUpdateInput) => Promise<StateUpdateResult<TData> | null>YesApply atomic update operations to a state value.

Link to this sectionStateDeleteInput

Input for deleting a state value.

NameTypeRequiredDescription
keystringYesKey within the scope.
scopestringYesState scope (namespace).

Link to this sectionStateDeleteResult

Result of a state delete operation.

NameTypeRequiredDescription
old_valueanyNoPrevious value (if it existed).

Link to this sectionStateEventData

Payload for state change events.

NameTypeRequiredDescription
event_typeStateEventTypeYesType of state change.
keystringYesKey within the scope.
new_valueTDataNoNew value (for create/update events).
old_valueTDataNoPrevious value (for update/delete events).
scopestringYesState scope (namespace).
type"state"Yes-

Link to this sectionStateEventType

Types of state change events.

NameTypeRequiredDescription
Created"state:created"Yes-
Deleted"state:deleted"Yes-
Updated"state:updated"Yes-

Link to this sectionStateGetInput

Input for retrieving a state value.

NameTypeRequiredDescription
keystringYesKey within the scope.
scopestringYesState scope (namespace).

Link to this sectionStateListInput

Input for listing all values in a state scope.

NameTypeRequiredDescription
scopestringYesState scope (namespace).

Link to this sectionStateSetInput

Input for setting a state value.

NameTypeRequiredDescription
keystringYesKey within the scope.
scopestringYesState scope (namespace).
valueanyYesValue to store.

Link to this sectionStateSetResult

Result of a state set operation.

NameTypeRequiredDescription
new_valueTDataYesNew value that was stored.
old_valueTDataNoPrevious value (if it existed).

Link to this sectionStateUpdateInput

Input for atomically updating a state value.

NameTypeRequiredDescription
keystringYesKey within the scope.
opsUpdateOp[]YesOrdered list of update operations to apply atomically.
scopestringYesState scope (namespace).

Link to this sectionStateUpdateResult

Result of a state update operation.

NameTypeRequiredDescription
errorsUpdateOpError[]NoPer-op errors. Currently emitted only by the merge op when input
violates the validation bounds. See UpdateOpError and the
UpdateMerge JSDoc in ./stream for the error codes. Field is
omitted from the JSON wire when empty.
new_valueTDataYesNew value after the update.
old_valueTDataNoPrevious value (if it existed).