shiftlabs Start free
Menu Python SDK

Python SDK reference

The shiftlabs module is what a Python workflow imports. Every deploy includes it, and the shiftlabs package on PyPI gives your editor its type hints and adds the testing kit. This page is generated from its Python source.

Duration

Milliseconds, or a string such as "30 seconds" with units from second to year, singular or plural.

pythontype alias
Duration: TypeAlias = int | float | str

FatalError

Raised in a step, fails the step and the run at once, with no more attempts. Raised outside a step, it fails the run as any error does.

pythonclass
class FatalError(Exception): ...

ContinuedAsNew

Raised by step.continue_as_new, and by a wait given continue_with where the run continues as new: the run ends completed, with no output, and its key's next run, run_id, starts with the state. Let it through: a step called after it raises again.

pythonclass
class ContinuedAsNew(BaseException):
    run_id: str

Retries

step.run(..., retries=...), step.exec(...) and step.activity(...): how many times to retry a failing step (a FatalError in step.run never is), the duration between attempts, and the backoff (exponential by default). Each step.run attempt counts as a step, its delay is a second at least, and Retry now ends the wait before the next.

pythonclass
class Retries(TypedDict):
    limit: int
    delay: Duration
    backoff: NotRequired[Literal["constant", "linear", "exponential"]]

PayloadSchema

@workflow(payload=...): a pydantic model or a JSON Schema dict.

pythontype alias
PayloadSchema: TypeAlias = type[_PayloadModel] | dict[str, Any]

Concurrency

@workflow(concurrency=...): at most limit runs of the workflow at once, from 1 to the workspace's concurrent runs. With key, a dotted path into the payload such as "customer.id", runs whose payloads hold the same value there share the limit, and a run without the field uses the key "". Runs past the limit wait in arrival order with the status queued, and start as runs with the same key end.

pythonclass
class Concurrency(TypedDict):
    limit: int
    key: NotRequired[str]

DecisionModel

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

pythontype alias
DecisionModel: TypeAlias = Literal[
    "@cf/cloudflare/clef",
    "@cf/cloudflare/clef-flash",
]

DecisionDefinition

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

pythonclass
class DecisionDefinition:
    version: int
    model: DecisionModel
    question: str | None
    choices: Sequence[str] | Mapping[str, str] | None
    yes_no: str | None
    score: Sequence[str] | None
    threshold: float | None
    state: Callable[
        [Any],
        Mapping[str, object] | Awaitable[Mapping[str, object]],
    ]

decision

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

question goes with choices, 2 to 255 options or a dict of options and what each means, or with score, 2 to 10 levels from the lowest; yes_no alone is a question answered "yes" or "no". state builds a dict of data fields from step.decide's input, the same fields every time and None for one you don't have: the deploy reads their names by calling it with a stand-in input. The most probable option is the answer when its probability is at least threshold, from 0 to 1. Give a new version, a whole number from 1, to change the question, the options or the state's fields; the model and the threshold can change under the same one.

pythonfunction
@overload
def decision(
    *,
    version: int,
    model: DecisionModel,
    question: str,
    choices: Sequence[str] | Mapping[str, str],
    state: Callable[
        [Any],
        Mapping[str, object] | Awaitable[Mapping[str, object]],
    ],
    threshold: float | None = None,
) -> DecisionDefinition: ...
@overload
def decision(
    *,
    version: int,
    model: DecisionModel,
    question: str,
    score: Sequence[str],
    state: Callable[
        [Any],
        Mapping[str, object] | Awaitable[Mapping[str, object]],
    ],
    threshold: float | None = None,
) -> DecisionDefinition: ...
@overload
def decision(
    *,
    version: int,
    model: DecisionModel,
    yes_no: str,
    state: Callable[
        [Any],
        Mapping[str, object] | Awaitable[Mapping[str, object]],
    ],
    threshold: float | None = None,
) -> DecisionDefinition: ...

WorkflowDefinition

What @workflow returns. A workflow module defines exactly one; shiftlabs.testing.run_workflow takes it.

pythonclass
class WorkflowDefinition:
    fn: Callable[[Context], Awaitable[Any]]
    payload: PayloadSchema | None
    concurrency: Concurrency | None
    search: Mapping[str, str] | None
    decisions: Mapping[str, DecisionDefinition] | None
    on_cancel: Callable[[CancelContext], object] | None
    key: str | None

workflow

Marks the module's entry: @workflow async def refund_check(ctx): …. @workflow(payload=Invoice) takes the payload's schema, a pydantic model or a JSON Schema dict: webhooks and API runs whose payload fails it get 400. @workflow(concurrency={"limit": 1, "key": "customer_id"}) caps the runs at once; runs past it wait. @workflow(search={"customer": "customer.id"}) tags each run from its payload as it arrives: up to 10 tag names, each to a dotted path into the payload. @workflow(decisions={"kind": kind}) names the decisions step.decide uses, read at deploy; each one's versions are kept under its name. @workflow(on_cancel=release) cleans up when a started run is cancelled: once the step that was running ends, the next one raises "cancelled" instead of starting, and release(ctx) runs with a CancelContext, its steps counted as any step, before the run ends cancelled. @workflow(key="customer.id") makes the value there, a string of 1 to 128 bytes or an integer, the run's key: a key has one open run, and a start while it has one starts nothing and answers that run. Read at deploy.

pythonfunction
@overload
def workflow(
    fn: Callable[[Context], Awaitable[Any]],
    /,
) -> WorkflowDefinition: ...
@overload
def workflow(
    *,
    payload: PayloadSchema | None = None,
    concurrency: Concurrency | None = None,
    search: Mapping[str, str] | None = None,
    decisions: Mapping[str, DecisionDefinition] | None = None,
    on_cancel: Callable[[CancelContext], object] | None = None,
    key: str | None = None,
) -> Callable[[Callable[[Context], Awaitable[Any]]], WorkflowDefinition]: ...

ApprovalDecision

What step.wait_for_approval returns. by: the approver's email or API key id, None when nobody answered in time; note: what the approver wrote.

pythonclass
class ApprovalDecision(TypedDict):
    approved: bool
    by: str | None
    note: str | None

ApprovalPolicy

step.wait_for_approval's policy: which of your rules asks (name, 1 to 100 characters) and how risky the change is (risk). Approvers see both.

pythonclass
class ApprovalPolicy(TypedDict, total=False):
    name: str
    risk: Literal["low", "medium", "high"]

ApprovalOptions

An undo's approval: step.wait_for_approval's keyword arguments, for the approval named undo <name>.

pythonclass
class ApprovalOptions(TypedDict, total=False):
    message: str | None
    timeout: Duration | None
    approvers: list[str] | None
    approvals: int | None
    policy: ApprovalPolicy | None

UndoContext

What an undo function gets: output, a copy of what its step returned, and error, what the run failed with.

pythonclass
class UndoContext(TypedDict, Generic[T]):
    output: T
    error: Exception

UndoOptions

step.run(..., undo=...) with retries, a timeout or an approval of its own: run is the undo function, and retries and timeout default as a step's. With approval the run first waits for an approval named undo <name>; denied or unanswered, this undo is skipped and the next one goes on.

pythonclass
class UndoOptions(TypedDict, Generic[T]):
    run: Callable[[UndoContext[T]], object]
    retries: NotRequired[Retries]
    timeout: NotRequired[Duration]
    approval: NotRequired[ApprovalOptions]

Winner

What step.wait_for_any returns: the name of the wait that finished first, and what it returns on its own: an event's data, or None once its timeout passed; an approval's decision; None for a sleep.

pythonclass
class Winner(TypedDict):
    name: str
    value: Any

SecretRef

{"secret": NAME} in step.exec's env or files, or anywhere in step.activity's input: a secret marked readable, whose value the runner gets for that call only.

pythonclass
class SecretRef(TypedDict):
    secret: str

ExecResult

What step.exec returns, and ExecError's result: the exit code (124 when the command timed out), the last 256 KiB of stdout and stderr with secret values replaced by "[redacted]", each stream's whole size in bytes, truncated when stdout or stderr holds only the end of its stream, timed_out, how long it ran in milliseconds, the name of the runner that ran it, and which try this was, 1 for the first.

pythonclass
class ExecResult(TypedDict):
    exit_code: int
    stdout: str
    stderr: str
    stdout_bytes: int
    stderr_bytes: int
    truncated: bool
    timed_out: bool
    duration_ms: int
    runner: str
    attempt: int

ExecError

Raised by step.exec when the command exits with a code outside ok_exit_codes, or times out. result holds its exit code and output.

pythonclass
class ExecError(Exception):
    result: ExecResult

ActivityResult

ActivityError's result: how the attempt that failed ran. The activity's name and its version in the activities file of the runner that ran it ("" for none), the exit code (124 when the runner stopped it), the program's standard output, the output's JSON text, up to 256 KiB, and the last 16 KiB of its standard error, both with secret values replaced by "[redacted]", each stream's whole size in bytes, truncated when one holds only the end of its stream, timed_out, heartbeat_timed_out when no heartbeat came within heartbeat, how long it ran in milliseconds, the name of the runner that ran it, and which try this was, 1 for the first.

pythonclass
class ActivityResult(TypedDict):
    activity: str
    version: str
    exit_code: int
    stdout: str
    stderr: str
    stdout_bytes: int
    stderr_bytes: int
    truncated: bool
    timed_out: bool
    heartbeat_timed_out: bool
    duration_ms: int
    runner: str
    attempt: int

ActivityError

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

pythonclass
class ActivityError(Exception):
    result: ActivityResult

DecisionResult

What step.decide returns: answer, the most probable option, or None when its probability is under the threshold; top, the most probable option whatever the threshold; every option's probability, from 0 to 1; a score decision's probability-weighted level, from 0 for the lowest, None for the others; the decision's version, the model that answered, and the threshold it was held to, None for none.

pythonclass
class DecisionResult(TypedDict):
    answer: str | None
    top: str
    probabilities: dict[str, float]
    score: float | None
    version: int
    model: DecisionModel
    threshold: float | None

CancelSignal

What a step.run(..., signal=True) function gets as signal: it aborts when the run is asked to cancel or terminate while the step runs, within about 5 seconds, or a minute once the step has run 5 minutes. The function may stop early: if it then raises, the step fails as cancelled, with no retries; if it returns, its result is kept.

  • aborted: bool

    True once the run was asked to cancel or terminate.

  • reason: Literal["cancelled", "terminated"] | None

    Why it aborted: "cancelled" or "terminated", None until it does.

  • async def wait() -> None

    Returns once the signal aborts, at once if it has. Outside a cancel or terminate it never returns, so race it with the step's work, as asyncio.wait(..., return_when=asyncio.FIRST_COMPLETED) does.

SignalFunction

The function step.run(..., signal=True) takes: it gets the step's arguments and signal, a CancelSignal, as a keyword-only argument, as in async def export(job_id: str, *, signal: CancelSignal) -> str.

pythonclass
class SignalFunction(Protocol[*Ts, T_co]): ...

Step

Code outside step.run() runs again every time the run resumes (after a sleep or a retry); only step results are durable, so side effects belong inside steps.

  • async def run(name: str, fn: Callable[[*Ts], Awaitable[T]], *args: *Ts, retries: Retries | None = None, timeout: Duration | None = None, undo: Callable[[UndoContext[T]], object] | UndoOptions[T] | None = None, signal: Literal[False] = False) -> T

    async def run(name: str, fn: Callable[[*Ts], T], *args: *Ts, retries: Retries | None = None, timeout: Duration | None = None, undo: Callable[[UndoContext[T]], object] | UndoOptions[T] | None = None, signal: Literal[False] = False) -> T

    async def run(name: str, fn: SignalFunction[*Ts, Awaitable[T]], *args: *Ts, retries: Retries | None = None, timeout: Duration | None = None, undo: Callable[[UndoContext[T]], object] | UndoOptions[T] | None = None, signal: Literal[True]) -> T

    async def run(name: str, fn: SignalFunction[*Ts, T], *args: *Ts, retries: Retries | None = None, timeout: Duration | None = None, undo: Callable[[UndoContext[T]], object] | UndoOptions[T] | None = None, signal: Literal[True]) -> T

    Runs fn(*args) once and stores its JSON-serializable result; a resumed run gets the stored result. If the workflow's function raises later, undo (a function of an UndoContext, or UndoOptions) undoes the step in a step named undo <name>, newest first among the completed steps with an undo. With signal=True, fn is called as fn(*args, signal=signal) with a CancelSignal that aborts when the run is asked to cancel or terminate while the step runs.

  • async def sleep(name: str, duration: Duration) -> None

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

  • async def sleep_until(name: str, until: datetime.datetime | int | float) -> None

    Durable sleep until a datetime or epoch seconds.

  • async def ask(name: str, *, agent: str, message: str, schema: None = None) -> str

    async def ask(name: str, *, agent: str, message: str, schema: dict[str, Any]) -> Any

    Asks agent and returns its final answer: the text, or with schema (a JSON Schema dict) the JSON that matches it. A run has one conversation per step, which the workflow owns; a resumed run gets the stored answer. An answer that doesn't match gets one more turn; a second miss fails the step, with no retries.

  • async def decide(name: str, decision: DecisionDefinition, input: Any) -> DecisionResult

    Asks decision's model its question about the fields decision.state(input) returns, and returns the answer with every option's probability; the run's detail keeps the trace. The decision must be named in @workflow(decisions={...}). A resumed run gets the stored answer, and state runs again, as code outside a step does.

  • async def start(name: str, *, workflow: str, payload: object = None) -> str

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

  • async def call(name: str, *, workflow: str, payload: object = None) -> Any

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

  • async def exec(name: str, *, run: str | None = None, command: list[str] | None = None, env: Mapping[str, str | SecretRef] | None = None, files: Mapping[str, str | SecretRef] | None = None, stdin: str | None = None, timeout: Duration | None = None, runner: str | None = None, profile: str | None = None, requires: list[str] | None = None, ok_exit_codes: list[int] | Literal["any"] | None = None, retries: Retries | None = None) -> ExecResult

    Runs a command on a runner in your own network and returns its result: run, a bash script, or command, a program and its arguments. env and files (by relative path) take text, or {"secret": NAME} for a secret marked readable, and stdin goes to the command's standard input. timeout defaults to "10 minutes", runner to the pool "default" and ok_exit_codes to [0] ("any" accepts every exit code); retries tries again after a failure. profile names the runner image profile the command needs, as "network", or "network@2026.11.1" for that image version only, and requires the tools the image must list, as ["helm"]: only a runner whose image manifest lists them takes the command; without profile, the project's runnerProfile in shiftlabs.config.ts applies, if it names one. Another exit code raises ExecError with the result, and a command no runner ran or finished raises an error that says why. A resumed run gets the stored result.

  • async def activity(label: str, /, *, name: str, input: object = {}, runner: str | None = None, profile: str | None = None, requires: list[str] | None = None, timeout: Duration | None = None, heartbeat: Duration | None = None, retries: Retries | None = None) -> Any

    Runs a registered activity on a runner in your own network and returns its output: the program the runner's activities file names for name reads input (any JSON, {} by default; None is null) on its standard input, and the JSON it writes is the output. {"secret": NAME} anywhere in input stands for a readable secret's value. runner defaults to the pool "default", timeout to "10 minutes" and heartbeat, how long the program may go without writing a heartbeat line to file descriptor 3, to none; retries tries again after a failure. profile and requires pick the runner image as step.exec's do. A failed activity raises ActivityError with the result, and one no runner ran or finished raises an error that says why. A resumed run gets the stored output.

  • async def wait_for_event(name: str, *, timeout: Duration | None = None, continue_with: object = None) -> Any

    Waits for the event name (sent to event_url(name) or POST /v1/runs/:id/events/:name) and returns its data, the parsed JSON body or the text, or None once timeout (default "24 hours") passes. An event sent before the run waits is kept. Waiting counts against the run's lifetime, not its steps. In a keyed workflow, continue_with is the state (JSON, not None) to continue as new with if the run must continue here: at half a per-run budget, or 2 hours before its lifetime ends, the wait raises ContinuedAsNew instead, and the key's next run gets the state as its payload.

  • async def continue_as_new(state: object) -> NoReturn

    In a keyed workflow, ends this run (completed, no output) and starts its key's next run on the workflow's current version, with state (JSON) as its payload and ctx.continued_from this run; events sent to the key meanwhile reach it. Raises ContinuedAsNew, a BaseException: let it through, as a step called after it raises.

  • def event_url(name: str) -> str

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

  • def idempotency_key(name: str) -> str

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

  • async def tag(tags: Mapping[str, str]) -> None

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

  • async def status(value: Mapping[str, Any] | None = None, /, **fields: Any) -> None

    Publishes a JSON object of 16 KiB at most, value with fields over it, as the run's status (GET /v1/runs/:id/status): await step.status(phase="sending", done=3, total=8). Not a step: returns at once, and a resumed run's calls outside steps don't publish again. Anything else raises TypeError.

  • async def snapshot(device: str, text: str, *, stage: str | None = None) -> None

    Keeps text, a device's configuration, as a snapshot of the run (GET /v1/runs/:id/snapshots), labelled with an optional stage such as "before": await step.snapshot("core-sw-1", config, stage="before"). Not a step: unbilled, only outside step.run(), and a resumed run keeps nothing again. The runner redacts the workspace's readable secrets and the credentials a config holds, such as SNMP communities, password hashes and keys, before it keeps the text. device takes 1 to 255 characters, stage 1 to 64 and the text at most 256 KiB after redaction, or this raises TypeError; a run keeps at most 1,000 snapshots.

  • async def wait_for_approval(name: str, *, message: str | None = None, timeout: Duration | None = None, approvers: list[str] | None = None, approvals: int | None = None, policy: ApprovalPolicy | None = None) -> ApprovalDecision

    Puts a request in the workspace's Approvals inbox, notifies its approvers, and waits for one to approve or deny. Unanswered by timeout (default "72 hours") it counts as denied. Waiting counts against the run's lifetime, not its steps. Names can't end like refund #2. approvers: up to 20 of "role:admin", "role:approver", "role:manager" or member emails; only they see and answer it. Default: every admin and approver. approvals: how many approvers must approve, 1 to 5 (default 1). The workspace's setting in Settings → Approvals is the least a request needs; asking for fewer has no effect. Under 2 or more, each approval comes from a different member; an API key can't approve. policy: {"name": ..., "risk": "low" | "medium" | "high"}, which approvers see.

  • async def wait_for_any(name: str, waits: Sequence[Awaitable[Any]], *, continue_with: object = None) -> Winner

    Waits for whichever of waits finishes first and returns its name and value: 1 to 10 calls of this step's wait_for_event, wait_for_approval and sleep, not awaited, with different names. The rest stop, a pending approval is withdrawn, and a resumed run gets the same winner. Names can't end like ack #2. A wait given here is used up: awaiting it raises RuntimeError("cannot reuse already awaited coroutine"). continue_with: as wait_for_event's, for the race.

Secrets

ctx.secrets.NAME: a stand-in for each secret with hosts, which the gateway swaps for the value on requests to those hosts. An unknown name raises KeyError.

pythonclass
class Secrets: ...

Vars

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

pythonclass
class Vars: ...

Log

ctx.log.info(message, fields), and debug, warn, error: one log line each, fields as JSON after the message.

  • def debug(message: object, fields: Mapping[str, object] | None = None) -> None

    A line at level debug.

  • def info(message: object, fields: Mapping[str, object] | None = None) -> None

    A line at level log.

  • def warn(message: object, fields: Mapping[str, object] | None = None) -> None

    A line at level warn.

  • def error(message: object, fields: Mapping[str, object] | None = None) -> None

    A line at level error.

State

ctx.state: JSON values kept per workflow, shared by all its runs and versions; the last write wins. Every method works only inside step.run() and raises outside one. A key is 1 to 512 bytes. Writes past the plan's limits (keys per workflow, value size, total) raise.

  • async def get(key: str) -> Any

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

  • async def set(key: str, value: Any) -> None

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

  • async def delete(key: str) -> None

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

  • async def list(prefix: str | None = None, after: str | None = None, limit: int | None = None) -> list[str]

    The workflow's keys in order: those starting with prefix, after after, at most limit (1 to 1,000).

Context

The run context, the one argument of the @workflow function.

  • payload: Any

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

  • run_id: str

    This run's id.

  • key: str | None

    A keyed workflow's run's key (@workflow(key=...)), None for any other run.

  • continued_from: str | None

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

  • step: Step

    Durable steps and sleeps.

  • vars: Vars

    vars.NAME: the workspace value, overridden per workflow.

  • secrets: Secrets

    secrets.NAME: a stand-in for each secret with hosts.

  • reveal: Callable[[str], str]

    reveal(name): the value of a secret marked readable. Every load is audited and the value is scrubbed from logs.

  • sign: Callable[[str, str, Literal["hex", "base64"]], Awaitable[str]]

    await sign(name, data, encoding="hex"): HMAC-SHA256 of data with a secret marked hmac. Returns only the signature.

  • log: Log

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

  • state: State

    await state.get(key), set, delete, list: JSON values kept per workflow across runs, only inside step.run().

CompletedStep

One of CancelContext's steps: a step.run call that completed before the run was cancelled, by name, and output, a copy of what it returned.

pythonclass
class CompletedStep(TypedDict):
    name: str
    output: Any

CancelContext

What @workflow(on_cancel=...)'s function gets when a started run is cancelled: the run's context, whose step runs steps that count as any step does, and steps.

  • steps: list[CompletedStep]

    The step.run calls outside another step's function that completed before the cancel, in the order the run called them.

Testing kit

shiftlabs.testing runs a workflow inside your test, the way the platform runs it, with no deploy. Only the PyPI package has it: deploys never include it. See Test a workflow.

StepType

The step method a RunStep was, or "undo": a step.run's undo, which runs once the workflow raised. A wait that continued the run as new (continue_at) shows as the continue_as_new it became.

pythontype alias
StepType: TypeAlias = Literal[
    "run",
    "sleep",
    "sleep_until",
    "wait_for_event",
    "wait_for_approval",
    "wait_for_any",
    "ask",
    "start",
    "call",
    "exec",
    "activity",
    "decide",
    "undo",
    "continue_as_new",
]

ApprovalAnswer

An answer in approvals given as a dict. by defaults to "test" and note to None.

pythonclass
class ApprovalAnswer(TypedDict):
    approved: bool
    by: NotRequired[str | None]
    note: NotRequired[str | None]

SecretValue

A secret in secrets with the flags PUT /v1/secrets/:NAME takes. Both are False unless given, as there: readable lets reveal(NAME) return the value, and hmac lets sign(NAME, …) sign with it.

pythonclass
class SecretValue(TypedDict):
    value: str
    readable: NotRequired[bool]
    hmac: NotRequired[bool]

ExecAnswer

A command's outcome in execs. stdout and stderr default to "". A command the runner stopped at its timeout exits with 124, so with timed_out True exit_code is 124 or left out.

pythonclass
class ExecAnswer(TypedDict):
    exit_code: NotRequired[int]
    stdout: NotRequired[str]
    stderr: NotRequired[str]
    timed_out: NotRequired[bool]

ExecRequest

What a function in execs gets: the step's name and its options as the platform checked them, with their defaults, None for run, command or profile, each of requires once, and timeout and the retries' delay in milliseconds.

pythonclass
class ExecRequest(TypedDict):
    name: str
    run: str | None
    command: list[str] | None
    env: dict[str, str | shiftlabs.SecretRef]
    files: dict[str, str | shiftlabs.SecretRef]
    stdin: str | None
    timeout: int
    runner: str
    profile: str | None
    requires: list[str]
    ok_exit_codes: list[int] | Literal["any"]
    retries: shiftlabs.Retries | None

ActivityAnswer

An activity's outcome in activities. output is the JSON its program writes, None when left out, and exit_code defaults to 0. A program the runner stopped exits with 124: with timed_out or heartbeat_timed_out True, exit_code is 124 or left out.

pythonclass
class ActivityAnswer(TypedDict):
    output: NotRequired[Any]
    exit_code: NotRequired[int]
    stderr: NotRequired[str]
    timed_out: NotRequired[bool]
    heartbeat_timed_out: NotRequired[bool]

ActivityRequest

What a function in activities gets: the step's name and its options as the platform checked them, with their defaults and secret references as given, and timeout, heartbeat and the retries' delay in milliseconds.

pythonclass
class ActivityRequest(TypedDict):
    step: str
    name: str
    input: Any
    runner: str
    profile: str | None
    requires: list[str]
    timeout: int
    heartbeat: int | None
    retries: shiftlabs.Retries | None

Cancel

run_workflow(cancel=...): cancels the run at the step named before or during, one of the two, and with undo True also undoes its completed steps, as POST /v1/runs/:id/cancel with {"undo": true} does.

pythonclass
class Cancel(TypedDict, total=False):
    before: str
    during: str
    undo: bool

RunStep

One step the run took. attempts: the attempts step.run, step.exec, step.activity or an undo made, 1 when the first succeeded, and 1 for every other step. output: what it returned: a result, the event's data, the decision, the answer, a run id. error: why it failed, if it did. An undo has its step.run's name, and its approval waits as "undo ".

pythonclass
@dataclasses.dataclass(frozen=True)
class RunStep:
    type: StepType
    name: str
    attempts: int = 1
    output: Any = None
    error: str | None = None

LogLine

A log line, as the run's logs show it: info writes level "log".

pythonclass
@dataclasses.dataclass(frozen=True)
class LogLine:
    level: Literal["debug", "log", "warn", "error"]
    message: str

StartedRun

A run that step.start or step.call started. name: the step's name.

pythonclass
@dataclasses.dataclass(frozen=True)
class StartedRun:
    name: str
    workflow: str
    payload: Any
    run_id: str

Snapshot

A snapshot step.snapshot kept: stage None when none was given, text redacted as the platform keeps it, and bytes its UTF-8 length.

pythonclass
class Snapshot(TypedDict):
    device: str
    stage: str | None
    text: str
    bytes: int

RunResult

What run_workflow returns: output when the workflow returned, error when it raised. steps: every step, in the order the workflow called them. state: the workflow's state when the run ended. tags: the run's tags when it ended, by name: its search keys' values from the payload, then what step.tag set. statuses: every value step.status published, in order, as JSON reads it back; the replay publishes none, as on the platform. snapshots: every snapshot step.snapshot kept, in order, redacted: first the readable secrets' values of 8 bytes or more, then the credentials packages/core's CONFIG_CREDENTIALS names; the replay keeps none. A run cancel reached ends "cancelled", with the error "cancelled", or on_cancel's when it raised. A run that continued as new ends "continued", with no output, and continued_with the state its key's next run gets.

pythonclass
@dataclasses.dataclass(frozen=True)
class RunResult:
    status: Literal["completed", "failed", "cancelled", "continued"]
    output: Any
    error: Exception | None
    steps: list[RunStep]
    logs: list[LogLine]
    state: dict[str, Any]
    started: list[StartedRun]
    tags: dict[str, str]
    statuses: list[Any] = dataclasses.field(default_factory=list[Any])
    snapshots: list[
        Snapshot,
    ] = dataclasses.field(default_factory=list[Snapshot])
    continued_with: Any = None

run_workflow

Runs the @workflow function in this process as the platform runs it, in an event loop of its own, and returns what it did. Steps run inline: retries happen at once, FatalError fails a step with no more attempts, and sleeps return at once. Waits are answered by step name: events gives a wait's data (none returns None, as a timeout does), approvals True, False or {"approved", "by", "note"} (none is denied), asks the agent's answer and calls the other run's result (none fails the step), starts a run id. An exception in asks, calls, starts or decisions fails that step with its message. execs gives each step.exec's outcome, {"exit_code", "stdout", "stderr", "timed_out"}, or a function of the ExecRequest and the attempt that returns one; an exception fails the attempt as a command no runner ran does, retries apply, and a step with none fails. activities does the same for step.activity, with {"output", "exit_code", "stderr", "timed_out", "heartbeat_timed_out"} and an ActivityRequest. decisions gives each step.decide's answer, the option the model picks or a dict of each option's probability, held to the decision's threshold; a step with none fails. @workflow(decisions=...) is read as a deploy reads it, so a decision the deploy would refuse raises TypeError "invalid decisions: …" before the run. secrets gives each secret's value, or {"value", "readable", "hmac"}: ctx.secrets.NAME reads a stand-in shaped like the platform's, reveal needs a readable secret and sign an hmac one. payload ({} when None) must pass the workflow's payload schema, and hold a keyed workflow's key, or this raises ValueError. @workflow(search=…) is read as the deploy reads it, so an invalid one raises TypeError "invalid search: …", and the run starts with the tags its payload gives the search keys. ctx.step.tag tags it as the platform does, with its messages: TypeError for tags the runner refuses, RuntimeError inside a step's function or past a run's 20 tags. ctx.step.snapshot keeps snapshots the same way: TypeError for what the runner refuses, past 256 KiB after redaction included, and RuntimeError inside a step's function or past a run's 1,000 snapshots. Then the workflow runs again on its stored step results, as a resumed run does, and this raises AssertionError "code outside a step changed on replay" if it calls other steps; replay=False skips that. The replay's step.tag and step.snapshot calls raise as the first run's did, and tag and keep nothing. Once the workflow raises, each step.run with undo that completed is undone, newest first, in a step of type "undo", in both runs; approvals answers an undo's approval by "undo ". An undo refused or failed for good logs why and stops the older ones, and the run keeps its error.

cancel cancels the run at the first step of its own (outside another step's function) with that name: "before" refuses it with "cancelled", and "during" runs it as the cancel comes: a step.run with signal=True gets an aborted signal, and the step fails as "cancelled", with no retries, if it raises. From there each new step raises "cancelled" and a sleep returns at once. Once the workflow returns or raises, the undos run if undo, with the error "cancelled", then on_cancel with the step.run calls that completed; one that raises is logged as "onCancel failed: ". Outside a cancel, a signal never aborts.

In a keyed workflow, continue_at n continues the run as new at its nth wait given continue_with (from 1, in the order the run makes them), as half a budget does on the platform, and continued_from is ctx.continued_from, to test a key's later run.

pythonfunction
def run_workflow(
    definition: shiftlabs.WorkflowDefinition,
    *,
    payload: object = None,
    secrets: Mapping[str, str | SecretValue] | None = None,
    vars: Mapping[str, str] | None = None,
    state: Mapping[str, object] | None = None,
    events: Mapping[str, object] | None = None,
    approvals: Mapping[str, bool | ApprovalAnswer] | None = None,
    asks: Mapping[str, object] | None = None,
    calls: Mapping[str, object] | None = None,
    starts: Mapping[str, str | Exception] | None = None,
    execs: Mapping[
        str,
        ExecAnswer | Exception | Callable[
            [ExecRequest, int],
            ExecAnswer | Exception | Awaitable[ExecAnswer | Exception],
        ],
    ] | None = None,
    activities: Mapping[
        str,
        ActivityAnswer | Exception | Callable[
            [ActivityRequest, int],
            ActivityAnswer | Exception | Awaitable[ActivityAnswer | Exception],
        ],
    ] | None = None,
    decisions: Mapping[
        str,
        str | Mapping[str, float] | Exception,
    ] | None = None,
    cancel: Cancel | None = None,
    replay: bool = True,
    continue_at: int | None = None,
    continued_from: str | None = None,
) -> RunResult: ...