Skip to content

Python SDK

the-open-engine-zeroshot is a typed asynchronous client for local, direct, and named hosted targets. Each platform wheel contains the corresponding zeroshot executable, which keeps the client and engine on one release line.

Install and run

Install from PyPI with Python 3.11 or newer. Pip selects the wheel for your OS and CPU:

python -m pip install the-open-engine-zeroshot

Supported platforms are Linux x64/ARM64, macOS Intel/Apple silicon, and Windows x64. Import the package as zeroshot:

import asyncio

from zeroshot import Client, UniformRuntime


async def main() -> None:
    runtime = UniformRuntime(
        harness="codex",
        provider="openai",
        model="PROVIDER_MODEL_ID",
        effort="high",
    )

    async with Client(runtime=runtime) as client:
        result = await client.run(
            "Add JSON status output and cover it with focused tests.",
            cwd="/path/to/folder",
            wait_timeout=21_600,
        )

    result.raise_for_failure()


if __name__ == "__main__":
    asyncio.run(main())

Opening a client captures the current folder; the default preset is Preset("software-change"). An omitted delivery selector uses the native template default: a PR for software-change, a comment for pr-review, code-review and issue-review. PR publication requires Git and credentials for a supported forge. Local delivery can reuse native gh or glab login. Use Preset("software-change", delivery="none") for local changes without publication. Per-run cwd= paths resolve from that captured folder, or LocalTarget.workspace when supplied. Local graphs without Git delivery accept plain folders. Push needs committed Git and a remote. run() submits once and waits; submit() returns a durable Run handle immediately.

Run input has the same submission and node-input limits as the CLI: 2 MiB for the stored submission and 1 MiB for each node's serialized start record, including its input and bookkeeping. A local early size refusal raises InvalidRequestError with code submission.too_large. A node-input overflow fails the admitted run with a size diagnostic.

Manage named targets

Client.list_targets() returns a tuple of typed NamedTarget records with name, origin and kind (hosted or direct), including the built-in platform target. It shares the local registry used by zeroshot target list and returns no login data. These operations use the user's local registry independently of the client's selected run target, and do not contact a target.

from zeroshot import Client


async def remove_old_target() -> None:
    async with Client() as client:
        for target in await client.list_targets():
            print(target.name, target.origin, target.kind)
        receipt = await client.remove_target("old-target")
        print(receipt.name, receipt.removed)

remove_target() returns TargetRemoveResult after deleting the registration, stored login and saved resume permissions. It raises InvalidRequestError for platform or an unknown name. Removal does not stop remote runs. Configure replacements with zeroshot target add and, for hosted targets, zeroshot target login.

Use a local Git worktree

Pass worktree=True to run() or submit() to create a retained Git worktree on a managed run branch, leaving the invoking checkout in place. The default is worktree=False. An omitted worktree_base, or worktree_base="local", starts at the invoking checkout's exact HEAD. Use worktree_base="remote" to fetch and start at that branch's upstream; an upstream is required:

from zeroshot import Client, UniformRuntime


async def submit_isolated(runtime: UniformRuntime) -> None:
    async with Client(runtime=runtime) as client:
        run = await client.submit(
            "Update the parser.",
            cwd="/path/to/repository",
            worktree=True,
            worktree_base="remote",
        )
        print(run.id)

Only committed files from the selected base are included. Uncommitted changes, untracked files, and installed dependencies are not copied, and Zeroshot performs no dependency setup. Worktrees remain after the run; when finished, inspect them with git worktree list and remove the chosen worktree explicitly with git worktree remove PATH.

These options apply only to local execution. Native preflight rejects worktree=True with DirectTarget or HostedTarget, a base without worktree=True, and bases other than local or remote, before target contact or controller startup.

Watch a submitted run

from zeroshot import Client, UniformRuntime


async def observe(runtime: UniformRuntime) -> None:
    async with Client(runtime=runtime) as client:
        run = await client.submit("Update the parser.")
        status = await run.status()
        async for event in run.watch(after=status.cursor):
            print(event)

A RunWaitTimeout carries the still-active run handle, and cancelling the Python task detaches in the same way. Neither action stops native work; only await run.force_stop() changes run lifetime.

status.active_executions entries expose optional started_at ledger recording times. Statuses yielded by run.watch() also expose optional recorded_at for the event producing that notification. Both use Unix milliseconds, remain None when unknown, and are not precise provider measurements. Imported history reports its import time rather than its original execution time. Use cursor for ordering and resumption, and execution to distinguish retries and simultaneous mapped executions.

Run on a direct target

Local execution uses LocalTarget. Docker/direct and hosted targets require a committed Git source, selected from the client workspace or per-run repository=, branch=, and revision=. repository= accepts a credential-free HTTPS/SSH Git URL or GitHub owner/name shorthand; source_connection= selects a named connection used only for Git checkout and delivery:

from zeroshot import Client, DirectTarget, UniformRuntime


async def run_direct(runtime: UniformRuntime) -> None:
    target = DirectTarget("http://127.0.0.1:8080")

    async with Client(target=target, runtime=runtime) as client:
        result = await client.run("Update the parser.")

    result.raise_for_failure()

Direct and hosted targets resolve GitHub access from their own stored github connection, and the client does not send GH_TOKEN to them. Pass forward_github_token=True to Client to send the submission environment's GH_TOKEN with runs and stacks instead, for example to a direct target with no stored connection. The submission then fails when GH_TOKEN is unset.

Submit a hosted stack

Log in with the CLI first, then pass that target's local name to HostedTarget. A stack is an atomic, immutable DAG of runs over one explicit repository, base branch, and hosted profile, submitted at once. delivery chooses how it lands:

  • "merge": the profile contains exactly one Git merge delivery node (builtin.git-delivery.merge@2 or @3). Each run merges into the base branch before its dependents start, and a run may need several others.
  • "stacked_pull_requests": the profile contains exactly one builtin.git-delivery.pr@2 node. zeroshot turns the runs into one linear stack: each run needs exactly the run before it, in dependency order with ties broken by run name. Each run opens a pull request against the previous run's branch, the first against the base branch, and nothing is merged.

In both modes, agent bindings must not declare GH_TOKEN; only the Git delivery binding may.

from datetime import UTC, datetime, timedelta

from zeroshot import Client, HostedTarget, StackRequest, StackRun


async def submit_release_stack() -> None:
    request = StackRequest(
        title="Release checkout update",
        repository="the-open-engine/zeroshot",
        branch="main",
        profile="org:software-change",
        delivery="merge",
        expires_at=(datetime.now(UTC) + timedelta(days=1)).isoformat(),
        runs={
            "backend": StackRun(input={"task": "Update the API."}),
            "frontend": StackRun(input={"task": "Update the client."}),
            "integrate": StackRun(
                input={"task": "Verify the combined changes and run the release tests."},
                needs=("backend", "frontend"),
            ),
        },
        submission_key="checkout-release-1",
    )

    async with Client(target=HostedTarget("platform")) as client:
        stack = await client.submit_stack(request)
        status = await stack.wait(wait_timeout=21_600)

    if not status.succeeded:
        raise RuntimeError(f"stack ended as {status.state}")

With a pull-request delivery profile and delivery="stacked_pull_requests", the same runs become the chain backend, frontend, integrate: three pull requests, each targeting the branch of the one before it.

Submission is atomic, and every run receives a stable run ID. needs gates readiness only; stack runs have no output interpolation or shared mutable input. Once its dependencies are delivered, Platform materializes the run against an exact source branch and revision. When materialization completes, readyAt is set and the run's queue deadline is the earlier of stack expiry and seven days after readyAt. With merge delivery, a merge conflict is repaired by the conflicting run itself in the same checkout and delivery loop. A descendant cannot repair a failed predecessor; it ends as dependency_failed. The v1 API has no aggregate event stream, so Stack.watch() polls and yields changed snapshots. Submit a stack covers delivery modes and reviewing a stacked pull-request chain.

Pass exact protocol documents

GraphSpec and RuntimePlan wrap exact JSON mappings without loss. Python neither copies the Rust schemas nor applies its own semantic checks:

from collections.abc import Mapping
from typing import Any

from zeroshot import Client, GraphSpec, RunRequest, RuntimePlan


async def submit_exact(
    client: Client,
    graph_document: Mapping[str, Any],
    runtime_document: Mapping[str, Any],
) -> None:
    request = RunRequest(
        title="Repair checkout",
        graph=GraphSpec.from_dict(graph_document),
        initial_input={"ticket": "OE-123"},
        runtime=RuntimePlan.from_dict(runtime_document),
        submission_key="oe-123-attempt-1",
    )

    result = await client.run(request)
    result.raise_for_failure()

An opaque RuntimePlan may carry per-node lanes and passes through unchanged, while UniformRuntime applies one lane to every agent node. For local execution, set worktree=True and optional worktree_base on the RunRequest itself. A complete request cannot be combined with string-submission overrides.

Before starting a local controller or contacting a direct target, the bundled executable performs the same preflight as the CLI.

The Python API reference documents the public client surface.

await run.suspend() returns the current status immediately; await run.resume() returns the successor's Run handle. run.watch() ends at suspension. Run.wait() and Client.run() raise RunSuspendedError, carrying run and status, when an attempt suspends. Status and summaries expose suspend_requested, reason, node, created_at and due_at. Read the ordered record with await run.vectors(after=None, limit=50) (RunVectorsPage.vectors, next_after) and read a complete entry with await run.vector(id). These methods use the client's selected target.

await run.discard_workspace() returns whether retained data was deleted. For a finished local run it frees the recovery lineage's checkpoints, including those of failed runs, while keeping the checkout, ledger, logs and delivery recovery state. Plain resume still uses the current checkout; checkpoint restore is no longer available. Named targets keep their existing retained workspace discard behavior.

Answer a human request

await client.inbox(after=None, limit=50) returns an InboxPage with requests and next_after. await run.request() returns the run's own InboxRequest, including text, declared signals/output, deadline, state and successor. await run.answer({"signals": {"decision": "approved"}, "output": {"feedback": ""}}) returns the successor Run. RunStatus.request carries the human request. All methods use the client's local or named target arguments; named targets need openengine.request-ask/v1. Answers follow resume's credential and forwarding rules. Invalid, repeated and late answers raise the existing CLI command error with its message. A late answer still starts the timeout successor. Deadlines default to 7 days and have a 30-day maximum; inbox reads never apply them. See Ask a person.

Standing direction

steer = await run.steer("Prioritize the parser regression.") records standing direction without continuing a suspended run. Use await run.steer(text, mode="once") to deliver once per node instance; mode="standing" delivers per provider conversation and remains the default. RunStatus.steers from Run.status() exposes excerpts, message modes, optional network origin metadata and recorded receiving executions; statuses streamed by Run.watch() omit them. omitted_steers reports the bounded listing's omissions. Each agent conversation receives a steer at its next tool call or prompt, within the Claude Code limits. await run.vector(steer.id) reads its full text, and await run.vectors() includes steer and steer_receipt entries. Direction is limited to 262,144 UTF-8 bytes and is stored as given; do not include secrets. Existing SDK error types report refusals.