shiftlabs Start free
Menu TypeScript SDK

TypeScript SDK reference

The shiftlabs module is what a TypeScript workflow, an agent's code and a project's shiftlabs.config.ts import. Every deploy includes it, and the shiftlabs package gives it its types. This page is generated from its TypeScript source. Python workflows have the Python SDK.

DurationUnit

The unit of a duration string, singular or plural.

typescripttype
type DurationUnit =
  "second" | "minute" | "hour" | "day" | "week" | "month" | "year";

Duration

A number of milliseconds or a string such as "30 seconds" or "10 minutes", with units from second to year.

typescripttype
type Duration =
  number | `${number} ${DurationUnit}` | `${number} ${DurationUnit}s`;

StandardJSONSchemaV1

A Standard JSON Schema (https://standardschema.dev): zod 4.2+, ArkType 2.1.28+, or Valibot through @valibot/to-json-schema. The platform reads jsonSchema.input({ target: "draft-2020-12" }) at deploy.

  • readonly "~standard": { readonly version: 1; readonly vendor: string; readonly types?: { readonly input: Input; readonly output: Output } | undefined; readonly jsonSchema: { readonly input: (options: { readonly target: string }) => Record<string, unknown>; readonly output: (options: { readonly target: string }) => Record<string, unknown>; }; }

    The schema library's Standard Schema properties; jsonSchema converts it to JSON Schema.

Schema

A Standard JSON Schema or a plain JSON Schema object. T is the type of the data it accepts.

typescripttype
type Schema<T = unknown> =
  StandardJSONSchemaV1<T, unknown> | Record<string, unknown>;

StepConfig

Retries and a timeout for one step, given as step.run(name, config, fn). Each attempt counts as a step.

  • retries?: { limit: number; delay: Duration; backoff?: "constant" | "linear" | "exponential" }

    limit: how many times to retry a failing step, default 5; a FatalError is never retried. delay: a duration between attempts, default "10 seconds". backoff: "constant", "linear" or "exponential" (the default).

  • timeout?: Duration

    A duration after which an attempt fails, default "10 minutes".

UndoContext

What an undo function gets.

  • output: T

    What the step returned.

  • error: Error

    The error the run failed with.

UndoFunction

Undoes a step once the run has failed: see RunConfig.undo. Its return value is dropped.

typescripttype
type UndoFunction<T = unknown> = (undo: UndoContext<T>) => unknown;

UndoOptions

An undo with retries, a timeout or an approval of its own.

  • run: UndoFunction<T>

    The undo itself.

  • retries?: { limit: number; delay: Duration; backoff?: "constant" | "linear" | "exponential" }

    As a step's retries: 5 retries, 10 seconds apart and doubling, when left out.

  • timeout?: Duration

    A duration after which an attempt fails, default "10 minutes".

  • approval?: WaitForApprovalOptions

    Waits for an approval named undo <name> before undoing; denied or unanswered, this undo is skipped.

RunConfig

step.run's config: StepConfig and an undo.

  • retries?: { limit: number; delay: Duration; backoff?: "constant" | "linear" | "exponential" }

    As in StepConfig.

  • timeout?: Duration

    As in StepConfig.

  • undo?: UndoFunction<T> | UndoOptions<T>

    Runs if the workflow's function throws after this step completed: a step named undo <name>, newest first, given the step's result and the run's error. One that fails for good stops the older ones. Undos count as steps.

SignalConfig

step.run's config with signal: true: fn gets { signal }. The other fields are RunConfig's.

  • retries?: { limit: number; delay: Duration; backoff?: "constant" | "linear" | "exponential" }

    As in StepConfig.

  • timeout?: Duration

    As in StepConfig.

  • undo?: UndoFunction<T> | UndoOptions<T>

    As in RunConfig.

  • signal: true

    Gives fn an AbortSignal that aborts when the run is asked to cancel or terminate while the step runs.

SignalContext

What a step's function gets with signal: true.

  • signal: AbortSignal

    Aborted within about 5 seconds of a cancel or terminate of the run, or a minute once the step has run 5 minutes. The step may stop early: if it then throws, it fails with cancelled, without retries.

CompletedStep

A step.run that completed before the run was cancelled.

  • name: string

    The step's name.

  • output: unknown

    What it returned.

CancelContext

What onCancel gets: the run's context, and its step.run calls that completed before the cancel.

typescripttype
type CancelContext<Payload = unknown> = Context<Payload> & {
  /** The completed `step.run` calls, in the order the run called them. */
  steps: CompletedStep[];
};

AskOptions

step.ask's options.

  • agent: string

    The name of an agent in this workspace.

  • message: string

    What to ask it, 1 to 4,000 characters.

RunPlanStep

A step the run means to take, for step.status({ plan }): the run page lists them before they run.

  • name: string

    The step's name, as step.run will give it.

  • group?: string

    The rollout group it changes, a group's id in rollout.

  • batch?: number

    The rollout batch it belongs to, 0 or more.

RolloutDeviceState

Where one device's change is, for step.status({ rollout }).

typescripttype
type RolloutDeviceState = "pending" | "changed" | "verified" | "failed" | "rolled_back";

RolloutState

A rollout the run page draws as a matrix, for step.status({ rollout }).

  • batches: { id: string; groups: { id: string; side: "A" | "B"; verify?: string; devices: { id: string; state: RolloutDeviceState }[] }[] }[]

    In order. Each group is one side ("A" or "B") of a pair changed one side at a time, with an optional verify step's name, and its devices with where each one's change is.

  • rule?: string

    How the rollout moves on, as text, such as "one side at a time, the next once both verify".

RunStatusValue

step.status's value: plan and rollout are checked for their shapes; every other key is yours.

typescripttype
type RunStatusValue = { plan?: RunPlanStep[]; rollout?: RolloutState } & Record<string, unknown>;

WaitForEventOptions

step.waitForEvent's options.

  • timeout?: Duration

    How long to wait before step.waitForEvent returns null, default "24 hours".

  • continueWith?: unknown

    A keyed workflow's state to continue as new with if the run must continue here (at half a per-run budget, or 2 hours before its lifetime ends): the wait throws ContinuedAsNew, and the key's next run gets this as its payload.

WaitForAnyOptions

step.waitForAny's options.

  • continueWith?: unknown

    As waitForEvent's: the state a keyed run continues as new with if it must continue at this race.

SnapshotOptions

step.snapshot's options.

  • stage?: string

    When it was taken, such as "before" or "after", 1 to 64 characters.

Approver

Who may answer an approval: "role:admin" (admins), "role:approver" (approvers), "role:manager" (admins and approvers) or a member's sign-in email. A developer never approves.

typescripttype
type Approver = "role:admin" | "role:approver" | "role:manager" | (string & {});

WaitForApprovalOptions

step.waitForApproval's options.

  • message?: string

    What approvers read in the Approvals inbox, 2,000 characters at most.

  • timeout?: Duration

    How long to wait before the approval counts as denied, default "72 hours".

  • approvers?: Approver[]

    Up to 20 roles or member emails. Only they see the request and get its notice; anyone else, admins included, can't answer it. Default: every admin and approver.

  • approvals?: number

    How many approvers must approve, 1 to 5 (default 1). Settings → Approvals sets the least a request needs; asking for fewer has no effect. Under 2 or more, each approval comes from a different member; an API key can't approve.

  • policy?: ApprovalPolicy

    What the request is: its policy's name, 1 to 100 characters, and its risk. Approvers see both.

ApprovalPolicy

step.waitForApproval's policy: which of your rules asks, and how risky the change is.

  • name?: string

    Such as "production change", 1 to 100 characters.

  • risk?: "low" | "medium" | "high"

    "low", "medium" or "high".

ApprovalDecision

What step.waitForApproval returns.

  • approved: boolean

    False when an approver denied, or nobody answered before the timeout.

  • by: string | null

    The approver's email, or the API key's id; null when nobody answered.

  • note: string | null

    The approver's note, if they left one.

Wait

What step.waitForEvent, step.waitForApproval and step.sleep return: a promise that starts waiting when awaited. Give one to step.waitForAny instead, not awaited, to race it against others. [outcome] exists only in types, to name the wait and its value in what step.waitForAny returns.

typescripttype
type Wait<T, Name extends string = string> = Promise<T> & { readonly [outcome]?: Winner<Name, T> };

Winner

What step.waitForAny returns: the wait that finished first, and what it returns on its own.

  • name: Name

    The wait's name.

  • value: Value

    An event's data, or null once its timeout passed; an approval's decision; null for a sleep.

WinnerOf

What step.waitForAny returns for the waits W: one Winner per wait, a sleep's value null.

typescripttype
type WinnerOf<W> = W extends Wait<infer T, infer Name> ? Winner<Name, [T] extends [void] ? null : T> : never;

StartOptions

What step.start and step.call start.

  • workflow: string

    The name of a workflow in this workspace.

  • payload?: unknown

    The new run's payload, default {}. It must be JSON and pass the workflow's payload schema.

SecretRef

A readable secret by name, in step.exec's env or files, or anywhere in step.activity's input. The runner gets its value for that call only.

  • secret: string

    The secret's name. Only a secret marked readable can be passed.

ExecOptions

step.exec's options. Give run or command, not both.

  • run?: string

    A bash script, run with bash --noprofile --norc -eo pipefail in the command's own folder.

  • command?: string[]

    A program and its arguments, run with no shell.

  • env?: Record<string, string | SecretRef>

    Environment variables for the command, up to 100, added to the runner's own. A name the runner also has takes this value.

  • files?: Record<string, string | SecretRef>

    Files written in the command's folder before it runs, up to 50, by relative path.

  • stdin?: string

    Text sent to the command's standard input.

  • timeout?: Duration

    How long the command may run before the runner stops it, default "10 minutes", up to your plan's limit.

  • runner?: string

    The pool of runners that may run it, default "default".

  • profile?: string

    The runner image profile the command needs, as "network" or "network@2026.11.1" (that image version only). Only a runner whose image manifest lists it takes the command. Default: the project's runnerProfile, else any runner.

  • requires?: string[]

    Tools the runner's image manifest must list, such as ["helm"], up to 64. None by default.

  • okExitCodes?: number[] | "any"

    The exit codes that count as success, default [0]. "any" accepts every exit code.

  • retries?: { limit: number; delay: Duration; backoff?: "constant" | "linear" | "exponential" }

    Tries the command again after a failure: limit more times, 0 to 10, delay apart, with backoff "exponential" unless given. No retries by default.

ExecResult

What step.exec returns, and an ExecError's result.

  • exitCode: number

    The command's exit code: 124 when it timed out.

  • stdout: string

    The last 256 KiB of the command's standard output, with secret values replaced by [redacted].

  • stderr: string

    The last 256 KiB of its standard error, with secret values replaced by [redacted].

  • stdoutBytes: number

    The size of all its standard output, in bytes.

  • stderrBytes: number

    The size of all its standard error, in bytes.

  • truncated: boolean

    True when stdout or stderr holds only the end of its stream.

  • timedOut: boolean

    True when the runner stopped the command at its timeout.

  • durationMs: number

    How long the command ran, in milliseconds.

  • runner: string

    The name of the runner that ran it.

  • attempt: number

    Which try this was, 1 for the first.

ActivityOptions

step.activity's options.

  • name: string

    The activity's name in the runner's activities file: lowercase letters, digits and -.

  • input?: unknown

    What the program reads as JSON on its standard input: any JSON value up to 256 KiB, {} by default. { secret: "NAME" } anywhere in it stands for a readable secret's value, which only the runner gets.

  • runner?: string

    The pool of runners that may run it, default "default". Only one that lists the activity takes it.

  • profile?: string

    As step.exec's: the runner image profile, name or name@version; by default the project's runnerProfile.

  • requires?: string[]

    As step.exec's: tools the runner's image manifest must list. None by default.

  • timeout?: Duration

    How long the activity may run before the runner stops it, default "10 minutes", up to your plan's limit.

  • heartbeat?: Duration

    How long the program may go without writing a heartbeat line to file descriptor 3 before the runner stops it, from 1 second to 1 day. None by default.

  • retries?: { limit: number; delay: Duration; backoff?: "constant" | "linear" | "exponential" }

    Tries the activity again after a failure: limit more times, 0 to 10, delay apart, with backoff "exponential" unless given. No retries by default.

ActivityResult

An ActivityError's result: how the attempt that failed ran.

  • activity: string

    The activity's name.

  • version: string

    Its version in the activities file of the runner that ran it, "" for none.

  • exitCode: number

    The program's exit code: 124 when the runner stopped it.

  • stdout: string

    The program's standard output, the output's JSON text: up to 256 KiB, secret values replaced by [redacted].

  • stderr: string

    The last 16 KiB of its standard error, with secret values replaced by [redacted].

  • stdoutBytes: number

    The size of all its standard output, in bytes.

  • stderrBytes: number

    The size of all its standard error, in bytes.

  • truncated: boolean

    True when stdout or stderr holds only the end of its stream.

  • timedOut: boolean

    True when the runner stopped the program at its timeout.

  • heartbeatTimedOut: boolean

    True when the runner stopped the program because no heartbeat came within heartbeat.

  • durationMs: number

    How long the program ran, in milliseconds.

  • runner: string

    The name of the runner that ran it.

  • attempt: number

    Which try this was, 1 for the first.

DecisionModel

Cloudflare's decision models on Workers AI. Clef reads up to 65,536 tokens of question and state, Clef-flash 24,576.

typescripttype
type DecisionModel = "@cf/cloudflare/clef" | "@cf/cloudflare/clef-flash";

DecisionOptions

decision's options: question with choices or score, or yesNo alone. A deploy that changes the question, the choices or levels, or the names of the fields state returns, under the same version, is refused.

  • version: number

    A whole number from 1. Give a new one to change the question, the choices or levels, or the state's fields.

  • model: DecisionModel

    The model that answers. The model and the threshold can change under the same version.

  • question?: string

    What to decide about the state, 1 to 2,000 characters, with choices or score.

  • choices?: readonly Option[] | { readonly [K in Option]: string }

    2 to 255 options, or an object of options and what each means. The answer is one of them.

  • yesNo?: string

    A question to answer yes or no, 1 to 2,000 characters. The answer is "yes" or "no".

  • score?: readonly Option[]

    2 to 10 levels, the lowest first. The answer is one of them.

  • threshold?: number

    From 0 to 1: the probability the most probable option needs to be the answer. Without one it always is.

  • state: (input: Input) => Record<string, unknown> | Promise<Record<string, unknown>>

    Builds what the model reads from step.decide's input: an object with the same data fields every time, null for one you don't have. A PNG, JPEG or WebP data URL in it is an image, 4 at most. Card and bank numbers are masked.

DecisionDefinition

What decision returns. Name it in workflow({ decisions }) and pass it to step.decide.

typescripttype
type DecisionDefinition<Input = unknown, Option extends string = string> = DecisionOptions<Input, Option> & { readonly kind: "shiftlabs.decision" };

DecisionResult

What step.decide returns.

  • answer: Option | null

    The most probable option, or null when its probability is under the threshold.

  • top: Option

    The most probable option, whatever the threshold.

  • probabilities: Record<Option, number>

    Every option's probability, from 0 to 1.

  • score: number | null

    A score decision's probability-weighted level, from 0 for the lowest; null for the others.

  • version: number

    The decision's version.

  • model: DecisionModel

    The model that answered.

  • threshold: number | null

    The threshold it was held to, null for none.

Step

Durable steps, sleeps, events and approvals: ctx.step.

  • run<T>(name: string, fn: () => T | Promise<T>): Promise<T>

    run<T>(name: string, config: SignalConfig<T>, fn: (run: SignalContext) => T | Promise<T>): Promise<T>

    run<T>(name: string, config: RunConfig<T>, fn: () => T | Promise<T>): Promise<T>

    Runs fn once and stores its result. When the run resumes, the step returns the stored result instead of running again. Runs fn once and stores its result, as run(name, fn). With signal: true, fn gets { signal }, which aborts when the run is asked to cancel or terminate while the step runs. Runs fn once and stores its result. When the run resumes, the step returns the stored result instead of running again. config.undo undoes it if the run fails later.

  • sleep<const Name extends string = string>(name: Name, duration: Duration): Wait<void, Name>

    Durable sleep. The run resumes after duration, on the same version. Give it to waitForAny as a timer.

  • sleepUntil(name: string, until: Date | number): Promise<void>

    Durable sleep until a Date or an epoch-milliseconds number.

  • ask(name: string, options: AskOptions & { schema?: undefined }): Promise<string>

    ask<Answer>(name: string, options: AskOptions & { schema: Schema<Answer> }): Promise<Answer>

    Asks agent and returns its final answer as text. A run has one conversation per step, which the workflow owns: a resumed run gets the stored answer. The run waits while the agent works and while its tools wait for approval. Asks agent for JSON that matches schema, a Standard JSON Schema or plain JSON Schema, and returns it. An answer that doesn't match gets one more turn that says what is wrong; a second miss fails the step, with no retries.

  • waitForEvent<T = unknown, const Name extends string = string>(name: Name, options?: WaitForEventOptions): Wait<T | null, Name>

    Waits for the event name (sent to eventUrl(name) or POST /v1/runs/:id/events/:name) and returns its data, the parsed JSON body or the text, or null once the timeout passes. An event sent before the run waits is kept. Names: 1 to 64 letters, digits, - and _, not starting with sl-. Waiting counts against the run's lifetime, not steps.

  • eventUrl(name: string): string

    A URL that sends this run the event name when POSTed to, with no API key: it reaches this run and event only.

  • idempotencyKey(name: string): string

    sl_ and 32 hex characters from this run's id and name: the same on every retry, replay and resume of the run, different in every other run. Pass it as Idempotency-Key to Stripe and similar APIs. Not a step; no network.

  • tag(tags: Readonly<Record<string, string>>): Promise<void>

    Tags the run, such as { incident: "INC-4211" }: not a step, unbilled, only outside step.run. A newer value replaces the older; a resumed run writes nothing again. A run holds 20 tags with its search keys, of 1 to 256 bytes.

  • status(value: RunStatusValue): Promise<void>

    Publishes value, a JSON object of 16 KiB at most, as the run's status (GET /v1/runs/:id/status). Not a step; a resumed run's calls outside steps don't publish again. Any other value, or a wrong plan or rollout, throws TypeError.

  • snapshot(device: string, text: string, options?: SnapshotOptions): Promise<void>

    Keeps text, device's config, as a run snapshot (GET /v1/runs/:id/snapshots), readable secrets and credentials such as SNMP communities, local user hashes and keys redacted: 256 KiB after redaction, else TypeError, 1,000 a run. Not a step: unbilled, only outside step.run; a resumed run keeps nothing again.

  • waitForApproval<const Name extends string = string>(name: Name, options?: WaitForApprovalOptions): Wait<ApprovalDecision, Name>

    Puts a request in the workspace's Approvals inbox and waits for an approver's answer; unanswered by the timeout, it counts as denied. Waiting counts against the run's lifetime, not steps. Names can't end like refund #2.

  • waitForAny<const W extends readonly Wait<unknown>[]>(name: string, waits: W, options?: WaitForAnyOptions): Promise<WinnerOf<W[number]>>

    Returns the name and value of whichever of waits finishes first: 1 to 10 waitForEvent, waitForApproval and sleep calls, not awaited, with different names. The rest stop, a pending approval is withdrawn, and a resumed run gets the same winner.

  • continueAsNew(state: unknown): Promise<never>

    In a keyed workflow, ends this run (completed, no output) and starts its key's next run on the current version with state as its payload; events sent meanwhile reach it. It throws ContinuedAsNew: let that through.

  • start(name: string, options: StartOptions): Promise<string>

    Starts a run of another workflow in this workspace and returns its run id, without waiting. The id comes from this run and name, so a resumed run never starts a second one. It counts toward your limits like any run.

  • call<T = unknown>(name: string, options: StartOptions): Promise<T>

    Starts a run like start, waits for it to end and returns its result; a failed run fails this step with its error. The wait counts toward the run's lifetime, not its steps, and the run sleeps while it waits.

  • exec(name: string, options: ExecOptions): Promise<ExecResult>

    Runs a command on a runner in your own network and returns its result. An exit code outside okExitCodes throws ExecError, and a command no runner ran or finished throws an Error. A resumed run gets the stored result.

  • activity<Output = unknown>(label: string, options: ActivityOptions): Promise<Output>

    Runs a registered activity on a runner in your own network and returns the JSON its program writes. If it fails, it throws ActivityError; if no runner ran or finished it, an Error. A resumed run gets the stored output.

  • decide<Input, Option extends string>(name: string, decision: DecisionDefinition<Input, Option>, input: Input): Promise<DecisionResult<Option>>

    Asks decision's model its question about the fields decision.state(input) returns, and returns the answer with every option's probability; the run's detail keeps the trace. A resumed run gets the stored answer.

Log

ctx.log: one log line per call, shown with the run. fields, if given, follow message as JSON.

  • debug(message: string, fields?: Record<string, unknown>): void

    A line at level debug.

  • info(message: string, fields?: Record<string, unknown>): void

    A line at level log.

  • warn(message: string, fields?: Record<string, unknown>): void

    A line at level warn.

  • error(message: string, fields?: Record<string, unknown>): void

    A line at level error.

StateListOptions

ctx.state.list's options. Keys come back in order; pass the last one as after for the next page.

  • prefix?: string

    Only keys that start with it.

  • after?: string

    Only keys after it.

  • limit?: number

    At most this many keys, 1 to 1,000. Default 1,000.

State

ctx.state: JSON values kept per workflow, shared by all its runs and versions. The last write wins. Every method works only inside step.run and throws outside one, since a read outside a step can differ when the run resumes. A key is 1 to 512 bytes. Writes past the plan's limits (keys per workflow, value size, total) throw.

  • get<T = unknown>(key: string): Promise<T | undefined>

    The value stored at key, or undefined if there is none.

  • set(key: string, value: unknown): Promise<void>

    Stores value as JSON at key, replacing what was there.

  • delete(key: string): Promise<void>

    Removes key. Removing a key that isn't there does nothing.

  • list(options?: StateListOptions): Promise<string[]>

    The workflow's keys, in order.

Context

The run context: the one object your function receives. Destructure what you need. Payload is the payload type you give workflow.

  • payload: Payload

    The webhook body: parsed JSON when the request is sent as application/json, the raw text otherwise.

  • runId: string

    This run's id.

  • key: string | null

    A keyed workflow's run's key (workflow({ key })), null for any other run.

  • continuedFrom: string | null

    The run this one continued as new from (step.continueAsNew), null for a key's first run and any other.

  • step: Step

    Durable steps and sleeps.

  • vars: Readonly<Record<string, string>>

    vars.NAME: the workspace value, overridden per workflow. A name that is not set reads as undefined.

  • secrets: Readonly<Record<string, string>>

    secrets.NAME for each secret with hosts. It's a stand-in string that the gateway replaces with the real value on requests to those hosts. An unknown name throws.

  • reveal(secret: string): string

    The value of a secret marked readable. Every load is audited. Wherever the value shows up in logs, in the run's output or in an error, it is replaced by [redacted].

  • sign(secret: string, data: string, encoding?: "hex" | "base64"): Promise<string>

    HMAC-SHA256 of data with a secret marked hmac. Returns only the signature (hex by default). The secret never enters your code.

  • log: Log

    log.info(message, fields?), and debug, warn, error: one log line each, shown with the run.

  • state: State

    JSON values kept per workflow across runs. Use it only inside step.run.

Concurrency

workflow's concurrency: at most limit runs of the workflow at once, per value of the payload field key when it names one. Runs past the limit wait in arrival order, with the status queued, and start as runs with the same key end.

  • limit: number

    Runs at once, from 1 to the workspace's concurrent runs.

  • key?: string

    A dotted path into the payload, such as "customer.id". Runs whose payloads hold the same value there share the limit; a run without the field uses the key "". Without key, the limit counts every run of the workflow.

WorkflowOptions

workflow's options, given as workflow({ payload, concurrency, decisions, search, onCancel, key }, run).

  • payload?: Schema<Payload>

    The payload's schema: a Standard JSON Schema, such as a zod object, or plain JSON Schema, read at deploy. A webhook or API run whose payload fails it gets 400, and a workflow tool with no parameters uses it.

  • concurrency?: Concurrency

    How many runs may run at once, read at deploy. Runs past it wait instead of being refused.

  • decisions?: Readonly<Record<string, DecisionDefinition<never, string>>>

    The decisions step.decide uses, by name, read at deploy. Each one's versions are kept under its name.

  • search?: Readonly<Record<string, string>>

    Search keys, read at deploy: up to 10 tag names, each to a dotted payload path such as "customer.id". A run gets each tag from its payload as it arrives, running no code: a string of 1 to 256 bytes, or a number or boolean as JSON.

  • onCancel?: (ctx: CancelContext<Payload>) => unknown

    Cleans up when a started run is cancelled: once the run's step that was running ends, its next step doesn't start, and onCancel runs instead, with its own steps, before the run ends cancelled. Read at deploy.

  • key?: string

    A dotted payload path such as "customer.id", read at deploy, whose value (a string of 1 to 128 bytes, or an integer) is the run's key. A key has one open run: a start while it has one starts nothing and answers that run.

WorkflowDefinition

What workflow returns. The module's default export must be one.

  • readonly kind: "shiftlabs.workflow"

    Marks the default export as a workflow.

  • readonly run: (ctx: Context<Payload>) => Promise<Result>

    The function given to workflow.

  • readonly payload?: Schema<Payload>

    The payload schema given to workflow, if any.

  • readonly concurrency?: Concurrency

    The concurrency given to workflow, if any.

  • readonly decisions?: Readonly<Record<string, DecisionDefinition<never, string>>>

    The decisions given to workflow, if any.

  • readonly search?: Readonly<Record<string, string>>

    The search keys given to workflow, if any.

  • readonly onCancel?: (ctx: CancelContext<Payload>) => unknown

    The onCancel given to workflow, if any.

  • readonly key?: string

    The key path given to workflow, if any.

workflow

The module's default export must be workflow(…). run receives the run context; Payload is the type of the webhook payload, which a payload schema sets, and Result of the value run returns. Code outside step.run runs again each time the run resumes, after a sleep or a retry. Only step results are stored. Put side effects inside steps.

typescriptsignature
function workflow<Payload = unknown, Result = unknown>(
  run: (ctx: Context<Payload>) => Promise<Result>,
): WorkflowDefinition<Payload, Result>;
function workflow<Payload = unknown, Result = unknown>(
  options: WorkflowOptions<Payload>,
  run: (ctx: Context<Payload>) => Promise<Result>,
): WorkflowDefinition<Payload, Result>;

FatalError

throw new FatalError(message) in a step fails the step and the run at once, with no more attempts. Thrown outside a step, it fails the run as any error does.

typescriptclass
class FatalError extends Error {
  constructor(message?: string);
}

ExecError

What step.exec throws when the command exits with a code outside okExitCodes, or times out. result holds its exit code and output.

typescriptclass
class ExecError extends Error {
  readonly result: ExecResult;
  constructor(message: string, result: ExecResult);
}

ActivityError

What step.activity throws when the activity fails: its program exits with a code other than 0, times out, misses a heartbeat, or writes output that isn't JSON or is over 256 KiB. result holds how it ran.

typescriptclass
class ActivityError extends Error {
  readonly result: ActivityResult;
  constructor(message: string, result: ActivityResult);
}

ContinuedAsNew

What step.continueAsNew, and a wait given continueWith, throw once the run continued as new: it ends completed, and its key's next run, runId, starts with the state. Let it through: a step called after it throws again.

typescriptclass
class ContinuedAsNew extends Error {
  readonly runId: string;
  constructor(runId: string);
}

decision

A decision: a question fixed in code that a decision model answers about the data fields state builds, with a probability for every option. Name it in workflow({ decisions }), then ask it with step.decide.

typescriptsignature
function decision<Input, const Option extends string>(
  options: DecisionOptions<Input, Option> & { choices: readonly Option[] | { readonly [K in Option]: string } },
): DecisionDefinition<Input, Option>;
function decision<Input, const Option extends string>(
  options: DecisionOptions<Input, Option> & { score: readonly Option[] },
): DecisionDefinition<Input, Option>;
function decision<Input>(
  options: DecisionOptions<Input, "yes" | "no"> & { yesNo: string },
): DecisionDefinition<Input, "yes" | "no">;

WorkflowToolOptions

A workflow tool's options, given to workflowTool.

  • description: string

    When to use the tool, 1 to 1,024 characters. The model chooses tools by it.

  • parameters?: Schema

    The arguments, an object schema up to 8 KB. shiftlabs deploy converts a Standard JSON Schema. Left out, the workflow's payload schema when the agent is deployed, or any object when it has none.

  • approval: "never" | "always" | { approvers?: Approver[]; approvals?: number }

    Required. "never": calls run without asking. "always": each call waits for an admin's approval. { approvers }: for one of them (see Approver); emails must be admins when you deploy. { approvals }: that many different members, 1 to 5; name at least that many members, or a role.

  • waitSeconds?: number

    How long a call waits for the run's output, 5 to 300 seconds. Default 60.

WorkflowToolDefinition

What workflowTool returns.

typescripttype
type WorkflowToolDefinition = WorkflowToolOptions & {
  readonly workflow: string;
};

workflowTool

A workflow tool: a call runs the workspace's workflow named workflow, with the model's arguments as its payload.

typescriptsignature
function workflowTool(
  workflow: string,
  options: WorkflowToolOptions,
): WorkflowToolDefinition;

FileReference

What file returns.

typescripttype
type FileReference = { readonly kind: "shiftlabs.file"; readonly path: string };

file

A text file's contents, such as long instructions: file("./agents/support.md"). shiftlabs deploy reads it, relative to the config file.

typescriptsignature
function file(path: string): FileReference;

AgentBudget

What an agent may spend on its model, in US dollars.

  • conversationUsd?: number

    What one conversation may spend, above 0 and at most 5. Default 0.5. Its next message is refused once it is spent.

  • monthlyUsd?: number

    What all its conversations may spend in a calendar month (UTC), above 0 and at most 1,000. Messages are refused once it is spent, until the month ends. No cap of its own when left out.

  • endUserDailyUsd?: number | null

    What each end user, a person your app names or a chat token's, may spend in a calendar day (UTC), all their conversations with it together: above 0 and at most 100, or null for no cap. Default 0.1. Their next message is refused once it is spent, until the day ends.

AgentAccess

Who may message an agent: the members from role up, and the members in members.

  • role?: "viewer" | "approver" | "developer" | "admin"

    The lowest role that may message it: "viewer", "approver", "developer" or "admin". API keys count by their role. When left out, only members may.

  • members?: string[]

    Up to 100 members, by the email they sign in with, who may message it whatever their role.

Model

A model agents may use. Editors complete the ids listed here; any other string still type-checks, and the deploy refuses an id that isn't listed, except <provider>/<model> on your own provider key (providerKey). Each model has a quality tier, and Free workspaces use the small models.

typescripttype
type Model =
  | "@cf/aisingapore/gemma-sea-lion-v4-27b-it"
  | "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b"
  | "@cf/deepseek-ai/deepseek-v4.1-flash-1017"
  | "@cf/deepseek-ai/deepseek-v4-flash-0731"
  | "@cf/deepseek-ai/deepseek-v4-pro-0813"
  | "@cf/google/gemma-3-12b-it"
  | "@cf/google/gemma-4-26b-a4b-it"
  | "@cf/ibm-granite/granite-4.0-h-micro"
  | "@cf/meta/llama-2-7b-chat-fp16"
  | "@cf/meta/llama-3-8b-instruct"
  | "@cf/meta/llama-3-8b-instruct-awq"
  | "@cf/meta/llama-3.1-70b-instruct-fp8-fast"
  | "@cf/meta/llama-3.1-8b-instruct"
  | "@cf/meta/llama-3.1-8b-instruct-awq"
  | "@cf/meta/llama-3.1-8b-instruct-fp8"
  | "@cf/meta/llama-3.1-8b-instruct-fp8-fast"
  | "@cf/meta/llama-3.2-11b-vision-instruct"
  | "@cf/meta/llama-3.2-1b-instruct"
  | "@cf/meta/llama-3.2-3b-instruct"
  | "@cf/meta/llama-3.3-70b-instruct-fp8-fast"
  | "@cf/meta/llama-4-scout-17b-16e-instruct"
  | "@cf/mistral/mistral-7b-instruct-v0.1"
  | "@cf/mistralai/mistral-small-3.1-24b-instruct"
  | "@cf/moonshotai/kimi-k2.5"
  | "@cf/moonshotai/kimi-k2.6"
  | "@cf/moonshotai/kimi-k2.7-code"
  | "@cf/nvidia/nemotron-3-120b-a12b"
  | "@cf/openai/gpt-oss-120b"
  | "@cf/openai/gpt-oss-20b"
  | "@cf/qwen/qwen2.5-coder-32b-instruct"
  | "@cf/qwen/qwen3-30b-a3b-fp8"
  | "@cf/qwen/qwen3.8-27b"
  | "@cf/qwen/qwq-32b"
  | "@cf/zai-org/glm-4.7-flash"
  | "@cf/zai-org/glm-5.2"
  | "@cf/zai-org/glm-5.3"
  | "@cf/zai-org/glm-5.3-flash"
  | (string & {});

AgentOptions

An agent, given to agent.

  • title: string

    1 to 80 characters, shown in the dashboard.

  • description?: string

    A sentence on what the agent does, up to 300 characters, shown in the dashboard's list of agents.

  • instructions: string | FileReference

    What the agent is for and how it works, 1 to 8,000 characters. Use file("./x.md") to keep them in a file.

  • model?: Model

    The model: a Workers AI id, default @cf/zai-org/glm-4.7-flash (Free workspaces use the small models), or <provider>/<model> such as "openai/gpt-4.1-mini" on your own provider key, with providerKey.

  • fallback?: Model[]

    Up to 3 more models, tried in order when a request to model fails before it answers; none of a lower tier. On your own key, only its provider's. Left out, the platform picks one (none on your key); [] means none.

  • providerKey?: string

    The workspace secret, by name (e.g. "OPENAI_API_KEY"), holding your own provider key, for a model named <provider>/<model>. Pro only. Your provider bills those calls, not shiftlabs. The secret must not be readable.

  • maxTurns?: number

    Model turns one message may take, 1 to 20. Default 6.

  • budget?: AgentBudget

    What it may spend: 0.5 per conversation, 0.1 a day per end user and no monthly cap of its own when left out.

  • access?: AgentAccess

    Who may message it. Every member from viewer up when left out.

  • welcome?: string

    Shown in the dashboard's chat before the first message, up to 500 characters.

  • suggestions?: string[]

    Up to 4 first messages, each up to 200 characters, offered in the dashboard's chat; choosing one sends it.

  • tools?: WorkflowToolDefinition[]

    Up to 16 workflow tools, from workflowTool. The tools in code count toward the 16.

  • code?: string

    The file, relative to the config, whose default export is tools({ ... }). Every tool in it joins the agent.

AgentDefinition

What agent returns.

typescripttype
type AgentDefinition = AgentOptions & { readonly kind: "shiftlabs.agent" };

agent

An agent for project's agents, under its name. shiftlabs deploy releases it with the project's workflows.

typescriptsignature
function agent(options: AgentOptions): AgentDefinition;

ScheduleOverlap

What a tick does while the run the schedule last started hasn't ended: "skip" starts nothing; "buffer-one" starts it once that run ends, at most one waiting; "allow" starts it anyway; "cancel-other" cancels that run and starts once it has ended.

typescripttype
type ScheduleOverlap = "skip" | "buffer-one" | "allow" | "cancel-other";

ScheduleOptions

A workflow schedule's options, given to schedule(workflow, options).

  • cron: string

    Five fields, minute hour day month weekday, such as "0 3 * * *"; or @hourly, @daily, @weekly, @monthly, @yearly.

  • timezone?: string

    An IANA time zone, such as "America/Detroit", that cron reads in, clock changes included. Default "UTC".

  • payload?: Payload

    The run's payload, JSON up to 16 KB, checked against the workflow's payload schema at deploy. Default {}.

  • overlap?: ScheduleOverlap

    A tick while the previous run hasn't ended. Default "allow". Trigger now and backfills don't follow it.

  • jitter?: Duration

    Starts each tick up to this much after its time, the same for a tick every time: 1 second to 1 day, shorter than the cron's gap.

  • catchup?: Duration

    After downtime or a pause, the missed ticks start one run only if the newest is at most this old: 1 minute to 365 days. Default: however old.

  • pauseOnFailure?: boolean

    Pause the schedule when a run it started fails, with a note naming the run.

AgentScheduleOptions

An agent schedule, given to schedule({ agent, message, cron }): each tick starts a conversation with message.

  • agent: string

    The agent's name, in this project or already in the workspace.

  • message: string

    The first message, 1 to 4,000 characters.

  • cron: string

    As for a workflow schedule.

  • timezone?: string

    As for a workflow schedule. Default "UTC".

  • jitter?: Duration

    As for a workflow schedule.

  • catchup?: Duration

    As for a workflow schedule.

ScheduleDefinition

What schedule returns.

typescripttype
type ScheduleDefinition =
  | ({
      readonly kind: "shiftlabs.schedule";
      readonly workflow: string;
    } & ScheduleOptions)
  | ({ readonly kind: "shiftlabs.schedule" } & AgentScheduleOptions);

schedule

A schedule for project's schedules, under its name: schedule("sync", { cron: "0 3 * * *" }) starts a run of the workflow sync at each tick, with the origin schedule; schedule({ agent, message, cron }) messages an agent.

typescriptsignature
function schedule<Payload = unknown>(
  workflow: string,
  options: ScheduleOptions<Payload>,
): ScheduleDefinition;
function schedule(options: AgentScheduleOptions): ScheduleDefinition;

ProjectOptions

A project, given to project.

  • workflows?: Record<string, string>

    Workflow name to its file (.ts, .js or .py), relative to the config file.

  • agents?: Record<string, AgentDefinition>

    Agent name to its agent(...).

  • schedules?: Record<string, ScheduleDefinition>

    Schedule name to its schedule(...). shiftlabs deploy replaces the workspace's schedules with these, in the same release; {} removes them all, and leaving schedules out keeps the workspace's as they are.

  • runnerProfile?: string

    The runner image profile, name or name@version, of step.exec and step.activity calls that name none. Each version keeps the one it was deployed with, so a rollback brings it back; without it, they run on any runner.

ProjectDefinition

What project returns.

typescripttype
type ProjectDefinition = ProjectOptions & {
  readonly kind: "shiftlabs.project";
};

project

The default export of shiftlabs.config.ts. shiftlabs deploy stages its workflows, then makes them and its agents current in one release.

typescriptsignature
function project(options: ProjectOptions): ProjectDefinition;

SqlCursor

What sql.exec returns.

  • toArray(): Record<string, unknown>[]

    Every row, one object each.

  • one(): Record<string, unknown>

    The only row. Throws unless there is exactly one.

  • readonly rowsWritten: number

    Rows the statement wrote.

ToolContext

What a code tool's function receives after its arguments. It runs with no network and no secrets.

  • sql: { exec(query: string, ...bindings: unknown[]): SqlCursor }

    A SQLite database of the agent's own, one per person who talks to it. It is kept between conversations.

  • conversation: string

    The conversation's id.

  • log: Log

    log.info(message, fields?), and debug, warn, error.

ToolFunction

A code tool's function. It gets the model's arguments and the context. The model reads its return value as JSON. Args is what parameters accepts; annotate it when parameters is a plain JSON Schema.

typescripttype
type ToolFunction<Args = unknown> = (args: Args, ctx: ToolContext) => unknown;

ToolOptions

A code tool's options, given to tool.

  • description: string

    When to use the tool, 1 to 1,024 characters. The model chooses tools by it. The upload refuses a tool without one.

  • parameters?: Parameters

    The arguments, an object schema up to 8 KB. The upload converts a Standard JSON Schema. Any object when left out.

  • waitSeconds?: number

    How long a call waits for the function, 5 to 300 seconds. Default 60.

ToolDefinition

What tool returns.

typescripttype
type ToolDefinition = ToolOptions & {
  readonly kind: "shiftlabs.tool";
  readonly run: ToolFunction<never>;
};

tool

A code tool, for tools in the agent's code: a call runs run with the model's arguments. It never waits for approval. With a Standard JSON Schema as parameters, run's arguments get its input type.

typescriptsignature
function tool<Parameters extends Schema, Args = ArgumentsOf<Parameters>>(
  options: ToolOptions<Parameters>,
  run: ToolFunction<Args>,
): ToolDefinition;

ToolsDefinition

What tools returns.

  • readonly kind: "shiftlabs.tools"

    Marks the default export as an agent's code.

  • readonly tools: Record<string, ToolDefinition>

    Tool name to its tool(...).

tools

The default export of an agent's code: tool name to tool(...). Names are lowercase letters, digits and hyphens. agent({ code }) adds every tool here to the agent.

typescriptsignature
function tools(definitions: Record<string, ToolDefinition>): ToolsDefinition;