Skip to content

Results

This page is the API reference for RunResult, RunStatus, RunError, Usage, Event, LocalLedger, ResultSink and phd.runs. Semantics (precedence, events per harness, cost source): Results and events.

Summary

RunResult

Dataclass with 34 fields (run_id, harness, model, stack, stack_hash, status, exit_code, error, result_text, structured_output, cost_usd, cost_source, usage, num_turns, duration_ms, session_id, resumable, resumed_from, run_dir, home_dir, cwd, project_config, autonomy, unsafe, credential_kind, started_at, finished_at, cli_version, sandbox, warnings, raw_final, events_path, stderr_path, session_cost_usd); field table in Results and events.

Member Purpose
.to_dict() -> dict JSON-ready dict (the result.json format)
RunResult.from_dict(data) -> RunResult rebuild from to_dict() output

RunStatus

StrEnum: SUCCEEDED, FAILED, TIMED_OUT, BUDGET_EXCEEDED, CANCELLED, AUTH_FAILED (values are the lower-case strings). Derived from RunResult.error.kind.

RunError

RunError(kind, message): why a run did not succeed. Kinds: cancelled, timeout, idle, schema, budget, stream_overflow, phd_internal, session, auth, model_unavailable, billing, harness_error, harness_crash, no_result.

Usage

Usage(input_tokens=0, cached_input_tokens=0, output_tokens=0, reasoning_tokens=0), .add(other) -> None. input_tokens includes cached input.

Event

Event(run_id, harness, type, data, ts, raw=None, summary=""), .to_dict() -> dict. Frozen. summary is a one-line, secret-scrubbed description (at most 500 characters) of message, tool_call and tool_result events and "" for the rest; see Event summary. type is one of run.started, session.started, message, tool_call, tool_result, usage, log, schema.repair, run.finished.

LocalLedger

Member Purpose
LocalLedger(root=None) ledger at root (default ~/.phd/runs)
.root absolute ledger directory
.list(*, harness=None, stack=None, since=None) -> list[RunResult] finished runs, oldest first
.get(run_id) -> RunResult one run; KeyError if no result.json
await .put(result) -> None write result.json atomically (it is a ResultSink)
.allocate() -> tuple[str, Path] create a new run directory (used by Dispatcher)
.write_record(run_dir, record) -> None / .read_record(run_id) -> dict run.json access (used by Dispatcher)

ResultSink

Protocol with one method, async def put(self, result: RunResult) -> None. Pass instances via Dispatcher(sinks=[...]).

phd.runs

Function Purpose
phd.runs.list(**filters) -> list[RunResult] LocalLedger().list(**filters) on the default ledger
phd.runs.get(run_id) -> RunResult LocalLedger().get(run_id) on the default ledger

Full reference

Rendered from the docstrings (MkDocs site only).

RunResult dataclass

RunResult(run_id: str, harness: str, model: str, stack: str, stack_hash: str, status: RunStatus, exit_code: int | None, error: RunError | None, result_text: str | None, structured_output: Any, cost_usd: float | None, cost_source: str, usage: Usage, num_turns: int | None, duration_ms: int, session_id: str | None, resumable: bool, resumed_from: str | None, run_dir: str, home_dir: str, cwd: str, project_config: str, autonomy: str, unsafe: bool, credential_kind: str, started_at: str, finished_at: str, cli_version: str | None = None, sandbox: str | None = None, warnings: list[str] = list(), raw_final: dict | None = None, events_path: str = '', stderr_path: str = '', session_cost_usd: float | None = None)

The normalized outcome of one run, written to <run_dir>/result.json.

Produced for every launched run, whatever happened; a failure is described by status and error, never raised. Field-by-field reference: docs/concepts/results-and-events.md.

Attributes:

Name Type Description
run_id str

YYYYmmdd-HHMMSS-<6 hex>.

harness str

Harness name.

model str

Spec.model.

stack str

"<name>@<version>".

stack_hash str

Stack.content_hash() of this run's stack, taken when the run was planned (also for a resumed turn, whose home is re-materialized).

status RunStatus

Overall outcome.

exit_code int | None

Harness exit code, or None if unknown.

error RunError | None

Why the run did not succeed, or None.

result_text str | None

The agent's final text answer, if any.

structured_output Any

The structured answer when Spec.output_schema is set (from the harness, else parsed from result_text as JSON when possible).

cost_usd float | None

Cost of this run, or None. For claude this is the turn's own cost: claude reports a session-cumulative figure on --resume, so PHD subtracts what the session had cost before (see session_cost_usd).

cost_source str

"harness" (claude when it reported total_cost_usd; opencode always) or "unknown" (codex; claude without a cost; PHD-internal failures). The value "estimated" is reserved and never produced today.

usage Usage

Token counts.

num_turns int | None

Turns reported (claude) or counted (codex turn.completed, opencode step_finish).

duration_ms int

Wall-clock time from launch to result.

session_id str | None

Harness session/thread id; pass it as start(..., session_id=) to resume.

resumable bool

True when the run home was kept and a session id is known (a resumed turn never deletes the shared home).

resumed_from str | None

For a turn started with session_id, the run the session was found in.

run_dir str

The run directory.

home_dir str

The run home (for a resumed turn, the session's shared home).

cwd str

The agent's working directory.

project_config str

Spec.project_config.

autonomy str

Spec.autonomy.

unsafe bool

Spec.unsafe.

credential_kind str

Credentials.kind (never the secret).

started_at str

ISO 8601 UTC timestamp.

finished_at str

ISO 8601 UTC timestamp.

cli_version str | None

Harness version (claude only today; None for codex and opencode).

sandbox str | None

Always None (no sandbox layer yet).

warnings list[str]

Pre-launch and materialization warnings, plus sink or cleanup failures.

raw_final dict | None

The harness's final JSON object (claude result line, last codex turn.completed, last opencode step_finish).

events_path str

Path of events.jsonl.

stderr_path str

Path of stderr.log.

session_cost_usd float | None

The harness's own cumulative cost for the whole session after this run, for harnesses that report cost per session (claude); None otherwise or when not reported. Absent from records written before it existed (loads as None).

to_dict

to_dict() -> dict

Return a JSON-ready dict (the result.json format); status becomes its string.

from_dict classmethod

from_dict(data: dict) -> RunResult

Rebuild a RunResult from to_dict() output (for example a parsed result.json).

RunStatus

Bases: StrEnum

Overall outcome of a run. Derived from RunResult.error.

SUCCEEDED when there is no error; CANCELLED, TIMED_OUT, BUDGET_EXCEEDED and AUTH_FAILED for error kinds cancelled, timeout / idle, budget and auth; FAILED for every other error kind. Members compare equal to their string values.

RunError dataclass

RunError(kind: str, message: str)

Why a run did not succeed.

Attributes:

Name Type Description
kind str

One of ERROR_KINDS: cancelled, timeout, idle, budget, stream_overflow, phd_internal, session, auth, billing, model_unavailable, harness_error, harness_crash, no_result, schema. The kinds are a stable contract (new ones may be added, none renamed or removed); read kind, never message. See docs/concepts/results-and-events.md for precedence.

message str

Human-readable detail (harness message, or exit code plus scrubbed stderr tail).

Usage dataclass

Usage(input_tokens: int = 0, cached_input_tokens: int = 0, output_tokens: int = 0, reasoning_tokens: int = 0)

Token counts for a run, normalized across harnesses.

Attributes:

Name Type Description
input_tokens int

All input tokens, including cached ones (claude and opencode add cache reads and cache writes to the uncached count).

cached_input_tokens int

Input tokens served from cache (cache reads).

output_tokens int

Output tokens.

reasoning_tokens int

Reasoning / thinking tokens where the harness reports them.

add

add(other: Usage) -> None

Add other's counts to this one in place.

Event dataclass

Event(run_id: str, harness: str, type: str, data: dict, ts: float, raw: dict | None = None, summary: str = '')

One normalized event from a run, as yielded by RunHandle.events and stored in events.jsonl.

Attributes:

Name Type Description
run_id str

The run that produced it.

harness str

The harness name.

type str

run.started, session.started, message, tool_call, tool_result, usage, log, schema.repair or run.finished.

data dict

Type-specific payload (for example {"text": ...} for message).

ts float

Unix timestamp (seconds) when PHD emitted the event.

raw dict | None

The harness JSON line the event came from; None for PHD's own events (run.started, run.finished, and log events for non-JSON stdout lines).

summary str

One line of plain text (no newline, at most 500 characters, secrets scrubbed) for message, tool_call and tool_result events, the same on every harness; "" for every other type. A tool call reads <Tool>: <key argument>, a tool result <Tool>: ok or <Tool>: failed (never the tool's output), a message is the first non-empty line of the agent's text.

to_dict

to_dict() -> dict

Return the event as a JSON-ready dict (the events.jsonl line format).

LocalLedger

LocalLedger(root: str | Path | None = None)

The on-disk run ledger: one directory per run under root.

Layout per run: <root>/<run_id>/ with run.json (launch record, secrets redacted), result.json, events.jsonl, stderr.log and home/. It is also the first ResultSink of every Dispatcher.

Attributes:

Name Type Description
root

Absolute ledger directory.

Open (lazily) the ledger at root; nothing is created until a run is allocated.

Parameters:

Name Type Description Default
root str | Path | None

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

None

allocate

allocate() -> tuple[str, Path]

Create a fresh, uniquely named run directory and return (run_id, run_dir).

write_record

write_record(run_dir: Path, record: dict) -> None

Write the launch record run.json into run_dir.

read_record

read_record(run_id: str) -> dict

Read a run's run.json.

Raises:

Type Description
NotResumable

The run has no run.json in this ledger.

write_session

write_session(run_dir: Path, record: dict) -> None

Atomically write session.json into run_dir: the session a run reported, written as soon as the harness reports it, so a run that dies before result.json can still be resumed.

put async

put(result: RunResult) -> None

Write result.json into result.run_dir atomically (temp file + rename).

get

get(run_id: str) -> RunResult

Load one run's result.

Raises:

Type Description
KeyError

The run has no result.json (unknown id, still running, or a dry run).

list

list(*, harness: str | None = None, stack: str | None = None, since: datetime | None = None) -> builtins.list[RunResult]

List finished runs, oldest first (by started_at).

Only runs with a readable result.json are listed; corrupt files are skipped.

Parameters:

Name Type Description Default
harness str | None

Keep only runs of this harness.

None
stack str | None

Keep only runs of this stack ref ("name@version").

None
since datetime | None

Keep only runs started at or after this time. started_at is UTC-aware, so pass an aware datetime (comparing with a naive one raises TypeError).

None

latest_for_session

latest_for_session(session_id: str) -> RunResult | None

Return the most recently started finished run whose session_id matches, or None.

Failed runs count: a run that recorded a session id can be resumed whatever its status.

find_session

find_session(session_id: str) -> SessionRef | None

Find the run to resume session_id from, or None.

The newest finished run of the session wins (as in latest_for_session). Without one, the newest session.json of a run that has no readable result.json (a run that crashed) is used. Unreadable or malformed session.json files are skipped.

ResultSink

Bases: Protocol

Anything that receives finished results: implement async put(result).

Pass instances as Dispatcher(..., sinks=[...]). Sinks are called in order after the local ledger; an exception from a sink is caught and appended to result.warnings (the result is still returned, and later sinks still run).

Example
class PrintSink:
    async def put(self, result: RunResult) -> None:
        print(result.run_id, result.status)

Dispatcher(spec, sinks=[PrintSink()])

put async

put(result: RunResult) -> None

Receive one finished RunResult.

runs

Query the default run ledger (~/.phd/runs): phd.runs.list(...) and phd.runs.get(run_id).

Runs recorded under a custom runs_root are not visible here; use LocalLedger(root) instead. The implementation lives in phd.results.runs.

get

get(run_id: str) -> RunResult

Load one run's result from the default ledger (~/.phd/runs).

Raises:

Type Description
KeyError

The run has no result.json there.

list

list(**filters) -> builtins.list[RunResult]

List finished runs in the default ledger (~/.phd/runs), oldest first.

Parameters:

Name Type Description Default
**filters Any

harness=, stack=, since=, as for LocalLedger.list.

{}
Example
import phd
for r in phd.runs.list(harness="claude")[-5:]:
    print(r.run_id, r.status, r.cost_usd)

Next: Models ยท See also: API overview, Results and events