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 |
|
sinks |
list[ResultSink]
|
|
warnings |
list[str]
|
Pre-launch warnings (adapter checks and model catalogue); copied into every
run's |
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 |
None
|
sinks
|
Sequence[ResultSink]
|
Extra |
()
|
catalog
|
ModelCatalog | None
|
Model catalogue to validate against. Defaults to a |
None
|
validate_model
|
bool
|
Set |
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 |
None
|
allow_temp_runs_root
|
bool
|
Allow a codex |
False
|
Raises:
| Type | Description |
|---|---|
HookUnsupported
|
A stack hook cannot be expressed for this harness. |
ModelNotSupported
|
Claude only: |
InvalidRunsRoot
|
codex with a |
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 |
None
|
Returns:
| Type | Description |
|---|---|
MaterializedHome
|
The |
MaterializedHome
|
|
Raises:
| Type | Description |
|---|---|
ModelNotSupported
|
|
MissingCredentials
|
A credential file cannot be read. |
MissingSecret
|
A placeholder has no value in |
NotResumable
|
|
StackNotFound
|
The stack's folder no longer exists (removed from the store). |
UnsupportedFeature
|
|
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
|
(unknown to the ledger, another harness, another |
RunHandle
|
|
RunHandle
|
with |
RunHandle
|
a run directory, |
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
|
|
HarnessNotInstalled
|
The harness CLI is not on PATH (and no |
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 |
NotResumable
|
Another live run is using the session right now ( |
UnsupportedFeature
|
|
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 |
None
|
Yields:
| Type | Description |
|---|---|
AsyncIterator[RunHandle]
|
The |
AsyncIterator[RunHandle]
|
result is a failed run with |
Raises:
| Type | Description |
|---|---|
PhdError
|
Any pre-launch error listed for |
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 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
RunResult
|
The finished |
|
raise |
RunResult
|
the result is a failed run with |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
Called while an event loop is running (for example in Jupyter); use
|
PhdError
|
Any pre-launch error listed for |
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 |
|
materialized |
The |
|
session_id |
str | None
|
The harness session id once the harness reports it (at once for a resumed turn); |
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