Skip to main content

Installation

npm install iii-sdk

Initialization

registerWorker

Creates and returns a connected SDK instance. The WebSocket connection is established automatically — there is no separate connect() call. Signature
registerWorker(address: string, options: InitOptions) => IIIClient

Parameters

NameTypeRequiredDescription
addressstringYesWebSocket URL of the III engine (e.g. ws://localhost:49134).
optionsInitOptionsYesOptional InitOptions for worker name, timeouts, reconnection, and OTel.

Example

import { registerWorker } from 'iii-sdk'

const worker = registerWorker(process.env.III_URL ?? 'ws://localhost:49134', {
  workerName: 'my-worker',
})

Methods

registerTrigger

Registers a new trigger. A trigger is a way to invoke a function when a certain event occurs. Signature
registerTrigger(trigger: RegisterTriggerInput) => Trigger

Parameters

NameTypeRequiredDescription
triggerRegisterTriggerInputYesThe trigger to register

Example

const trigger = worker.registerTrigger({
  type: 'cron',
  function_id: 'my-service::process-batch',
  config: { expression: '0 */5 * * * * *' },
})

// Later, remove the trigger
trigger.unregister()

registerFunction

Registers a new function with a local handler or an HTTP invocation config. Signature
registerFunction(functionId: string, handler: HttpInvocationConfig | RemoteFunctionHandler<any, any>, options: RegisterFunctionOptions) => FunctionRef

Parameters

NameTypeRequiredDescription
functionIdstringYesUnique function identifier
handlerHttpInvocationConfig | RemoteFunctionHandler<any, any>YesAsync handler for local execution, or an HTTP invocation config for external functions (Lambda, Cloudflare Workers, etc.)
optionsRegisterFunctionOptionsYesOptional function registration options (description, request/response formats, metadata)

Example

// Local handler
const ref = worker.registerFunction(
  'greet',
  async (data: { name: string }) => ({ message: `Hello, ${data.name}!` }),
  { description: 'Returns a greeting' },
)

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

// Later, remove the function
ref.unregister()

trigger

Invokes a function using a request object. Signature
trigger(request: TriggerRequest<TInput>) => Promise<TOutput>

Parameters

NameTypeRequiredDescription
requestTriggerRequest<TInput>YesThe trigger request containing function_id, payload, and optional action/timeout

Example

// Synchronous invocation
const result = await worker.trigger<{ name: string }, { message: string }>({
  function_id: 'greet',
  payload: { name: 'World' },
  timeoutMs: 5000,
})
console.log(result.message) // "Hello, World!"

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

// Enqueue for async processing
const receipt = await worker.trigger({
  function_id: 'process-order',
  payload: { orderId: '123' },
  action: TriggerAction.Enqueue({ queue: 'orders' }),
})

registerTriggerType

Registers a new trigger type. A trigger type is a way to invoke a function when a certain event occurs. Signature
registerTriggerType(triggerType: RegisterTriggerTypeInput, handler: TriggerHandler<TConfig>) => TriggerTypeRef<TConfig>

Parameters

NameTypeRequiredDescription
triggerTypeRegisterTriggerTypeInputYesThe trigger type to register
handlerTriggerHandler<TConfig>YesThe handler for the trigger type

Example

type CronConfig = { expression: string }

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

unregisterTriggerType

Unregisters a trigger type. Signature
unregisterTriggerType(triggerType: RegisterTriggerTypeInput) => void

Parameters

NameTypeRequiredDescription
triggerTypeRegisterTriggerTypeInputYesThe trigger type to unregister

Example

worker.unregisterTriggerType({ id: 'cron', description: 'Fires on a cron schedule' })

shutdown

Gracefully shutdown the iii, cleaning up all resources. Signature
shutdown() => Promise<void>

Example

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

Subpath Exports

The iii-sdk package provides additional entry points:
Import pathContents
iii-sdk/channelChannel, ChannelReader, ChannelWriter, StreamChannelRef
iii-sdk/engineEngineFunctions, EngineTriggers, RemoteFunctionHandler
iii-sdk/errorsInvocationError, InvocationErrorInit, isErrorBody
iii-sdk/helpersChannelDirection, ChannelItem, createChannel, createStream, extractChannelRefs, isChannelRef
iii-sdkEnqueueResult, IIIClient, InitOptions, MiddlewareFunctionInput, StreamRequest, StreamResponse, TelemetryOptions, TriggerAction, registerWorker
iii-sdk/internalInternalHttpRequest
iii-sdk/protocolErrorBody, MessageType, RegisterFunctionFormat, RegisterFunctionInput, RegisterFunctionMessage, RegisterFunctionOptions, RegisterTriggerInput, RegisterTriggerMessage, RegisterTriggerTypeInput, RegisterTriggerTypeMessage, etc.
iii-sdk/runtimeFunctionRef, IIIConnectionState, TriggerTypeRef
iii-sdk/stateIState, StateDeleteInput, StateDeleteResult, StateEventData, StateEventType, StateGetInput, StateListInput, StateSetInput, StateSetResult, StateUpdateInput, etc.
iii-sdk/streamIStream
iii-sdk/triggerTrigger, TriggerConfig, TriggerHandler

Types

iii-sdk

EnqueueResult · InitOptions · MiddlewareFunctionInput · StreamRequest · StreamResponse · TelemetryOptions

EnqueueResult

Result returned when a function is invoked with TriggerAction.Enqueue.
NameTypeRequiredDescription
messageReceiptIdstringYesUnique receipt ID for the enqueued message.

InitOptions

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.
invocationTimeoutMsnumberNoDefault timeout for trigger() in milliseconds. Defaults to 30000.
otelOmit<OtelConfig, "engineWsUrl">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.
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. Defaults to hostname:pid.

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.
NameTypeRequiredDescription
actionTriggerActionNoRouting action, if any.
contextRecord<string, unknown>YesAuth context returned by the auth function for this session.
function_idstringYesID of the function being invoked.
payloadRecord<string, unknown>YesPayload sent by the caller.

StreamRequest

Incoming streaming request received by a function registered with a stream trigger.
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.
NameTypeRequiredDescription
close() => voidYesClose the response.
headers(headers: Record<string, string>) => voidYesSet response headers.
status(statusCode: number) => voidYesSet the HTTP status code.
streamNodeJS.WritableStreamYesWritable stream for the response body.

TelemetryOptions

Worker labels reported to the engine (language, framework, project).
NameTypeRequiredDescription
amplitude_api_keystringNo-
frameworkstringNo-
languagestringNo-
project_namestringNo-

iii-sdk/channel

Channel · ChannelReader · ChannelWriter · StreamChannelRef

Channel

A streaming channel pair for worker-to-worker data transfer. Created via the createChannel helper from iii-sdk/helpers.
NameTypeRequiredDescription
readerChannelReaderYesReader end of the channel.
readerRefStreamChannelRefYesSerializable reference to the reader (can be sent to other workers).
writerChannelWriterYesWriter end of the channel.
writerRefStreamChannelRefYesSerializable 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.
NameTypeRequiredDescription
streamReadableYesNode.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.
NameTypeRequiredDescription
streamWritableYesNode.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.
NameTypeRequiredDescription
access_keystringYesAccess key for authentication.
channel_idstringYesUnique channel identifier.
direction"read" | "write"YesWhether this ref is for reading or writing.

iii-sdk/engine

RemoteFunctionHandler

RemoteFunctionHandler

Async function handler for a registered function. Receives the invocation payload and returns the result.
type RemoteFunctionHandler = (data: TInput) => Promise<TOutput>

iii-sdk/errors

InvocationError · InvocationErrorInit

InvocationError

NameTypeRequiredDescription
codestringYes-
function_idstringNo-
stacktracestringNo-

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.
NameTypeRequiredDescription
codestringYes-
function_idstringNo-
messagestringYes-
stacktracestringNo-

iii-sdk/helpers

ChannelDirection · ChannelItem

ChannelDirection

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]

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.
type ChannelItem = { type: "text"; value: string } | { type: "binary"; value: Uint8Array }

iii-sdk/internal

InternalHttpRequest

InternalHttpRequest

NameTypeRequiredDescription
bodyTBodyYes-
headersRecord<string, string | string[]>Yes-
methodstringYes-
path_paramsRecord<string, string>Yes-
query_paramsRecord<string, string | string[]>Yes-
request_bodyChannelReaderYes-
responseChannelWriterYes-

iii-sdk/protocol

ErrorBody · MessageType · RegisterFunctionFormat · RegisterFunctionInput · RegisterFunctionMessage · RegisterFunctionOptions · RegisterTriggerInput · RegisterTriggerMessage · RegisterTriggerTypeInput · RegisterTriggerTypeMessage · TriggerRequest

ErrorBody

NameTypeRequiredDescription
codestringYes-
messagestringYes-
stacktracestringNo-

MessageType

NameTypeRequiredDescription
InvocationResult"invocationresult"Yes-
InvokeFunction"invokefunction"Yes-
RegisterFunction"registerfunction"Yes-
RegisterTrigger"registertrigger"Yes-
RegisterTriggerType"registertriggertype"Yes-
TriggerRegistrationResult"triggerregistrationresult"Yes-
UnregisterFunction"unregisterfunction"Yes-
UnregisterTrigger"unregistertrigger"Yes-
UnregisterTriggerType"unregistertriggertype"Yes-
WorkerRegistered"workerregistered"Yes-

RegisterFunctionFormat

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

RegisterFunctionInput

type RegisterFunctionInput = Omit<RegisterFunctionMessage, "message_type">

RegisterFunctionMessage

NameTypeRequiredDescription
descriptionstringNoThe description of the function
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>No-
request_formatRegisterFunctionFormatNoThe request format of the function
response_formatRegisterFunctionFormatNoThe response format of the function

RegisterFunctionOptions

type RegisterFunctionOptions = Omit<RegisterFunctionMessage, "message_type" | "id">

RegisterTriggerInput

type RegisterTriggerInput = Omit<RegisterTriggerMessage, "message_type" | "id">

RegisterTriggerMessage

NameTypeRequiredDescription
configunknownYes-
function_idstringYes-
idstringYes-
message_typeMessageType.RegisterTriggerYes-
metadataRecord<string, unknown>No-
typestringYes-

RegisterTriggerTypeInput

type RegisterTriggerTypeInput = Omit<RegisterTriggerTypeMessage, "message_type">

RegisterTriggerTypeMessage

NameTypeRequiredDescription
descriptionstringYes-
idstringYes-
message_typeMessageType.RegisterTriggerTypeYes-

TriggerRequest

Request object passed to IIIClient.trigger.
NameTypeRequiredDescription
actionTriggerActionNoRouting action. Omit for synchronous request/response.
function_idstringYesID of the function to invoke.
payloadTInputYesPayload to pass to the function.
timeoutMsnumberNoOverride the default invocation timeout in milliseconds.

iii-sdk/runtime

FunctionRef · IIIConnectionState · TriggerTypeRef

FunctionRef

Handle returned by IIIClient.registerFunction. Contains the function’s id and an unregister() method.
NameTypeRequiredDescription
idstringYesThe unique function identifier.
unregister() => voidYesRemoves this function from the engine.

IIIConnectionState

Connection state for the III WebSocket
type IIIConnectionState = "disconnected" | "connecting" | "connected" | "reconnecting" | "failed"

TriggerTypeRef

Typed handle returned by IIIClient.registerTriggerType. Provides convenience methods to register triggers and functions scoped to this trigger type, so callers don’t need to repeat the type field.
NameTypeRequiredDescription
idstringYesThe trigger type identifier.
registerFunctionFunctionRefYesRegister a function and immediately bind it to this trigger type.
registerTriggerTriggerYesRegister a trigger bound to this trigger type.
unregistervoidYesUnregister this trigger type from the engine.

iii-sdk/state

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

IState

Interface for state management operations. Available via the iii-sdk/state subpath export.
NameTypeRequiredDescription
deletePromise<StateDeleteResult>YesDelete a state value.
getPromise<TData | null>YesRetrieve a value by scope and key.
listPromise<TData[]>YesList all values in a scope.
setPromise<StateSetResult<TData> | null>YesSet (create or overwrite) a state value.
updatePromise<StateUpdateResult<TData> | null>YesApply atomic update operations to a state value.

StateDeleteInput

Input for deleting a state value.
NameTypeRequiredDescription
keystringYesKey within the scope.
scopestringYesState scope (namespace).

StateDeleteResult

Result of a state delete operation.
NameTypeRequiredDescription
old_valueanyNoPrevious value (if it existed).

StateEventData

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-

StateEventType

Types of state change events.
NameTypeRequiredDescription
Created"state:created"Yes-
Deleted"state:deleted"Yes-
Updated"state:updated"Yes-

StateGetInput

Input for retrieving a state value.
NameTypeRequiredDescription
keystringYesKey within the scope.
scopestringYesState scope (namespace).

StateListInput

Input for listing all values in a state scope.
NameTypeRequiredDescription
scopestringYesState scope (namespace).

StateSetInput

Input for setting a state value.
NameTypeRequiredDescription
keystringYesKey within the scope.
scopestringYesState scope (namespace).
valueanyYesValue to store.

StateSetResult

Result of a state set operation.
NameTypeRequiredDescription
new_valueTDataYesNew value that was stored.
old_valueTDataNoPrevious value (if it existed).

StateUpdateInput

Input for atomically updating a state value.
NameTypeRequiredDescription
keystringYesKey within the scope.
opsUpdateOp[]YesOrdered list of update operations to apply atomically.
scopestringYesState scope (namespace).

StateUpdateResult

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

iii-sdk/stream

IStream

IStream

Interface for custom stream implementations. Passed to IIIClient.createStream to override the engine’s built-in stream storage.
NameTypeRequiredDescription
deletePromise<StreamDeleteResult>YesDelete a stream item.
getPromise<TData | null>YesRetrieve a single item by group and item ID.
listPromise<TData[]>YesList all items in a group.
listGroupsPromise<string[]>YesList all group IDs in a stream.
setPromise<StreamSetResult<TData> | null>YesSet (create or overwrite) a stream item.
updatePromise<StreamUpdateResult<TData> | null>YesApply atomic update operations to a stream item.

iii-sdk/trigger

Trigger · TriggerConfig · TriggerHandler

Trigger

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

TriggerConfig

Configuration passed to a trigger handler when a trigger instance is registered or unregistered.
NameTypeRequiredDescription
configTConfigYesTrigger-specific configuration.
function_idstringYesFunction to invoke when the trigger fires.
idstringYesTrigger instance ID.
metadataRecord<string, unknown>NoArbitrary metadata attached to the trigger.

TriggerHandler

Handler interface for custom trigger types. Passed to IIIClient.registerTriggerType.
NameTypeRequiredDescription
registerTriggerPromise<void>YesCalled when a trigger instance is registered.
unregisterTriggerPromise<void>YesCalled when a trigger instance is unregistered.