shiftlabs Start free
Menu Workflows

Workflows

Each workflow is a TypeScript or Python module, with the files and packages it imports.

The entry

workflow<Payload, Result>(fn) takes the type of the webhook payload and of the value fn returns. fn receives the run context. workflow({ payload }, fn) also takes the payload's schema, workflow({ concurrency }, fn) caps how many runs run at once, workflow({ key }, fn) keeps one open run per key, and workflow({ search }, fn) tags each run from its payload.

refund-check
import { workflow } from "shiftlabs";

export default workflow<{ id: string }>(
  async ({ payload, step, secrets, log }) => {
    const charge = await step.run("fetch charge", () =>
      fetch(`https://api.stripe.com/v1/charges/${payload.id}`, {
        headers: { authorization: `Bearer ${secrets.STRIPE_KEY}` },
      }).then((r) => r.json()),
    );
    log.info("charge loaded", { id: charge.id });
    await step.sleep("cool-off", "10 minutes");
    await step.run(
      "notify",
      { retries: { limit: 3, delay: "30 seconds", backoff: "exponential" } },
      () =>
        fetch("https://hooks.slack.com/services/T0/B0/x", {
          method: "POST",
          body: JSON.stringify({ text: charge.id }),
        }),
    );
  },
);

In TypeScript, the module's default export must be workflow(…). In Python, exactly one function must be decorated with @workflow. Otherwise the deploy fails with bundle failed and a hint. The deploy loads the code once, with no network, so code that runs at import time can't reach anything. Loading may take 60 seconds: past that, the deploy returns 503 {"error": "temporarily unavailable"} with a detail and Retry-After: 30, nothing is deployed, and the current version stays. Deploy again. A deploy that waited for its packages to build loads without that limit. The deploy response also lists the secret names the code reads and warns about any that are not set.

Every deploy includes the shiftlabs module. You don't need to bundle it yourself. Requests made with the global fetch go through the egress gateway, which replaces stand-ins and applies connections, limits and attribution.

Payload schemas

Give workflow the payload's schema, and webhooks and runs started from the API are checked against it before the run starts.

invoice-check
import { workflow } from "shiftlabs";

export default workflow<{ invoiceId: string; amount: number }>({
  payload: {
    type: "object",
    properties: { invoiceId: { type: "string" }, amount: { type: "number" } },
    required: ["invoiceId", "amount"],
  },
}, async ({ payload, step }) => {
  return step.run("check", () => ({
    invoiceId: payload.invoiceId,
    ok: payload.amount < 1000,
  }));
});

payload takes JSON Schema (draft 2020-12), or a schema that implements Standard JSON Schema: zod 4.2+, ArkType 2.1.28+, or Valibot through @valibot/to-json-schema. The SDK depends on none of them: install the one you use as an npm package. In Python, pass a pydantic model, with pydantic listed under packages, or a JSON Schema dict.

The deploy reads the schema when it loads the code and stores it with the version, up to 32 KB as JSON. The deploy answer shows it as payloadSchema, and GET /v1/workflows as payload_schema. A schema that can't be read fails the deploy with 400, and so does a pattern that isn't a JavaScript regular expression with the u flag, such as Python's (?P<name>…), (?i) or \Z, or relative $id values nested so deeply inside each other that the schema resolves to over 32,768 schemas, about 14 levels. The answer says where in the schema, such as at #/properties/phone. Runs are checked against the schema of the version that is current.

  • Webhooks

    A delivery whose payload fails the schema gets 400 {"error": "payload does not match the schema", "detail"} and starts no run. It counts toward no quota. A retry of a delivery that already started a run still gets 200 {"duplicate": true, "runId"}, even if the schema changed since.

  • Run now

    POST /v1/workflows/:workflow/runs, the dashboard's Run now and MCP's run_workflow get the same 400. A repeated Idempotency-Key still gets the run it started. A re-run of a run's own version sends its payload again without a check; one on the current version, or with another payload, is checked against the schema of the version it runs on.

  • Agent tools

    A workflow tool with no parameters shows the model the schema. See Agents.

  • The dashboard

    Run now shows a form built from the schema when each property is a string, a number, an integer, a boolean or a list of strings to choose from, and the JSON editor otherwise.

detail lists up to 10 problems, one a line, each with its place in the payload, such as /amount: Instance type "string" is invalid. Expected "number". A body sent without content-type: application/json is the raw text, so an object schema refuses it, and the answer says to send JSON. Each check may use 100 ms of CPU time; a payload that needs more gets the same 400. Long arrays under uniqueItems and patterns with nested repeats are the usual cause.

Concurrency

Give workflow a concurrency to cap how many of its runs run at once. Runs past the cap wait their turn instead of being refused.

sync-customer
import { workflow } from "shiftlabs";

export default workflow<{ customer: { id: string } }>({
  concurrency: { limit: 1, key: "customer.id" },
}, async ({ payload, step }) => {
  return step.run("sync", () => ({ customer: payload.customer.id }));
});

limit is how many runs may run at once, from 1 to your workspace's runs at once. key is optional: a dotted path into the payload, such as customer.id. With a key, the limit holds for each value, so one customer's runs go one at a time while other customers' runs go alongside. Runs whose payload has no value there, or null, share one key. Values compare as JSON, so "42" and 42 are different keys.

The deploy reads the setting when it loads the code and stores it with the version. The deploy answer and GET /v1/workflows show it as concurrency. A limit that isn't a whole number from 1 to your runs at once, or a key that isn't letters, digits, _, - and $ joined by dots, fails the deploy with 400 {"error": "invalid concurrency", "detail"}.

  • Waiting

    A run past the limit waits with the status queued, and GET /v1/runs, GET /v1/runs/:id and the run's page give the reason, queued_reason: "concurrency". Waiting runs start in the order they arrived, as runs with their key end, whether they completed or failed. One whose payload is too large to start fails with payload too large when its turn comes, unbilled, and the runs behind it go on.

  • Every start

    Webhooks, schedules, Run now, the API, MCP, re-runs, step.start, step.call and agent tools wait the same way. A webhook still gets 202 with the run's id.

  • Limits

    A waiting run counts toward runs per 24 hours, but not toward runs at once until it starts. Up to 1,000 runs of a workflow can wait on Free and 10,000 on Pro. Past that, a start gets 429 {"error": "quota exceeded", "limit": "concurrencyQueue"}. A waiting run's lifetime counts from when it arrived, and one that waits past it fails, unbilled. While your workspace is at its steps or CPU time per 24 hours, past its spending limit or with a payment failing, or while shiftlabs pauses new runs, no waiting run starts, even with room in its group. They start in order within 5 minutes after that ends.

  • Deploys

    The current version's setting holds for every run of the workflow, older versions' too. A deploy, release or rollback that changes it applies at once: a new key regroups the runs that haven't ended, a higher limit starts waiting runs, and removing the setting starts every waiting run your runs at once allow. A staged version changes nothing until its release. Deleting the workflow fails its waiting runs.

  • Events

    An event sent to a waiting run gets 409, with a hint to send it once the run starts.

  • Paused

    While the workflow is paused, its new runs are held. After the resume, they wait their turn here like any other start.

A run that calls its own workflow with step.call and the same key waits for itself: the called run can't start until the caller ends. Use another key, or step.start.

Keyed runs

Give workflow a key to keep one open run per value, such as one run per customer or per order. While a key's run is open, a start with that key starts nothing and answers that run.

customer-session
import { workflow } from "shiftlabs";

export default workflow<{ customer: { id: string } }>({
  key: "customer.id",
}, async ({ payload, step }) => {
  await step.sleep("cool off", "1 hour");
  return step.run("follow up", () => ({ customer: payload.customer.id }));
});

key is a dotted path into the payload, as concurrency's is. The value there is the run's key: a string of 1 to 128 bytes, or an integer, which keys as its digits, so 42 and "42" are one key. A start whose payload has neither there gets 400 {"error": "payload has no key"} and starts nothing.

A key's run is open until it ends, however it ends. Meanwhile POST /v1/workflows/:workflow/runs with that key returns 200 {"runId", "versionHash", "started": false} naming the open run, and a webhook 200 {"runId", "started": false}. That start's payload reaches no run. Once the run ends, the next start opens a new one.

  • Every start

    Webhooks, Run now, the API, MCP, schedules, re-runs, resumes and step.start answer the open run; a schedule's tick records it as the tick's run. An agent's tool call fails with an error that names it. step.call can't wait for a keyed workflow: it fails with a message to use step.start.

  • Find a key's run

    GET /v1/workflows/:workflow/open-run?key= returns the open run, {workflow, key, runId, openedAt}, or 404 {"error": "no open run"}, and GET /v1/runs?workflow=&key= lists the key's runs. The run's page shows its key, and on the Runs screen, picking a keyed workflow lets you open a key's run. The clients have workflows.openRun (Python workflows.open_run), the CLI shiftlabs workflows open-run <workflow> <key>, and MCP get_open_run.

  • Limits

    An open keyed run counts toward your runs at once like any run: a start that would open a key past it gets 429, and a start to a key that's open never does. For more keys open at once, ask for a higher runs-at-once limit. A keyed run lives up to your plan's run lifetime, and its page shows when that ends.

  • Deploys

    The deploy reads key and stores it with the version, and the deploy answer and GET /v1/workflows show it as key. A run keys by the path of the version it runs on, in the payload it starts with: a re-run on the run's own version keys as the run did, and one on the current version or with another payload keys by those. A path that isn't letters, digits, _, - and $ joined by dots fails the deploy with 400 {"error": "invalid key", "detail"}.

  • Kept

    A run's key is erased with its payload, 14 days after the run arrived or when it ends, whichever is later. Keep secrets out of keys: anyone who can see runs sees them.

Events to a key

Send an event to a keyed workflow's key, and the key's open run gets it at its step.waitForEvent. When the key has no open run, the event's data starts one as its payload, and that run gets the event too. One call serves both cases: a customer's first message opens their run, and each message after it reaches that run.

chat-session
import { workflow } from "shiftlabs";

export default workflow<{ customer: { id: string }; text: string }>({
  key: "customer.id",
}, async ({ payload, step }) => {
  // The message that opened the run is its payload and its first event.
  for (let turn = 1; ; turn++) {
    const message = await step.waitForEvent<{ text: string }>("message", { timeout: "1 hour" });
    if (!message) return { customer: payload.customer.id, turns: turn - 1 };
    await step.run(`answer ${turn}`, () =>
      fetch("https://chat.example.com/answers", {
        method: "POST",
        body: JSON.stringify({ customer: payload.customer.id, text: message.text }),
      }).then((r) => r.status),
    );
  }
});

POST /v1/workflows/:workflow/events/:name?key= sends the event name, with the body as its data, read as any event's is. The key is ?key=, or without it the data's value at the workflow's key path. It returns 202 {"runId", "event", "key", "started"}: started is true when the event opened the run.

An event that opens a run must hold the key, and it's checked against the payload schema as a start's payload is; one sent to an open run isn't. A key in the data that isn't ?key= returns 400 {"error": "key mismatch"}, and a workflow without a key 409.

  • Every sender

    The clients' events.sendToKey(workflow, name, data, { key }), in Python events.send_to_key(workflow, name, data, key=…), the CLI's shiftlabs workflows send <workflow> <event> --key <key> --data <json>, and MCP's send_workflow_event. Events sent to a keyed run by its id, with POST /v1/runs/:id/events/:name or an event URL, arrive the same way.

  • Triggers

    A trigger with an event sends each delivery to its payload's key as that event instead of starting a run: set it when you create the trigger, or with PATCH /v1/triggers/:id {"event": "message"}, and null turns it off. Its delivery log shows a delivery to an open run as sent to that run.

  • Kept until taken

    The platform keeps each event until a wait takes it, before the run starts too, and sends it again if sending it to the run failed. A run keeps at most 100 events and 1 MiB of them that its waits haven't taken, and a workspace 16 MiB; past that an event returns 429 {"error": "too many events waiting"} with Retry-After. Events a run never took go when it ends. An event can arrive twice, rarely: make what you do with one safe to repeat.

  • Limits

    Each event counts toward the run's eventsPerRun, the one that opened it too. An event that opens a run counts toward your runs as any start does, so a workspace at its spending limit can't send events to keys.

Continue as new

A keyed run can hand its key on to a fresh run: it ends, and the key's next run starts on the workflow's current version, with the state you pass as its payload. Events sent to the key meanwhile reach the next run. A key that stays busy for months keeps going this way, one run after another, each within a run's limits.

order-tracker
import { workflow } from "shiftlabs";

type State = { customer: { id: string }; orders?: number };

export default workflow<State>({
  key: "customer.id",
}, async ({ payload, step }) => {
  // The first run's payload opened the key; each next run's is the state the run before it handed on.
  const state = { customer: payload.customer, orders: payload.orders ?? 0 };
  for (;;) {
    const order = await step.waitForEvent<{ total: number }>("order", { timeout: "30 days", continueWith: state });
    if (!order) return state;
    state.orders = await step.run(`record order ${state.orders + 1}`, () => state.orders + 1);
  }
});

step.continueAsNew(state), in Python step.continue_as_new(state), continues the run there. A wait given continueWith (Python continue_with), on step.waitForEvent or step.waitForAny, continues with that state once the run has used half of one of its per-run limits, its steps, dispatches or events, or 2 hours before its lifetime ends. Until then it waits as any wait does.

Either way the code gets ContinuedAsNew, which names the next run as runId (Python run_id): let it through, as a step after it throws. The run ends completed with no output, and runs no undos. The next run's continuedFrom (Python continued_from) is the run it continues, and key its key; a key's first run has continuedFrom null.

  • The next run

    It runs the workflow's current version, so each continue picks up your latest deploy, and gets a lifetime and per-run limits of its own: its steps, dispatches and events count from 0. Its origin is continue, with the run it continues as origin_ref. It keeps the key whatever the state holds, and takes over the run's place in your runs at once. It counts toward your runs per day and is billed as a run. A limit that's reached is tried again for about an hour, then the run fails with it.

  • Without continueWith

    Nothing else continues a run. A keyed run whose code never calls step.continueAsNew or gives a wait continueWith fails once its lifetime ends, with an error that starts limit runLifetimeHours=, as any run does. That frees its key, and the key's next start or event opens a fresh run, which gets none of the old run's state.

  • Events

    Events the run hadn't taken go to the next run. An event sent to the old run by its id or its event URL goes to the key's open run, whose id the 202 names. One sent as the run hands on can reach both runs: make what you do with an event safe to repeat.

  • The chain

    GET /v1/runs/:id returns chain: {root, seq, previous, next, gone}, the key's first run, this run's number among them, the runs before and after it, and the ids history has removed, 35 days after each ended. The run's page shows the chain above its details, and GET /v1/runs?workflow=&key= lists every run of the key.

  • Limits

    A state is JSON, at most 1 MiB, as a payload is. Outside a keyed workflow continueWith is ignored and step.continueAsNew throws. A step.waitForAny of sleeps alone continues only at half a limit. A run that started before this release keeps waiting at its continueWith waits as before.

  • Tests

    runWorkflow's continueAt: n continues the run at its nth continueWith wait, and a run that continued ends continued with continuedWith, the state. continuedFrom sets the run's continuedFrom. In Python: continue_at, continued_from and continued_with.

Search keys and tags

Tag runs with what you'll look them up by, such as a customer or an incident, then find them by those tags in run lists, exports and searches. Search keys tag each run from its payload when it arrives, and step.tag adds tags from what the run finds out.

refund
import { workflow } from "shiftlabs";

type Refund = { customer: { id: string }; invoice: string };

export default workflow<Refund>({
  search: { customer: "customer.id", invoice: "invoice" },
}, async ({ payload, step }) => {
  const refund = await step.run("refund", () =>
    fetch(`https://api.example.com/invoices/${payload.invoice}/refund`, {
      method: "POST",
    }).then((r) => r.json()),
  );
  await step.tag({ refund: refund.id });
  return refund.id;
});

search maps up to 10 tag names to dotted paths into the payload, such as customer.id. Each run gets those tags from its payload when it arrives, before any of your code runs: a string as it is, a number as the payload writes it (42, 1.5), true or false. A path with nothing there, null, an object, a list, an empty string or a value over 256 bytes gives no tag. Tag names are 1 to 64 letters, digits, - and _.

The deploy reads search when it loads the code and stores it with the version. The deploy answer and GET /v1/workflows show it as search, and a re-run gets its version's. A search that isn't an object of names to paths, has more than 10, or has a bad name or path fails the deploy with 400 {"error": "invalid search", "detail"}.

  • step.tag

    step.tag(tags) tags the run with 1 to 20 names and values, such as what a step returned. It isn't a step: it doesn't count toward the run's steps and isn't billed. Call it outside step.run: inside a step's function it throws step.tag works only outside step.run: tag with what the step returns. A name tagged again takes the newer value, a search key's too. When the run resumes, the calls it already made write nothing again.

  • Limits

    A run holds at most 20 tags, its search keys included. A call that would add a 21st throws a run has at most 20 tags: <name> would be its 21st and adds none of its tags. Values are strings of 1 to 256 bytes, so turn a number into one, such as String(id) (str(id) in Python). A readable secret's value in a tag is replaced by [redacted].

  • Finding runs

    Filter run lists, exports, MCP's list_runs and the Runs screen by tag, and cancel or re-run the runs that have one. Search matches tag values too. See Find runs. Search doesn't read what a run returned, so tag what you'll look for.

  • Kept with the run

    GET /v1/runs and GET /v1/runs/:id give each run's tags, and the run's page shows them. They expire with the run's history, 35 days after it ends.

  • Personal data

    Every member who can see a run sees its tags, in lists, exports and searches, and erasing a person doesn't remove them. Tag with ids, not emails or names.

Files and npm packages

A TypeScript workflow can import its own files and npm packages. shiftlabs deploy sends the workflow's file, each file it imports by a relative path, and package.json with package-lock.json when it imports a package. The packages install once, when you deploy, and each version keeps the ones it was deployed with.

workflows/invoice-check.ts
import { workflow } from "shiftlabs";
import * as z from "zod";
import { cents } from "../lib/money.ts";

export default workflow({
  payload: z.object({ invoiceId: z.string(), amount: z.number() }),
}, async ({ payload, step }) => {
  return step.run("check", () => ({
    invoiceId: payload.invoiceId,
    cents: cents(payload.amount),
  }));
});
shellterminal
# writes package.json and package-lock.json
npm install zod
# sends the 4 files, then waits while zod installs
npx shiftlabs deploy workflows/invoice-check.ts
  • Installed when you deploy

    The packages the workflow imports install, with what they depend on, at the versions package-lock.json pins. Nothing installs when a run starts. The deploy answer lists them under packages, such as zod@4.6.7, and the version keeps them: a later deploy that changes them leaves earlier versions as they were.

  • Once per set of packages

    If the same packages were installed before, the deploy goes live right away. A new set returns 202 with a deployId, like a Python package build, and goes live when the install finishes, usually within a minute. shiftlabs deploy waits for it. Installs count as package builds: a workspace can start 20 new builds a day, Python's and npm's together, and have 5 deploys waiting on them. See Rate limits.

  • package-lock.json

    The lockfile npm 7 and later write. One that doesn't match package.json is refused: run npm install and deploy again. pnpm, Yarn and Bun lockfiles aren't read; npm install --package-lock-only writes a package-lock.json beside them.

  • registry.npmjs.org only

    A package from another registry, a git URL or a local folder is refused, and so is a download that doesn't match the lockfile's integrity. Private packages can't be installed.

  • Install scripts never run

    A package with one installs without running it, and the deploy answer warns. A package that needs its script, to build native code or download a program, won't work.

  • Node.js built-ins

    Workflows run with Node.js compatibility, so packages that import node:crypto, node:buffer and the like work, and so do CommonJS packages that require() them. Native addons, and packages that need a real file system or other programs, don't.

  • A package's browser or worker build is used before its Node.js build.
  • A workflow gets one version of each package. A lockfile that pins two versions of a package the workflow needs is refused; npm dedupe often fixes it.
  • Import your own files by their names, such as ./money.ts, or with no extension. shiftlabs deploy refuses ./money.js for money.ts.
  • Packages are bundled with your code and scanned with it. A workflow may need at most 150 packages, their JavaScript and JSON files may take 6 MiB, and the bundle may be 1.5 MiB.
  • Your package.json stays importable, as in import pkg from "../package.json".
  • A deploy of several files is JSON: {"entry", "files"}, up to 1 MiB and 100 files. See Deploy and triggers.

Python packages

List packages at the top of the file. They're built once, when you deploy.

pythonrefund_check.py
# /// script
# dependencies = ["httpx", "numpy>=2"]
# ///
import httpx
import numpy as np
from shiftlabs import workflow


@workflow
async def refund_check(ctx):
    async def fetch_charge():
        async with httpx.AsyncClient() as http:
            r = await http.get(
                f"https://api.stripe.com/v1/charges/{ctx.payload['id']}",
                headers={"authorization": f"Bearer {ctx.secrets.STRIPE_KEY}"},
            )
            return r.json()

    charge = await ctx.step.run("fetch charge", fetch_charge)
    return {"cents": int(np.round(charge["amount"]))}

If the same set of packages has been built before, the deploy goes live right away and the response lists the exact versions under packages. A new set returns 202 with a deployId. The version goes live when the build finishes, usually within a minute. A workspace's builds run one at a time, so a second new set waits for the first. A build that takes longer than 3 minutes fails. GET /v1/deploys/:id shows building, live or failed with the reason.

Pure-Python packages work as published. Compiled ones, such as numpy, need a build for our Python runtime. Without one, the deploy fails with the reason. Each version keeps the packages it was deployed with. To get the newest versions, deploy with ?upgrade=1: the packages are built again for your workspace alone, and its later deploys keep them. Another workspace's upgrade never changes yours. Use async HTTP clients such as httpx's AsyncClient.

A Python workflow can import modules from its file's folder and below, such as helpers.py or lib/util.py. shiftlabs deploy sends the ones it imports. List packages in the workflow file's own # /// script block.

Python editor types

The shiftlabs package on PyPI is the module the platform runs, with type hints, for your editor and type checker.

shellterminal
uv add --dev shiftlabs  # or: pip install shiftlabs
npx shiftlabs types  # writes shiftlabs_types.pyi with your secret and var names
pythonrefund_check.py
from shiftlabs import Context, workflow


async def charge(invoice_id: str, cents: int) -> dict[str, str]:
    ...


@workflow
async def refund_check(ctx: Context) -> None:
    charged = await ctx.step.run(
        "charge",
        charge,
        ctx.payload["id"],
        500,
        retries={"limit": 3, "delay": "30 seconds"},
    )
    ctx.log.info("charged", {"id": charged["id"], "region": ctx.vars.REGION})

Install it for development only. The platform still adds the module to every Python workflow when you deploy, so don't list it under # /// script. It needs Python 3.11 or later. Install the version the platform runs: GET /v1/version reports it as sdk. Annotate the entry as ctx: Context, and step.run checks fn's arguments and returns its result's type.

Without generated names, any ctx.secrets.NAME and ctx.vars.NAME type-checks. npx shiftlabs types writes shiftlabs_types.pyi at the project root with your workspace's names. Type checkers such as pyright and mypy read it before the package's default, so a misspelled name is an error. Run it again after adding or removing a secret or var.

Draft with AI

POST /v1/workflows/:workflow/draft asks a model to write a workflow's files from a request in plain words, given the files the workflow has now. The answer is a draft: read it, change what you need and deploy it yourself. Nothing is deployed for you. Drafts work where agents are on, with a developer key.

shellcurl
# Developer key. Answers 202 {"draft", "status": "working"}; Location names the draft.
curl -X POST https://api.shiftlabs.org/v1/workflows/invoice-check/draft \
  -H "authorization: Bearer $SHIFTLABS_API_KEY" -H "content-type: application/json" \
  -H "idempotency-key: invoice-check-1" \
  -d '{"prompt": "Email each overdue invoice to its customer.", "files": [], "entry": "workflows/invoice-check.ts"}'

# {"draft", "status": "working"} while the model writes, then "done" with "files", "notes", "model" and "tokens".
curl https://api.shiftlabs.org/v1/workflows/invoice-check/draft/<draft> \
  -H "authorization: Bearer $SHIFTLABS_API_KEY"
  • The request

    prompt: what you want, 1 to 4,000 characters. files: the workflow's files now, each {"path", "content"}, at most 100, with the paths a deploy of several files takes, or [] for a new workflow. entry: the entry file's path, when there is one. The prompt and every path and content may take 64,512 bytes together, on every plan.

  • Your secrets stay out

    Before the model gets the request, each value of your readable secrets in it, and text shaped like an AWS, Stripe, GitHub, Slack or Google key, is replaced with [redacted], and so is a PEM private key, whole: from its BEGIN line through its END line, or to the end of the text when it has no END line. What the model writes is redacted the same way each time you read or stream the draft. The audit log's workflow_draft entry, one for each draft, has the model, the draft, the request's size in bytes and who asked, never the prompt or a file.

  • The draft

    done: files, each file the model added or changed, whole; notes, what it changed and why; model; and tokens, {input, output}. failed: error says why and retry whether sending the request again may help. model: the model failed, or stopped answering for 2 minutes, and no other model is tried. length: its answer was cut off at the model's output limit, so send less. unparseable: it wrote no file a deploy would take. budget, with retry false: the draft reached its $0.10, or the workspace its model allowance.

  • Stream it

    With Accept: text/event-stream the POST answers the draft's stream instead, with a conversation's events: the request as the model got it, the answer as it is written, then a status other than working, after which the stream closes. Read the draft then. GET …/draft/:id/stream streams it again, or from its Last-Event-ID. Text that could be the start of a secret's value or a credential waits for what follows it, and a private key from its BEGIN line waits for its END line, or for the answer's end, so the answer can arrive in larger pieces than a conversation's.

  • Yours alone

    Only the member or key that started a draft reads or streams it, and only under the workflow it was drafted for. Anyone else, or another workflow's name, gets 404, as for a draft that doesn't exist, even with conversation.read_others. A draft isn't an agent's conversation: no agent lists it, and the agent routes return 404 for it.

  • A draft counts toward the model tokens per 24 hours, the model use per month and the messages a minute, 30 per workspace and 10 per person, but not the messages per 24 hours. See Agent limits.
  • Past the model allowance, a draft returns 403 {"error": "quota exceeded", "limit", "max"}, with detail and resetsAt past the month's model use. Past the messages a minute, it returns 429 {"error": "rate limited"} with Retry-After: 60, and past the Pro spending limit 429 with Retry-After: 3600.
  • Past 64,512 bytes it returns 413 {"error": "draft too large", "max": 64512}, and a bad prompt, file, entry or field 400 with the problem.
  • An Idempotency-Key works as for an agent message: the same key and request again within 24 hours answer the same draft without asking the model again, and the key on any other request returns 409.
  • A draft is kept as long as a conversation: 7 days on Free and 30 on Pro. See How long conversations are kept.

Run context

Your function receives one object. Destructure what you need.

  • payload

    The webhook body: parsed JSON when the request is sent as application/json, the raw text otherwise. With a payload schema, webhooks and API runs whose payload fails it start no run.

  • step

    Durable steps, sleeps, events, approvals and tags. See Durable steps, Events, Approvals and Tags.

  • vars

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

  • secrets

    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. See Secrets and connections.

  • reveal(secret)

    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]. Logs are redacted with the values your secrets had when the code loaded and the values they have when the lines arrive, so a secret changed while code runs is redacted too. If shiftlabs can't read your secrets then, it keeps none of that invocation's lines, and shows one error line saying they were withheld.

  • sign(secret, data, "hex" | "base64")

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

  • log

    log.info(message, fields?), and debug, warn, error: one log line each, shown with the run. A line printed in a step's function, with log or console, carries the step's name as its step.

  • state

    JSON values kept per workflow across runs, used inside steps. See State.

  • runId

    This run's id.

  • key · continuedFrom

    A keyed run's key, and the run it continued as new from, null for a key's first run; both null for any other run. In Python, ctx.key and ctx.continued_from.

Durable steps

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

  • step.run(name, fn)
    step.run(name, config, fn)

    Runs fn once and stores its result. When the run resumes, the step returns the stored result instead of running again.

  • step.sleep(name, duration)

    Durable sleep. The run resumes after duration, on the same version.

  • step.sleepUntil(name, until)

    Durable sleep until a Date or an epoch-milliseconds number. In Python, step.sleep_until(name, until) takes a datetime or epoch seconds.

  • step.ask(name, { agent, message, schema })

    Asks one of the workspace's agents and returns its answer. See Ask an agent.

  • step.start(name, { workflow, payload })

    Starts a run of another workflow and returns its run id. See Start another workflow.

  • step.call(name, { workflow, payload })

    Starts a run of another workflow, waits for it to end and returns its result. See Wait for another workflow.

  • step.exec(name, { run, command, env, files, timeout, runner })

    Runs a command on a runner in your own network and returns its exit code and output. See Run a command.

  • step.activity(label, { name, input, runner, timeout, heartbeat })

    Runs an activity your runners register, with JSON in and out, and returns its output. See Run a registered activity.

  • step.decide(name, decision, input)

    Asks a decision model a question fixed in code and returns the answer with every option's probability. See Decide with a model.

7d10ce5b · refund-check

Completed
Version
1d9a281e · rev A
Dispatches
2
Duration
10 min 2 s
  1. queued21:30:14.227
  2. started989 ms21:30:15.216
  3. fetch charge212 ms21:30:15.301 · result stored
  4. cool-off10 min21:30:15.514
  5. notify95 ms21:40:15.902 · same version
  6. completed21:40:16.010
  • retries.limit

    How many times to retry a failing step. Default 5. Each attempt counts as a step: a step that fails twice and then passes counts 3.

  • retries.delay

    A duration between attempts. Default "10 seconds". A delay under a second waits a second. While a step waits, Retry now starts its next attempt at once.

  • retries.backoff

    "constant", "linear" or "exponential". Default "exponential", which doubles the delay each time: 10, 20, 40, 80 and 160 seconds.

  • timeout

    A duration after which an attempt fails. Default "10 minutes".

  • undo

    A function that reverses the step, run if the workflow fails later. See Undo a step.

charge
import { workflow, FatalError } from "shiftlabs";

export default workflow<{ card: string }>(async ({ payload, step }) => {
  await step.run("charge", async () => {
    const r = await fetch("https://api.example.com/charges", {
      method: "POST",
      body: payload.card,
    });
    if (r.status === 402) throw new FatalError("card declined");
    if (!r.ok) throw new Error(`charge failed: ${r.status}`);
  });
});

FatalError fails the step and the run at once, with no more attempts, whatever retries says. Any other error in a step is retried. Thrown outside a step, a FatalError fails the run as any error does.

Rules that keep runs correct

  • 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.
  • A run stays on the version that was current when its webhook arrived, even after a redeploy.
  • A run may be dispatched by the engine at most 50 times and live at most 168 hours on the free tier, 720 hours (30 days) on Pro. Each invocation gets 2,000 ms of CPU and 50 subrequests, and a run 10 seconds of CPU in all on the free tier (60 on Pro): its next dispatch fails the run with limit cpuMsPerRun=10000. Your fetch and sign calls use the subrequests; steps, sleeps and state don't. The full list is under Limits.
  • A run executes at most 100 steps on the free tier and 1,000 on Pro. The step after that fails the run, with the error limit stepsPerRun=100 on the free tier. Each attempt of a step.run counts, retries included; sleeps and the waits between attempts don't. In a run started before 3 November 2026, a step.run counts once however often it is retried.
  • When shiftlabs briefly fails to load your version's code at a dispatch (a dropped connection, a reset), it loads it again after 5 seconds, then 10 seconds, at most twice per run. None of your code has run by then, and the wait may count as one more dispatch. A version that still doesn't load fails the run with platform error, unbilled.

Undo a step

Give step.run an undo function to reverse what the step did when a later part of the run fails: delete the record it created, refund the charge it made. When the workflow's function throws, each completed step's undo runs, newest first, before the run ends failed.

dns-setup
import { workflow } from "shiftlabs";

const records = "https://api.example.com/zones/example.com/records";

export default workflow<{ host: string }>(async ({ payload, step }) => {
  const createRecord = async () => {
    const r = await fetch(records, {
      method: "POST",
      body: JSON.stringify({ name: payload.host, type: "CNAME", content: "edge.example.com" }),
    });
    if (!r.ok) throw new Error(`create failed: ${r.status}`);
    return (await r.json()) as { id: string };
  };
  const deleteRecord = async (id: string) => {
    const r = await fetch(`${records}/${id}`, { method: "DELETE" });
    if (!r.ok && r.status !== 404) throw new Error(`delete failed: ${r.status}`);
  };

  await step.run("create dns record", { undo: ({ output }) => deleteRecord(output.id) }, createRecord);
  await step.run("issue certificate", async () => {
    const r = await fetch("https://api.example.com/certificates", { method: "POST", body: payload.host });
    if (!r.ok) throw new Error(`certificate failed: ${r.status}`);
  });
});
  • undo

    A function of { output, error }: a copy of what the step returned, fresh for each attempt, and the error the run failed with. It can be async, and what it returns is dropped. In Python, undo= takes a function of a dict with the keys "output" and "error".

  • undo: { run, retries, timeout, approval }

    run is the undo function, and retries and timeout its own, with the same defaults as any step. With approval, the run first waits for an approval named undo <name>, with the options step.waitForApproval takes. In Python, undo={"run": fn, "retries": …, "timeout": …, "approval": {"message": …}}.

  • On the run

    GET /v1/runs/:id and GET /v1/runs show when the first undo began as undo_at, null when none ran. The run's page shows it as Undo, and its timeline has undo and undo failed with the step's name. A skipped undo shows only as its denied approval.

How undos run

  • Only a step.run with undo whose step completed is undone. A step still running when the function throws is waited for, and undone if it completes.
  • Undos run only when the workflow's function throws. A run that returns, or catches the error and returns, undoes nothing, and neither does a run that is cancelled or terminated, unless the cancel asks for undo.
  • Undos run newest first, in the reverse of the order the run called step.run. Each is a step named undo <name>, retried as any step is. The run then fails with its own error, whatever the undos did.
  • With approval, an approved undo runs. A denied one, or one nobody answers before its timeout, is skipped, and the next undo goes on.
  • An undo that still fails after its retries, or throws FatalError, stops the undos: older steps aren't undone, and the run's logs get undo <name> failed: <message> at level error. Make an undo safe to run twice, as the 404 above does: a retry can follow an attempt that did the work.
  • Each undo attempt counts as a step toward steps per run and the workspace's steps, and its code uses the run's CPU. An undo's approval is one more step, as every approval request is. A run past its step limit can't undo, since its undo steps are refused like any step.
  • A step with undo takes a name of at most 251 characters, and one with an undo approval at most 95, which can't end with a space, # and a number. Longer names, an undo that is neither a function nor { run, … }, or one on a step.run called inside another step's function, throw a TypeError when step.run is called.

Ask an agent

step.ask(name, { agent, message, schema }) asks one of the workspace's agents and returns its final answer as text. With schema, it returns the JSON that matches the schema, typed by it.

invoice-check
import { workflow } from "shiftlabs";

type Review = { ok: boolean; reason: string };

export default workflow<{ invoiceId: string; amount: number }>(
  async ({ payload, step }) => {
    const review = await step.ask<Review>("review", {
      agent: "invoice-reviewer",
      message: `Check invoice ${payload.invoiceId} for ${payload.amount} USD.`,
      schema: {
        type: "object",
        properties: { ok: { type: "boolean" }, reason: { type: "string" } },
        required: ["ok", "reason"],
      },
    });
    return review.ok ? { paid: true } : { paid: false, reason: review.reason };
  },
);
  • One conversation per step

    Each run gets one conversation with the agent for each step name. When the run resumes, step.ask returns the stored answer and starts no other conversation. A second step.ask with the same name in the same run gets a conversation of its own.

  • Owned by the workflow

    The conversation is started by workflow invoice-check, and its run is the run that asked. Developers and admins find it on the agent's From workflows tab, linked to the run. Nobody can add messages to it. Once the run has ended, the agent's tools don't run any more, approved calls included.

  • Key scope

    A workflow deployed with an API key scoped to some workflows asks an agent that has only those workflows' tools, since it can start only those itself. Deployed from the dashboard, or with a key whose scope names no workflows, it asks an agent with all its tools.

  • Waiting

    The run waits while the agent works, and while its tools wait for approval, up to 72 hours. Waiting uses no CPU, but counts toward the run's lifetime of 168 hours (720 on Pro). Starting the conversation is a step, and so is each read of the answer: when the agent is done, and once a day while it isn't.

  • Schema

    schema takes JSON Schema or a Standard JSON Schema such as zod, as payload does, up to 32 KB. The agent is told to answer with JSON that matches it. The answer is read as JSON, as the JSON between its first { or [ and its last } or ], or as the text itself. An answer that doesn't match gets one more turn that tells the agent what is wrong. If that answer doesn't match either, the step fails with what doesn't match.

  • Limits

    The message counts as a run, as every agent message does, and toward the messages a minute: 30 per workspace, and 10 per workflow. Over them, step.ask tries again for about 5 minutes before its step fails. The agent's model use counts toward the workspace's model allowance and the agent's budgets. The extra turn for a schema isn't another message.

step.ask fails at once, with no retries, when agents are off in the workspace, there is no such agent, the plan can't use the agent's model, a limit is reached, or the conversation ends without an answer: failed, stopped at maxTurns, budget reached, monthly budget reached or allowance reached. The error says which. Catch it to go on without the answer. The built-in helper answers people only, so step.ask can't ask it. A workflow deployed with an API key limited to some agents can ask only those.

Decide with a model

step.decide(name, decision, input) asks one of Cloudflare's decision models a question fixed in code, about data fields your code builds from input, and returns the answer with every option's probability. Declare each decision with decision() and name it in workflow({ decisions }), in Python @workflow(decisions={…}).

intake
import { decision, workflow } from "shiftlabs";

type Document = { fileName: string; from: string; text: string };

const kind = decision({
  version: 1,
  model: "@cf/cloudflare/clef-flash",
  question: "What kind of document is this?",
  choices: {
    invoice: "A bill asking for payment of new charges",
    receipt: "Proof of a payment already made",
    statement: "A summary of an account listing earlier invoices and payments",
    other: "Anything else",
  },
  threshold: 0.7,
  state: (doc: Document) => ({ file: doc.fileName, sender: doc.from, text: doc.text }),
});

export default workflow<Document>({ decisions: { kind } }, async ({ payload, step }) => {
  const found = await step.decide("classify", kind, payload);
  if (found.answer !== null) return { kind: found.answer };
  const check = await step.waitForApproval("check the kind", {
    message: `Is ${payload.fileName} an invoice? The model leans to ${found.top}.`,
  });
  return { kind: check.approved ? "invoice" : "other" };
});
jsonfound
{
  "answer": "statement",
  "top": "statement",
  "probabilities": { "invoice": 0.03, "receipt": 0.01, "statement": 0.95, "other": 0.01 },
  "score": null,
  "version": 1,
  "model": "@cf/cloudflare/clef-flash",
  "threshold": 0.7
}
  • Questions

    question with choices picks one of 2 to 255 options, given as a list or as an object of options and what each means. question with score picks one of 2 to 10 levels, lowest first, and score in the answer is the probability-weighted level, from 0. yesNo alone (yes_no in Python) is a question answered "yes" or "no". Questions and options never carry your data: only the fields state returns do.

  • Threshold

    The most probable option is the answer when its probability is at least threshold. Below it, answer is null, and top and probabilities still say where the model leaned: send the item to a person, as above. Without a threshold, the most probable option is always the answer.

  • Versions

    Every deploy reads each decision's question, its options or levels with their descriptions, and the names of the fields state returns. A deploy that changes any of them under a version deployed before, staged deploys included, is refused with 409 and "error": "decision changed without a new version": give the decision a new version. The model and the threshold can change under the same version. A deleted workflow keeps its decisions' versions in the trash, and a restore brings them back; once the workflow is deleted for good, they're forgotten.

  • State

    state builds an object of data fields from step.decide's input, with the same fields every time: null for one you don't have. The deploy reads their names by calling state with a stand-in input, so build the fields from the input without parsing or checking it: a state that throws fails the deploy. state runs again each time the run resumes, as code outside a step does.

  • Python

    decision() takes the same options as keyword arguments, yes_no for yesNo, and state is a function or an async function that returns a dict. A refused deploy's detail names the options as TypeScript does, such as yesNo. step.decide returns a dict with the same keys, None where TypeScript has null. The stand-in input gives another stand-in for every attribute, item, call and arithmetic, iterates as empty, counts as true and converts to 0 or "": doc["from"].lower() and round(doc["amount"] * 100) work, and json.loads(doc["body"]) fails the deploy.

  • Masking

    Card numbers (13 to 19 digits that pass the Luhn check), IBANs, a number after a label such as Account, Routing or Sort code, and the digits of a field named like accountNumber, iban or cardNumber reach the model with all but their last 4 characters as •. Readable secrets reach it as [redacted].

  • Size

    Clef reads 65,536 tokens and Clef-flash 24,576, the question included. The platform counts 3 bytes of state as a token and refuses a state that doesn't fit, and refuses an answer that used the whole window, since the model may have read only part of the state. A PNG, JPEG or WebP data URL in the state is an image, counted as 1,027 tokens: 4 at most, up to 4 MiB each and 8 MiB in all.

  • Trace

    The run's detail keeps each decision as the model read it: the state, the version, the model, every option's probability, the threshold and the answer. GET /v1/runs/:id returns them under decisions, and the dashboard shows them with the run. They go with the run's history, 35 days after it ends.

  • Model use

    Each decision is a step. Its model use counts toward the workspace's model allowance, as agents' does: Clef is 0.24 USD and Clef-flash 0.038 USD per million input tokens, and the answer adds nothing. Decisions need agents on in Settings → Agents.

step.decide fails at once, with no retries, when agents are off, the spending limit or the model allowance is reached, the run's version has no such decision, or the state has other fields, too many images or more than the model reads. The error says which. A failed call to the model is tried again, 5 times over about 5 minutes. A resumed run gets the stored answer and asks the model nothing.

Schedules

A schedule starts a workflow on a cron, in your time zone. List schedules in shiftlabs.config.ts, and shiftlabs deploy releases them with your workflows and agents. A schedule can also message an agent.

shiftlabs.config.ts
import { project, schedule } from "shiftlabs";

export default project({
  workflows: { sync: "./workflows/sync.ts" },
  schedules: {
    nightly: schedule("sync", {
      cron: "0 3 * * *",
      timezone: "America/Detroit",
      payload: { full: true },
    }),
    "every-15-minutes": schedule("sync", {
      cron: "*/15 * * * *",
      overlap: "skip",
      jitter: "30 seconds",
      catchup: "1 hour",
      pauseOnFailure: true,
    }),
  },
});

A cron has five fields: minute, hour, day of the month, month and day of the week. Each takes *, a number, a list (1,15), a range (1-5) and a step (*/15, 0-30/10). Months and days take names too, such as JAN and MON, and Sunday is 0 or 7. When both the day of the month and the day of the week are set, a day that matches either runs. @hourly, @daily, @weekly, @monthly and @yearly also work.

timezone is an IANA name, such as America/Detroit or Europe/London, and defaults to UTC. The cron follows that zone's clock. A time that is skipped when clocks go forward runs an hour later that day. A time that happens twice when clocks go back runs once, the first time, unless the hour field is *: then it runs every hour as the clock shows it.

  • overlap

    What a tick does while the schedule's last run hasn't ended: the run its previous tick started, a waiting tick's, or one Trigger now started. "allow", the default, starts it anyway. "skip" starts nothing and records lastSkipped: "the previous run hasn't ended". "buffer-one" waits and starts the tick as soon as that run ends; one tick waits at most, and a tick while one waits is skipped with lastSkipped: "a tick is already waiting for the previous run". "cancel-other" cancels that run, with stop_requested_by schedule:<name>, and starts the tick once it has ended; a newer tick replaces one still waiting. GET /v1/schedules shows a waiting tick's cron time as buffered. Backfilled runs neither count nor wait.

  • jitter

    A duration from 1 second to 1 day, shorter than the cron's shortest gap between two ticks. Each tick starts up to that long after its cron time, at a delay fixed for that tick. nextAt stays the cron time.

  • catchup

    A duration from 1 minute to 365 days. After downtime or a pause, the schedule starts once for the ticks it missed only if the newest of them is at most that old, and the run is the oldest missed tick within it. Otherwise nothing starts until the next tick, and the schedule records lastSkipped: "missed by more than <catchup>".

  • pauseOnFailure

    true pauses the schedule when a run it started fails: a tick's, Trigger now's or a backfill's, but not a cancelled or terminated one. pausedBy is pauseOnFailure and the note run <runId> failed: <error>, and the audit log records schedule_pause. Resume it once the cause is fixed.

The four options are optional. Left out, a schedule works as before: each tick starts a run even while the last one goes on, and missed ticks start once however late they are. An agent's schedule takes jitter and catchup only; overlap or pauseOnFailure on one returns 400. The options are part of the release, like the cron.

  • Runs

    Each tick starts a run of the workflow's current version, with the origin schedule and the schedule's name as origin_ref. The Runs screen can filter by it. The run's payload is payload, or {}. The release checks it against the workflow's payload schema.

  • Missed ticks

    When ticks are missed, for example while the platform is down or the schedule is paused, the schedule runs once when it's back, not once for each missed tick, however late. With catchup, it runs only if the newest missed tick is at most that old. To run each missed tick, backfill them.

  • Paused workflows

    A tick while the workflow is paused starts nothing and holds nothing. The schedule records lastSkipped: "the workflow is paused" in GET /v1/schedules, and the Schedules screen shows that the last tick was skipped. The first tick after the resume starts a run.

  • Limits

    A scheduled run counts like any run. One that a limit refuses, such as runs per day, starts nothing, and the Schedules screen shows why on that schedule.

  • Releases

    Schedules are part of a release. The project's schedules replace all of the workspace's schedules; schedules: {} removes them, and a project without schedules leaves them alone. Rolling back a release puts its schedules back; rolling back to a release made before schedules existed leaves them as they are.

  • Dashboard

    The Schedules screen lists each schedule with its next and last run, its options, whether it is paused and by whom, and a backfill's progress. Developers and admins can change a schedule's cron, time zone, options and payload or message, or remove it. Each change makes a new release. The next shiftlabs deploy of a project with schedules replaces those changes. Pause, Resume, Trigger now, Backfill and Stop backfill make no release: see Pause, trigger or backfill a schedule.

  • Free workspaces can have 5 schedules, each running at most every 5 minutes. Pro workspaces can have 50, each running as often as every minute. A release that adds more gets 403 {"error": "quota exceeded", "limit": "schedules", "max"}; an added or changed cron that runs too often gets 403 {"error": "plan", "detail"}. After a move to Free, the schedules in place keep running, and you can still edit or remove them.
  • Adding or changing a schedule needs the run.start capability, which developers hold.
  • Pausing and resuming a schedule needs workflow.pause, and Trigger now and backfill need run.start. Developers hold both. An agent's schedule also needs agent.deploy.
  • A schedule's workflow must exist once the release is in. A schedule whose workflow is deleted later records workflow not found at each tick until a release changes it. An agent's schedule skips its ticks while its agent is in the trash, and is erased with the agent.
  • payload is JSON of up to 16 KB.
  • Schedule names use lowercase letters, digits and hyphens.

Pause, trigger or backfill a schedule

Pause a schedule to stop its ticks, for example while a system it calls is down. Trigger it to start a run now, or backfill it to run the ticks it missed. None of these makes a release.

shellcurl
# Developer key. Answers {"schedule", "paused": true, "pausedAt", "pausedBy", "note"}.
curl -X POST https://api.shiftlabs.org/v1/schedules/nightly/pause \
  -H "authorization: Bearer $SHIFTLABS_API_KEY" -H "content-type: application/json" \
  -d '{"note": "billing API is down"}'

# Answers {"schedule", "paused": false, "nextAt"}.
curl -X POST https://api.shiftlabs.org/v1/schedules/nightly/resume \
  -H "authorization: Bearer $SHIFTLABS_API_KEY"

# Start one run now. Answers 202 {"schedule", "runId"}.
curl -X POST https://api.shiftlabs.org/v1/schedules/nightly/trigger \
  -H "authorization: Bearer $SHIFTLABS_API_KEY"

# Run each tick from 1 October that hasn't run. Answers 202 {"schedule", "backfill"}.
curl -X POST https://api.shiftlabs.org/v1/schedules/nightly/backfill \
  -H "authorization: Bearer $SHIFTLABS_API_KEY" -H "content-type: application/json" \
  -d '{"from": "2026-10-01T00:00:00Z"}'

# Stop the backfill. Answers {"schedule", "backfill"}, ended "cancelled".
curl -X DELETE https://api.shiftlabs.org/v1/schedules/nightly/backfill \
  -H "authorization: Bearer $SHIFTLABS_API_KEY"
  • Pause

    A paused schedule starts nothing until it is resumed: no ticks, no waiting tick and no backfill progress, and Trigger now gets 409 {"error": "schedule paused"}. The note is optional. Pausing a paused schedule changes nothing and keeps the first pause's who and note. A release that changes a paused schedule keeps it paused, and one that removes it drops the pause. A deploy or rollback never pauses or resumes a schedule.

  • Resume

    The schedule goes on. Ticks missed while it was paused start once, at once, as after downtime, unless catchup leaves them out. The answer's nextAt is the tick due next, already past when one was missed.

  • Trigger now

    Starts one run now with the schedule's payload, the origin schedule and the schedule's name as origin_ref, even while a run goes on, and the next tick stays when it was. Later ticks' overlap treats the run as the schedule's last one. It counts like any run: 429 {"error": "quota exceeded", "limit", "max"} with Retry-After at a limit, 429 past the spending limit, and 503 {"error": "runs are paused"}. A tick that would start nothing gets 409 with why, such as the workflow is paused or workflow not found. An agent's schedule starts one conversation and answers {"schedule", "conversationId"}, or 409 with why it didn't start, as its tick would record it, such as agents are off in this workspace or limit runsPerDay.

  • Backfill

    {"from", "to"?}, in milliseconds or ISO 8601, starts a run for each tick of the cron from from up to to, oldest first: from included, to not. to defaults to now, and a later one counts as now. A tick that has a run already, because it ran on time or an earlier backfill started it, is counted skipped and never starts again. Backfilled runs ignore overlap and catchup. Each start counts like any run: one a limit refuses makes the backfill wait, with error saying why, and try the same tick again once the limit allows, or after 60 seconds. A paused schedule's or workflow's backfill waits too. Deleting the workflow, a release that changes the schedule, or waiting until its next tick is older than run history keeps (34 days) stops it with ended: "stopped". Removing the schedule removes its backfill. Workflow schedules only.

  • Progress

    GET /v1/schedules shows the latest backfill as backfill: {from, to, ticks, started, skipped, next, error, requestedBy, requestedAt, ended, endedAt}. next is the tick it starts next, and null once it has ended. ended is null while it runs, then done, cancelled or stopped, and error says why it waits or why it stopped.

  • Limits

    A note is up to 500 characters. A backfill reaches back 31 days at most, so that each tick's own run is still in the run history, and covers 1,440 ticks at most, one day of a cron that runs every minute. A bigger range gets 400 with ticks: send a second backfill once the first ends. One backfill runs per schedule at a time: another gets 409 {"error": "a backfill is running", "backfill"}. A backfill starts up to 25 ticks every 5 seconds.

  • Who and audit

    Pausing and resuming need workflow.pause, and Trigger now and backfill run.start, which developers hold. An agent's schedule also needs agent.deploy. A key scoped to other workflows or agents gets 404 {"error": "schedule not found"}. Trigger now of an agent's schedule with a key scoped to some workflows returns 403 when the schedule may start other workflows: see Scheduled messages. GET /v1/schedules shows pausedAt, pausedBy (an email, an API key id or pauseOnFailure) and pauseNote. The audit log records schedule_pause, schedule_resume, schedule_trigger, schedule_backfill and schedule_backfill_cancel, with the schedule's name.

  • Dashboard and MCP

    Each row on the Schedules screen has Pause or Resume, Trigger now, Backfill for a workflow schedule, and Stop backfill while one runs. Pause takes a note, and Backfill a range in UTC, the last 24 hours by default. MCP has list_schedules, pause_schedule, resume_schedule, trigger_schedule, backfill_schedule and stop_backfill.

Routes
RouteMethodMinimum role
/v1/schedules/:schedule/pause {"note"?}; {schedule, paused, pausedAt, pausedBy, note}POSTdeveloper
/v1/schedules/:schedule/resume {schedule, paused, nextAt}POSTdeveloper
/v1/schedules/:schedule/trigger 202 {schedule, runId}, or {schedule, conversationId} for an agent's schedule; 403 for a key an agent's schedule reaches past; 409 while paused or when it would start nothingPOSTdeveloper
/v1/schedules/:schedule/backfill {"from", "to"?}; 202 {schedule, backfill}; 400 for a bad range, over 1,440 ticks or an agent's schedule; 409 while paused or while a backfill runsPOSTdeveloper
/v1/schedules/:schedule/backfill {schedule, backfill}, ended cancelled; 409 {"error": "no backfill is running"}DELETEdeveloper

Events

A run can wait for something outside it, such as a signature or a payment. step.waitForEvent pauses the run until the event arrives, and step.eventUrl gives the sender a URL to post it to.

invoice-signature
import { workflow, FatalError } from "shiftlabs";

export default workflow<{ invoiceId: string }>(async ({ payload, step }) => {
  await step.run("send for signature", () =>
    fetch("https://sign.example.com/requests", {
      method: "POST",
      body: JSON.stringify({
        document: payload.invoiceId,
        callback: step.eventUrl("signed"),
      }),
    }),
  );
  const signed = await step.waitForEvent<{ signer: string }>("signed", {
    timeout: "5 days",
  });
  if (!signed) throw new FatalError("not signed in time");
  return { signer: signed.signer };
});
  • step.waitForEvent(name, { timeout })

    Waits for the event name and returns its data: the JSON body it was sent with, parsed, or the text. Returns null once timeout passes, "24 hours" by default. In Python, step.wait_for_event(name, timeout=…) returns None. In a keyed workflow, continueWith lets the wait continue the run as new.

  • step.eventUrl(name)

    A URL that sends this run the event name. Anyone with it can post to it without an API key, so give it only to the service that sends the event. It reaches this run and this event name, nothing else. In Python, step.event_url(name).

  • POST /v1/runs/:id/events/:name

    Sends the event with an API key, for the developer role and up (run.start). The body is the event's data.

  • Send event

    On a run's page in the dashboard, under its status, with the events the run waits for listed. MCP clients send one with the send_event tool.

How events arrive

  • An event sent before the run waits for it is kept until the run does. Each wait takes one event of its name, the oldest first.
  • Names are 1 to 64 letters, digits, - and _. Names that start with sl- are reserved.
  • The body is the event's data, 256 KiB at most: parsed JSON when sent as application/json, the text otherwise. JSON null returns 400, so null from a wait always means the timeout passed.
  • A sent event returns 202 {runId, event}. Once the run has finished, an event returns 409 {"error": "run finished"}, and events no wait took are dropped. Before the run has started, the API returns 409 {"error": "run not started"} with a Retry-After, and a hint when the run waits for its workflow's concurrency or is held while it is paused; a keyed run keeps the event instead. When the run can't be reached, an event returns 503 {"error": "temporarily unavailable"} with Retry-After: 1. It may still have arrived, and a copy sent again waits for the next wait of that name.
  • Waiting is not a step, so it doesn't count toward the steps a run may take. It counts toward the run's lifetime, 168 hours on the free tier and 720 on Pro: a run still waiting then fails.
  • A run takes 100 events on the free tier and 1,000 on Pro, from all senders together. The next one returns 403 {"error": "quota exceeded", "limit": "eventsPerRun", "max"}. An event refused with 409 doesn't count.
  • An event URL that isn't one step.eventUrl made returns 404. Event URLs count toward the webhook rate limits: 100 per 10 seconds per run, within the workspace's limit for its triggers.

Status

step.status(value) publishes where a run is, such as { phase: "sending", done: 3, total: 8 }. The run's page in the dashboard shows the latest as it changes, with the events the run waits for, and GET /v1/runs/:id/status returns it.

send-reminders
import { workflow } from "shiftlabs";

export default workflow<{ customers: string[] }>(async ({ payload, step }) => {
  const total = payload.customers.length;
  for (const [done, customer] of payload.customers.entries()) {
    await step.status({ phase: "sending", done, total });
    await step.run(`remind ${customer}`, async () => {
      await fetch("https://mail.example.com/reminders", {
        method: "POST",
        body: JSON.stringify({ customer }),
      });
    });
  }
  await step.status({ phase: "done", done: total, total });
});
  • step.status(value)

    Publishes value, a JSON object of 16 KiB at most, as the run's status in place of the last one. It returns at once, and the latest is written at most once a second. In Python, step.status(value) or step.status(phase=…, done=…).

  • GET /v1/runs/:id/status

    {runId, state, status, publishedAt, waits, events}: the latest status, null before the first, and when it was published; the approvals and events the run waits for, each {kind, name, since, until} with kind approval or event; and {sent, max}, its events against the plan's limit. For the viewer role and up (run.view).

  • GET /v1/runs/:id/status/stream

    The same as Server-Sent Events, while the run goes on.

How a status is kept

  • step.status is not a step: it doesn't count toward the steps a run may take, and it is not billed. Neither are reads of a status.
  • When a run resumes, after a sleep, a wait or a retry, your code runs again from the top. A step.status call it makes again outside a step doesn't publish again, so the status stays where the run left it.
  • The last status is written before the run's end is, and stays with the run. A workspace keeps the last status of its 1,000 most recently ended runs; an older run's reads null.
  • A readable secret's value in a status shows as [redacted], as in the run's output.
  • A value that isn't a JSON object, or is over 16 KiB as JSON, throws a TypeError. Before the platform has step.status, a call throws an error that says so.

Plans and rollouts

Two keys of a status have a shape the run's page draws: plan, the steps the run means to take, and rollout, a change made to devices in batches, one side of each pair at a time. Every other key is yours.

vlan-change
await step.status({
  plan: [{ name: "backup" }, { name: "apply core A", group: "core", batch: 0 }, { name: "apply core B", group: "core", batch: 0 }],
  rollout: {
    rule: "one side at a time, the next once both verify",
    batches: [
      {
        id: "core",
        groups: [
          { id: "core", side: "A", verify: "ping gateways", devices: [{ id: "sw-1", state: "verified" }] },
          { id: "core", side: "B", devices: [{ id: "sw-2", state: "pending" }] },
        ],
      },
    ],
  },
});
  • plan

    A list of steps, each { name, group?, batch? }: name the step's, group a group's id in rollout, batch a whole number from 0. The run's page lists them under its steps, grouped by batch, each queued until a step of its name runs.

  • rollout

    { batches, rule? }. Each batch is { id, groups }, each group { id, side, verify?, devices } with side "A" or "B", and each device { id, state } with state one of pending, changed, verified, failed and rolled_back. rule says, as text, how the rollout moves on. The run's page draws it under the steps as a matrix: a row for each group id in a batch, with its side A and side B devices, each side's verify beside it, and rule under it. A side of more than 8 devices shows counts by state until you expand it.

  • A plan or rollout of another shape throws a TypeError naming what's wrong, such as step.status: rollout.batches[0].groups[1].side must be "A" or "B". A status without them is checked as before. A run's page shows one published before this check as plan status couldn't be read or rollout status couldn't be read.
  • The 16 KiB holds the whole status. A device {"id":"sw-0001","state":"verified"} takes 36 bytes as JSON with its comma, so one rollout fits at most about 450 such devices, and fewer once batch and group fields and your other keys take their share. Past that, publish the batch in progress and counts for the others.
  • Only the latest status is kept, at most once a second: a rollout that moves faster shows its state as of each write, not each change.

Stream a run's status

GET /v1/runs/:id/status/stream sends a run's status as Server-Sent Events. Each event is one data: line with the JSON GET /v1/runs/:id/status returns, at once and then each time it changes.

shellcurl
# -N prints each event as it arrives; the stream ends when the run does.
curl -N https://api.shiftlabs.org/v1/runs/<run>/status/stream \
  -H "authorization: Bearer $SHIFTLABS_API_KEY"
  • The status is read every 2 seconds, so a change arrives within 2 seconds. Of several changes in that time, you get the latest.
  • Once the run has ended, its last event has the id end and the stream closes. Reconnecting with Last-Event-ID: end gets 204, which stops a browser's EventSource.
  • A stream also ends after 5 minutes: reconnect to go on. While nothing changes, a comment line comes every 20 seconds.
  • A workspace opens 60 streams a minute. The next one gets 429.
  • A browser's EventSource can't send the authorization header. Read the stream with fetch, an SSE client that sends headers, or the client's runs.watch(id).

Config snapshots

step.snapshot(device, text) keeps a device's configuration with the run, such as a switch's running config before and after a change. GET /v1/runs/:id/snapshots lists what a run kept, and GET /v1/runs/:id/snapshots/diff?device= shows what changed on a device between its first snapshot in the run and its last.

add-vlan
import { workflow } from "shiftlabs";

export default workflow<{ device: string; vlan: number }>(async ({ payload, step }) => {
  const show = ["ssh", payload.device, "show running-config"];
  const before = await step.exec("config before", { command: show });
  await step.snapshot(payload.device, before.stdout, { stage: "before" });
  await step.exec("add vlan", { command: ["ssh", payload.device, `vlan ${payload.vlan}`] });
  const after = await step.exec("config after", { command: show });
  await step.snapshot(payload.device, after.stdout, { stage: "after" });
});
  • step.snapshot(device, text, { stage })

    Keeps text, the config of device, redacted. device names the device, 1 to 255 characters. The optional stage says when it was taken, such as "before", 1 to 64 characters. In Python, step.snapshot(device, text, stage=…).

  • GET /v1/runs/:id/snapshots

    [{device, takenAt, bytes, stage}]: the run's snapshots in the order it took them, without their text. bytes is the redacted text's size, and stage is null when the call gave none. For the viewer role and up (run.view), and written to the audit log as snapshot_view, with the run's id.

  • GET /v1/runs/:id/snapshots/diff?device=

    {device, from, to, added, removed, hunks, truncated}: the device's first snapshot in the run against its last. from and to are each {takenAt, bytes, stage}. Each hunk is {oldStart, oldLines, newStart, newLines, lines} as in diff -u, every line starting with a space, - or +. A device with fewer than two snapshots in the run gets 404. For the viewer role and up (run.view), and written to the audit log as snapshot_view, with the run's id.

How snapshots are kept

  • step.snapshot is not a step: it doesn't count toward the steps a run may take, and it is not billed. Call it outside step.run, with what a step returned. Inside a step's function it throws.
  • When a run resumes, your code runs again from the top. A step.snapshot call it makes again keeps nothing again.
  • Before the text is kept, the workspace's readable secrets are redacted, as in the run's output, and so are the credentials configs hold: SNMP communities and SNMPv3 keys, passwords, secrets and their hashes, TACACS+ and RADIUS keys, routing, NTP and key chain keys, ISAKMP and pre-shared keys, and private keys. Each shows as [redacted], so a diff doesn't show a changed credential.
  • A text over 256 KiB after redaction throws a TypeError, as does a device or stage of the wrong length. A run keeps at most 1,000 snapshots, and the next call throws. Before the platform has step.snapshot, a call throws an error that says so.
  • A diff is computed when you read it, from two snapshots of 256 KiB at most, and shows at most 2,000 hunk lines. Past that, truncated is true, and added and removed still count every changed line. When the two differ in more than 2,000 lines, everything from the first change to the last shows as removed and added.
  • A snapshot is kept for 35 days after the run ends, the same as the run; a run still going keeps its snapshots. Purging its workflow from the trash, or deleting the workspace, erases it sooner.

Idempotency keys

A step that calls a payment API can run more than once: after a retry, or when a run resumes after a failure. step.idempotencyKey(name) gives the API a key that stays the same each time, so it does the work once.

refund-once
import { workflow } from "shiftlabs";

export default workflow<{ charge: string }>(
  async ({ payload, step, secrets }) => {
    const refund = await step.run("refund", async () => {
      const response = await fetch("https://api.stripe.com/v1/refunds", {
        method: "POST",
        headers: {
          authorization: `Bearer ${secrets.STRIPE_KEY}`,
          "idempotency-key": step.idempotencyKey("refund"),
        },
        body: new URLSearchParams({ charge: payload.charge }),
      });
      return response.json();
    });
    return { refund: refund.id };
  },
);
  • step.idempotencyKey(name)

    sl_ followed by 32 hex characters. It is the same on every retry, replay and resume of the run, and different in every other run. Use one name per call you make. It is not a step and makes no request. In Python, step.idempotency_key(name).

Approvals

A run can stop until a person approves, such as before a large refund. step.waitForApproval puts a request in the workspace's Approvals inbox, notifies the approvers, and waits for one of them to answer.

refund-approval
import { workflow } from "shiftlabs";

export default workflow<{ invoiceId: string; amount: number }>(
  async ({ payload, step }) => {
    if (payload.amount > 500) {
      const decision = await step.waitForApproval("refund", {
        message: `Refund $${payload.amount} on invoice ${payload.invoiceId}?`,
        timeout: "2 days",
        approvers: ["ana@acme.com", "role:admin"],
      });
      if (!decision.approved) return { refunded: false, note: decision.note };
    }
    await step.run("refund", () =>
      fetch(
        `https://billing.example.com/invoices/${payload.invoiceId}/refund`,
        { method: "POST" },
      ),
    );
    return { refunded: true };
  },
);
  • step.waitForApproval(name, { message, timeout, approvers, approvals, policy })

    Puts the request name in the Approvals inbox, with message for the approvers, and waits for the answer. Returns { approved, by, note }: by is the approver's email or API key id, note what they wrote. In Python, step.wait_for_approval(name, message=…, timeout=…, approvers=…, approvals=…, policy=…) returns a dict.

  • timeout

    How long approvers have, "72 hours" by default. A request nobody answers in time counts as denied: approved is false and by is null. It runs out at the latest about 1 hour 45 minutes before the run's lifetime ends, so the run still gets the answer. With less time left, it runs out at once.

  • approvers

    Who may answer: up to 20 of role:admin, role:approver, role:manager and members' emails. Only they see the request and get its notice. Left out, every admin and approver. A developer never approves, so naming role:developer or role:viewer throws an error.

  • approvals

    How many different members must approve, 1 to 5. The workspace's two approvers setting is the least a request needs, so asking for fewer changes nothing. With 2 or more, the run waits for the last approval, and by and note are its own. A list of approvers naming only members must name at least that many, or the call throws an error. In a workspace with no members, asking for 2 or more makes a request nobody can approve, so it expires as denied.

  • policy

    What the request is, for its approvers: { name, risk }, a name of 1 to 100 characters for the rule that asks, such as "production change", and a risk of "low", "medium" or "high". Both optional. Anything else throws an error. It changes nothing about who answers or how: a deny always needs a reason.

How approvals work

  • Admins answer on the Approvals screen, on the run's page, where the run shows as waiting, or with the API: GET /v1/approvals?kinds=workflow lists the requests, and POST /v1/approvals/:id answers one. See Approve or deny. A request with approvers is listed to them alone, and anyone else gets 403.
  • The workspace's alert emails and webhook get an approvals.waiting notice, or, for a request that names only members, those members. It never includes the message.
  • Each call is one request and one step. A resumed run doesn't ask again: it gets the answer to the same request.
  • Waiting is not a step. It counts toward the run's lifetime, 168 hours on the free tier and 720 on Pro.
  • Names are 1 to 100 characters and can't end with a space, # and a number, such as refund #2. A message is 2,000 characters at most.

Wait for whichever comes first

A run can wait for several things at once and go on with the first to happen: an event, an approval or a timer. step.waitForAny takes the waits, not awaited, and returns which one finished first with what it returned.

ack-or-grace
import { workflow } from "shiftlabs";

export default workflow<{ release: string }>(async ({ payload, step }) => {
  await step.run("ask for an ack", () =>
    fetch("https://chat.example.com/hooks/releases", {
      method: "POST",
      body: JSON.stringify({ text: `Ack ${payload.release}: ${step.eventUrl("ack")}` }),
    }),
  );
  const first = await step.waitForAny("ack or grace", [
    step.waitForEvent("ack", { timeout: "1 day" }),
    step.waitForApproval("override", {
      message: `Ship ${payload.release} without an ack?`,
    }),
    step.sleep("grace", "2 hours"),
  ]);
  if (first.name === "override" && !first.value.approved) {
    return { shipped: false, note: first.value.note };
  }
  await step.run("ship", () =>
    fetch(`https://deploy.example.com/releases/${payload.release}`, { method: "POST" }),
  );
  return { shipped: true, after: first.name };
});
  • step.waitForAny(name, [waits])

    Waits for whichever of waits finishes first and returns { name, value }: that wait's name, and what it returns on its own. In Python, step.wait_for_any(name, [waits]) returns a dict.

  • waits

    1 to 10 calls of step.waitForEvent, step.waitForApproval and step.sleep, not awaited, each with a name of its own. step.sleepUntil can't be one: race a step.sleep for the time left instead.

  • value

    An event's data, or null once its timeout passes. An approval's { approved, by, note }, denied once its timeout passes. null for a sleep.

How a race works

  • Each wait keeps its own timeout. The first to finish wins, and when two finish at once, the one listed first.
  • The others stop. Their pending approval requests leave the inbox as withdrawn, with a note such as "ack" came first. An event that comes after the race stays for the run's next wait of that name.
  • While the race waits, its events are listed with the events the run waits for under its status, and the losers leave that list once a wait wins.
  • An approval answered before the event the run saw first still wins: it counts from when the approver answered.
  • A resumed run gets the same winner and doesn't wait again.
  • step.waitForEvent, step.waitForApproval and step.sleep start waiting when awaited. Give the race the call itself: a wait already awaited, or awaited after a race took it, throws a TypeError. In Python, awaiting a wait the race took raises a RuntimeError.
  • In TypeScript, comparing first.name gives first.value the type of that wait's answer. step.waitForEvent<T>(…) with a type for its data makes its name a plain string.
  • Waiting is not a step. A race of timers, or of one event and timers, takes no step. Any other race takes one, plus one for each approval it asks for. Waiting counts toward the run's lifetime.
  • Names are 1 to 100 characters and can't end with a space, # and a number, such as ack #2.

Run a command

step.exec(name, options) runs a shell script or a program on a runner you host in your own network, next to your clusters and servers, and returns its exit code and output. The run waits while the command runs.

list-pods
import { workflow } from "shiftlabs";

export default workflow(async ({ step }) => {
  const pods = await step.exec("list pods", { command: ["kubectl", "get", "pods", "-n", "apps"] });
  return pods.stdout;
});
  • Give run, a bash script, or command, a program and its arguments. Pass values in env, and readable secrets as { secret: "NAME" } in env or files.
  • An exit code other than 0, or one not in okExitCodes, throws ExecError with the result. timeout defaults to 10 minutes, and retries runs the command again after a failure.
  • profile and requires send the command only to a runner whose image has that profile, such as "k8s" or "network@2026.11.1", and those tools. See Choose a runner by its image.
  • A runner runs whatever its allowed workflows send. Give it only the credentials those workflows need, and limit it to named workflows. See Run commands in your network.

Run a registered activity

step.activity(label, options) runs an activity that the runners of a pool list in their activities file: a program that reads JSON on its standard input and writes JSON on its standard output. The workflow names the activity and passes its input, and gets the output back. A runner with an activities file runs nothing else, and checks each input against the activity's schema before it runs anything.

deploy-service
import { ActivityError, workflow } from "shiftlabs";

export default workflow<{ service: string; version: string }>(async ({ payload, step }) => {
  try {
    const deployed = await step.activity<{ url: string }>("deploy", {
      name: "deploy-service",
      input: { ...payload, token: { secret: "DEPLOY_TOKEN" } },
      timeout: "15 minutes",
      heartbeat: "1 minute",
    });
    return { deployed: true, url: deployed.url };
  } catch (err) {
    if (err instanceof ActivityError) return { deployed: false, exitCode: err.result.exitCode, stderr: err.result.stderr };
    throw err;
  }
});
  • name is an activity in the activities file of the pool's runners, and runner picks the pool, "default" unless given. Only a runner that lists the activity takes the job, and with profile or requires, only one whose image has them too.
  • input is any JSON value up to 256 KiB, {} by default; in Python, None sends null. { secret: "NAME" } anywhere in it passes a readable secret, whose value only the runner gets.
  • The JSON the program writes is what step.activity returns, and no output returns null. An exit code other than 0, a timeout, a missed heartbeat, or output that isn't JSON or is over 256 KiB throws ActivityError with the result. timeout defaults to 10 minutes; with heartbeat, the program must write a heartbeat at least that often; and retries runs the activity again after a failure.
  • When the activities file asks for an approval, the run waits for one in the Approvals inbox before any runner takes the job. See Approvals for activities.

Start another workflow

step.start(name, { workflow, payload }) starts a run of another workflow in your workspace and returns the new run's id. It doesn't wait for that run.

fan-out
import { workflow } from "shiftlabs";

export default workflow<{ invoices: string[] }>(async ({ payload, step }) => {
  const runs = [];
  for (const id of payload.invoices) {
    runs.push(
      await step.start(`check ${id}`, {
        workflow: "invoice-check",
        payload: { invoiceId: id },
      }),
    );
  }
  return { runs };
});
  • Same run, same id

    The id comes from this run and the step's name, so when the run resumes or the step is retried, it gets the same id back and no second run starts. Give each start its own name: a name already used for another workflow fails the step.

  • Origin

    The new run is listed with origin workflow, and its origin_ref is the id of the run that started it. The Runs screen links to that run.

  • Limits

    The new run counts toward runs per 24 hours and concurrent runs like any run, and it is refused while your workspace is at its spending limit. The start is retried like any step, then fails.

  • Payload

    payload defaults to {} and must be JSON, at most 1 MiB. When the workflow has a payload schema, a payload that fails it fails the step at once, with no retry.

  • Workspace

    A workflow can start only workflows in its own workspace. A name that isn't deployed there fails the step at once.

  • Key scope

    A workflow deployed with an API key scoped to some workflows can start only those. Another fails the step at once with this workflow's deployer can't reach workflow <name>, whether it exists or not.

  • Steps

    Each start is one step toward the steps per run.

  • Stopping

    A run started with step.start keeps going when the run that started it is cancelled or terminated. While its workflow is paused, the new run is held, and the start still returns its id.

Wait for another workflow

step.call(name, { workflow, payload }) starts a run the way step.start does, waits for it to end, and returns what that run returned.

pay
import { workflow } from "shiftlabs";

export default workflow<{ invoiceId: string }>(async ({ payload, step }) => {
  const check = await step.call<{ ok: boolean }>("check", {
    workflow: "invoice-check",
    payload,
  });
  if (!check.ok) return { paid: false };
  await step.run("pay", () => pay(payload.invoiceId));
  return { paid: true };
});
  • Failures

    When the other run fails, the step fails at once with that run's error, with no retry. Catch it to carry on. If your run was paused for more than 7 days after the other run completed, the step returns the workspace's copy of its result, which a workspace keeps for 35 days up to 64 KB a run and 16 MiB in all; without one, it fails with run <id> completed, but its output is no longer kept, with no retry.

  • Waiting

    Your run sleeps while it waits, and wakes when the other run ends. The wait counts toward your run's lifetime (168 hours on the free tier, 720 on Pro) and each wake toward its dispatches, not its steps.

  • Steps

    A call is two steps: the start and the result. Its name is at most 240 characters.

  • Everything else

    As for step.start: the same run id when your run resumes, origin workflow, the same limits, payload rules and key scope.

  • Only its own run

    A call reads only a run your run started. Any other run id fails the step with run <id> failed: run not found, with no retry. A call gets another id only when code outside steps changes between resumes, so that a step.run of the same name came first.

  • Stopping

    Cancelling or terminating your run also cancels or terminates the run it waits for. When the other run is cancelled or terminated, the step fails with run <id> failed: cancelled (or terminated), with no retry. While the other workflow is paused, the called run is held, and your run waits until the resume.

State

state keeps small JSON values for a workflow: cursors, last-seen ids, keys you've already handled. Every run of the workflow, on any version, reads and writes the same values, and the last write wins. Deleting the workflow moves its state to the trash with it. A restore brings it back, and it is erased with the workflow.

  • state.get(key)

    The value stored at key, or undefined (None in Python) if there is none.

  • state.set(key, value)

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

  • state.delete(key)

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

  • state.list({ prefix, after, limit })

    The workflow's keys in order, at most limit (1 to 1,000, default 1,000). Pass the last key as after for the next page. Python: state.list(prefix=…, after=…, limit=…).

orders
import { workflow } from "shiftlabs";

export default workflow<{ orderId: string }>(
  async ({ payload, step, state, runId }) => {
    const key = `order:${payload.orderId}`;
    const fresh = await step.run("claim", async () => {
      const claimed = await state.get<{ runId: string }>(key);
      if (claimed && claimed.runId !== runId) return false;
      await state.set(key, { runId });
      return true;
    });
    if (!fresh) return "already handled";
    // …
  },
);

The claim stores the run's id, not just a flag: if an attempt stops after state.set but before the step's result is saved, the retry finds its own run's claim and carries on.

Rules for state

  • Use state only inside step.run. Called outside a step, every method throws, because a read there can return something else when the run resumes.
  • A key is 1 to 512 bytes. Two runs that write the same key at once don't merge: the last write wins.
  • A workflow holds at most 1,000 keys on the free tier (10,000 on Pro), and one value is at most 64 KiB as JSON (256 KiB on Pro). All workflows' state together, keys included, is at most 10 MiB (1 GiB on Pro). A write past a limit throws, with an error such as limit stateValueBytes=65536. Deleting a key, or replacing a value with a smaller one, always works.
  • GET /v1/usage shows each workflow's keys and bytes in state, and their total in stateBytes. The dashboard shows the total under Workspace.

Test a workflow

runWorkflow(workflow, options) from shiftlabs/testing runs a workflow inside your test, the way the platform runs it, with no deploy. In Python, run_workflow(workflow, …) from shiftlabs.testing does the same.

invoice-check.test.ts
import assert from "node:assert/strict";
import { test } from "node:test";
import { workflow } from "shiftlabs";
import { runWorkflow } from "shiftlabs/testing";
import invoiceCheck from "./workflows/invoice-check.ts";

test("an invoice the reviewer turns down isn't paid", async () => {
  const result = await runWorkflow(invoiceCheck, {
    payload: { invoiceId: "in_1", amount: 1200 },
    asks: { review: { ok: false, reason: "over budget" } },
  });
  assert.equal(result.status, "completed");
  assert.deepEqual(result.output, { paid: false, reason: "over budget" });
  assert.deepEqual(result.steps.map((s) => s.name), ["review"]);
});

test("step names don't come from the clock", async () => {
  const charge = workflow(async ({ step }) => {
    await step.run(`charge ${Date.now()}`, () => "charged");
  });
  await assert.rejects(
    runWorkflow(charge),
    /code outside a step changed on replay/,
  );
});

Install the shiftlabs package for development: npm's has shiftlabs/testing and PyPI's shiftlabs.testing. Deploys never include them. Any test runner works, such as node:test, Vitest, Bun, pytest or unittest. In Python, run_workflow runs the workflow in an event loop of its own and returns when the run ends, from sync and async tests alike.

Nothing is mocked for you: mock fetch or your HTTP client with your test framework, such as node:test's t.mock.method(globalThis, "fetch", …) or Python's unittest.mock. A mock that stands in for a step's function returns that step's result, so give it one the step can store: Python's AsyncMock() alone returns a MagicMock, so set return_value. Python's js and workers modules load only on the platform, so a test of a workflow that imports them gives them a stand-in first, in sys.modules.

  • payload

    The run's payload, {} by default. It's checked against the workflow's payload schema first, as a webhook's is. One that fails throws payload does not match the schema with the problems the platform lists in detail. A keyed workflow's payload must hold its key, or it throws payload has no key; a test runs one run, so a key's open run doesn't come into it.

  • secrets

    Each secret's value, or { value, readable, hmac } with the flags Secrets sets, both false unless given, as there. secrets.NAME reads a stand-in shaped like the platform's, as code there does. reveal(NAME) returns the value only for a readable secret, and sign signs only with an hmac one. A secret you leave out throws when read.

  • vars

    What vars.NAME reads. A var you leave out reads as undefined (None), as on the platform.

  • state

    The workflow's state when the run starts. The result's state is what it holds when the run ends.

  • events

    Each wait's data, by event name. A wait with none returns null (None), as when its timeout passes.

  • approvals

    Each approval's answer, by name: true, false or { approved, by, note }. by is "test" unless you give it. One with none is denied with by null, as when nobody answers in time. A request that needs several approvals takes this one answer for all of them. An undo's approval is named undo <name>.

  • asks

    Each step.ask's answer, by step name: the agent's text, or the JSON its schema asks for. Text is read as the platform reads an agent's answer, and an answer that doesn't match the schema fails the step. A step with none fails, with an error that says what to add.

  • calls

    Each step.call's result, by step name: what the other workflow's run returned. A step with none fails.

  • starts

    Each step.start's run id, by step name. One with none gets an id made from the run and the name.

  • execs

    Each step.exec's answer, by step name: { exitCode, stdout, stderr, timedOut }, or a function of the options and the try number that returns one. An exit code outside okExitCodes throws ExecError, and retries apply. A step with none fails, with an error that says what to add. Nothing runs.

  • activities

    Each step.activity's answer, by step name: { output, exitCode, stderr, timedOut, heartbeatTimedOut }, each optional, or a function of the request and the try number that returns one. output is what step.activity returns, null when left out. A failure throws ActivityError with the platform's message, and retries apply. A step with none fails, with an error that says what to add. Nothing runs, and no approval is asked for: answer a denial with an Error.

  • decisions

    Each step.decide's answer, by step name: the option the model picks, or each option's probability, as { invoice: 0.6, receipt: 0.4 }. The decision's threshold applies, so a probability under it answers null (None). A step with none fails, with an error that says what to add. No model is asked.

  • cancel

    Cancels the run at a step, by name: { before: "<step>" } refuses that step's first call, which throws cancelled without running. { during: "<step>" } runs that step with its signal already aborted, then refuses the next step; if the step throws, it fails with cancelled, without retries. Add undo: true to run the undos first, as a cancel with undo does. A step the run never reaches changes nothing. In Python, cancel={"before": "<step>"}, a dict with the same keys.

  • replay

    false skips the replay check below.

How a test runs the workflow

  • Steps run at once, in the test's process. Retries happen without their delay, sleeps return at once, and no timeout passes. FatalError ends a step at its first attempt. The wait before a retry is listed in steps as a sleep, such as charge (retry 1), as the platform runs it.
  • A step's function runs once. Later code and the replay get a stored copy of what it returned, as on the platform. In TypeScript that's anything structuredClone copies. In Python it's None, booleans, numbers, strings, lists, tuples, dicts, sets and bytes: tuples come back as lists, dict keys as strings, bytes as memoryview and whole floats as int. Anything else, such as a function, a Response or a datetime, ends the run with the platform's error, which the workflow can't catch.
  • state works only inside step.run, as on the platform.
  • Undos run when the workflow throws, as on the platform, with their retries at once. The result's steps lists them after the step that failed, each with type "undo", the forward step's name, its attempts and its error if it failed. A skipped undo shows as its undo <name> approval step, with the decision as its output, and no undo step. The result's status is failed, and error the run's own error.
  • With cancel, the run cleans up as on the platform: the undos newest first with undo, then onCancel with the steps that completed. The result's status is cancelled, and error is cancelled, or onCancel's message when it threw, with the log line onCancel failed: <message>. steps lists the cleanup's steps after the run's, without the refused step. A step with signal outside a cancel gets a signal that never aborts.
  • An Error in asks, calls, starts, execs, activities or decisions (an exception in Python) fails that step with its message, as a refused ask, a failed run, a refused start, a command or activity that never ran or a refused decision does.
  • workflow({ decisions }), and @workflow(decisions={…}) in Python, is read as a deploy reads it, so a decision the deploy would refuse throws invalid decisions before the run, and a state with other fields than the deploy read fails its step.
  • workflow({ search }) is read as a deploy reads it, so one the deploy would refuse throws invalid search before the run, and the run starts with the tags its payload gives the search keys. step.tag tags it as on the platform: it throws inside a step's function, past 20 tags, and for a name or value the platform refuses, with the platform's message. The replay changes no tags. workflow({ key }) is read the same way: a path the deploy would refuse throws invalid key.
  • step.snapshot keeps what the platform would: the text with the test's readable secrets and the credentials redacted. It throws as on the platform, with the platform's message: inside a step's function, past 1,000 snapshots, for a text over 256 KiB after redaction, and for a device or stage the platform refuses. The replay keeps nothing.
  • step.start and step.call start nothing: the result's started lists the runs they would start, with their payloads. step.eventUrl returns a URL on hooks.shiftlabs.invalid, which reaches nothing.
  • Names and options are checked as the platform checks them, so an event name with a . throws in the test too. Plan limits, such as steps per run and state size, aren't applied.
  • The result is { status, output, error, steps, logs, state, started, tags, statuses, snapshots }. status is completed, failed, or cancelled with cancel, and error is what the workflow threw. steps lists each step with its attempts and what it returned or why it failed. logs has each line as the run's logs show it: log.info writes level log. tags holds the run's tags when it ended, by name. statuses lists what step.status published, in order. snapshots lists what step.snapshot kept, in order, each { device, stage, text, bytes } with text redacted.

The replay check. When a run resumes after a sleep, a retry or a wait, the platform runs the code outside steps again, and answers each step from storage by its name and how many times the run has called that name. A sleep's duration is part of it, and step.run, step.start and step.call count their calls of a name together. Code that picks steps from the time, a random number or anything else outside the payload and step results calls other steps then, and those run again. So after the first run, runWorkflow runs the workflow once more on the stored results, at least a millisecond later. If that calls a step the first run didn't, calls a step fewer or more times, gets a result another kind of step stored, or ends another way, the test fails with code outside a step changed on replay and the first difference. Steps that run in parallel may come back in any order, and names made from step results, such as a step per item of a list a step returned, pass. A sleep whose duration comes from the time, such as dueAt - Date.now(), fails.

Stop a run

Cancel a run to end it before its next step. Terminate it to stop it at once.

shellcurl
# Cancel (developer key). Answers 202 {"runId", "status": "cancelled", "cleanup"}, or "cancelling"
# while a step or the run's cleanup runs: the run ends once they finish.
curl -X POST https://api.shiftlabs.org/v1/runs/<runId>/cancel \
  -H "authorization: Bearer $SHIFTLABS_API_KEY"

# Terminate (admin key). Answers 202 {"runId", "status": "terminated"}. A step in progress is cut off.
curl -X POST https://api.shiftlabs.org/v1/runs/<runId>/terminate \
  -H "authorization: Bearer $SHIFTLABS_API_KEY"
  • Cancel

    The step running now finishes, and the run ends cancelled before its next step. A started run whose workflow has onCancel runs it first, and the answer says "cleanup": true. Until the run ends, the answer and the run's page say cancelling. A run that is sleeping or waiting, for an event, an approval, an agent or another run, is cancelled at once, after its cleanup if it has one. So is a run that hasn't started: queued, held or waiting for its concurrency, and it gets no cleanup. Developers can cancel.

  • Terminate

    The run stops at once, even in the middle of a step, and ends terminated. A step cut off this way may have done part of its work, so cancel when you can. Admins can terminate. terminating means Workflows didn't answer in time, and the workspace keeps trying.

  • Runs it started

    Cancelling or terminating a run also cancels or terminates the runs it started with step.call that haven't ended. Runs it started with step.start keep going.

  • Who and when

    GET /v1/runs and GET /v1/runs/:id show stop_requested (cancel or terminate), stop_requested_at and stop_requested_by, an email or API key id. They stay after the run ends. The audit log records run_cancel and run_terminate. GET /v1/runs?status=cancelled and ?status=terminated list the runs that ended this way.

  • Ended runs

    A run that has ended gets 409 {"error": "run already ended", "status"}. Cancelling a run that is already cancelling answers 202 with cancelling again.

  • Billing and alerts

    A cancelled or terminated run counts only if its code ran. It isn't a failure, so it sends no alert.

  • Dashboard and CLI

    While a run hasn't ended, its page has Cancel run for developers and Terminate run for admins. The CLI has shiftlabs runs cancel <run-id> [--undo] and shiftlabs runs terminate <run-id>.

Clean up when a run is cancelled

Give the workflow an onCancel to clean up what a cancelled run left: delete the server it created, release the hold it placed. Once the step running at the cancel ends, the run's function stops before its next step, then onCancel runs with the steps that completed, before the run ends cancelled.

provision
import { workflow } from "shiftlabs";

const servers = "https://api.example.com/servers";

export default workflow<{ name: string }>(
  {
    onCancel: async ({ steps, step }) => {
      const created = steps.find((s) => s.name === "create server");
      if (!created) return;
      const { id } = created.output as { id: string };
      await step.run("delete server", async () => {
        const r = await fetch(`${servers}/${id}`, { method: "DELETE" });
        if (!r.ok && r.status !== 404) throw new Error(`delete failed: ${r.status}`);
      });
    },
  },
  async ({ payload, step }) => {
    const server = await step.run("create server", async () => {
      const r = await fetch(servers, { method: "POST", body: JSON.stringify({ name: payload.name }) });
      return (await r.json()) as { id: string };
    });
    // signal aborts soon after a cancel, so the poll stops instead of running out its timeout.
    await step.run("wait until ready", { signal: true, timeout: "30 minutes" }, async ({ signal }) => {
      for (;;) {
        const r = await fetch(`${servers}/${server.id}`, { signal });
        if (((await r.json()) as { ready: boolean }).ready) return;
        await new Promise((resolve) => setTimeout(resolve, 10_000));
        signal.throwIfAborted();
      }
    });
  },
);
  • onCancel

    A function of the run's context and steps. It can be async, and what it returns is dropped. Its step is the run's own, so its steps are stored, retried and listed as any step. It's read at deploy. In Python, @workflow(on_cancel=fn), and fn gets a context with ctx.steps.

  • steps

    The step.run calls that completed before the cancel, in the order the run called them, each { name, output } with what the step returned, as stored. Sleeps, waits and other kinds of steps aren't listed. In Python, a list of dicts with the keys "name" and "output".

  • signal

    step.run(name, { signal: true, ...config }, fn) gives fn { signal }, an AbortSignal that aborts within about 5 seconds of a cancel or terminate of the run while the step runs, or within a minute once the step has run 5 minutes. Pass it to fetch or check it, to stop a long step early. If the step then throws, it fails with cancelled, without retries; if it returns, its result is kept. In Python, step.run(name, fn, *args, signal=True) calls fn(*args, signal=signal), with signal.aborted, signal.reason ("cancelled" or "terminated") and await signal.wait().

  • On the run

    The cancel answers "cleanup": true and cancelling while the cleanup runs. GET /v1/runs/:id and GET /v1/runs show when it began as cleanup_at, null when none ran. The run's page shows it as Cleanup, and its timeline has cleanup, with what ran (onCancel, undo or undo, onCancel), and cleanup failed with the error.

shellcurl
# Developer key. Answers 202 {"runId", "status": "cancelling", "cleanup": true}.
curl -X POST https://api.shiftlabs.org/v1/runs/<runId>/cancel \
  -H "authorization: Bearer $SHIFTLABS_API_KEY" -H "content-type: application/json" \
  -d '{"undo": true}'

Cancel with undo. A cancel with {"undo": true} also runs the undo handlers of the run's completed steps, newest first, before onCancel, each with error cancelled. An undo that fails for good stops the older ones, as on a failure, and onCancel still runs. The clients take sl.runs.cancel(id, { undo: true }), and sl.runs.cancel(id, undo=True) in Python. The CLI has shiftlabs runs cancel <run-id> --undo, and on the run's page, Cancel run has Also undo completed steps. undo must be true or false, else the cancel gets 400 {"error": "undo must be true or false"}.

How a cleanup runs

  • Only a run that started gets a cleanup, and only when its workflow has onCancel or the cancel asks for undo. A run that hasn't started ends cancelled at once, and a terminated run gets no cleanup. Terminating a run during its cleanup ends it at once, terminated.
  • Once the step running at the cancel ends, each new step or wait of the run's function throws cancelled without running, and sleeps end at once, so the function returns or throws quickly. The cleanup runs either way. A step or wait whose result was stored still returns it.
  • The run stays cancelling until its cleanup ends, then ends cancelled.
  • onCancel runs once per run. If it throws, the run still ends cancelled, its logs get onCancel failed: <message> at level error, and its timeline cleanup failed. Make its steps safe to run twice, as the 404 above does: a retry can follow an attempt that did the work.
  • Each cleanup step attempt counts as a step toward steps per run and the workspace's steps, and its code uses the run's CPU, as any step's does. A run past its step limit can't clean up, since its steps are refused.
  • undo needs a version deployed since cleanup on cancel shipped, in November 2026. A run of an older version gets 409 {"error": "this run's version can't undo on cancel: deploy the workflow again"}, and nothing is cancelled. An older version has no onCancel either: deploy it again for that too.
  • Cancel many runs runs each run's onCancel, without undos: undo is only for one run's cancel. A run started with step.call, cancelled with the run that called it, runs its own onCancel, without undos.

Pause a run

Pause one run to hold it where it is, for example while you check what its next step will do. Unpause it to go on from there.

shellcurl
# Developer key. Answers 202 {"runId", "status": "paused", "pausedAt", "pausedBy"}, or "pausing"
# while a step runs: the run holds once that step finishes.
curl -X POST https://api.shiftlabs.org/v1/runs/<runId>/pause \
  -H "authorization: Bearer $SHIFTLABS_API_KEY"

# Answers 202 {"runId", "status": "running", "pausedAt": null, "pausedBy": null}.
curl -X POST https://api.shiftlabs.org/v1/runs/<runId>/unpause \
  -H "authorization: Bearer $SHIFTLABS_API_KEY"
  • Where it holds

    The step running now finishes, and no other starts until you unpause the run. A sleep or a wait that ends while the run is paused goes on when you unpause it.

  • Limits

    A paused run still counts toward runs at once and its workflow's concurrency, and its lifetime keeps running: paused past it, it fails like any run past its lifetime.

  • Stop it instead

    A paused run can be cancelled, which ends it at once, or terminated.

  • Refused

    A run that hasn't started gets 409: cancel it, or pause its workflow. So does a run being cancelled. A run that has ended gets 409 {"error": "run already ended", "status"}.

  • Who and when

    GET /v1/runs and GET /v1/runs/:id show the run as paused, with paused_at and paused_by, an email or API key id, and GET /v1/runs?status=paused lists paused runs. Developers can pause and unpause, and the audit log records run_pause and run_unpause.

  • A workflow's pause

    Pausing a run is separate from pausing its workflow, which holds the workflow's new runs and lets started ones go on.

  • Dashboard, CLI and MCP

    While a run is running, sleeping or waiting, its page has Pause run. While it's paused, it has Unpause. The CLI has shiftlabs runs pause <run-id> and shiftlabs runs unpause <run-id>, and MCP pause_run and unpause_run.

Retry now

When a step.run, step.exec or step.activity attempt fails and the step waits before its next attempt, Retry now starts that attempt at once, for example after you've fixed what made it fail.

shellcurl
# Developer key. Answers 202 {"runId", "retried": ["charge (retry 1)#1"]}.
curl -X POST https://api.shiftlabs.org/v1/runs/<runId>/retry \
  -H "authorization: Bearer $SHIFTLABS_API_KEY"
  • What it can cut short

    The wait between attempts that a step's retries set, for step.run, step.exec and step.activity. A run that started before Retry now covered a kind of step waits out that step's delays itself: before 1 November 2026 for commands and activities, before 3 November 2026 for step.run. So does a step.run whose name is over 180 characters, and an undo's retries. A run that isn't waiting to retry a step Retry now can end gets 409.

  • When

    GET /v1/runs/:id shows retrying_until, when the next attempt would start without Retry now.

  • Steps

    Each step.run attempt is a step of its own, so each counts toward steps per run and your workspace's steps: a step that fails twice and then passes counts 3, where it counted 1 before 3 November 2026. The wait before an attempt isn't a step. Commands and activities count as before.

  • Who, dashboard, CLI and MCP

    Developers can retry now, and the audit log records run_retry with the waits it ended. While a run waits to retry a step, its page has Retry now. The CLI has shiftlabs runs retry <run-id>, and MCP retry_run.

Re-run a run

Re-run a run as a new run, for example once you've deployed a fix for what made it fail. The new run uses the run's own version and payload, or the workflow's current version, and you can give it another payload.

shellcurl
# Developer key. Answers 202 {"runId", "versionHash"}: versionHash is the version the new run uses.
curl -X POST https://api.shiftlabs.org/v1/runs/<runId>/rerun \
  -H "authorization: Bearer $SHIFTLABS_API_KEY" -H "content-type: application/json" \
  -d '{"version": "current"}'

# With another payload, checked against the current version's payload schema.
curl -X POST https://api.shiftlabs.org/v1/runs/<runId>/rerun \
  -H "authorization: Bearer $SHIFTLABS_API_KEY" -H "content-type: application/json" \
  -d '{"version": "current", "payload": {"invoiceId": "in_42", "amount": 1200}}'
  • The new run

    A new run with the origin rerun and rerun_of set to the run. It counts toward your limits and is billed like any run, a paused workflow holds it, and the workflow's concurrency makes it wait its turn, as for any start.

  • Which version

    With no body, or "version": "same", the run's own version. With "version": "current", the workflow's current version, such as one with a fix you deployed after the run failed. versionHash in the answer, and on the new run, is the version it uses.

  • Payload

    The run's own, or payload in its place: any JSON value up to 1 MiB. A payload on another version than the run's, or one you give, must match the schema of the version the new run uses. One that doesn't gets 400 {"error": "payload does not match the schema", "detail"} and starts nothing.

  • How long

    While the run's payload is kept: 14 days. After that a re-run gets 410.

  • Who, dashboard, CLI and MCP

    Re-running needs run.start, which developers hold. A run's page has Re-run, on the current version by default once a newer one is deployed, and Edit payload and re-run, which opens the payload form filled in with the run's payload. The CLI has shiftlabs runs rerun <run-id> [--current] [--payload <json>], and MCP's rerun takes version and payload. To re-run many runs, see Cancel or re-run many runs.

Resume a failed run

Resume a failed run from one of its steps, for example once you've fixed what made its last step fail. The new run doesn't run the steps before that one again: they return what they returned in the failed run. It runs the failed run's version, or the workflow's current version, such as the fix you deployed.

shellcurl
# Developer key. Starts at the step the run failed at. Answers 202 {"runId", "from": {"step", "occurrence", "kind"},
# "seeded", "versionHash"}: seeded counts the steps it didn't run again, versionHash is the version it runs.
curl -X POST https://api.shiftlabs.org/v1/runs/<runId>/resume \
  -H "authorization: Bearer $SHIFTLABS_API_KEY"

# From an earlier step: its name, and which call of it when the run used the name more than once.
curl -X POST https://api.shiftlabs.org/v1/runs/<runId>/resume \
  -H "authorization: Bearer $SHIFTLABS_API_KEY" -H "content-type: application/json" \
  -d '{"step": "migrate", "occurrence": 1}'

# On the workflow's current version.
curl -X POST https://api.shiftlabs.org/v1/runs/<runId>/resume \
  -H "authorization: Bearer $SHIFTLABS_API_KEY" -H "content-type: application/json" \
  -d '{"step": "deploy", "version": "current"}'

# The steps it can resume from. Answers {"points": [{"step", "occurrence", "kind", "outcome"}], "more", "until"}.
curl https://api.shiftlabs.org/v1/runs/<runId>/resume \
  -H "authorization: Bearer $SHIFTLABS_API_KEY"
  • The new run

    A new run with the same payload, of the same version or, with "version": "current", the workflow's current one, with the origin resume and rerun_of set to the failed run. It counts toward your limits and is billed like any run.

  • Steps before it

    Each returns what it returned in the failed run, without running, and one that threw throws the same error. An approval given before the failure stands and isn't asked again, and commands, agents, decisions and runs those steps started don't run again. They don't count toward the run's steps.

  • Idempotency keys

    The new run's idempotency keys are the failed run's, so an API that took a step's key does the work once even when the step runs again. Resuming a resumed run keeps the first run's keys.

  • Which step

    Any step the failed run reached, up to the one it failed at. A step whose result isn't plain JSON, such as a Date, a Map or bytes, can be resumed from but not past. A step the run never reached gets 400. GET /v1/runs/:id/resume lists the steps a resume can start from, in the order the run called them, up to 1,000, with how each ended in the run.

  • On the current version

    The steps before the one you resume from must be the failed run's: the same kinds and names, in the same order. The new run checks each as it replays it, and fails at the first that differs, before running it, with an error naming both, such as call 2 is step.run("drain-all") in this version and step.run("drain") in that run. Steps started in parallel that finished in another order count as different: resume those on the run's own version. The run's payload must match the current version's schema, or the request gets 400.

  • Undone runs

    A failed run whose undo functions ran gets 409 and has no Resume from: they reversed what the steps a resume would skip did. Re-run it instead.

  • How long

    While the failed run's payload is kept: 14 days. GET /v1/runs/:id shows resume, the step a resume starts at unless you name one, and until. A workspace keeps 8 MiB of failed runs' step results and drops the oldest past that. Runs that failed before resume existed, and runs of a version deployed before it, get 409: deploy the version again and re-run them.

  • Who, dashboard, CLI and MCP

    Resuming needs run.start, which developers hold. A failed run's page has Resume from, named for the step it failed at, next to Re-run, and lists its steps under Steps, each with Resume from here, on the current version by default once a newer one is deployed. The resumed run links back to the failed one. The CLI has shiftlabs runs resume <run-id> [--step <name>] [--occurrence <n>] [--current], and MCP resume_run with id, step, occurrence and version.

Pause a workflow

Pause a workflow to hold its new runs, for example while you fix a bug. Runs already started keep going.

shellcurl
# Developer key. Answers {"workflow", "paused": true, "pausedAt", "pausedBy", "heldRuns"}.
curl -X POST https://api.shiftlabs.org/v1/workflows/refund-check/pause \
  -H "authorization: Bearer $SHIFTLABS_API_KEY"

# Start the held runs in the order they arrived. Answers {"workflow", "paused": false, "resumed", "dropped"}.
curl -X POST https://api.shiftlabs.org/v1/workflows/refund-check/resume \
  -H "authorization: Bearer $SHIFTLABS_API_KEY"

# Or resume and end the held runs, cancelled and unbilled.
curl -X POST https://api.shiftlabs.org/v1/workflows/refund-check/resume \
  -H "authorization: Bearer $SHIFTLABS_API_KEY" -H "content-type: application/json" \
  -d '{"drop": true}'
  • Held runs

    While the workflow is paused, its new runs are held: stored, but not started. Webhooks, Run now, the API, MCP, re-runs, agent tools, step.start and step.call all hold the same way. A held run is listed queued with queued_reason: "paused", and the start answers 202 with "held": true.

  • Resume

    Resuming starts the held runs in the order they arrived, and resumed counts them. Each starts at once, or waits its turn like a run past the workflow's concurrency, which includes waiting while your workspace is at a daily cap or its spending limit.

  • Drop

    {"drop": true} ends the held runs cancelled instead, and dropped counts them. Dropped runs aren't billed.

  • Schedules

    Schedule ticks are skipped while the workflow is paused: they start nothing and hold nothing. The schedule records lastSkipped: "the workflow is paused".

  • Limits

    A held run counts toward runs per 24 hours and toward the runs that can wait per workflow: 1,000 on Free and 10,000 on Pro. Past that, a start gets 429 {"error": "quota exceeded", "limit": "concurrencyQueue"}. A held run doesn't count toward runs at once. Its lifetime, 168 hours on Free and 720 on Pro, counts from when it arrived, and a run held past it fails, unbilled.

  • Who and when

    GET /v1/workflows shows paused_at, paused_by (an email or API key id) and held_runs. Developers can pause and resume, and the audit log records workflow_pause and workflow_resume.

  • Dashboard and CLI

    The workflow's page has Pause workflow. While it is paused, a banner offers Resume and Resume and drop held runs, and held runs show as held. The CLI has shiftlabs workflows pause <name> and shiftlabs workflows resume <name> [--drop].

Pausing a workflow that is already paused answers the same and changes nothing. Resuming one that isn't paused answers resumed: 0 and dropped: 0.

Cancel or re-run many runs

Cancel or re-run the runs that match a filter, up to 1,000 in one request.

shellcurl
# Developer key. Answers {"matched", "cancelled", "cancelling", "more"}.
curl -X POST https://api.shiftlabs.org/v1/runs/cancel \
  -H "authorization: Bearer $SHIFTLABS_API_KEY" -H "content-type: application/json" \
  -d '{"workflow": "refund-check", "status": "queued"}'

# Re-run the runs that failed since 09:00 UTC, on the current version.
# Answers {"matched", "rerun", "skipped", "mismatched", "runIds", "stopped", "nextBefore"}.
curl -X POST https://api.shiftlabs.org/v1/runs/rerun \
  -H "authorization: Bearer $SHIFTLABS_API_KEY" -H "content-type: application/json" \
  -d '{"workflow": "refund-check", "status": "failed", "since": "2026-10-27T09:00:00Z", "version": "current"}'

# How many that would take, without re-running any. Answers {"matched", "rerunnable", "older", "more"}.
curl -X POST https://api.shiftlabs.org/v1/runs/rerun \
  -H "authorization: Bearer $SHIFTLABS_API_KEY" -H "content-type: application/json" \
  -d '{"workflow": "refund-check", "status": "failed", "preview": true}'
  • Filter

    Every field is optional: workflow, status, origin, since, until, tags and limit, from 1 to 1,000, the default. since and until are milliseconds or ISO 8601 times, compared with when the run was queued: since included, until not. tags is an object of up to 10 tags, such as {"customer": "cus_42"}, that a run must all have. A bad field, or one the filter doesn't take, gets 400. A key scoped to some workflows reaches only their runs.

  • Cancel

    POST /v1/runs/cancel cancels the matching runs that haven't ended and weren't asked to stop yet, oldest first, as Cancel does, and each started run runs its workflow's onCancel. status is queued, running, sleeping, waiting or paused. cancelled counts the runs that hadn't started, which end at once. cancelling counts the runs in flight, which end within seconds, or once their running step and cleanup finish. When more is true, more runs match: send the same request again.

  • Re-run

    POST /v1/runs/rerun re-runs the matching runs, newest first, as POST /v1/runs/:id/rerun does, with the origin rerun: each on its own version and payload, or with "version": "current" on its workflow's current version, which leaves out a run whose payload that version's schema refuses and counts it in mismatched. status takes any status. skipped counts runs that can't be re-run, because their payload is older than 14 days or their workflow was deleted. runIds lists the new runs.

  • Preview

    With "preview": true the request re-runs nothing and counts what it would take: matched, rerunnable, those whose payload and workflow are still there, older, those that ran another version than their workflow's current one, and more, when more runs match past limit. Payloads aren't checked against the schema until the re-run.

  • Waiting their turn

    A re-run batch never gets 429 for runs at once. New runs past your runs at once wait their turn and start as runs end, like runs past a workflow's concurrency, and like them wait while your workspace is at a daily cap or its spending limit.

  • Stopped

    Other limits stop the batch: runsPerDay, stepsPerDay, cpuSecondsPerDay, concurrencyQueue, or runs paused across the platform. Then stopped is {"reason", "retryAt"}. To go on, send the request again with before set to nextBefore, which is also set when more runs match. Past the spending limit or while a payment is failing, the request gets 429 and re-runs nothing.

  • Who and dashboard

    Cancel needs run.cancel and re-run run.start, which developers hold. The audit log records runs_cancel and runs_rerun, with the filter, the counts and the version. On the Runs screen, Cancel matching runs and Re-run matching runs act on the screen's filters, and Re-run matching runs first shows how many runs it would re-run and how many ran an older version, on the current version by default when some did.

Routes
RouteMethodMinimum role
/v1/runs/:id/cancel {"undo"?}; 202 {runId, status, cleanup}: cancelled, or cancelling while a step or the run's cleanup runs; 409 once the run has ended, or for undo on a version deployed before cleanup on cancel shippedPOSTdeveloper
/v1/runs/:id/terminate 202 {runId, status}: terminated, or terminating while Workflows hasn't answered; 409 once the run has endedPOSTadmin
/v1/runs/:id/pause 202 {runId, status, pausedAt, pausedBy}: paused, or pausing while a step finishes; 409 for a run not started, ended or being cancelledPOSTdeveloper
/v1/runs/:id/unpause 202 {runId, status, pausedAt, pausedBy}; 409 when the run isn't pausedPOSTdeveloper
/v1/runs/:id/retry 202 {runId, retried}; 409 when the run isn't waiting to retry a commandPOSTdeveloper
/v1/runs/:id/resume {"step"?, "occurrence"?, "version"?}; 202 {runId, from, seeded, versionHash}; 400 when the payload doesn't match the current version's schema; 409 when its step results aren't kept, or its undo functions ranPOSTdeveloper
/v1/runs/:id/resume {points: [{step, occurrence, kind, outcome}], more, until}: the steps a resume can start fromGETviewer
/v1/runs/cancel {"workflow"?, "status"?, "origin"?, "since"?, "until"?, "tags"?, "limit"?}; {matched, cancelled, cancelling, more}POSTdeveloper
/v1/runs/:id/rerun {"version"?, "payload"?}; 202 {runId, versionHash}; 400 when the payload doesn't match the schema of the version it runs on; 410 once its payload is gonePOSTdeveloper
/v1/runs/rerun the same filter, any status, "before"?, "version"? and "preview"?; {matched, rerun, skipped, mismatched, runIds, stopped, nextBefore}, or with preview {matched, rerunnable, older, more}POSTdeveloper
/v1/workflows/:workflow/pause {workflow, paused, pausedAt, pausedBy, heldRuns}POSTdeveloper
/v1/workflows/:workflow/resume {"drop"?}; {workflow, paused, resumed, dropped}POSTdeveloper

API

Deploy, run, roll back and delete workflows with the /v1 API. See Deploy and triggers for examples and Releases to make several versions current together.

Routes
RouteMethodMinimum role
/v1/workflows [{name, current_hash, updated_at, payload_schema, concurrency, search, paused_at, paused_by, held_runs}]; payload_schema is the current version's payload schema, or null, concurrency its concurrency {limit, key?}, or null, search its search keys {name: path}, or null, and paused_at null unless the workflow is pausedGETviewer
/v1/workflows/:workflow body: the source, or several files as JSON; {versionHash, runtime, sizeBytes, secrets, packages, payloadSchema, concurrency, search, warnings}, or 202 {deployId} while new Python or npm packages install; ?stage=1 stages it for a release; ?profile= gives the version a default runner profile, name or name@version, and 400 {error: "invalid runner profile", detail} for another; empty, it gives none; without ?profile, the version keeps the current version's defaultPUTdeveloper
/v1/workflows/:workflow/validate the body and ?profile PUT takes, without ?stage; {ok, loadChecked, errors, warnings}: checks the code as a deploy does and deploys nothingPOSTdeveloper
/v1/workflows/:workflow {deleted, revokedTriggers, droppedVars, unlinkedConnections, purgeAt}; moves it to the trash for 7 days; runs stayDELETEdeveloper
/v1/workflows/:workflow/versions newest first: [{rev, hash, deployed_at, deployed_by, runtime, current}]GETviewer
/v1/workflows/:workflow/versions/:hash/source {hash, language, source}, with entry and files for a workflow of several files; auditedGETdeveloper
/v1/workflows/:workflow/runs body: the payload, 1 MiB at most, also as JSON, as for a webhook; 202 {runId, versionHash}; 400 when it fails the payload schema; takes an Idempotency-KeyPOSTdeveloper
/v1/workflows/:workflow/rollback {"hash"}; new runs use that version: {workflow, current}POSTdeveloper
/v1/deploys deploys that waited on packages; ?status=building|live|failed; newest first, 50 a page; ?limit= (up to 100) and ?before= from Next-BeforeGETviewer
/v1/deploys/:id {id, workflow, status, packages, created_at, finished_at, result}GETviewer