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.
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.
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;
jsonSchemaconverts it to JSON Schema.
Schema
A Standard JSON Schema or a plain JSON Schema object. T is the type of the data it accepts.
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; aFatalErroris never retried.delay: a duration between attempts, default"10 seconds".backoff:"constant","linear"or"exponential"(the default).timeout?: DurationA duration after which an attempt fails, default
"10 minutes".
UndoContext
What an undo function gets.
output: TWhat the step returned.
error: ErrorThe error the run failed with.
UndoFunction
Undoes a step once the run has failed: see RunConfig.undo. Its return value is dropped.
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?: DurationA duration after which an attempt fails, default
"10 minutes".approval?: WaitForApprovalOptionsWaits 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?: DurationAs 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?: DurationAs in
StepConfig.undo?: UndoFunction<T> | UndoOptions<T>As in
RunConfig.signal: trueGives
fnanAbortSignalthat 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: AbortSignalAborted 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: stringThe step's name.
output: unknownWhat it returned.
CancelContext
What onCancel gets: the run's context, and its step.run calls that completed before the cancel.
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: stringThe name of an agent in this workspace.
message: stringWhat 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: stringThe step's name, as
step.runwill give it.group?: stringThe rollout group it changes, a group's
idinrollout.batch?: numberThe rollout batch it belongs to, 0 or more.
RolloutDeviceState
Where one device's change is, for step.status({ rollout }).
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?: stringHow 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.
type RunStatusValue = { plan?: RunPlanStep[]; rollout?: RolloutState } & Record<string, unknown>;
WaitForEventOptions
step.waitForEvent's options.
timeout?: DurationHow long to wait before
step.waitForEventreturnsnull, default"24 hours".continueWith?: unknownA 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?: unknownAs
waitForEvent's: the state a keyed run continues as new with if it must continue at this race.
SnapshotOptions
step.snapshot's options.
stage?: stringWhen 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.
type Approver = "role:admin" | "role:approver" | "role:manager" | (string & {});
WaitForApprovalOptions
step.waitForApproval's options.
message?: stringWhat approvers read in the Approvals inbox, 2,000 characters at most.
timeout?: DurationHow 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?: numberHow 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?: ApprovalPolicyWhat the request is: its policy's
name, 1 to 100 characters, and itsrisk. Approvers see both.
ApprovalPolicy
step.waitForApproval's policy: which of your rules asks, and how risky the change is.
name?: stringSuch as
"production change", 1 to 100 characters.risk?: "low" | "medium" | "high""low","medium"or"high".
ApprovalDecision
What step.waitForApproval returns.
approved: booleanFalse when an approver denied, or nobody answered before the timeout.
by: string | nullThe approver's email, or the API key's id;
nullwhen nobody answered.note: string | nullThe 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.
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: NameThe wait's name.
value: ValueAn event's data, or
nullonce its timeout passed; an approval's decision;nullfor a sleep.
WinnerOf
What step.waitForAny returns for the waits W: one Winner per wait, a sleep's value null.
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: stringThe name of a workflow in this workspace.
payload?: unknownThe 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: stringThe secret's name. Only a secret marked readable can be passed.
ExecOptions
step.exec's options. Give run or command, not both.
run?: stringA bash script, run with
bash --noprofile --norc -eo pipefailin 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?: stringText sent to the command's standard input.
timeout?: DurationHow long the command may run before the runner stops it, default
"10 minutes", up to your plan's limit.runner?: stringThe pool of runners that may run it, default
"default".profile?: stringThe 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'srunnerProfile, 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:
limitmore times, 0 to 10,delayapart, withbackoff"exponential"unless given. No retries by default.
ExecResult
What step.exec returns, and an ExecError's result.
exitCode: numberThe command's exit code: 124 when it timed out.
stdout: stringThe last 256 KiB of the command's standard output, with secret values replaced by
[redacted].stderr: stringThe last 256 KiB of its standard error, with secret values replaced by
[redacted].stdoutBytes: numberThe size of all its standard output, in bytes.
stderrBytes: numberThe size of all its standard error, in bytes.
truncated: booleanTrue when
stdoutorstderrholds only the end of its stream.timedOut: booleanTrue when the runner stopped the command at its timeout.
durationMs: numberHow long the command ran, in milliseconds.
runner: stringThe name of the runner that ran it.
attempt: numberWhich try this was, 1 for the first.
ActivityOptions
step.activity's options.
name: stringThe activity's name in the runner's activities file: lowercase letters, digits and
-.input?: unknownWhat 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?: stringThe pool of runners that may run it, default
"default". Only one that lists the activity takes it.profile?: stringAs
step.exec's: the runner image profile,nameorname@version; by default the project'srunnerProfile.requires?: string[]As
step.exec's: tools the runner's image manifest must list. None by default.timeout?: DurationHow long the activity may run before the runner stops it, default
"10 minutes", up to your plan's limit.heartbeat?: DurationHow 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:
limitmore times, 0 to 10,delayapart, withbackoff"exponential"unless given. No retries by default.
ActivityResult
An ActivityError's result: how the attempt that failed ran.
activity: stringThe activity's name.
version: stringIts version in the activities file of the runner that ran it,
""for none.exitCode: numberThe program's exit code: 124 when the runner stopped it.
stdout: stringThe program's standard output, the output's JSON text: up to 256 KiB, secret values replaced by
[redacted].stderr: stringThe last 16 KiB of its standard error, with secret values replaced by
[redacted].stdoutBytes: numberThe size of all its standard output, in bytes.
stderrBytes: numberThe size of all its standard error, in bytes.
truncated: booleanTrue when
stdoutorstderrholds only the end of its stream.timedOut: booleanTrue when the runner stopped the program at its timeout.
heartbeatTimedOut: booleanTrue when the runner stopped the program because no heartbeat came within
heartbeat.durationMs: numberHow long the program ran, in milliseconds.
runner: stringThe name of the runner that ran it.
attempt: numberWhich 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.
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: numberA whole number from 1. Give a new one to change the question, the choices or levels, or the state's fields.
model: DecisionModelThe model that answers. The model and the threshold can change under the same version.
question?: stringWhat to decide about the state, 1 to 2,000 characters, with
choicesorscore.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?: stringA 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?: numberFrom 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,nullfor 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.
type DecisionDefinition<Input = unknown, Option extends string = string> = DecisionOptions<Input, Option> & { readonly kind: "shiftlabs.decision" };
DecisionResult
What step.decide returns.
answer: Option | nullThe most probable option, or
nullwhen its probability is under the threshold.top: OptionThe most probable option, whatever the threshold.
probabilities: Record<Option, number>Every option's probability, from 0 to 1.
score: number | nullA score decision's probability-weighted level, from 0 for the lowest;
nullfor the others.version: numberThe decision's version.
model: DecisionModelThe model that answered.
threshold: number | nullThe threshold it was held to,
nullfor 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
fnonce and stores its result. When the run resumes, the step returns the stored result instead of running again. Runsfnonce and stores its result, asrun(name, fn). Withsignal: true,fngets{ signal }, which aborts when the run is asked to cancel or terminate while the step runs. Runsfnonce and stores its result. When the run resumes, the step returns the stored result instead of running again.config.undoundoes 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 towaitForAnyas a timer.sleepUntil(name: string, until: Date | number): Promise<void>Durable sleep until a
Dateor 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
agentand 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. Asksagentfor JSON that matchesschema, 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 toeventUrl(name)orPOST /v1/runs/:id/events/:name) and returns its data, the parsed JSON body or the text, ornullonce the timeout passes. An event sent before the run waits is kept. Names: 1 to 64 letters, digits,-and_, not starting withsl-. Waiting counts against the run's lifetime, not steps.eventUrl(name: string): stringA URL that sends this run the event
namewhen POSTed to, with no API key: it reaches this run and event only.idempotencyKey(name: string): stringsl_and 32 hex characters from this run's id andname: the same on every retry, replay and resume of the run, different in every other run. Pass it asIdempotency-Keyto 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 outsidestep.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 wrongplanorrollout, 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, elseTypeError, 1,000 a run. Not a step: unbilled, only outsidestep.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
waitsfinishes first: 1 to 10waitForEvent,waitForApprovalandsleepcalls, 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
stateas its payload; events sent meanwhile reach it. It throwsContinuedAsNew: 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
okExitCodesthrowsExecError, and a command no runner ran or finished throws anError. 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, anError. 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 fieldsdecision.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>): voidA line at level
debug.info(message: string, fields?: Record<string, unknown>): voidA line at level
log.warn(message: string, fields?: Record<string, unknown>): voidA line at level
warn.error(message: string, fields?: Record<string, unknown>): voidA 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?: stringOnly keys that start with it.
after?: stringOnly keys after it.
limit?: numberAt 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, orundefinedif there is none.set(key: string, value: unknown): Promise<void>Stores
valueas JSON atkey, 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: PayloadThe webhook body: parsed JSON when the request is sent as
application/json, the raw text otherwise.runId: stringThis run's id.
key: string | nullA keyed workflow's run's key (
workflow({ key })),nullfor any other run.continuedFrom: string | nullThe run this one continued as new from (
step.continueAsNew),nullfor a key's first run and any other.step: StepDurable steps and sleeps.
vars: Readonly<Record<string, string>> vars.NAME: the workspace value, overridden per workflow. A name that is not set reads asundefined.secrets: Readonly<Record<string, string>> secrets.NAMEfor 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): stringThe 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
datawith a secret markedhmac. Returns only the signature (hex by default). The secret never enters your code.log: Loglog.info(message, fields?), anddebug,warn,error: one log line each, shown with the run.state: StateJSON 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: numberRuns at once, from 1 to the workspace's concurrent runs.
key?: stringA 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"". Withoutkey, 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
parametersuses it.concurrency?: ConcurrencyHow 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.decideuses, 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>) => unknownCleans up when a started run is cancelled: once the run's step that was running ends, its next step doesn't start, and
onCancelruns instead, with its own steps, before the run endscancelled. Read at deploy.key?: stringA 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?: ConcurrencyThe 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>) => unknownThe
onCancelgiven toworkflow, if any.readonly key?: stringThe 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.
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.
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.
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.
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.
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.
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: stringWhen to use the tool, 1 to 1,024 characters. The model chooses tools by it.
parameters?: SchemaThe arguments, an object schema up to 8 KB.
shiftlabs deployconverts 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 (seeApprover); 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?: numberHow long a call waits for the run's output, 5 to 300 seconds. Default 60.
WorkflowToolDefinition
What workflowTool returns.
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.
function workflowTool(
workflow: string,
options: WorkflowToolOptions,
): WorkflowToolDefinition;
FileReference
What file returns.
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.
function file(path: string): FileReference;
AgentBudget
What an agent may spend on its model, in US dollars.
conversationUsd?: numberWhat one conversation may spend, above 0 and at most 5. Default 0.5. Its next message is refused once it is spent.
monthlyUsd?: numberWhat 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 | nullWhat each end user, a
personyour 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, ornullfor 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, onlymembersmay.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.
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: string1 to 80 characters, shown in the dashboard.
description?: stringA sentence on what the agent does, up to 300 characters, shown in the dashboard's list of agents.
instructions: string | FileReferenceWhat the agent is for and how it works, 1 to 8,000 characters. Use
file("./x.md")to keep them in a file.model?: ModelThe 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, withproviderKey.fallback?: Model[]Up to 3 more models, tried in order when a request to
modelfails 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?: stringThe workspace secret, by name (e.g.
"OPENAI_API_KEY"), holding your own provider key, for amodelnamed<provider>/<model>. Pro only. Your provider bills those calls, not shiftlabs. The secret must not be readable.maxTurns?: numberModel turns one message may take, 1 to 20. Default 6.
budget?: AgentBudgetWhat 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?: AgentAccessWho may message it. Every member from viewer up when left out.
welcome?: stringShown 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 incodecount toward the 16.code?: stringThe file, relative to the config, whose default export is
tools({ ... }). Every tool in it joins the agent.
AgentDefinition
What agent returns.
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.
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.
type ScheduleOverlap = "skip" | "buffer-one" | "allow" | "cancel-other";
ScheduleOptions
A workflow schedule's options, given to schedule(workflow, options).
cron: stringFive fields, minute hour day month weekday, such as
"0 3 * * *"; or@hourly,@daily,@weekly,@monthly,@yearly.timezone?: stringAn IANA time zone, such as
"America/Detroit", thatcronreads in, clock changes included. Default"UTC".payload?: PayloadThe run's payload, JSON up to 16 KB, checked against the workflow's payload schema at deploy. Default
{}.overlap?: ScheduleOverlapA tick while the previous run hasn't ended. Default
"allow". Trigger now and backfills don't follow it.jitter?: DurationStarts 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?: DurationAfter 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?: booleanPause 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: stringThe agent's name, in this project or already in the workspace.
message: stringThe first message, 1 to 4,000 characters.
cron: stringAs for a workflow schedule.
timezone?: stringAs for a workflow schedule. Default
"UTC".jitter?: DurationAs for a workflow schedule.
catchup?: DurationAs for a workflow schedule.
ScheduleDefinition
What schedule returns.
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.
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,.jsor.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 deployreplaces the workspace's schedules with these, in the same release;{}removes them all, and leavingschedulesout keeps the workspace's as they are.runnerProfile?: stringThe runner image profile,
nameorname@version, ofstep.execandstep.activitycalls 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.
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.
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: numberRows 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: stringThe conversation's id.
log: Loglog.info(message, fields?), anddebug,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.
type ToolFunction<Args = unknown> = (args: Args, ctx: ToolContext) => unknown;
ToolOptions
A code tool's options, given to tool.
description: stringWhen to use the tool, 1 to 1,024 characters. The model chooses tools by it. The upload refuses a tool without one.
parameters?: ParametersThe arguments, an object schema up to 8 KB. The upload converts a Standard JSON Schema. Any object when left out.
waitSeconds?: numberHow long a call waits for the function, 5 to 300 seconds. Default 60.
ToolDefinition
What tool returns.
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.
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.
function tools(definitions: Record<string, ToolDefinition>): ToolsDefinition;