npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ironflow/core

v0.60.0

Published

Core types, schemas, and protocol definitions for Ironflow SDK

Readme

@ironflow/core

Shared types, Zod schemas, error classes, constants, and utilities for the Ironflow JavaScript SDK. This package is the foundation that both @ironflow/browser and @ironflow/node depend on. It contains zero platform-specific code and runs in any JavaScript environment.

  • Source: sdk/js/core/src/
  • Entry point: @ironflow/core (re-exports everything from index.ts)
  • Sub-path exports: @ironflow/core/schemas, @ironflow/core/protocol, @ironflow/core/gen
  • Runtime dependency: zod (v4+)
  • Optional dependencies: @bufbuild/protobuf, @connectrpc/connect (only for /gen sub-path)
  • License: LicenseRef-Ironflow-EULA (see LICENSE)

Docs: https://docs.ironflow.run


Table of Contents

  1. Installation
  2. Branded Types
  3. Function Types
  4. Event Types
  5. Step Types
  6. Run Types
  7. Subscription Types
  8. Entity Stream Types
  9. Pub/Sub Types
  10. KV Types
  11. Config Types
  12. Auth Types
  13. Audit Types
  14. Webhook Types
  15. Projection Types
  16. Error Classes
  17. Schemas
  18. Protocol Types
  19. Constants
  20. Utilities
  21. Upcasters
  22. Logger
  23. SecretsClient
  24. Paused State Types
  25. Time-Travel Debugging Types
  26. Server Capabilities
  27. Secrets Management Types
  28. Entity Stream Extension Types
  29. Project / Environment Types
  30. Event Schema Registry Types
  31. Webhook Management Types
  32. User and Tenant Types
  33. File Storage Types
  34. Admin Helpers
  35. Convenience Aliases
  36. Sub-Path Exports

Installation

npm install @ironflow/core

Most users do not install this package directly. It is included as a dependency of @ironflow/browser (browser client, subscriptions) and @ironflow/node (worker, serve, projections), both of which re-export core types.


Branded Types

Branded types provide compile-time type safety for ID strings. A RunId cannot be accidentally passed where a FunctionId is expected.

import type {
  RunId, FunctionId, StepId, EventId, JobId, WorkerId, SubscriptionId,
  Branded,
} from '@ironflow/core';

import {
  createRunId, createFunctionId, createStepId,
  createEventId, createJobId, createWorkerId, createSubscriptionId,
} from '@ironflow/core';

Factory Functions

Each factory casts a plain string to the branded type at zero runtime cost:

const runId: RunId = createRunId('run_abc123');
const fnId: FunctionId = createFunctionId('my-workflow');
const stepId: StepId = createStepId('step_001');
const eventId: EventId = createEventId('evt_xyz');
const jobId: JobId = createJobId('job_456');
const workerId: WorkerId = createWorkerId('wkr_789');
const subId: SubscriptionId = createSubscriptionId('sub_012');

Branded Helper

You can create your own branded types:

type OrderId = Branded<string, 'OrderId'>;

Function Types

FunctionConfig

Full configuration for a workflow function.

import type { FunctionConfig } from '@ironflow/core';

interface FunctionConfig<TEventSchema extends z.ZodType = z.ZodType> {
  /** Unique function identifier */
  id: string;
  /** Display name for the function */
  name?: string;
  /** Human-readable description shown in the dashboard */
  description?: string;
  /** Event triggers that invoke this function */
  triggers: Trigger[];
  /** Retry configuration for failed steps */
  retry?: RetryConfig;
  /** Function timeout in milliseconds (unset: no per-function budget) */
  timeout?: number;
  /** Concurrency control configuration */
  concurrency?: ConcurrencyConfig;
  /** Circuit breaker overrides; unset fields use the server defaults */
  circuitBreaker?: CircuitBreakerConfig;
  /** Soft start-rate limit; runs over the limit wait in the queue */
  throttle?: ThrottleConfig;
  /** Debounce configuration — collapse rapid-fire events into a single invocation */
  debounce?: DebounceConfig;
  /** Execution mode: "push" for serverless, "pull" for workers */
  mode?: ExecutionMode;
  /** JSON path for an actor key; stored by the server, not used for routing yet */
  actorKey?: string;
  /** Zod schema; validated at runtime before the handler runs */
  schema?: TEventSchema;
  /** Secret names this function requires (resolved by engine at execution time) */
  secrets?: string[];
  /** Default timeout for all step.run() calls ("30s", "5m", "1h") */
  stepTimeout?: string;
  /** Enable audit recording for this function */
  recording?: boolean;
  /** Select the workflow audit event families captured for this function */
  recordingProfile?: RecordingProfile;
  /** Cancel-on-event specs (OR semantic). Auto-cancels run with cause "cancel-on-event". */
  cancelOn?: CancelOnConfig[];
  /** Custom metadata (e.g., service, team, owner) */
  metadata?: Record<string, unknown>;
}

CancelOnConfig

Auto-cancel a running workflow when a matching event arrives (issue #546 P3 / #572).

interface CancelOnConfig {
  /** Event name to match (e.g., "order.cancelled") */
  event: string;
  /** JSON-path that must equal the running run's corresponding field */
  match: string;
}
const cancelOn: CancelOnConfig[] = [
  { event: 'order.cancelled', match: 'orderId' }, // path inside event.data
];

Trigger

interface Trigger {
  /** Event name pattern to match (e.g., "order.placed") */
  event: string;
  /** Optional CEL expression for filtering */
  expression?: string;
  /** Cron schedule expression (e.g., "0 9 * * *" for 9am daily) */
  cron?: string;
}

RetryConfig

interface RetryConfig {
  /** Total attempts, including the first (server default: 25) */
  maxAttempts?: number;
  /** Initial delay between retries in ms (server default: 1000) */
  initialDelayMs?: number;
  /** Backoff multiplier (server default: 2.0) */
  backoffFactor?: number;
  /** Maximum delay between retries in ms (server default: 300000) */
  maxDelayMs?: number;
  /** What happens when a retryable failure has used every attempt (server default: "pause") */
  onExhausted?: OnExhausted;
}

type OnExhausted = "pause" | "fail";

Only the fields you set are sent; the server applies its defaults to the rest when each run is created. "pause" holds the run, with its completed steps, until it is resumed. "fail" ends the run and runs its compensations. A non-retryable error always fails at once.

CircuitBreakerConfig

interface CircuitBreakerConfig {
  /** Consecutive failed attempts that open the circuit (server default: 5) */
  failureThreshold?: number;
  /** First open window in ms; each failed probe doubles it (server default: 60000) */
  openDurationMs?: number;
  /** Cap for the doubling window in ms (server default: 600000); at least openDurationMs */
  maxOpenDurationMs?: number;
}

ThrottleConfig

interface ThrottleConfig {
  /** Runs allowed to start per period. At least 1 */
  limit: number;
  /** Window length in ms. At least 1000 */
  periodMs: number;
  /** Path into the event data to throttle per value; omit to throttle the whole function */
  key?: string;
}

A soft throttle: runs over the limit wait in the queue and are never dropped. Retries and resumed runs are not throttled.

ConcurrencyConfig

interface ConcurrencyConfig {
  /** Maximum concurrent executions */
  limit: number;
  /** Path into the event data payload for grouping (e.g., "customerId") */
  key?: string;
}

DebounceConfig

Collapses rapid-fire events into a single invocation after a quiet period. Async-only — TriggerSync rejects debounced functions with FailedPrecondition.

interface DebounceConfig {
  /** Quiet period in milliseconds. Floor: 1000 (1 second). */
  periodMs: number;
  /** JSON path for per-key debouncing (e.g., "userId"). Omit for a global lane. */
  key?: string;
  /**
   * Optional starvation cap. Handler fires at least once every maxWaitMs
   * even under continuous resets. Must be >= periodMs. Omit for no cap.
   */
  maxWaitMs?: number;
}

Example — debounce search-as-you-type events per user for 5 seconds:

const processSearch = ironflow.createFunction(
  {
    id: "process-search",
    triggers: [{ event: "search.requested" }],
    debounce: { periodMs: 5000, key: "userId" },
  },
  async ({ event, step }) => {
    /* ... */
  }
);

ExecutionMode

type ExecutionMode = "push" | "pull";
  • "push" -- HTTP POST to serverless functions (Next.js, Lambda). For tasks under 10 seconds.
  • "pull" -- gRPC/HTTP polling for long-running workers. No timeout limits.

RecordingProfile

type RecordingProfile = "all" | "run_lifecycle" | "steps";

Which workflow audit event families a function captures. Setting a profile enables recording on its own -- recording: true is equivalent to recordingProfile: "all".

FunctionContext

Context object passed to every function handler.

interface FunctionContext<TEvent = unknown> {
  /** The triggering event */
  event: IronflowEvent<TEvent>;
  /** Step execution client */
  step: StepClient;
  /** Run information */
  run: RunInfo;
  /** Logger instance */
  logger: Logger;
  /** Resolved environment secrets (read-only) */
  secrets: SecretsClient;
}

FunctionHandler and IronflowFunction

type FunctionHandler<TEvent = unknown, TResult = unknown> = (
  ctx: FunctionContext<TEvent>
) => Promise<TResult>;

interface IronflowFunction<TEvent = unknown, TResult = unknown> {
  config: FunctionConfig;
  handler: FunctionHandler<TEvent, TResult>;
}

Usage (typically via @ironflow/node's createFunction()):

import { createFunction } from '@ironflow/node';

const myWorkflow = createFunction({
  id: 'process-order',
  triggers: [{ event: 'order.placed' }],
  retry: { maxAttempts: 5 },
  concurrency: { limit: 10, key: 'customerId' }, // path into event.data
  mode: 'pull',
  secrets: ['STRIPE_KEY'],
  stepTimeout: '30s',
}, async ({ event, step, logger, secrets }) => {
  const charge = await step.run('charge', async () => {
    return stripe.charges.create({ amount: event.data.amount });
  });
  return { chargeId: charge.id };
});

RegisteredFunction

The server-side view of a function, returned by getFunction / listFunctions.

interface RegisteredFunction {
  id: string;
  name: string;
  description: string;
  triggers: Trigger[];
  retry?: RetryConfig;
  timeoutMs: number;
  concurrency?: ConcurrencyConfig;
  debounce?: DebounceConfig;
  preferredMode?: ExecutionMode;
  endpointUrl: string;
  actorKey: string;
  status: FunctionStatus;
  version: number;
  createdAt: Date;
  updatedAt: Date;
  recording: boolean;
  recordingProfile?: RecordingProfile;
  metadata?: Record<string, unknown>;
  cancelOn: CancelOnConfig[];
}

type FunctionStatus = "active" | "paused" | "archived" | "unspecified";

Function History

type FunctionChangeType =
  | "created"
  | "update"
  | "status_change"
  | "rollback"
  | "delete";

interface FunctionHistoryEntry {
  eventId: string;
  entityVersion: number;
  functionId: string;
  functionSnapshot?: RegisteredFunction;
  actorId: string;
  changeReason: string;
  changeType: FunctionChangeType;
  recordedAt: Date;
}

interface ListFunctionHistoryOptions {
  limit?: number;
  fromVersion?: number;
}

interface ListFunctionHistoryResult {
  entries: FunctionHistoryEntry[];
  hasMore: boolean;
}

Event Types

IronflowEvent

interface IronflowEvent<T = unknown> {
  /** Unique event ID */
  id: string;
  /** Event name (e.g., "order.placed") */
  name: string;
  /** Event schema version */
  version: number;
  /** Event payload data */
  data: T;
  /** Event timestamp */
  timestamp: Date;
  /** Optional idempotency key for deduplication */
  idempotencyKey?: string;
  /** Event source (e.g., "webhook", "sdk", "api") */
  source?: string;
  /** Additional metadata */
  metadata?: Record<string, unknown>;
  /**
   * Authenticated emitter the engine recorded (e.g. "apikey:<id>", "user:<id>",
   * "webhook:<source-id>", "nats", "platform"). Set by the engine from the
   * caller's credential. Only on events returned by waiting steps.
   */
  emittedBy?: string;
}

EventSource Constants

import { EventSource, type EventSourceType } from '@ironflow/core';

EventSource.API       // "api"
EventSource.CRON      // "cron"
EventSource.WEBHOOK   // "webhook"

// EventSourceType is the union of the EventSource values
const src: EventSourceType = EventSource.API;

EventFilter

Used with step.waitForEvent().

interface EventFilter {
  /** Request payload stored as the waiting step input, visible via getRunSteps and the dashboard. */
  payload?: unknown;
  /** Event name to wait for */
  event: string;
  /** JSON path for matching (e.g., "data.orderId"), not an expression. */
  match?: string;
  /** Non-empty literal compared at match; omitted/empty snapshots the triggering event. Requires match. */
  matchValue?: string;
  /** Timeout duration (default: "7d") */
  timeout?: Duration;
}

EmitOptions and EmitResult

interface EmitOptions {
  /** Event schema version (default 1) */
  version?: number;
  /** Optional deduplication key */
  idempotencyKey?: string;
  /** Optional metadata (headers, etc.) */
  metadata?: Record<string, unknown>;
}

interface EmitResult {
  /** IDs of runs created by this event */
  runIds: string[];
  /** ID of the stored event */
  eventId: string;
}

/** One run's outcome. `emitSync()` returns `EmitSyncResult[]` -- one per
 *  matched trigger -- and never throws on a run outcome. */
interface EmitSyncResult {
  /** ID of the triggered run */
  runId: string;
  /** ID of the function that handled the event */
  functionId: string;
  /** Final run status */
  status: RunStatus;
  /** Function return value */
  output: unknown;
  /** Present when the run failed */
  error?: { message: string; code?: string };
  /** Wall-clock duration in milliseconds */
  durationMs: number;
  /** The wait budget expired; the run is still going server-side */
  waitTimedOut: boolean;
}

StoredEvent and Event Reads

StoredEvent is an event as persisted by the server (distinct from IronflowEvent, the shape a handler receives).

interface StoredEvent {
  id: string;
  name: string;
  timestamp: Date;
  data: unknown;
  source: string;
  metadata?: unknown;
  idempotencyKey?: string;
  processed: boolean;
  createdAt: Date;
  entityId?: string;
  entityType?: string;
  runId?: string;
}

interface ListEventsOptions {
  name?: string;
  names?: string[];
  sources?: string[];
  search?: string;
  since?: string;
  until?: string;
  limit?: number;
  cursor?: string;
  before?: string;
}

interface ListEventsResult {
  events: StoredEvent[];
  count: number;
  limit: number;
  nextCursor?: string;
  prevCursor?: string;
  hasNext: boolean;
  hasPrev: boolean;
  approxTotal?: number;
  approxTotalCapped: boolean;
}

interface ListEventNamesOptions {
  sources?: string[];
  since?: string;
  until?: string;
}

interface ListEventNamesResult {
  names: EventNameCount[];
  scanned: number;
  truncated: boolean;
  scanCap: number;
}

interface EventNameCount {
  name: string;
  count: number;
}

TriggerBatchEvent

One entry of a triggerBatch() call.

interface TriggerBatchEvent {
  event: string;
  data: unknown;
  version?: number;
  idempotencyKey?: string;
  metadata?: Record<string, unknown>;
}

TriggerBatchResult

One result of a triggerBatch() call, in request order. error is set when the item did not emit; the other items still do.

interface TriggerBatchResult extends EmitResult {
  error?: { code: string; message: string };
}

Step Types

StepClient

The durable step execution interface. All methods are memoized -- on retry, previously completed steps return their stored result without re-executing.

interface StepClient {
  /**
   * Execute a step with memoization.
   * Use for any non-idempotent operation (API calls, payments, emails).
   */
  run<T>(name: string, fn: () => Promise<T>, options?: StepRunOptions): Promise<T>;

  /**
   * Durable sleep. Worker can restart; workflow resumes after duration.
   * @param duration - "1h", "30m", "7d" or milliseconds as number
   */
  sleep(name: string, duration: Duration): Promise<void>;

  /**
   * Durable sleep until a specific time.
   * @param until - Date object or ISO 8601 string
   */
  sleepUntil(name: string, until: Date | string): Promise<void>;

  /**
   * Wait for an external event. Used for human-in-the-loop and async callbacks.
   */
  waitForEvent<T = unknown>(name: string, filter: EventFilter): Promise<IronflowEvent<T>>;

  /**
   * Execute multiple branches in parallel.
   * "failFast" (default): first failure cancels pending branches.
   * "allSettled": all branches complete, errors in results.
   */
  parallel<T extends unknown[]>(
    name: string,
    branches: { [K in keyof T]: (step: StepClient) => Promise<T[K]> },
    options?: ParallelOptions
  ): Promise<T>;

  /** allSettled overload -- results contain T[K] | Error */
  parallel<T extends unknown[]>(
    name: string,
    branches: { [K in keyof T]: (step: StepClient) => Promise<T[K]> },
    options: ParallelOptions & { onError: "allSettled" }
  ): Promise<{ [K in keyof T]: T[K] | Error }>;

  /**
   * Map over items executing steps in parallel.
   */
  map<T, R>(
    name: string,
    items: T[],
    fn: (item: T, step: StepClient, index: number) => Promise<R>,
    options?: ParallelOptions
  ): Promise<R[]>;

  /** allSettled overload -- results contain R | Error */
  map<T, R>(
    name: string,
    items: T[],
    fn: (item: T, step: StepClient, index: number) => Promise<R>,
    options: ParallelOptions & { onError: "allSettled" }
  ): Promise<(R | Error)[]>;

  /**
   * Register a compensation handler (Saga pattern).
   * On failure, compensations run in reverse order.
   */
  compensate(stepName: string, fn: () => Promise<void>): void;

  /**
   * Invoke another function and wait for its result (durable).
   * Target function must have no event triggers.
   */
  invoke<T = unknown>(
    functionId: string,
    input?: unknown,
    options?: { timeout?: string }
  ): Promise<T>;

  /**
   * Fire-and-forget invoke. Returns the child run ID immediately.
   */
  invokeAsync(functionId: string, input?: unknown): Promise<{ runId: string }>;

  /**
   * Publish to a developer pub/sub topic (durable, memoized).
   * Does NOT trigger workflow functions -- use emit for that.
   */
  publish(
    topic: string,
    data: unknown,
    options?: PublishOptions
  ): Promise<PublishResult>;
}

StepRunOptions

interface StepRunOptions {
  /** Timeout for this step ("30s", "5m", "1h"). Overrides function-level stepTimeout. */
  timeout?: string;
}

Duration

type Duration = string | number;
// String: "1s", "30s", "5m", "2h", "7d"
// Number: milliseconds

ParallelOptions

interface ParallelOptions {
  /** Maximum concurrent branches (default: unlimited) */
  concurrency?: number;
  /** Error handling: "failFast" (default) or "allSettled" */
  onError?: "failFast" | "allSettled";
  /** Set false to silence the warning when no branch uses the scoped step client (default: true). Durability is unchanged. */
  expectScopedClient?: boolean;
}

Run Types

RunStatus

type RunStatus = "running" | "completed" | "failed" | "cancelled" | "paused" | "waiting_for_capacity" | "waiting";

A server newer than the SDK can send a status this union does not list. The SDK passes it through in lower case instead of throwing, so keep a default branch when you switch on a status.

RunInfo

Minimal run context passed inside FunctionContext.

interface RunInfo {
  id: string;
  functionId: string;
  attempt: number;
  maxAttempts?: number; // total attempts the run may make; 0 from an engine that predates it
  onExhausted?: "pause" | "fail" | ""; // what the final failed attempt does; "" from an engine that predates it
  startedAt: Date;
  environment?: string; // environment of the run's outbound calls
}

Run

Full run details returned by API queries.

interface Run {
  cancellationCause?: string;
  cancellationEvent?: CancellationEvent;  // The matched rule and event, retained for a cancelled run
  id: string;
  functionId: string;
  eventId: string;
  status: RunStatus;
  attempt: number;
  maxAttempts: number;
  input?: unknown;
  output?: unknown;
  error?: { message: string; code?: string };
  startedAt?: Date;
  endedAt?: Date;
  createdAt: Date;
  updatedAt: Date;
}

interface CancellationEvent {
  eventId: string;
  eventName: string;
  matchPath: string;
  matchValue: string;
}

ListRunsOptions and ListRunsResult

interface ListRunsOptions {
  functionId?: string;
  status?: RunStatus;
  limit?: number;
  cursor?: string;
}

interface ListRunsResult {
  runs: Run[];
  nextCursor?: string;
  totalCount: number;
}

InvokeResult, InvokeSyncOptions, InvokeSyncResult

/** Same shape as EmitResult, the return type of emit(). */
interface InvokeResult {
  runIds: string[];
  eventId: string;
}

/** Argument to the ID-keyed invoke(), which targets one function. */
interface InvokeSyncOptions<TInput = unknown> {
  data: TInput;
  /** Server-side wait budget in ms (default: 30000), NOT a transport deadline */
  timeout?: number;
  idempotencyKey?: string;
  metadata?: Record<string, unknown>;
}

/** Exactly one run. No waitTimedOut -- invoke() throws RunWaitTimeoutError,
 *  RunFailedError and RunCancelledError instead (ADR 0067). */
type InvokeSyncResult = Omit<EmitSyncResult, "waitTimedOut">;

RunStep, RunStepsResult and RunStreamsResult

interface RunStep {
  id: string;
  runId: string;
  stepId: string;
  stepType: string;
  sequence: number;
  status: string;
  input?: unknown;
  output?: unknown;
  originalOutput?: unknown;   // pre-patch value, when the step was patched
  error?: unknown;
  inputHash?: string;
  attempt: number;
  durationMs?: number;
  startedAt?: Date;
  endedAt?: Date;
  sleepUntil?: string;
  waitEventName?: string;
  waitTimeout?: string;
  patchedAt?: string;
  patchedBy?: string;
  compensationFor?: string;
  createdAt: Date;
  updatedAt: Date;
}

interface RunStepsResult {
  steps: RunStep[];
  count: number;
}

/** Entity streams a run touched. */
interface RunStreamsResult {
  entityIds: string[];
}

Run frames and createRunVersionFilter

A subscription to system.run.> delivers frames for run transitions; one write can publish two (.failed and .updated). The payload of a system.run.{runId}.{event} frame is a RunEvent. Step frames (system.run.{runId}.step.{stepId}.{event}) have a different shape.

interface RunEvent {
  id: string;
  functionId: string;
  eventId: string;
  executionMode: string;
  status: string;
  attempt: number;
  maxAttempts: number;
  version?: number;   // Rises with every write to the run; absent on `deleted` frames, when the committed version is unknown, and on older servers
  createdAt: string;
  updatedAt: string;
  startedAt?: string;
  completedAt?: string;
  output?: unknown;
  error?: unknown;
  timestamp: string;
}

type RunVersionFilter = (event: SubscriptionEvent) => boolean;

function createRunVersionFilter(options?: { maxRuns?: number }): RunVersionFilter;

Frames for one run can arrive out of order, so a completed frame can land before the running one. createRunVersionFilter() returns a filter that drops older run and step frames and late frames for a deleted run. It passes frames outside system.run., frames with no usable version, and frames whose version ties the highest seen. It remembers up to maxRuns run and step identities (default 10000), then forgets the least recent. Use one filter per subscription.

const keep = createRunVersionFilter();
await client.subscribe('system.run.>', {
  onEvent: (event) => {
    if (keep(event)) render(event.data as RunEvent);
  },
});

Subscription Types

SubscribeOptions

interface SubscribeOptions {
  /** Number of historical events to replay (0 = no replay) */
  replay?: number;
  /** Resume after this stream sequence; 0 means from the beginning */
  startAfterSequence?: number | bigint;
  /** Include event metadata (timestamp, sequence) */
  includeMetadata?: boolean;
  /** CEL expression for content-based filtering */
  filter?: string;
  /** Consumer group to join for load-balanced delivery */
  consumerGroup?: string;
}

startAfterSequence cannot be combined with replay or consumerGroup. When set, the SDK advances the cursor to each delivered event and uses that position after a transport reconnect. Delivery remains at-least-once, so the frame in flight during a disconnect may repeat. Make the handler idempotent or dedupe on event.meta.sequence.

AckMode, BackpressureMode, AckType

type AckMode = "auto" | "manual";
type BackpressureMode = "drop" | "block" | "buffer";
type AckType = "ack" | "nak" | "term";

A server newer than the SDK can send an AckMode, BackpressureMode or ConsumerGroupStatus value these unions do not list. The SDK passes it through, so keep a default branch when you switch on one.

SubscriptionEvent

interface SubscriptionEvent<T = unknown> {
  /** Event topic (e.g., "system.run.abc123.updated") */
  topic: string;
  /** Event payload data */
  data: T;
  /** Event metadata (if includeMetadata was true) */
  meta?: EventMetadata;
  /** Event ID (for consumer group ack/nak/term) */
  eventId?: string;
}

EventMetadata

interface EventMetadata {
  timestamp?: Date;        // Absent when the server sent none it could read
  sequence?: number;       // Stream sequence number
  sequenceExact?: string;  // Same sequence as a decimal string; survives past Number.MAX_SAFE_INTEGER
}

Subscription

interface Subscription {
  id: string;
  pattern: string;
  connectionState: ConnectionState;
  lastEvent?: SubscriptionEvent<unknown>;
  unsubscribe(): void;
}

AckableSubscription

Extends Subscription with manual acknowledgment methods for consumer groups.

interface AckableSubscription extends Subscription {
  ack(eventId: string): Promise<void>;
  nak(eventId: string, delay?: number): Promise<void>;
  term(eventId: string): Promise<void>;
}

AckHandle

interface AckHandle {
  ack(): void;
  nak(): void;
}

ConnectionState

type ConnectionState = "connecting" | "connected" | "disconnected" | "reconnecting";

SubscriptionCallbacks

interface SubscriptionCallbacks<T = unknown> {
  onEvent?: (event: SubscriptionEvent<T>) => void;
  onError?: (error: SubscriptionErrorInfo) => void;
  onStateChange?: (state: ConnectionState) => void;
}

SubscriptionErrorInfo

interface SubscriptionErrorInfo {
  subscriptionId?: string;
  code: string;
  message: string;
  retrying?: boolean;
}

BufferConfig

interface BufferConfig {
  size: number;
  strategy: "drop-oldest" | "drop-newest" | "block";
}

ConsumerGroupConfig and ConsumerGroup

interface ConsumerGroupConfig {
  name: string;
  pattern: string;
  filterExpr?: string;          // CEL expression
  ackMode?: AckMode;            // default: "auto"
  backpressure?: BackpressureMode; // default: "buffer"
  maxInflight?: number;         // default: 100
  maxRedeliveries?: number;     // default: 3
  redeliverDelayMs?: number;    // default: 5000
  metadata?: Record<string, unknown>;
}

interface ConsumerGroup {
  id: string;
  name: string;
  pattern: string;
  filterExpr?: string;
  ackMode: AckMode;
  backpressure: BackpressureMode;
  maxInflight: number;
  maxRedeliveries: number;
  redeliverDelayMs: number;
  metadata?: Record<string, unknown>;
  status: ConsumerGroupStatus;
  memberCount: number;
  createdAt: Date;
  updatedAt: Date;
}

type ConsumerGroupStatus = "active" | "paused" | "deleted";

UpdateConsumerGroupInput

Every field is optional; only the ones present are applied.

interface UpdateConsumerGroupInput {
  pattern?: string;
  filterExpr?: string;
  ackMode?: AckMode;
  backpressure?: BackpressureMode;
  maxInflight?: number;
  maxRedeliveries?: number;
  redeliverDelayMs?: number;
  metadata?: Record<string, unknown>;
  status?: Exclude<ConsumerGroupStatus, "deleted">;
}

Entity Stream Types

Entity streams implement event sourcing per entity with optimistic concurrency.

AppendEventInput

interface AppendEventInput {
  /** Event name (e.g., "order.created") */
  name: string;
  /** Event payload data */
  data: Record<string, unknown>;
  /** Entity type (e.g., "order", "user") */
  entityType: string;
}

AppendOptions

interface AppendOptions {
  /** Expected entity version for optimistic concurrency control (-1 to skip) */
  expectedVersion?: number;
  /** Idempotency key to prevent duplicate appends */
  idempotencyKey?: string;
  /** Event schema version (default: 1) */
  version?: number;
  /** Cross-cutting metadata (causation, correlation, tenant, trace) attached to the event */
  metadata?: Record<string, unknown>;
}

AppendResult

interface AppendResult {
  entityVersion: number;
  /**
   * ID of the appended event. Appends run through the transactional
   * outbox (#487), so no NATS sequence is known at append time — for
   * read-your-writes, resolve this ID with
   * projections.waitForEvent(eventId, projection).
   */
  eventId: string;
}

ReadStreamOptions

interface ReadStreamOptions {
  /** Start reading from this version (inclusive, default: 0) */
  fromVersion?: number;
  /** Maximum number of events to return (0 = all) */
  limit?: number;
  /** Read direction (default: "forward") */
  direction?: "forward" | "backward";
}

StreamEvent

interface StreamEvent {
  id: string;
  name: string;
  data: Record<string, unknown>;
  entityVersion: number;
  version: number;          // Schema version
  timestamp: Date;
  source?: string;
  metadata?: Record<string, unknown>;
}

StreamInfo

interface StreamInfo {
  entityId: string;
  entityType: string;
  version: number;
  eventCount: number;
  createdAt: Date;
  updatedAt: Date;
}

EntitySubscribeOptions

interface EntitySubscribeOptions {
  /** Entity type (e.g., "order") -- required to construct NATS subject pattern */
  entityType: string;
  onEvent: (event: StreamEvent) => void;
  onError?: (error: Error) => void;
  /** Number of historical events to replay from NATS stream (0 = live only) */
  replay?: number;
}

Pub/Sub Types

Developer pub/sub for topic-based messaging. Unlike emit(), publishing to a topic does NOT trigger workflow functions.

PublishOptions

interface PublishOptions {
  idempotencyKey?: string;
}

PublishResult

interface PublishResult {
  eventId: string;
  sequence: number;   // JetStream sequence number
}

TopicInfo

interface TopicInfo {
  name: string;
  messageCount: number;
  consumerCount: number;
  firstMessageAt?: Date;
  lastMessageAt?: Date;
}

TopicStats

interface TopicStats {
  name: string;
  messageCount: number;
  consumerCount: number;
  lag: number;
  firstSeq: number;
  lastSeq: number;
}

KV Types

Key-value store backed by NATS JetStream KV.

KVBucketConfig

interface KVBucketConfig {
  name: string;
  description?: string;
  ttlSeconds?: number;      // 0 = no expiry
  maxValueSize?: number;    // bytes
  maxBytes?: number;        // total bucket size in bytes
  history?: number;         // historical values per key (default: 1)
}

KVBucketInfo

interface KVBucketInfo {
  name: string;
  description?: string;
  ttl_seconds?: number;
  values: number;
  bytes: number;
  history: number;
  created_at: Date;
}

KVEntry

interface KVEntry {
  key: string;
  value: unknown;        // stored bytes as base64 from get(), or parsed JSON from getJSON()
  revision: number;
  created_at: Date;
  operation: string;     // "put" or "delete"
}

KVPutResult

interface KVPutResult {
  revision: number;
}

KVListKeysResult

interface KVListKeysResult {
  keys: string[];
  count: number;
}

KVListBucketsResult

interface KVListBucketsResult {
  buckets: KVBucketInfo[];
  count: number;
}

KVWatchEvent

interface KVWatchEvent {
  type: "kv_update";
  key: string;
  value: string;          // the stored bytes, base64-encoded; "" for a delete
  revision: number;
  operation: "put" | "delete";
  bucket: string;
}

KVWatchCallbacks

interface KVWatchCallbacks {
  onUpdate: (event: KVWatchEvent) => void;
  onError?: (error: Error) => void;
  onClose?: () => void;
}

KVWatchOptions

interface KVWatchOptions {
  /** Key pattern to watch (e.g., "user.*", "session.>"). Empty = all keys. */
  key?: string;
}

KVWatcher

interface KVWatcher {
  stop: () => void;
}

Config Types

Environment-scoped configuration management built on the KV store.

ConfigResponse

interface ConfigResponse {
  name: string;
  data: Record<string, unknown>;
  revision: number;
  updatedAt: Date;
}

ConfigEntry

Summary (without full data), used in list responses.

interface ConfigEntry {
  name: string;
  revision: number;
  updatedAt: Date;
}

ConfigSetResult

interface ConfigSetResult {
  name: string;
  revision: number;
}

ConfigWatchCallbacks

interface ConfigWatchCallbacks {
  onUpdate: (event: ConfigWatchEvent) => void;
  onError?: (error: Error) => void;
  onClose?: () => void;
}

ConfigWatchEvent and ConfigWatcher

interface ConfigWatchEvent {
  type: string; // always "config_update" for data events
  name: string;
  data: Record<string, unknown> | null; // null after the config is deleted
  revision: number;
  updatedAt: Date;
}

interface ConfigWatcher {
  stop: () => void;
}

Auth Types

Types for API key, organization, role, and policy-set management.

API Keys

interface APIKey {
  id: string;
  name: string;
  key_prefix: string;
  role_ids?: string[];
  environment_id?: string;  // the environment the key is bound to
  tool_scopes?: string[];   // the agent tools the key may call
  created_at: Date;
  expires_at?: Date;
  last_used_at?: Date;
}

interface APIKeyWithSecret extends APIKey {
  /** Full API key -- only returned on creation */
  key: string;
}

interface CreateAPIKeyInput {
  name: string;
  env_id?: string;
  role_ids?: string[];
  expires_in?: string;
  /** Limit the agent tools the key may call. A caller grants only scopes it holds, unless it is an admin. */
  tool_scopes?: string[];
}

Organizations

interface Organization {
  id: string;
  name: string;
  created_at: Date;
  updated_at: Date;
}

interface CreateOrgInput {
  name: string;
}

interface UpdateOrgInput {
  name?: string;
}

Roles

interface Role {
  id: string;
  org_id: string;
  name: string;
  is_default: boolean;
  created_at: Date;
}

interface CreateRoleInput {
  name: string;
  org_id: string;
}

interface UpdateRoleInput {
  name?: string;
}

Policy set

type PolicySetMode = "enforce" | "monitor";

interface PolicySet {
  /** 0 when the org has no set. */
  version: number;
  modules: Record<string, string>;
  decision?: string;
  mode: PolicySetMode | "";
  updated_at?: Date;
  updated_by?: string;
  /** False when the server stores the set but does not enforce it. */
  enforcement_active?: boolean;
}

interface PolicySetInput {
  modules: Record<string, string>;
  decision?: string;
  /** Omitted: keep the current mode; a new set starts in "monitor". */
  mode?: PolicySetMode;
}

interface PolicySetVersion {
  version: number;
  mode: PolicySetMode;
  decision?: string;
  created_at: Date;
  created_by?: string;
}

interface PolicySetDryRunInput {
  /** Omitted: evaluate against the active set. */
  set?: PolicySetInput;
  input: { request: Record<string, unknown>; subject: Record<string, unknown>; [key: string]: unknown };
  explain?: boolean;
}

interface PolicySetDryRunResult {
  decision: "allow" | "deny"; // the set's own verdict, whatever its mode
  mode: PolicySetMode;
  version?: number;
  reasons?: string[];
  reasons_omitted?: number;
  entrypoint?: string;
  error?: string;
  explain?: string;
}

POLICY_SET_ERROR_CODES holds the values of IronflowError.code that the policy-set routes return: compileError, v0Syntax, reservedNamespace, builtinForbidden, schemaError, entrypointType, badFileName, tooLarge, compileTimeout, badMode, badDecision, sprintfFormat, badRequest, forbidden, notFound, versionConflict, preconditionRequired, selfLockout, rateLimited, busy and notPropagated.

notPropagated (HTTP 503) is not retryable. The write committed as the version in the message. Send the same request again with ifVersion set to that version (a no-op that finishes propagation). Never send it again with the old version.


Audit Types

Audit trail for function execution recording.

interface AuditEvent {
  id: string;
  runId: string;
  functionId: string;
  stepId?: string;
  eventType: string;
  payload: Record<string, unknown>;
  metadata?: Record<string, string>;
  createdAt: Date;
}

interface GetAuditTrailOptions {
  eventType?: string;
  fromTimestamp?: Date | string;
  toTimestamp?: Date | string;
  limit?: number;
  cursor?: string;
}

interface AuditTrailResult {
  events: AuditEvent[];
  totalCount: number;
  nextCursor?: string;
}

/** Environment-wide audit feed; narrows GetAuditTrailOptions by run or function. */
interface ListAuditEventsOptions extends GetAuditTrailOptions {
  runId?: string;
  functionId?: string;
}

Webhook Types

Types for defining webhook sources that transform inbound HTTP requests into Ironflow events.

interface WebhookRequest {
  body: string;
  headers: Record<string, string>;
}

interface WebhookEvent {
  name: string;
  data: unknown;
  idempotencyKey?: string;
}

interface WebhookConfig {
  id: string;
  /** Verify the webhook signature. Throw to reject (HTTP 401). The return value is ignored. */
  verify: (req: WebhookRequest) => unknown | Promise<unknown>;
  /** Transform the JSON-parsed request body into an Ironflow event. */
  transform: (payload: unknown) => WebhookEvent | Promise<WebhookEvent>;
}

interface IronflowWebhook {
  config: WebhookConfig;
}

Projection Types

Projections build read models from event streams.

ProjectionMode and ProjectionStatus

type ProjectionMode = "managed" | "external";
// "managed": pure reducer, state stored by Ironflow
// "external": side-effect handler, you manage storage

type ProjectionStatus = "active" | "rebuilding" | "paused" | "error";

ProjectionConfig

interface ProjectionConfig<TState = unknown, TEvent = unknown> {
  /** Unique projection name */
  name: string;
  /** Event names to subscribe to (supports wildcards like "order.*") */
  events: string[];
  /** Execution mode -- auto-detected from initialState if omitted */
  mode?: ProjectionMode;
  /** Handler function */
  handler: ManagedProjectionHandler<TState, TEvent> | ExternalProjectionHandler<TEvent>;
  /** Initial state factory (required for managed, absent for external) */
  initialState?: () => TState;
  /** JSONPath for partition key extraction (e.g., "$.customerId") */
  partitionKey?: string;
  /** Max retries per event (default 3) */
  maxRetries?: number;
  /** Batch size for polling (default 100) */
  batchSize?: number;
}

ProjectionContext

interface ProjectionContext {
  event: { id: string; name: string; seq: number; timestamp: Date; metadata?: Record<string, unknown> };
  projection: { name: string; version: number };
  logger: Logger;
}

Handlers

/** Managed: pure reducer. Returns new state. */
type ManagedProjectionHandler<TState = unknown, TEvent = unknown> = (
  state: TState,
  event: TEvent & { name: string; data: unknown; metadata?: Record<string, unknown> },
  ctx: ProjectionContext
) => TState;

/** External: side effects. Return void or Promise<void>. */
type ExternalProjectionHandler<TEvent = unknown> = (
  event: TEvent & { name: string; data: unknown; metadata?: Record<string, unknown> },
  ctx: ProjectionContext
) => void | Promise<void>;

Determinism & Idempotence (managed mode)

Managed reducers run under at-least-once delivery. PG-backed rebuild (#486) and the live NATS tail can both invoke the handler for the same event during the overlap window; node failover and retries can replay events at any time. Correctness depends on the reducer. Four rules:

  • Deterministic — same (state, event) → same newState. No Date.now(), new Date() with no args, Math.random(), crypto.randomUUID(), env reads. Derive timestamps from event.timestamp and IDs from event.data.
  • Pure — no network, no DB writes, no console.log as intent. Side effects require mode: "external".
  • Aliasing-safe — return a fresh object; don't mutate and return the argument.
  • Idempotent — the same event may be applied multiple times. Prefer keyed-map accumulation (state.byId[id] = ...) over counters (state.count += 1); key accumulators on event.id when you must accumulate.

See docs/explanation/projections.md for examples and rationale.

IronflowProjection

interface IronflowProjection<TState = unknown, TEvent = unknown> {
  config: ProjectionConfig<TState, TEvent>;
}

ProjectionStatusInfo

interface ProjectionStatusInfo {
  name: string;
  status: ProjectionStatus;
  mode: ProjectionMode;
  lastEventSeq: number;
  lag: number;
  errorMessage?: string;
  updatedAt: Date;
}

ProjectionStateResult

Returned by client.projections.get() (Node) and ironflow.getProjection() (browser) after peelProjectionEnvelope() strips the server REST wire shape. name, version, mode, status, lastEventSeq, updatedAt, and errorMessage come from the registry envelope. partition, state, lastEventId, and lastEventTime come from the inner state row. lastEventTime is undefined when no state row exists yet (projection registered, no events applied); state is {} in that case. errorMessage is omitted when the projection is healthy.

interface ProjectionStateResult<TState = unknown> {
  name: string;
  partition: string;
  state: TState;
  lastEventId: string;
  lastEventTime?: Date;
  lastEventSeq: number;
  version: number;
  mode: ProjectionMode;
  status?: ProjectionStatus;
  errorMessage?: string;
  updatedAt: Date;
}

GetProjectionOptions and RebuildProjectionOptions

interface GetProjectionOptions {
  partition?: string;
}

interface RebuildProjectionOptions {
  partition?: string;
  fromEventId?: string;
  dryRun?: boolean;
}

ProjectionSubscriptionCallbacks

interface ProjectionSubscriptionCallbacks<TState = unknown> {
  onUpdate: (state: TState, event: { id: string; name: string }) => void;
  onError?: (error: Error) => void;
}

peelProjectionEnvelope

Strips the server REST wire envelope into a ProjectionStateResult.

import { peelProjectionEnvelope } from '@ironflow/core';

const state = peelProjectionEnvelope<{ count: number }>(rawResponse, requestedPartition);

requestedPartition is optional. It becomes partition when the server sends no partition key (default "__global__"). A malformed envelope throws a non-retryable IronflowError with code PROJECTION_ENVELOPE_DRIFT.

SQL Projections

For projections backed by relational tables.

interface CreateSQLProjectionInput {
  name: string;
  /**
   * DDL for the projection: one CREATE TABLE on a proj_-prefixed table, plus
   * optional CREATE EXTENSION (vector, pg_trgm) before it and CREATE INDEX
   * statements on that same table after it. Index names must start with the
   * table name.
   */
  tableSql: string;
  /** Map of event_name → parameterized SQL handler (INSERT/UPDATE/DELETE) */
  eventHandlers: Record<string, string>;
  events: string[];
  description?: string;
}

interface QuerySQLProjectionOptions {
  where?: string; // e.g. "status = 'OPEN'" or "tsv @@ plainto_tsquery('revenue')"
  orderBy?: string; // e.g. "created_at DESC" or "embedding <=> '[0.1,0.2]'"
  limit?: number; // default 100
  offset?: number; // pagination offset
}

interface SQLProjectionQueryResult {
  columns: string[];
  rows: string[][]; // each row is string values in column order
  typedRows: SQLProjectionValue[][]; // SQL types preserved
  totalCount: number; // total matches before limit/offset
}

type SQLProjectionValue = string | number | boolean | null;

where and orderBy are parsed into bound parameters, never concatenated into SQL. Beyond ordinary filters they accept a fixed set of expressions: @@ with plainto_tsquery / websearch_to_tsquery in where, and pgvector distance (<->, <=>, <#>) or ts_rank(...) in orderBy. Those expressions need the PostgreSQL backend. See the browser SDK reference for the full grammar.

Projection Management Types

interface RebuildJob {
  name: string;
  status: string;
  progress: number;
  startedAt: Date;
}

interface ListProjectionPartitionsOptions {
  query?: string;
  limit?: number;
}

interface ListProjectionPartitionsResult {
  partitions: string[];
  returned: number;
}

/**
 * Result of waitForCatchup / waitForCatchupBatch / waitForEvent (#473).
 * On success exactly one of `caughtUp` or `timedOut` is true.
 */
interface WaitResult {
  caughtUp: boolean;
  timedOut: boolean;
  /** Cursor at the moment of response */
  currentSeq: number;
  /** The minSeq the client was waiting for */
  targetSeq: number;
  /** targetSeq - currentSeq. 0 when caught up */
  behindByEvents: number;
  rebuilding?: boolean;
  /** "managed" or "external" (informational) */
  mode?: string;
}

/**
 * One frame from waitForProjectionCatchupStream (#476). Seq fields are
 * `bigint` because the server values are uint64.
 */
interface WaitProgress {
  currentSeq: bigint;
  targetSeq: bigint;
  behindByEvents: bigint;
  terminal: boolean;
  caughtUp: boolean;
  timedOut: boolean;
  error?: string;
  mode?: string;
}

Usage example (via @ironflow/node):

import { createProjection } from '@ironflow/node';

const orderStats = createProjection({
  name: 'order-stats',
  events: ['order.placed', 'order.cancelled'],
  initialState: () => ({ total: 0, cancelled: 0 }),
  handler: (state, event) => {
    if (event.name === 'order.placed') return { ...state, total: state.total + 1 };
    if (event.name === 'order.cancelled') return { ...state, cancelled: state.cancelled + 1 };
    return state;
  },
});

Error Classes

All errors extend IronflowError. Each has a code string and a retryable boolean.

import {
  IronflowError, ConnectionError, SubscriptionError, TimeoutError,
  ValidationError, SchemaValidationError, SignatureError,
  FunctionNotFoundError, RunNotFoundError, StepError, NonRetryableError,
  NotConfiguredError, InvokeError, InvokeTimeoutError, StepTimeoutError,
  RunWaitTimeoutError, RunFailedError, RunCancelledError,
  AgentInvokeTimeoutError, MemoryCatchupTimeoutError,
  UnauthenticatedError, EnterpriseRequiredError, UnauthorizedError,
  ConflictError, ContendedError, InjectionUnverifiedError, QueueFullError,
  PreconditionFailedError, PreconditionRequiredError, PayloadTooLargeError, UnsupportedMediaTypeError,
  isRetryable, isIronflowError, toError,
  AUTH_HELP, throwIfAuthError,
} from '@ironflow/core';

IronflowError (base class)

class IronflowError extends Error {
  readonly code: string;
  readonly status?: number;   // HTTP status when the failure came from a response
  readonly retryable: boolean;
  readonly details?: Record<string, unknown>;

  constructor(message: string, options?: {
    code?: string;       // default: "UNKNOWN_ERROR"
    status?: number;
    retryable?: boolean; // default: false
    details?: Record<string, unknown>;
    cause?: Error;
  });
}

Error Reference Table

| Class | Code | Retryable | When Thrown | |---|---|---|---| | ConnectionError | CONNECTION_LOST | true | WebSocket/HTTP connection lost | | SubscriptionError | SUBSCRIPTION_ERROR | true | Subscription setup or delivery failure (has subscriptionId) | | TimeoutError | TIMEOUT | true | HTTP request timeout | | ValidationError | VALIDATION_ERROR | false | Invalid input data (has validationErrors) | | SchemaValidationError | VALIDATION_ERROR | false | Zod schema validation failure (extends ValidationError) | | SignatureError | SIGNATURE_INVALID | false | Invalid webhook signature | | FunctionNotFoundError | FUNCTION_NOT_FOUND | false | Function ID not in registry | | RunNotFoundError | RUN_NOT_FOUND | false | Run ID not found in store | | StepError | STEP_FAILED | true | Step execution failure (has stepId, stepName) | | NonRetryableError | NON_RETRYABLE | false | Permanent failure, skip retries | | RetryAfterError | RETRY_AFTER | true | Retry after a delay: new RetryAfterError(message, retryAfterMs). The engine waits retryAfterMs instead of the computed backoff, capped at the policy's maxDelayMs (has retryAfterMs) | | NotConfiguredError | NOT_CONFIGURED | false | Client used before configure() | | InvokeError | INVOKE_FAILED | false | step.invoke() target failed (has functionId, childRunId) | | InvokeTimeoutError | INVOKE_FAILED | false | step.invoke() timed out (has timeoutMs) | | StepTimeoutError | STEP_TIMEOUT | true | step.run() exceeded its timeout (has stepName, timeout) | | RunWaitTimeoutError | RUN_WAIT_TIMEOUT | false | invoke stopped waiting while the run remained active (has runId, functionId, runStatus, timeoutMs). emitSync sets waitTimedOut per result instead of throwing | | RunFailedError | RUN_FAILED | false | invoke/InvokeFunctionSync run failed (has runId, output). emitSync reports status + error per result instead | | RunCancelledError | RUN_CANCELLED | false | invoke/InvokeFunctionSync run cancelled (has runId). emitSync reports status per result instead | | AgentInvokeTimeoutError | AGENT_INVOKE_TIMEOUT | true | agents.invoke() exceeded timeoutMs (has runId, timeoutMs) | | MemoryCatchupTimeoutError | MEMORY_CATCHUP_TIMEOUT | true | agents.readMemory() waited past timeoutMs for projection catch-up (has projection, minSeq, timeoutMs) | | UnauthenticatedError | unauthenticated | false | No/invalid API key (HTTP 401) | | EnterpriseRequiredError | ENTERPRISE_REQUIRED | false | HTTP 402. Legacy — Ironflow ships a single tier (ADR 0015) and the server no longer returns 402; retained for compatibility | | UnauthorizedError | permission_denied | false | Insufficient permissions (HTTP 403) | | ConflictError | already_exists | false | HTTP 409 that is not a lost race — e.g. an idempotency key reused with a different request. Do not resend the same body | | ContendedError | CONTENDED | false | HTTP 409 from a lost CAS race (Connect aborted). Nothing was applied — re-read and reissue | | InjectionUnverifiedError | INJECTION_UNVERIFIED | false | Connect aborted + Ironflow-Error-Reason: injection_unverified. injectStepOutput wrote the step but could not confirm the run stood still. Unlike ContendedError the write did land — read the step and decide, do not reissue | | QueueFullError | QUEUE_FULL | false | @ironflow/browser's offline write queue hit its 500-write / 5 MB cap | | PreconditionFailedError | PRECONDITION_FAILED | false | HTTP 412. An If-Match or If-None-Match precondition failed (file storage) | | PreconditionRequiredError | PRECONDITION_REQUIRED | false | HTTP 428. The write needs If-Match with the version you read (policy set) | | PayloadTooLargeError | PAYLOAD_TOO_LARGE | false | HTTP 413. A file is larger than the server, bucket or token cap (file storage) | | UnsupportedMediaTypeError | UNSUPPORTED_MEDIA_TYPE | false | HTTP 415. The bucket or signed URL does not allow the content type (file storage) |

Utility Functions

// Check if an error is retryable. An IronflowError carries its own flag;
// anything else (a plain Error, a thrown string) is retryable.
isRetryable(error: unknown): boolean

// Type guard for IronflowError
isIronflowError(error: unknown): error is IronflowError

// Normalize any thrown value to an Error instance
toError(error: unknown): Error

// Throw UnauthenticatedError on 401 / UnauthorizedError on 403, both with
// AUTH_HELP appended; returns silently on any other status. AUTH_HELP is the
// shared "set IRONFLOW_API_KEY / see the startup banner" guidance string (#1673).
throwIfAuthError(status: number, context: string): void

// Map a Connect JSON error to the matching IronflowError subclass. The
// `aborted` code is refined by the ERROR_REASON_HEADER ("Ironflow-Error-Reason")
// response header: ERROR_REASON.injectionUnverified -> InjectionUnverifiedError,
// anything else -> ContendedError.
connectHTTPError(status: number, message: string, code?: string, options?: { retryable?: boolean; authHelp?: string; reason?: string }): IronflowError

// The error ready() throws when the readiness probe fails: code NOT_READY, the
// HTTP status, retryable, and the failing dependencies in `details.issues`
// (the server's `issues` map, for example { nats: "disconnected" }).
notReadyError(status: number, body?: { issues?: Record<string, string> } | null): IronflowError

// The error code of a failed response. The body's own `code` wins (a capitalised
// generic code from an older server becomes its Connect code). Without one, the
// status maps to a Connect code: 401 "unauthenticated", 403 "permission_denied",
// 404 "not_found", 409 "already_exists", 429 "resource_exhausted", and so on.
connectCodeForStatus(status: number, code?: string | null): string

Usage:

try {
  await client.emit('order.placed', { amount: 100 });
} catch (err) {
  if (isRetryable(err)) {
    // Safe to retry
  }
  if (err instanceof FunctionNotFoundError) {
    console.error(`Function ${err.functionId} not registered`);
  }
}

Schemas

Zod schemas for runtime validation of API responses, WebSocket messages, and webhook payloads. All schemas are exported from @ironflow/core or the @ironflow/core/schemas sub-path.

Validation Helpers

import { parseAndValidate, validate, RunResponseSchema } from '@ironflow/core';

// Parse JSON string and validate against schema
// Throws SchemaValidationError on failure
const run = parseAndValidate(RunResponseSchema, jsonString, 'GetRun response');

// Validate already-parsed data against schema
// Throws SchemaValidationError on failure
const run = validate(RunResponseSchema, parsedData, 'GetRun response');

// Flatten Zod issues into "path: message" strings (used by both helpers above)
formatZodIssues(issues: readonly z.core.$ZodIssue[]): string[]

Available Schemas

Run & Status:

  • RunStatusSchema -- z.enum(["running", "completed", "failed", "cancelled", "paused", "waiting_for_capacity", "waiting"])
  • RunStatusWireSchema -- the protobuf JSON spelling (RUN_STATUS_RUNNING, ...), transformed to the public status. RUN_STATUS_UNSPECIFIED and unknown values are rejected rather than mapped

Push Request (serve.ts):

  • PushRequestSchema -- Full push mode request from engine to SDK
  • PushRequestEventSchema -- Event portion of push request
  • CompletedStepSchema -- Memoized step from previous execution
  • ResumeContextSchema -- Resume context for sleep/waitForEvent/invoke

API Responses:

  • TriggerResponseSchema -- { runIds?, eventId }
  • TriggerSyncResultItemSchema -- Individual sync trigger result
  • TriggerSyncResponseSchema -- { results?, eventId }
  • RunResponseSchema -- Full run details
  • ListRunsResponseSchema -- { runs?, nextCursor?, totalCount? }
  • RegisterFunctionResponseSchema -- { created? }
  • InvokeFunctionSyncResponseSchema -- { result }, one TriggerSyncResultItemSchema
  • HealthResponseSchema -- { status }
  • ErrorResponseSchema -- { code?, message? }
  • EmptyResponseSchema -- {}

Consumer Groups:

  • AckModeSchema -- ACK_MODE_AUTO, ACK_MODE_MANUAL, ACK_MODE_UNSPECIFIED, or any other ACK_MODE_* name a newer server adds
  • BackpressureModeSchema -- the same rule for BACKPRESSURE_MODE_*
  • ConsumerGroupStatusSchema -- the same rule for CONSUMER_GROUP_STATUS_*
  • ConsumerGroupResponseSchema
  • ListConsumerGroupsResponseSchema

Worker Job Assignment:

  • JobAssignmentSchema -- Full job assignment for pull-mode workers
  • JobEventSchema, JobCompletedStepSchema, JobContextSchema

WebSocket Messages:

  • WSServerMessageSchema -- Discriminated union of all server messages
  • WSEventMessageSchema -- Event delivery
  • WSSubscriptionResultSchema -- Subscribe confirmation
  • WSSubscriptionResultItemSchema -- Single subscribe result item
  • WSSubscriptionErrorSchema -- Subscription error
  • WSErrorSchema -- General error
  • EventMetadataSchema

Audit:

  • AuditEventSchema

Time-Travel Debugging:

  • TimeTravelStepSnapshotSchema
  • TimeTravelRunStateSnapshotSchema
  • TimeTravelTimelineEventSchema

Inferred Types

import type {
  ValidatedPushRequest,
  ValidatedRunResponse,
  ValidatedJobAssignment,
  ValidatedWSServerMessage,
} from '@ironflow/core';

These are z.infer<> types derived from the corresponding schemas.


Protocol Types

Low-level protocol types for SDK authors building custom transports. Import from @ironflow/core or @ironflow/core/protocol.

Push Mode (HTTP)

interface PushRequest {
  run_id: string;
  function_id: string;
  attempt: number;
  event: {
    id: string; name: string; data: unknown; timestamp: string;
    version?: number; idempotency_key?: string; source?: string;
    metadata?: Record<string, unknown>;
  };
  steps: CompletedStep[];
  resume?: ResumeContext;
}

interface PushResponse {
  status: "completed" | "yielded" | "failed";
  steps: StepResult[];
  result?: unknown;
  error?: {
    message: string; code?: string; step_id?: string;
    retryable: boolean; stack?: string;
  };
  yield?: YieldInfo;
}

interface CompletedStep {
  id: string; name: string;
  status: "completed" | "failed" | "timed_out";
  output?: unknown; error?: string;
}

interface ResumeContext {
  step_id: string;
  type: "sleep" | "wait_for_event" | "invoke_function" | "invoke_function_async";
  data?: unknown;
}

interface StepResult {
  id: string; name: string;
  type: "invoke" | "sleep" | "wait_for_event" | "compensate";
  status: "completed" | "failed";
  started_at: string; ended_at?: string; duration_ms?: number;
  output?: unknown;
  error?: { message: string; retryable: boolean; stack?: string };
  compensation_for?: string;
}

Yield Types

type YieldInfo = SleepYield | WaitEventYield | InvokeFunctionYield | InvokeFunctionAsyncYield;

interface SleepYield { step_id: string; type: "sleep"; until: string; }
interface WaitEventYield { step_id: string; type: "wait_for_event"; event_filter: { payload?: unknown; event: string; match?: string; timeout?: string; }; }
interface InvokeFunctionYield { step_id: string; type: "invoke_function"; function_id: string; input?: unknown; invoke_timeout_ms?: number; }
interface InvokeFunctionAsyncYield { step_id: string; type: "invoke_function_async"; function_id: string; input?: unknown; }

WebSocket Protocol

Client to server:

interface WSSubscribeRequest {
  type: "subscribe";
  subscription: {
    pattern: string;
    options?: {
      replay?: number; startAfterSequence?: number | bigint;
      includeMetadata?: boolean; filter?: string;
      consumerGroup?: string;
    };
  };
}

interface WSUnsubscribeRequest { type: "unsubscribe"; subscriptionId: string; }
interface WSAckRequest { type: "ack"; eventId: string; ackType: AckType; subscriptionId?: string; redeliverDelay?: number; }

type WSClientMessage = WSSubscribeRequest | WSUnsubscribeRequest | WSAckRequest;

Server to client:

interface WSSubscriptionResult {
  type: "subscription_result";
  // A newer server can send a status other than "ok" or "error"; treat it as a failure.
  results: Array<{ pattern: string; status: "ok" | "error" | (string & {}); subscriptionId?: string; code?: string; message?: string; }>;
}
interface WSEventMessage { type: "event"; subscriptionId: string; topic: string; data: unknown; meta?: EventMetadata; eventId?: string; }
interface WSSubscriptionError { type: "subscription_error"; subscriptionId: string; code: string; message: string; retrying: boolean; }
interface WSError { type: "error"; code: string; message: string; }

type WSServerMessage = WSSubscriptionResult | WSEventMessage | WSSubscriptionError | WSError;

Retry Types

interface RetryEvent { attempt: number; maxAttempts: number; error: Error; delayMs: number; }
interface RetryInfo { eventId: string; attempt: number; maxAttempts: number; delayMs?: number; }

interface ClientRetryConfig {
  maxAttempts?: number;          // default: 3
  initialDelayMs?: number;       // default: 100
  maxDelayMs?: number;           // default: 10000
  backoffMultiplier?: number;    // default: 2.0
  connectionRetryDelayMs?: number; // default: 2000
  onRetry?: (event: RetryEvent) => void;
}

Subscribe/Resume Helpers

Values, not types. Both SDK transports share them so a WebSocket and a ConnectRPC subscription resume identically.

import {
  createWSSubscribeRequest,      // (pattern, options?) => WSSubscribeRequest
  serializeWSSubscribeRequest,   // (request) => string; validates the cursor before sending
  startAfterSequenceToBigInt,    // (number | bigint) => bigint; rejects unsafe/negative cursors
  subscriptionOptionsForReconnect, // (options?) => options with `replay` stripped
  advanceResumeCursor,           // (options, sequence) => options with startAfterSequence moved forward
  resumeSequenceFromMetadata,    // (sequence?, sequenceExact?) => number | bigint | undefined
} from '@ironflow/core';

replay applies only to the first subscribe, which is why subscriptionOptionsForReconnect drops it. resumeSequenceFromMetadata prefers the exact string form so sequences past Number.MAX_SAFE_INTEGER survive.

Wire Converters

Each converter maps one wire object to the SDK shape it returns. The casing it reads depends on the route. Connect responses are protobuf JSON: camelCase, with int64 as a string and zero values omitted. WebhookService alone registers the UseProtoNames codec, so the webhook converters read snake_case on both transports. runStepFromWire, userFromWire and tenantFromWire read snake_case too. runInspectionFromWire, stepInspectionFromWire, functionListFromWire and schemaFromWire return snake_case shapes.

import {
  webhookVerifyConfigToWire,
  webhookVerifyConfigFromWire,
  webhookGraceToWire,               // tri-state grace → wire; throws above the cap
  WEBHOOK_SECRET_GRACE_CAP_SECONDS, // 604800 (7 days)
  webhookSourceFromWire,
  webhookDeliveryFromWire,
  registeredFunctionFromWire,
  functionHistoryEntryFromWire,
  storedEventFromWire,
  runStepFromWire,
  consumerGroupFromWire,
  userFromWire,
  tenantFromWire,
  functionListF