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.
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 }),
}),
);
},
);
import json
from workers import fetch
from shiftlabs import workflow
@workflow
async def refund_check(ctx):
async def fetch_charge():
r = await fetch(
f"https://api.stripe.com/v1/charges/{ctx.payload['id']}",
headers={"authorization": f"Bearer {ctx.secrets.STRIPE_KEY}"},
)
return await r.json()
charge = await ctx.step.run("fetch charge", fetch_charge)
ctx.log.info("charge loaded", {"id": charge["id"]})
await ctx.step.sleep("cool-off", "10 minutes")
async def notify():
await fetch(
"https://hooks.slack.com/services/T0/B0/x",
method="POST",
body=json.dumps({"text": charge["id"]}),
)
await ctx.step.run(
"notify",
notify,
retries={"limit": 3, "delay": "30 seconds", "backoff": "exponential"},
)
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.
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,
}));
});
# /// script
# dependencies = ["pydantic"]
# ///
from pydantic import BaseModel
from shiftlabs import workflow
class Invoice(BaseModel):
invoiceId: str
amount: float
@workflow(payload=Invoice)
async def invoice_check(ctx):
invoice = Invoice.model_validate(ctx.payload)
return await ctx.step.run(
"check",
lambda: {"invoiceId": invoice.invoiceId, "ok": invoice.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 gets200 {"duplicate": true, "runId"}, even if the schema changed since. - Run now
POST /v1/workflows/:workflow/runs, the dashboard's Run now and MCP'srun_workflowget the same400. A repeatedIdempotency-Keystill 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
parametersshows 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.
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 }));
});
from shiftlabs import workflow
@workflow(concurrency={"limit": 1, "key": "customer.id"})
async def sync_customer(ctx):
return await ctx.step.run(
"sync",
lambda: {"customer": ctx.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, andGET /v1/runs,GET /v1/runs/:idand 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 withpayload too largewhen 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.calland agent tools wait the same way. A webhook still gets202with 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.
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 }));
});
from shiftlabs import workflow
@workflow(key="customer.id")
async def customer_session(ctx):
await ctx.step.sleep("cool off", "1 hour")
return await ctx.step.run(
"follow up",
lambda: {"customer": ctx.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.startanswer 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 usestep.start. - Find a key's run
GET /v1/workflows/:workflow/open-run?key=returns the open run,{workflow, key, runId, openedAt}, or404 {"error": "no open run"}, andGET /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 haveworkflows.openRun(Pythonworkflows.open_run), the CLIshiftlabs workflows open-run <workflow> <key>, and MCPget_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
keyand stores it with the version, and the deploy answer andGET /v1/workflowsshow it askey. 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 with400 {"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.
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),
);
}
});
import json
from workers import fetch
from shiftlabs import workflow
@workflow(key="customer.id")
async def chat_session(ctx):
customer = ctx.payload["customer"]["id"]
turn = 0
# The message that opened the run is its payload and its first event.
while True:
message = await ctx.step.wait_for_event("message", timeout="1 hour")
if message is None:
return {"customer": customer, "turns": turn}
turn += 1
async def answer():
body = json.dumps({"customer": customer, "text": message["text"]})
response = await fetch("https://chat.example.com/answers", method="POST", body=body)
return response.status
await ctx.step.run(f"answer {turn}", answer)
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 Pythonevents.send_to_key(workflow, name, data, key=…), the CLI'sshiftlabs workflows send <workflow> <event> --key <key> --data <json>, and MCP'ssend_workflow_event. Events sent to a keyed run by its id, withPOST /v1/runs/:id/events/:nameor an event URL, arrive the same way. - Triggers
A trigger with an
eventsends each delivery to its payload's key as that event instead of starting a run: set it when you create the trigger, or withPATCH /v1/triggers/:id {"event": "message"}, andnullturns 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"}withRetry-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.
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);
}
});
from shiftlabs import workflow
@workflow(key="customer.id")
async def order_tracker(ctx):
# The first run's payload opened the key; each next run's is the state the run before it handed on.
state = {"customer": ctx.payload["customer"], "orders": ctx.payload.get("orders", 0)}
while True:
order = await ctx.step.wait_for_event("order", timeout="30 days", continue_with=state)
if order is None:
return state
count = state["orders"] + 1
state["orders"] = await ctx.step.run(f"record order {count}", lambda: count)
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 asorigin_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
continueWithNothing else continues a run. A keyed run whose code never calls
step.continueAsNewor gives a waitcontinueWithfails once its lifetime ends, with an error that startslimit 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
202names. 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/:idreturnschain:{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, andGET /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
continueWithis ignored andstep.continueAsNewthrows. Astep.waitForAnyof sleeps alone continues only at half a limit. A run that started before this release keeps waiting at itscontinueWithwaits as before. - Tests
runWorkflow'scontinueAt: ncontinues the run at its nthcontinueWithwait, and a run that continued endscontinuedwithcontinuedWith, the state.continuedFromsets the run'scontinuedFrom. In Python:continue_at,continued_fromandcontinued_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.
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;
});
from workers import fetch
from shiftlabs import workflow
@workflow(search={"customer": "customer.id", "invoice": "invoice"})
async def refund(ctx):
invoice = ctx.payload["invoice"]
async def send():
r = await fetch(
f"https://api.example.com/invoices/{invoice}/refund",
method="POST",
)
return await r.json()
made = await ctx.step.run("refund", send)
await ctx.step.tag({"refund": made["id"]})
return made["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.tagstep.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 outsidestep.run: inside a step's function it throwsstep.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 21stand adds none of its tags. Values are strings of 1 to 256 bytes, so turn a number into one, such asString(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_runsand 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/runsandGET /v1/runs/:idgive each run'stags, 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.
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),
}));
});
# 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.jsonpins. Nothing installs when a run starts. The deploy answer lists them underpackages, such aszod@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
202with adeployId, like a Python package build, and goes live when the install finishes, usually within a minute.shiftlabs deploywaits 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.jsonis refused: runnpm installand deploy again. pnpm, Yarn and Bun lockfiles aren't read;npm install --package-lock-onlywrites apackage-lock.jsonbeside 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:bufferand the like work, and so do CommonJS packages thatrequire()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 dedupeoften fixes it. - Import your own files by their names, such as
./money.ts, or with no extension.shiftlabs deployrefuses./money.jsformoney.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.jsonstays importable, as inimport 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.
# /// 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.
uv add --dev shiftlabs # or: pip install shiftlabs
npx shiftlabs types # writes shiftlabs_types.pyi with your secret and var names
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.
# 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'sworkflow_draftentry, 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; andtokens,{input, output}.failed:errorsays why andretrywhether 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, withretryfalse: the draft reached its $0.10, or the workspace its model allowance. - Stream it
With
Accept: text/event-streamthe 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 astatusother thanworking, after which the stream closes. Read the draft then.GET …/draft/:id/streamstreams it again, or from itsLast-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 withconversation.read_others. A draft isn't an agent's conversation: no agent lists it, and the agent routes return404for 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"}, withdetailandresetsAtpast the month's model use. Past the messages a minute, it returns429 {"error": "rate limited"}withRetry-After: 60, and past the Pro spending limit429withRetry-After: 3600. - Past 64,512 bytes it returns
413 {"error": "draft too large", "max": 64512}, and a bad prompt, file, entry or field400with the problem. - An
Idempotency-Keyworks 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 returns409. - 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.
payloadThe 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.stepDurable steps, sleeps, events, approvals and tags. See Durable steps, Events, Approvals and Tags.
varsVars as
vars.NAME: the workspace value, overridden per workflow. A name that is not set reads asundefined. See Vars.secretssecrets.NAMEfor each secret with hosts. It's a stand-in string that the gateway replaces with the real value on requests to those hosts. An unknown name throws. 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
datawith a secret markedhmac. Returns only the signature (hex by default). The secret never enters your code.loglog.info(message, fields?), anddebug,warn,error: one log line each, shown with the run. A line printed in a step's function, withlogorconsole, carries the step's name as itsstep.stateJSON values kept per workflow across runs, used inside steps. See State.
runIdThis run's id.
key·continuedFromA keyed run's key, and the run it continued as new from,
nullfor a key's first run; bothnullfor any other run. In Python,ctx.keyandctx.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
fnonce 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
Dateor an epoch-milliseconds number. In Python,step.sleep_until(name, until)takes adatetimeor 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
- queued21:30:14.227
- started989 ms21:30:15.216
- fetch charge212 ms21:30:15.301 · result stored
- cool-off10 min21:30:15.514
- notify95 ms21:40:15.902 · same version
- completed21:40:16.010
retries.limitHow 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.delayA 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.timeoutA duration after which an attempt fails. Default
"10 minutes".undoA function that reverses the step, run if the workflow fails later. See Undo a step.
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}`);
});
});
from workers import fetch
from shiftlabs import FatalError, workflow
@workflow
async def charge(ctx):
async def attempt():
r = await fetch(
"https://api.example.com/charges",
method="POST",
body=ctx.payload["card"],
)
if r.status == 402:
raise FatalError("card declined")
if not r.ok:
raise Exception(f"charge failed: {r.status}")
await ctx.step.run("charge", attempt)
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.runruns 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. Yourfetchandsigncalls use the subrequests; steps, sleeps andstatedon'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=100on the free tier. Each attempt of astep.runcounts, retries included; sleeps and the waits between attempts don't. In a run started before 3 November 2026, astep.runcounts 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.
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}`);
});
});
import json
from workers import fetch
from shiftlabs import workflow
RECORDS = "https://api.example.com/zones/example.com/records"
@workflow
async def dns_setup(ctx):
host = ctx.payload["host"]
async def create_record():
r = await fetch(
RECORDS,
method="POST",
body=json.dumps({"name": host, "type": "CNAME", "content": "edge.example.com"}),
)
if not r.ok:
raise Exception(f"create failed: {r.status}")
return await r.json()
async def delete_record(record_id):
r = await fetch(f"{RECORDS}/{record_id}", method="DELETE")
if not r.ok and r.status != 404:
raise Exception(f"delete failed: {r.status}")
async def issue_certificate():
r = await fetch("https://api.example.com/certificates", method="POST", body=host)
if not r.ok:
raise Exception(f"certificate failed: {r.status}")
await ctx.step.run("create dns record", create_record, undo=lambda u: delete_record(u["output"]["id"]))
await ctx.step.run("issue certificate", issue_certificate)
undoA 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 }runis the undo function, andretriesandtimeoutits own, with the same defaults as any step. Withapproval, the run first waits for an approval namedundo <name>, with the optionsstep.waitForApprovaltakes. In Python,undo={"run": fn, "retries": …, "timeout": …, "approval": {"message": …}}.- On the run
GET /v1/runs/:idandGET /v1/runsshow when the first undo began asundo_at,nullwhen none ran. The run's page shows it as Undo, and its timeline hasundoandundo failedwith the step's name. A skipped undo shows only as its denied approval.
How undos run
- Only a
step.runwithundowhose 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 namedundo <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 getundo <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
undotakes a name of at most 251 characters, and one with an undoapprovalat most 95, which can't end with a space,#and a number. Longer names, anundothat is neither a function nor{ run, … }, or one on astep.runcalled inside another step's function, throw aTypeErrorwhenstep.runis 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.
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 };
},
);
from shiftlabs import workflow
REVIEW = {
"type": "object",
"properties": {"ok": {"type": "boolean"}, "reason": {"type": "string"}},
"required": ["ok", "reason"],
}
@workflow
async def invoice_check(ctx):
review = await ctx.step.ask(
"review",
agent="invoice-reviewer",
message=(
f"Check invoice {ctx.payload['invoiceId']} "
f"for {ctx.payload['amount']} USD."
),
schema=REVIEW,
)
return (
{"paid": True}
if review["ok"]
else {"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.askreturns the stored answer and starts no other conversation. A secondstep.askwith 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 itsrunis 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
schematakes JSON Schema or a Standard JSON Schema such as zod, aspayloaddoes, 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.asktries 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={…}).
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" };
});
from shiftlabs import decision, workflow
def kind_state(doc):
return {"file": doc["fileName"], "sender": doc["from"], "text": doc["text"]}
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=kind_state,
)
@workflow(decisions={"kind": KIND})
async def intake(ctx):
found = await ctx.step.decide("classify", KIND, ctx.payload)
if found["answer"] is not None:
return {"kind": found["answer"]}
check = await ctx.step.wait_for_approval(
"check the kind",
message=(
f"Is {ctx.payload['fileName']} an invoice? "
f"The model leans to {found['top']}."
),
)
return {"kind": "invoice" if check["approved"] else "other"}
{
"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
questionwithchoicespicks one of 2 to 255 options, given as a list or as an object of options and what each means.questionwithscorepicks one of 2 to 10 levels, lowest first, andscorein the answer is the probability-weighted level, from 0.yesNoalone (yes_noin Python) is a question answered"yes"or"no". Questions and options never carry your data: only the fieldsstatereturns do. - Threshold
The most probable option is the answer when its probability is at least
threshold. Below it,answerisnull, andtopandprobabilitiesstill 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
statereturns. A deploy that changes any of them under aversiondeployed before, staged deploys included, is refused with409and"error": "decision changed without a new version": give the decision a newversion. 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
statebuilds an object of data fields fromstep.decide's input, with the same fields every time:nullfor one you don't have. The deploy reads their names by callingstatewith a stand-in input, so build the fields from the input without parsing or checking it: astatethat throws fails the deploy.stateruns again each time the run resumes, as code outside a step does. - Python
decision()takes the same options as keyword arguments,yes_noforyesNo, andstateis a function or anasyncfunction that returns a dict. A refused deploy'sdetailnames the options as TypeScript does, such asyesNo.step.decidereturns a dict with the same keys,Nonewhere TypeScript hasnull. The stand-in input gives another stand-in for every attribute, item, call and arithmetic, iterates as empty, counts as true and converts to0or"":doc["from"].lower()andround(doc["amount"] * 100)work, andjson.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,RoutingorSort code, and the digits of a field named likeaccountNumber,ibanorcardNumberreach 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/:idreturns them underdecisions, 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.
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.
overlapWhat 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 recordslastSkipped: "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 withlastSkipped: "a tick is already waiting for the previous run"."cancel-other"cancels that run, withstop_requested_byschedule:<name>, and starts the tick once it has ended; a newer tick replaces one still waiting.GET /v1/schedulesshows a waiting tick's cron time asbuffered. Backfilled runs neither count nor wait.jitterA 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.
nextAtstays the cron time.catchupA 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>".pauseOnFailuretruepauses 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.pausedByispauseOnFailureand the noterun <runId> failed: <error>, and the audit log recordsschedule_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
scheduleand the schedule's name asorigin_ref. The Runs screen can filter by it. The run's payload ispayload, 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"inGET /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
schedulesreplace all of the workspace's schedules;schedules: {}removes them, and a project withoutschedulesleaves 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 deployof a project withschedulesreplaces 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 gets403 {"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.startcapability, which developers hold. - Pausing and resuming a schedule needs
workflow.pause, and Trigger now and backfill needrun.start. Developers hold both. An agent's schedule also needsagent.deploy. - A schedule's workflow must exist once the release is in. A schedule whose workflow is deleted later records
workflow not foundat 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. payloadis 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.
# 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
catchupleaves them out. The answer'snextAtis the tick due next, already past when one was missed. - Trigger now
Starts one run now with the schedule's payload, the origin
scheduleand the schedule's name asorigin_ref, even while a run goes on, and the next tick stays when it was. Later ticks'overlaptreats the run as the schedule's last one. It counts like any run:429 {"error": "quota exceeded", "limit", "max"}withRetry-Afterat a limit,429past the spending limit, and503 {"error": "runs are paused"}. A tick that would start nothing gets409with why, such asthe workflow is pausedorworkflow not found. An agent's schedule starts one conversation and answers{"schedule", "conversationId"}, or409with why it didn't start, as its tick would record it, such asagents are off in this workspaceorlimit runsPerDay. - Backfill
{"from", "to"?}, in milliseconds or ISO 8601, starts a run for each tick of the cron fromfromup toto, oldest first:fromincluded,tonot.todefaults 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 countedskippedand never starts again. Backfilled runs ignoreoverlapandcatchup. Each start counts like any run: one a limit refuses makes the backfill wait, witherrorsaying 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 withended: "stopped". Removing the schedule removes its backfill. Workflow schedules only. - Progress
GET /v1/schedulesshows the latest backfill asbackfill:{from, to, ticks, started, skipped, next, error, requestedBy, requestedAt, ended, endedAt}.nextis the tick it starts next, and null once it has ended.endedis null while it runs, thendone,cancelledorstopped, anderrorsays 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
400withticks: send a second backfill once the first ends. One backfill runs per schedule at a time: another gets409 {"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 backfillrun.start, which developers hold. An agent's schedule also needsagent.deploy. A key scoped to other workflows or agents gets404 {"error": "schedule not found"}. Trigger now of an agent's schedule with a key scoped to some workflows returns403when the schedule may start other workflows: see Scheduled messages.GET /v1/schedulesshowspausedAt,pausedBy(an email, an API key id orpauseOnFailure) andpauseNote. The audit log recordsschedule_pause,schedule_resume,schedule_trigger,schedule_backfillandschedule_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_scheduleandstop_backfill.
| Route | Method | Minimum role |
|---|---|---|
/v1/schedules/:schedule/pause {"note"?}; {schedule, paused, pausedAt, pausedBy, note} | POST | developer |
/v1/schedules/:schedule/resume {schedule, paused, nextAt} | POST | developer |
/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 nothing | POST | developer |
/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 runs | POST | developer |
/v1/schedules/:schedule/backfill {schedule, backfill}, ended cancelled; 409 {"error": "no backfill is running"} | DELETE | developer |
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.
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 };
});
import json
from workers import fetch
from shiftlabs import FatalError, workflow
@workflow
async def invoice_signature(ctx):
async def send():
body = {
"document": ctx.payload["invoiceId"],
"callback": ctx.step.event_url("signed"),
}
await fetch(
"https://sign.example.com/requests",
method="POST",
body=json.dumps(body),
)
await ctx.step.run("send for signature", send)
signed = await ctx.step.wait_for_event("signed", timeout="5 days")
if signed is None:
raise FatalError("not signed in time")
return {"signer": signed["signer"]}
step.waitForEvent(name, { timeout })Waits for the event
nameand returns its data: the JSON body it was sent with, parsed, or the text. Returnsnulloncetimeoutpasses,"24 hours"by default. In Python,step.wait_for_event(name, timeout=…)returnsNone. In a keyed workflow,continueWithlets 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/:nameSends 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_eventtool.
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 withsl-are reserved. - The body is the event's data, 256 KiB at most: parsed JSON when sent as
application/json, the text otherwise. JSONnullreturns400, sonullfrom a wait always means the timeout passed. - A sent event returns
202 {runId, event}. Once the run has finished, an event returns409 {"error": "run finished"}, and events no wait took are dropped. Before the run has started, the API returns409 {"error": "run not started"}with aRetry-After, and ahintwhen 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 returns503 {"error": "temporarily unavailable"}withRetry-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 with409doesn't count. - An event URL that isn't one
step.eventUrlmade returns404. 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.
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 });
});
import json
from workers import fetch
from shiftlabs import workflow
@workflow
async def send_reminders(ctx):
customers = ctx.payload["customers"]
total = len(customers)
for done, customer in enumerate(customers):
await ctx.step.status(phase="sending", done=done, total=total)
async def remind(customer=customer):
body = json.dumps({"customer": customer})
await fetch("https://mail.example.com/reminders", method="POST", body=body)
await ctx.step.run(f"remind {customer}", remind)
await ctx.step.status(phase="done", done=total, 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)orstep.status(phase=…, done=…).GET /v1/runs/:id/status{runId, state, status, publishedAt, waits, events}: the latest status,nullbefore the first, and when it was published; the approvals and events the run waits for, each{kind, name, since, until}withkindapprovalorevent; and{sent, max}, its events against the plan's limit. For the viewer role and up (run.view).GET /v1/runs/:id/status/streamThe same as Server-Sent Events, while the run goes on.
How a status is kept
step.statusis 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.statuscall 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 hasstep.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.
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" }] },
],
},
],
},
});
planA list of steps, each
{ name, group?, batch? }:namethe step's,groupa group'sidinrollout,batcha whole number from 0. The run's page lists them under its steps, grouped bybatch, each queued until a step of itsnameruns.rollout{ batches, rule? }. Each batch is{ id, groups }, each group{ id, side, verify?, devices }withside"A"or"B", and each device{ id, state }withstateone ofpending,changed,verified,failedandrolled_back.rulesays, as text, how the rollout moves on. The run's page draws it under the steps as a matrix: a row for each groupidin a batch, with its side A and side B devices, each side'sverifybeside it, andruleunder it. A side of more than 8 devices shows counts by state until you expand it.
- A
planorrolloutof another shape throws aTypeErrornaming what's wrong, such asstep.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 asplan status couldn't be readorrollout 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.
# -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
endand the stream closes. Reconnecting withLast-Event-ID: endgets204, which stops a browser'sEventSource. - 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
EventSourcecan't send theauthorizationheader. Read the stream withfetch, an SSE client that sends headers, or the client'sruns.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.
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" });
});
from shiftlabs import workflow
@workflow
async def add_vlan(ctx):
device = ctx.payload["device"]
show = ["ssh", device, "show running-config"]
before = await ctx.step.exec("config before", command=show)
await ctx.step.snapshot(device, before["stdout"], stage="before")
await ctx.step.exec("add vlan", command=["ssh", device, f"vlan {ctx.payload['vlan']}"])
after = await ctx.step.exec("config after", command=show)
await ctx.step.snapshot(device, after["stdout"], stage="after")
step.snapshot(device, text, { stage })Keeps
text, the config ofdevice, redacted.devicenames the device, 1 to 255 characters. The optionalstagesays 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.bytesis the redacted text's size, andstageisnullwhen the call gave none. For the viewer role and up (run.view), and written to the audit log assnapshot_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.fromandtoare each{takenAt, bytes, stage}. Each hunk is{oldStart, oldLines, newStart, newLines, lines}as indiff -u, every line starting with a space,-or+. A device with fewer than two snapshots in the run gets404. For the viewer role and up (run.view), and written to the audit log assnapshot_view, with the run's id.
How snapshots are kept
step.snapshotis not a step: it doesn't count toward the steps a run may take, and it is not billed. Call it outsidestep.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.snapshotcall 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 hasstep.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,
truncatedistrue, andaddedandremovedstill 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.
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 };
},
);
from urllib.parse import urlencode
from workers import fetch
from shiftlabs import workflow
@workflow
async def refund_once(ctx):
async def refund():
headers = {
"authorization": f"Bearer {ctx.secrets.STRIPE_KEY}",
"idempotency-key": ctx.step.idempotency_key("refund"),
}
response = await fetch(
"https://api.stripe.com/v1/refunds",
method="POST",
headers=headers,
body=urlencode({"charge": ctx.payload["charge"]}),
)
return await response.json()
refund = await ctx.step.run("refund", refund)
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.
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 };
},
);
from workers import fetch
from shiftlabs import workflow
@workflow
async def refund_approval(ctx):
invoice, amount = ctx.payload["invoiceId"], ctx.payload["amount"]
if amount > 500:
decision = await ctx.step.wait_for_approval(
"refund",
message=f"Refund ${amount} on invoice {invoice}?",
timeout="2 days",
approvers=["ana@acme.com", "role:admin"],
)
if not decision["approved"]:
return {"refunded": False, "note": decision["note"]}
async def refund():
await fetch(
f"https://billing.example.com/invoices/{invoice}/refund",
method="POST",
)
await ctx.step.run("refund", refund)
return {"refunded": True}
step.waitForApproval(name, { message, timeout, approvers, approvals, policy })Puts the request
namein the Approvals inbox, withmessagefor the approvers, and waits for the answer. Returns{ approved, by, note }:byis the approver's email or API key id,notewhat they wrote. In Python,step.wait_for_approval(name, message=…, timeout=…, approvers=…, approvals=…, policy=…)returns a dict.timeoutHow long approvers have,
"72 hours"by default. A request nobody answers in time counts as denied:approvedisfalseandbyisnull. 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.approversWho may answer: up to 20 of
role:admin,role:approver,role:managerand members' emails. Only they see the request and get its notice. Left out, every admin and approver. A developer never approves, so namingrole:developerorrole:viewerthrows an error.approvalsHow 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
byandnoteare its own. A list ofapproversnaming 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.policyWhat the request is, for its approvers:
{ name, risk }, anameof 1 to 100 characters for the rule that asks, such as"production change", and ariskof"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=workflowlists the requests, andPOST /v1/approvals/:idanswers one. See Approve or deny. A request withapproversis listed to them alone, and anyone else gets403. - The workspace's alert emails and webhook get an
approvals.waitingnotice, 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 asrefund #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.
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 };
});
import json
from workers import fetch
from shiftlabs import workflow
@workflow
async def ack_or_grace(ctx):
release = ctx.payload["release"]
async def ask():
text = f"Ack {release}: {ctx.step.event_url('ack')}"
await fetch(
"https://chat.example.com/hooks/releases",
method="POST",
body=json.dumps({"text": text}),
)
await ctx.step.run("ask for an ack", ask)
first = await ctx.step.wait_for_any("ack or grace", [
ctx.step.wait_for_event("ack", timeout="1 day"),
ctx.step.wait_for_approval(
"override", message=f"Ship {release} without an ack?"
),
ctx.step.sleep("grace", "2 hours"),
])
if first["name"] == "override" and not first["value"]["approved"]:
return {"shipped": False, "note": first["value"]["note"]}
async def ship():
await fetch(f"https://deploy.example.com/releases/{release}", method="POST")
await ctx.step.run("ship", ship)
return {"shipped": True, "after": first["name"]}
step.waitForAny(name, [waits])Waits for whichever of
waitsfinishes 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.waits1 to 10 calls of
step.waitForEvent,step.waitForApprovalandstep.sleep, not awaited, each with a name of its own.step.sleepUntilcan't be one: race astep.sleepfor the time left instead.valueAn event's data, or
nullonce its timeout passes. An approval's{ approved, by, note }, denied once its timeout passes.nullfor 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.waitForApprovalandstep.sleepstart waiting when awaited. Give the race the call itself: a wait already awaited, or awaited after a race took it, throws aTypeError. In Python, awaiting a wait the race took raises aRuntimeError.- In TypeScript, comparing
first.namegivesfirst.valuethe type of that wait's answer.step.waitForEvent<T>(…)with a type for its data makes its name a plainstring. - 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 asack #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.
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;
});
from shiftlabs import workflow
@workflow
async def list_pods(ctx):
pods = await ctx.step.exec("list pods", command=["kubectl", "get", "pods", "-n", "apps"])
return pods["stdout"]
- Give
run, a bash script, orcommand, a program and its arguments. Pass values inenv, and readable secrets as{ secret: "NAME" }inenvorfiles. - An exit code other than 0, or one not in
okExitCodes, throwsExecErrorwith the result.timeoutdefaults to 10 minutes, andretriesruns the command again after a failure. profileandrequiressend 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.
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;
}
});
from shiftlabs import ActivityError, workflow
@workflow
async def deploy_service(ctx):
try:
deployed = await ctx.step.activity(
"deploy",
name="deploy-service",
input={**ctx.payload, "token": {"secret": "DEPLOY_TOKEN"}},
timeout="15 minutes",
heartbeat="1 minute",
)
except ActivityError as err:
return {"deployed": False, "exit_code": err.result["exit_code"], "stderr": err.result["stderr"]}
return {"deployed": True, "url": deployed["url"]}
nameis an activity in the activities file of the pool's runners, andrunnerpicks the pool,"default"unless given. Only a runner that lists the activity takes the job, and withprofileorrequires, only one whose image has them too.inputis any JSON value up to 256 KiB,{}by default; in Python,Nonesendsnull.{ secret: "NAME" }anywhere in it passes a readable secret, whose value only the runner gets.- The JSON the program writes is what
step.activityreturns, and no output returnsnull. An exit code other than 0, a timeout, a missed heartbeat, or output that isn't JSON or is over 256 KiB throwsActivityErrorwith the result.timeoutdefaults to 10 minutes; withheartbeat, the program must write a heartbeat at least that often; andretriesruns 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.
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 };
});
from shiftlabs import workflow
@workflow
async def fan_out(ctx):
runs = []
for invoice_id in ctx.payload["invoices"]:
runs.append(
await ctx.step.start(
f"check {invoice_id}",
workflow="invoice-check",
payload={"invoiceId": invoice_id},
)
)
return {"runs": 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 itsorigin_refis 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
payloaddefaults 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.startkeeps 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.
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 };
});
from shiftlabs import workflow
@workflow
async def pay(ctx):
check = await ctx.step.call(
"check",
workflow="invoice-check",
payload=ctx.payload,
)
if not check["ok"]:
return {"paid": False}
await ctx.step.run("pay", pay_invoice, ctx.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, originworkflow, 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 astep.runof 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(orterminated), 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, orundefined(Nonein Python) if there is none.state.set(key, value)Stores
valueas JSON atkey, 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 asafterfor the next page. Python:state.list(prefix=…, after=…, limit=…).
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";
// …
},
);
from shiftlabs import workflow
@workflow
async def orders(ctx):
key = f"order:{ctx.payload['orderId']}"
async def claim():
claimed = await ctx.state.get(key)
if claimed and claimed["runId"] != ctx.run_id:
return False
await ctx.state.set(key, {"runId": ctx.run_id})
return True
if not await ctx.step.run("claim", claim):
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
stateonly insidestep.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/usageshows each workflow's keys and bytes instate, and their total instateBytes. 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.
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/,
);
});
import time
import pytest
from shiftlabs import workflow
from shiftlabs.testing import run_workflow
from invoice_check import invoice_check
def test_an_invoice_the_reviewer_turns_down_is_not_paid():
result = run_workflow(
invoice_check,
payload={"invoiceId": "in_1", "amount": 1200},
asks={"review": {"ok": False, "reason": "over budget"}},
)
assert result.status == "completed", result.error
assert result.output == {"paid": False, "reason": "over budget"}
assert [s.name for s in result.steps] == ["review"]
def test_step_names_do_not_come_from_the_clock():
@workflow
async def charge(ctx):
await ctx.step.run(f"charge {time.time()}", lambda: "charged")
with pytest.raises(
AssertionError,
match="code outside a step changed on replay",
):
run_workflow(charge)
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.
payloadThe run's payload,
{}by default. It's checked against the workflow's payload schema first, as a webhook's is. One that fails throwspayload does not match the schemawith the problems the platform lists indetail. A keyed workflow's payload must hold its key, or it throwspayload has no key; a test runs one run, so a key's open run doesn't come into it.secretsEach secret's value, or
{ value, readable, hmac }with the flags Secrets sets, bothfalseunless given, as there.secrets.NAMEreads a stand-in shaped like the platform's, as code there does.reveal(NAME)returns the value only for areadablesecret, andsignsigns only with anhmacone. A secret you leave out throws when read.varsWhat
vars.NAMEreads. A var you leave out reads asundefined(None), as on the platform.stateThe workflow's state when the run starts. The result's
stateis what it holds when the run ends.eventsEach wait's data, by event name. A wait with none returns
null(None), as when its timeout passes.approvalsEach approval's answer, by name:
true,falseor{ approved, by, note }.byis"test"unless you give it. One with none is denied withbynull, 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 namedundo <name>.asksEach
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.callsEach
step.call's result, by step name: what the other workflow's run returned. A step with none fails.startsEach
step.start's run id, by step name. One with none gets an id made from the run and the name.execsEach
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 outsideokExitCodesthrowsExecError, andretriesapply. A step with none fails, with an error that says what to add. Nothing runs.activitiesEach
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.outputis whatstep.activityreturns,nullwhen left out. A failure throwsActivityErrorwith the platform's message, andretriesapply. 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 anError.decisionsEach
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 answersnull(None). A step with none fails, with an error that says what to add. No model is asked.cancelCancels the run at a step, by name:
{ before: "<step>" }refuses that step's first call, which throwscancelledwithout running.{ during: "<step>" }runs that step with its signal already aborted, then refuses the next step; if the step throws, it fails withcancelled, without retries. Addundo: trueto 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.replayfalseskips 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.
FatalErrorends a step at its first attempt. The wait before a retry is listed instepsas a sleep, such ascharge (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
structuredClonecopies. In Python it'sNone, booleans, numbers, strings, lists, tuples, dicts, sets andbytes: tuples come back as lists, dict keys as strings,bytesasmemoryviewand whole floats asint. Anything else, such as a function, aResponseor adatetime, ends the run with the platform's error, which the workflow can't catch. stateworks only insidestep.run, as on the platform.- Undos run when the workflow throws, as on the platform, with their retries at once. The result's
stepslists them after the step that failed, each withtype"undo", the forward step'sname, itsattemptsand itserrorif it failed. A skipped undo shows as itsundo <name>approval step, with the decision as its output, and no undo step. The result'sstatusisfailed, anderrorthe run's own error. - With
cancel, the run cleans up as on the platform: the undos newest first withundo, thenonCancelwith the steps that completed. The result'sstatusiscancelled, anderroriscancelled, oronCancel's message when it threw, with the log lineonCancel failed: <message>.stepslists the cleanup's steps after the run's, without the refused step. A step withsignaloutside a cancel gets a signal that never aborts. - An
Errorinasks,calls,starts,execs,activitiesordecisions(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 throwsinvalid decisionsbefore 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 throwsinvalid searchbefore the run, and the run starts with the tags its payload gives the search keys.step.tagtags 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 throwsinvalid key.step.snapshotkeeps 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.startandstep.callstart nothing: the result'sstartedlists the runs they would start, with their payloads.step.eventUrlreturns a URL onhooks.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 }.statusiscompleted,failed, orcancelledwithcancel, anderroris what the workflow threw.stepslists each step with itsattemptsand what it returned or why it failed.logshas each line as the run's logs show it:log.infowrites levellog.tagsholds the run's tags when it ended, by name.statuseslists whatstep.statuspublished, in order.snapshotslists whatstep.snapshotkept, in order, each{ device, stage, text, bytes }withtextredacted.
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.
# 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
cancelledbefore its next step. A started run whose workflow hasonCancelruns it first, and the answer says"cleanup": true. Until the run ends, the answer and the run's page saycancelling. 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.terminatingmeans 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/runsandGET /v1/runs/:idshowstop_requested(cancelorterminate),stop_requested_atandstop_requested_by, an email or API key id. They stay after the run ends. The audit log recordsrun_cancelandrun_terminate.GET /v1/runs?status=cancelledand?status=terminatedlist 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 answers202withcancellingagain. - 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]andshiftlabs 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.
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();
}
});
},
);
import asyncio
import json
from workers import fetch
from shiftlabs import workflow
SERVERS = "https://api.example.com/servers"
async def delete_server(ctx):
created = [s for s in ctx.steps if s["name"] == "create server"]
if not created:
return
server_id = created[0]["output"]["id"]
async def delete():
r = await fetch(f"{SERVERS}/{server_id}", method="DELETE")
if not r.ok and r.status != 404:
raise Exception(f"delete failed: {r.status}")
await ctx.step.run("delete server", delete)
@workflow(on_cancel=delete_server)
async def provision(ctx):
async def create():
r = await fetch(SERVERS, method="POST", body=json.dumps({"name": ctx.payload["name"]}))
return await r.json()
# signal aborts soon after a cancel, so the poll stops instead of running out its timeout.
async def wait_until_ready(server_id, signal):
while not signal.aborted:
r = await fetch(f"{SERVERS}/{server_id}")
if (await r.json())["ready"]:
return
await asyncio.sleep(10)
raise Exception("cancelled")
server = await ctx.step.run("create server", create)
await ctx.step.run("wait until ready", wait_until_ready, server["id"], signal=True)
onCancelA function of the run's context and
steps. It can be async, and what it returns is dropped. Itsstepis 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), andfngets a context withctx.steps.stepsThe
step.runcalls 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".signalstep.run(name, { signal: true, ...config }, fn)givesfn{ signal }, anAbortSignalthat 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 tofetchor check it, to stop a long step early. If the step then throws, it fails withcancelled, without retries; if it returns, its result is kept. In Python,step.run(name, fn, *args, signal=True)callsfn(*args, signal=signal), withsignal.aborted,signal.reason("cancelled"or"terminated") andawait signal.wait().- On the run
The cancel answers
"cleanup": trueandcancellingwhile the cleanup runs.GET /v1/runs/:idandGET /v1/runsshow when it began ascleanup_at,nullwhen none ran. The run's page shows it as Cleanup, and its timeline hascleanup, with what ran (onCancel,undoorundo, onCancel), andcleanup failedwith the error.
# 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
onCancelor the cancel asks forundo. A run that hasn't started endscancelledat 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
cancelledwithout 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
cancellinguntil its cleanup ends, then endscancelled. onCancelruns once per run. If it throws, the run still endscancelled, its logs getonCancel failed: <message>at level error, and its timelinecleanup 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.
undoneeds a version deployed since cleanup on cancel shipped, in November 2026. A run of an older version gets409 {"error": "this run's version can't undo on cancel: deploy the workflow again"}, and nothing is cancelled. An older version has noonCanceleither: deploy it again for that too.- Cancel many runs runs each run's
onCancel, without undos:undois only for one run's cancel. A run started with step.call, cancelled with the run that called it, runs its ownonCancel, 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.
# 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 gets409 {"error": "run already ended", "status"}. - Who and when
GET /v1/runsandGET /v1/runs/:idshow the run aspaused, withpaused_atandpaused_by, an email or API key id, andGET /v1/runs?status=pausedlists paused runs. Developers can pause and unpause, and the audit log recordsrun_pauseandrun_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>andshiftlabs runs unpause <run-id>, and MCPpause_runandunpause_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.
# 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
retriesset, forstep.run,step.execandstep.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 forstep.run. So does astep.runwhose name is over 180 characters, and an undo's retries. A run that isn't waiting to retry a step Retry now can end gets409. - When
GET /v1/runs/:idshowsretrying_until, when the next attempt would start without Retry now. - Steps
Each
step.runattempt 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_retrywith the waits it ended. While a run waits to retry a step, its page has Retry now. The CLI hasshiftlabs runs retry <run-id>, and MCPretry_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.
# 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
rerunandrerun_ofset 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.versionHashin the answer, and on the new run, is the version it uses. - Payload
The run's own, or
payloadin 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 gets400 {"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 hasshiftlabs runs rerun <run-id> [--current] [--payload <json>], and MCP'sreruntakesversionandpayload. 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.
# 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 originresumeandrerun_ofset 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, aMapor bytes, can be resumed from but not past. A step the run never reached gets400.GET /v1/runs/:id/resumelists 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 gets400. - Undone runs
A failed run whose undo functions ran gets
409and 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/:idshowsresume, the step a resume starts at unless you name one, anduntil. 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, get409: 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 hasshiftlabs runs resume <run-id> [--step <name>] [--occurrence <n>] [--current], and MCPresume_runwithid,step,occurrenceandversion.
Pause a workflow
Pause a workflow to hold its new runs, for example while you fix a bug. Runs already started keep going.
# 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.startandstep.callall hold the same way. A held run is listedqueuedwithqueued_reason: "paused", and the start answers202with"held": true. - Resume
Resuming starts the held runs in the order they arrived, and
resumedcounts 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 runscancelledinstead, anddroppedcounts 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/workflowsshowspaused_at,paused_by(an email or API key id) andheld_runs. Developers can pause and resume, and the audit log recordsworkflow_pauseandworkflow_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>andshiftlabs 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.
# 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,tagsandlimit, from 1 to 1,000, the default.sinceanduntilare milliseconds or ISO 8601 times, compared with when the run was queued:sinceincluded,untilnot.tagsis 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, gets400. A key scoped to some workflows reaches only their runs. - Cancel
POST /v1/runs/cancelcancels 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'sonCancel.statusisqueued,running,sleeping,waitingorpaused.cancelledcounts the runs that hadn't started, which end at once.cancellingcounts the runs in flight, which end within seconds, or once their running step and cleanup finish. Whenmoreistrue, more runs match: send the same request again. - Re-run
POST /v1/runs/rerunre-runs the matching runs, newest first, asPOST /v1/runs/:id/rerundoes, with the originrerun: 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 inmismatched.statustakes any status.skippedcounts runs that can't be re-run, because their payload is older than 14 days or their workflow was deleted.runIdslists the new runs. - Preview
With
"preview": truethe 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, andmore, when more runs match pastlimit. Payloads aren't checked against the schema until the re-run. - Waiting their turn
A re-run batch never gets
429for 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, orruns pausedacross the platform. Thenstoppedis{"reason", "retryAt"}. To go on, send the request again withbeforeset tonextBefore, which is also set when more runs match. Past the spending limit or while a payment is failing, the request gets429and re-runs nothing. - Who and dashboard
Cancel needs
run.canceland re-runrun.start, which developers hold. The audit log recordsruns_cancelandruns_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.
| Route | Method | Minimum 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 shipped | POST | developer |
/v1/runs/:id/terminate 202 {runId, status}: terminated, or terminating while Workflows hasn't answered; 409 once the run has ended | POST | admin |
/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 cancelled | POST | developer |
/v1/runs/:id/unpause 202 {runId, status, pausedAt, pausedBy}; 409 when the run isn't paused | POST | developer |
/v1/runs/:id/retry 202 {runId, retried}; 409 when the run isn't waiting to retry a command | POST | developer |
/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 ran | POST | developer |
/v1/runs/:id/resume {points: [{step, occurrence, kind, outcome}], more, until}: the steps a resume can start from | GET | viewer |
/v1/runs/cancel {"workflow"?, "status"?, "origin"?, "since"?, "until"?, "tags"?, "limit"?}; {matched, cancelled, cancelling, more} | POST | developer |
/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 gone | POST | developer |
/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} | POST | developer |
/v1/workflows/:workflow/pause {workflow, paused, pausedAt, pausedBy, heldRuns} | POST | developer |
/v1/workflows/:workflow/resume {"drop"?}; {workflow, paused, resumed, dropped} | POST | developer |
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.
| Route | Method | Minimum 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 paused | GET | viewer |
/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 default | PUT | developer |
/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 nothing | POST | developer |
/v1/workflows/:workflow {deleted, revokedTriggers, droppedVars, unlinkedConnections, purgeAt}; moves it to the trash for 7 days; runs stay | DELETE | developer |
/v1/workflows/:workflow/versions newest first: [{rev, hash, deployed_at, deployed_by, runtime, current}] | GET | viewer |
/v1/workflows/:workflow/versions/:hash/source {hash, language, source}, with entry and files for a workflow of several files; audited | GET | developer |
/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-Key | POST | developer |
/v1/workflows/:workflow/rollback {"hash"}; new runs use that version: {workflow, current} | POST | developer |
/v1/deploys deploys that waited on packages; ?status=building|live|failed; newest first, 50 a page; ?limit= (up to 100) and ?before= from Next-Before | GET | viewer |
/v1/deploys/:id {id, workflow, status, packages, created_at, finished_at, result} | GET | viewer |