Skip to content

Dispatcher

This page is the API reference for Dispatcher and RunHandle, plus the MaterializedHome returned by Dispatcher.plan. Behaviour in context: Run lifecycle.

Summary

Dispatcher

Dispatcher(spec, *, runs_root=None, sinks=(), catalog=None, validate_model=True, executables=None, allow_temp_runs_root=False) Validates the spec against its harness (hooks, features, model, codex runs root) and runs agents for it.

Member Purpose
.plan(inputs, *, session_id=None) -> MaterializedHome dry run: write the run home and run.json, launch nothing
await .start(inputs, *, session_id=None) -> RunHandle materialize and launch; returns once the process has started
async with .run(inputs, *, session_id=None) as handle start as a context manager: leaving the block cancels a run that has not finished and waits for it to end (Run lifecycle)
.spawn(inputs, *, session_id=None) -> RunResult blocking start + wait; RuntimeError inside a running event loop
.spec the Spec
.ledger the LocalLedger at runs_root
.sinks [ledger, *sinks]
.warnings pre-launch warnings, copied into every run

session_id (a previous RunResult.session_id) continues that harness session: PHD finds the session's latest run in the ledger and re-materializes its home from this dispatcher's Spec, keeping the harness's session data. The session's original rules are re-applied on every turn; new Inputs.rules are not allowed then. With plan, session_id previews the resumed turn in the plan's own run home without modifying the session. See Run lifecycle.

RunHandle

Returned by start; not constructed directly.

Member Purpose
async for ev in .events() normalized Events until run.finished; single consumer
await .wait() -> RunResult the result; never raises for a failed run
await .cancel() -> RunResult kill the process tree; status cancelled if still running
.run_id this run's id
.session_id the harness session id once reported (set at once for a resumed turn); None before. Announced by one session.started event
.done True once the run has finished and its result exists
.resumed_from for a resumed session, the run it was found in; else None
.materialized the launched MaterializedHome

MaterializedHome

Not exported from phd (import path phd.materialize.MaterializedHome), but returned by plan() and available as RunHandle.materialized.

Field / method Meaning
run_id, run_dir, home ids and paths of the run
argv harness command line (argv[0] is the bare CLI name)
env variables PHD sets for the child; hidden from repr()
stdin the first user message
warnings pre-launch and materialization warnings
redacted_env() -> dict env with secret-looking values replaced by <redacted>

Full reference

Rendered from the docstrings (MkDocs site only).

Dispatcher

Dispatcher(spec: Spec, *, runs_root: str | Path | None = None, sinks: Sequence[ResultSink] = (), catalog: ModelCatalog | None = None, validate_model: bool = True, executables: dict[str, list[str]] | None = None, allow_temp_runs_root: bool = False)

Runs agents described by one Spec: dry runs, fresh runs and resumed sessions.

Errors that can be detected before launch are raised as PhdError subclasses. Anything that goes wrong after the harness starts is returned as data in RunResult (status, error); spawn and RunHandle.wait never raise for a failed run.

Every run allocates <runs_root>/<run_id>/ and writes run.json there before launch; the result is written to result.json and then handed to each extra sink.

Attributes:

Name Type Description
spec

The spec this dispatcher runs.

ledger

The LocalLedger at runs_root; always the first sink.

sinks list[ResultSink]

[ledger, *sinks].

warnings list[str]

Pre-launch warnings (adapter checks and model catalogue); copied into every run's warnings.

Example
d = Dispatcher(spec)
result = d.spawn(Inputs(brief="task.md"))          # blocking
again = d.spawn(Inputs(msg="now fix the failing test"), session_id=result.session_id)

Validate the spec against its harness and prepare the ledger.

Parameters:

Name Type Description Default
spec Spec

The run description.

required
runs_root str | Path | None

Ledger directory. Defaults to ~/.phd/runs.

None
sinks Sequence[ResultSink]

Extra ResultSinks that receive every RunResult after the local ledger.

()
catalog ModelCatalog | None

Model catalogue to validate against. Defaults to a ModelCatalog that uses executables and shares its codex / opencode lookups (codex debug models / opencode models) with every other dispatcher in the process. Those lookups are slow, so they do not run here: they run in a worker thread on the first start() (or synchronously in plan()).

None
validate_model bool

Set False to skip model validation entirely.

True
executables dict[str, list[str]] | None

Per-harness argv prefix replacing the CLI name (also for the codex / opencode model catalogue command: a wrapper must support debug models / models, or use validate_model=False), for example {"claude": ["/opt/claude/bin/claude"]}. Skips the PATH lookup.

None
allow_temp_runs_root bool

Allow a codex runs_root under the system temp dir.

False

Raises:

Type Description
HookUnsupported

A stack hook cannot be expressed for this harness.

ModelNotSupported

Claude only: spec.model is not a known claude model. For codex the check is lazy and start() / run() / plan() raise it; an opencode miss is only a warning.

InvalidRunsRoot

codex with a runs_root under the system temp dir.

plan

plan(inputs: Inputs, *, session_id: str | None = None) -> MaterializedHome

Dry run: allocate a run directory and write the run home, but launch nothing.

Writes the run home and <run_dir>/run.json exactly as start would, except that credential copies (codex auth.json) are deleted again before this returns: nothing runs, so none stays at rest. No result.json is written, so the run never appears in LocalLedger.list. With session_id this previews a resumed turn without modifying the session: the session checks run, the session's rules are applied and argv carries the harness's resume flag for that session, but the files are written into this plan's own <run_dir>/home, never into the session's shared home (so env points at the preview home, not the session's).

Parameters:

Name Type Description Default
inputs Inputs

The task.

required
session_id str | None

Plan a turn that continues this harness session (see start).

None

Returns:

Type Description
MaterializedHome

The MaterializedHome: run_id, run_dir, home, argv, env (use

MaterializedHome

redacted_env() to print it), stdin (the first user message) and warnings.

Raises:

Type Description
ModelNotSupported

spec.model is not in the harness catalogue (loaded synchronously here).

MissingCredentials

A credential file cannot be read.

MissingSecret

A placeholder has no value in Spec.secrets.

NotResumable

session_id cannot be continued: the session is busy or its home is tampered with (see start), and, unlike start, also when no run has the session, it belongs to another harness, it ran in another cwd, its home is gone, or its run crashed with resumable=False (there is no run to return from a dry run).

StackNotFound

The stack's folder no longer exists (removed from the store).

UnsupportedFeature

session_id together with inputs.rules.

start async

start(inputs: Inputs, *, session_id: str | None = None) -> RunHandle

Materialize and launch a run; return as soon as the process has started.

With session_id, the run continues that harness session (a value from a previous RunResult.session_id). PHD finds the latest finished run of the session in this dispatcher's ledger (or, if none finished, the newest run that crashed after reporting it) and re-materializes its home from this spec: skills, identity, MCP servers, hooks, settings and credentials all come from the new spec, while the harness's session data in the home is kept. The run gets its own run_id and run directory; RunResult.resumed_from names the run the session was found in. The first message is built from inputs as for a fresh run. The rules the session started with (recorded as rules_text in each run's run.json) are re-applied to the system prompt on every resumed turn; passing new inputs.rules is not allowed.

Parameters:

Name Type Description Default
inputs Inputs

The task.

required
session_id str | None

Continue this harness session instead of starting a new one.

None

Returns:

Type Description
RunHandle

A RunHandle to stream events from, wait on, or cancel. When session_id cannot be resumed

RunHandle

(unknown to the ledger, another harness, another cwd, its home gone, or a crashed run with

RunHandle

resumable=False) nothing is launched: the handle is already done and its result is a failed run

RunHandle

with error.kind == "session" (the reason is in error.message). Such a run still gets a run id,

RunHandle

a run directory, result.json and events.jsonl (run.started, run.finished), and reaches the sinks.

A caller cancelled while start() is still planning leaves nothing behind: once the worker thread finishes, the session lock is released and a fresh run's directory is removed (a resumed turn's shared home is kept).

Nothing here blocks the event loop: the model catalogue lookup (first call only), the home materialization and the ledger writes run in worker threads.

Raises:

Type Description
ModelNotSupported

spec.model is not in the harness catalogue (codex; raised before anything is launched or written). An opencode miss is a warning.

HarnessNotInstalled

The harness CLI is not on PATH (and no executables override).

StackNotFound

The stack's folder no longer exists (removed from the store).

MissingCredentials

A credential file cannot be read.

MissingSecret

A placeholder has no value in Spec.secrets.

NotResumable

Another live run is using the session right now (<home>/.phd-session.lock; a lock left by a dead process is taken over automatically), or the session's recorded home is not a run home of this ledger or contains a link (tampering), or its run.json is gone.

UnsupportedFeature

session_id together with inputs.rules (rules are part of the session's system prompt).

Example
handle = await d.start(inputs)
async for ev in handle.events():
    print(ev.type, ev.data)
result = await handle.wait()
nxt = await (await d.start(Inputs(msg="now fix it"), session_id=result.session_id)).wait()

run async

run(inputs: Inputs, *, session_id: str | None = None) -> AsyncIterator[RunHandle]

start() as an async context manager: leaving the block ends the run.

On exit for any reason (the block ended, an exception, task cancellation), a run that has not finished is cancelled and PHD waits for the harness to die before the exception goes on. The result is recorded in the ledger as usual (status cancelled).

Parameters:

Name Type Description Default
inputs Inputs

The task.

required
session_id str | None

Continue this harness session (see start).

None

Yields:

Type Description
AsyncIterator[RunHandle]

The RunHandle. A session that cannot be resumed does not raise: the handle is already done and its

AsyncIterator[RunHandle]

result is a failed run with error.kind == "session" (see start).

Raises:

Type Description
PhdError

Any pre-launch error listed for start, raised on entering the block.

Example
async with d.run(inputs) as handle:
    async for ev in handle.events():
        print(ev.type)
    result = await handle.wait()

spawn

spawn(inputs: Inputs, *, session_id: str | None = None) -> RunResult

Blocking wrapper: start(inputs, session_id=...) then wait().

Parameters:

Name Type Description Default
inputs Inputs

The task.

required
session_id str | None

Continue this harness session (see start).

None

Returns:

Name Type Description
RunResult

The finished RunResult (check status and error). A session that cannot be resumed does not

raise RunResult

the result is a failed run with error.kind == "session" (see start).

Raises:

Type Description
RuntimeError

Called while an event loop is running (for example in Jupyter); use await start(...) there.

PhdError

Any pre-launch error listed for start.

RunHandle

RunHandle(dispatcher: Dispatcher, m: MaterializedHome, resumed_from: str | None, stack_hash: str, lock: SessionLock | None = None, session_id: str | None = None, session_cost_before: float = 0.0)

One live run. Created by Dispatcher.start, not directly.

A background task reads the harness's stdout, turns each line into Events (also appended to events.jsonl), builds the RunResult when the process exits, and hands it to every sink.

Attributes:

Name Type Description
run_id

This run's id.

resumed_from

For a resumed session, the run the session was found in; else None.

materialized

The MaterializedHome that was launched.

session_id str | None

The harness session id once the harness reports it (at once for a resumed turn); None before.

done property

done: bool

True once the run has finished and its RunResult exists.

unlaunched async classmethod

unlaunched(d: Dispatcher, run_id: str, run_dir: Path, stack_hash: str, reason: str) -> RunHandle

A handle for a run that was never launched: session_id cannot be resumed, so the run is finished at once with error.kind == "session" (reason is the message). No home is created and no lock taken (home_dir is ""). events.jsonl holds run.started and run.finished; result.json is written and every sink receives the result, as for any run.

events async

events() -> AsyncIterator[Event]

Yield normalized events until the run finishes (the last one is run.finished).

Events go through a single queue: each event is delivered to exactly one iterator, so use one consumer. Iterating again after the run has finished yields nothing; read events.jsonl (RunResult.events_path) for the full record.

wait async

wait() -> RunResult

Wait for the run to finish and return its RunResult. Never raises for a failed run.

Cancelling the awaiting task does not stop the run (the wait is shielded); use cancel.

cancel async

cancel() -> RunResult

Kill the harness process tree and return the result.

A run still in progress finishes with status cancelled. On a run that has already finished this just returns the existing result.


Next: Results ยท See also: API overview, Run lifecycle