Skip to content

Spec and stack

This page is the API reference for Spec, Inputs, Credentials, Stack and HookDef. Field-by-field behaviour per harness: Spec, Inputs, Credentials and Stacks.

Summary

Spec

Spec(harness, model, stack, cwd, credentials, harness_config={}, project_config="ignore", autonomy="restricted", unsafe=False, secrets={}, timeout_s=1800.0, budget_usd=None, output_schema=None, resumable=True, harness_builtins=False, idle_timeout_s=None, schema_repair=False, chrome=False) Mutable dataclass describing what runs, where and how; validates everything in its constructor.

Inputs

Inputs(brief=None, msg=None, rules=None) Frozen dataclass: the task for one run. Resolves brief / rules to absolute paths; needs a brief or a non-blank msg.

Credentials

Member Purpose
Credentials.claude_oauth_token(token) -> Credentials claude, token from claude setup-token โ†’ CLAUDE_CODE_OAUTH_TOKEN
Credentials.anthropic_api_key(key) -> Credentials claude, API key โ†’ ANTHROPIC_API_KEY
Credentials.claude_host_login(path=None) -> Credentials claude, host login file copied into the run home (default ~/.claude/.credentials.json)
Credentials.codex_auth_file(path=None) -> Credentials codex, auth.json copied into the run home (default ~/.codex/auth.json)
Credentials.opencode_auth_file(path=None, providers=()) -> Credentials opencode, auth JSON (filtered) โ†’ OPENCODE_AUTH_CONTENT
Credentials.from_host(harness) -> Credentials the host login for any harness at its default path
.opencode_auth_content() -> str the opencode auth file as JSON text, filtered to providers
fields harness, kind, secret, path, providers frozen; secret hidden from repr()

Stack

Member Purpose
Stack.load(root) -> Stack load and validate a stack directory
.ref -> str "<name>@<version>"
.check_harness(harness) -> None raise StackIncompatible if harnesses excludes it
.content_hash() -> str "sha256:<hex>" over the stack's files
fields root, name, version, description, harnesses, default_models, agent_name, identity, skills, mcp_servers, hooks frozen dataclass

HookDef

HookDef(event, command, tool=None, timeout_s=30.0), .as_dict() -> dict Frozen dataclass: one neutral hook.

Full reference

Rendered from the docstrings (MkDocs site only).

Spec dataclass

Spec(harness: str, model: str, stack: Stack, cwd: Path, credentials: Credentials, harness_config: dict[str, Any] = dict(), project_config: str = 'ignore', autonomy: str = 'restricted', unsafe: bool = False, secrets: dict[str, str] = dict(), timeout_s: float = 1800.0, budget_usd: float | None = None, output_schema: dict | None = None, resumable: bool = True, harness_builtins: bool = False, idle_timeout_s: float | None = None, schema_repair: bool = False, chrome: bool = False)

What to run, where, and how: everything about a run except the task itself.

All validation happens in the constructor, so a Spec that exists is internally consistent. cwd is resolved to an absolute path. Per-harness effects of each field are listed in docs/concepts/spec-and-inputs.md and docs/concepts/combinations.md.

Attributes:

Name Type Description
harness str

"claude", "codex" or "opencode".

model str

The model name passed to the harness (--model / -m). Checked against the harness catalogue by Dispatcher unless validate_model=False.

stack Stack

The agent: identity, skills, MCP servers and hooks (Stack.load(...)).

cwd Path

The agent's working directory. Must exist.

credentials Credentials

How the run authenticates; must be for the same harness.

harness_config dict[str, Any]

Extra settings deep-merged into the harness's own config file (settings.json / config.toml / opencode.json). On a scalar conflict PHD's value wins and a warning is recorded.

project_config str

"ignore" (default; repo instructions and settings are not loaded), "instructions_only" (PHD appends the repo's AGENTS.md / CLAUDE.md to the system prompt) or "full" (the harness loads repo config natively).

autonomy str

"restricted" (default) or "full" (bypasses harness permission checks).

unsafe bool

Must be True to use autonomy="full"; recorded in the result.

secrets dict[str, str]

Values for ${env:NAME} placeholders in the stack's .mcp.json and hook commands. Excluded from repr(); scrubbed from the crash stderr tail.

timeout_s float

Wall-clock limit for the run, including writing the prompt. On expiry the process tree is killed and the result has status timed_out. Default 1800.

budget_usd float | None

Cost cap. claude gets --max-budget-usd (claude reports cost only in its final line, where PHD also checks this turn's own cost); opencode is stopped by PHD as soon as the summed step_finish cost exceeds it; codex reports no cost, so it is not enforced (a warning is added).

output_schema dict | None

JSON Schema for a structured final answer (claude --json-schema, codex --output-schema; opencode gets an instruction in its AGENTS.md). PHD validates the answer on every harness (see schema_repair).

resumable bool

Keep the run home after the run so its session can be resumed (Dispatcher.start(..., session_id=)). False deletes it once the result is built.

harness_builtins bool

Keep the harness's own bundled skills and plugins. Default False suppresses them so the agent sees only its stack's skills.

idle_timeout_s float | None

Stop the run when the harness prints nothing for this many seconds (RunError(kind="idle"), status timed_out). Default None (off). Claude and codex print nothing while a tool runs: set it above your longest expected tool call.

schema_repair bool

With output_schema, when the answer does not match, resume the session once and ask for a corrected answer. Default False (fail at once with kind="schema").

chrome bool

claude only: pass --chrome so the agent can drive the host's Chrome through the Claude in Chrome extension. Needs Credentials.claude_host_login (the token kinds do not work with it) and the extension installed. The agent acts in your real Chrome profile, with its sign-ins, and PHD has no sandbox. Default False.

Raises:

Type Description
UnknownHarness

harness is not supported.

InvalidSpec

Blank model; bad project_config / autonomy; non-bool harness_builtins; non-positive or non-finite timeout_s or budget_usd; bad idle_timeout_s / schema_repair / chrome; malformed output_schema (also one with a $ref that does not resolve).

CwdNotFound

cwd is not a directory.

UnsafeAutonomy

autonomy="full" without unsafe=True.

UnsupportedFeature

chrome=True with a harness other than claude.

MissingCredentials

credentials.harness differs from harness, or chrome=True without a claude_host_login credential.

StackIncompatible

The stack's harnesses list excludes harness.

MissingSecret

The stack references ${env:NAME} values absent from secrets.

Example
spec = Spec(harness="claude", model="sonnet", stack=Stack.load("config"),
            cwd="path/to/repo", credentials=Credentials.from_host("claude"))

Inputs dataclass

Inputs(brief: Path | None = None, msg: str | None = None, rules: Path | None = None)

The task for one run: a brief file, a message, and an optional rules file.

Paths are expanded (~) and resolved to absolute paths at construction. The brief and the message become the first user message (on stdin); the rules file is appended to the system prompt. See docs/concepts/prompt-assembly.md.

Attributes:

Name Type Description
brief Path | None

A task brief file of any name. Inlined as # Task brief.

msg str | None

A free-form message. Inlined as # Message after the brief.

rules Path | None

A binding rules file. Appended to the system prompt as ## Project rules (binding).

Raises:

Type Description
InputNotFound

brief or rules is given but is not a file.

EmptyTask

Neither brief nor a non-blank msg is given.

Example
Inputs(brief="task.md", rules="RULES.md", msg="focus on the parser")
Inputs(msg="List your skills.")

Credentials dataclass

Credentials(harness: str, kind: str, secret: str | None = None, path: Path | None = None, providers: tuple[str, ...] = ())

How one run authenticates.

Build it with one of the classmethod constructors rather than the raw dataclass. The value names a credential kind; file-based kinds only remember the path, and the file is read when the run is materialized (Dispatcher.plan / start / spawn) and again on every resume. Each run gets the credential injected into its own environment or config home; the host's login files are never modified.

Only kind is recorded in RunResult.credential_kind; secret is excluded from repr().

Attributes:

Name Type Description
harness str

The harness this credential is for ("claude", "codex" or "opencode"). Must equal Spec.harness, otherwise Spec raises MissingCredentials.

kind str

One of "claude_oauth_token", "anthropic_api_key", "claude_host_login", "codex_auth_file", "opencode_auth_file".

secret str | None

The token or API key for the token kinds; None for file kinds.

path Path | None

The auth file for the file kinds; None for token kinds.

providers tuple[str, ...]

For opencode_auth_file only: the provider entries to copy into the run (empty means all entries).

Example
from phd import Credentials

creds = Credentials.from_host("claude")            # ~/.claude/.credentials.json
creds = Credentials.claude_oauth_token(token)      # token from `claude setup-token`

claude_oauth_token classmethod

claude_oauth_token(token: str) -> Credentials

Use a long-lived OAuth token from claude setup-token.

Preferred for claude: no refresh-token rotation, and it works on macOS where the host login lives in the Keychain. Injected as CLAUDE_CODE_OAUTH_TOKEN.

Parameters:

Name Type Description Default
token str

The token string.

required

Returns:

Type Description
Credentials

A claude_oauth_token credential.

anthropic_api_key classmethod

anthropic_api_key(key: str) -> Credentials

Use an Anthropic API key for claude. Injected as ANTHROPIC_API_KEY.

Parameters:

Name Type Description Default
key str

The API key.

required

Returns:

Type Description
Credentials

An anthropic_api_key credential.

claude_host_login classmethod

claude_host_login(path: str | Path | None = None) -> Credentials

Use the host's claude auth login session.

The file is copied verbatim (byte for byte, refresh token included) into the run home as .credentials.json (mode 0600 on POSIX) at materialize time and again on resume, and deleted when the turn ends. PHD never writes to path. This is the full login that Spec.chrome (claude --chrome) needs; the token kinds do not work with it.

Parameters:

Name Type Description Default
path str | Path | None

The credentials file. Defaults to ~/.claude/.credentials.json.

None

Returns:

Type Description
Credentials

A claude_host_login credential.

Raises:

Type Description
MissingCredentials

The file does not exist (for example on macOS, where the login is kept in the Keychain; use claude_oauth_token there, which cannot drive Chrome).

codex_auth_file classmethod

codex_auth_file(path: str | Path | None = None) -> Credentials

Use a codex auth.json (from codex login).

The file is copied verbatim (byte for byte) into the run home as auth.json (mode 0600 on POSIX) at materialize time and again on resume, and deleted when the turn ends. PHD never writes to path.

Parameters:

Name Type Description Default
path str | Path | None

The auth file. Defaults to ~/.codex/auth.json.

None

Returns:

Type Description
Credentials

A codex_auth_file credential.

Raises:

Type Description
MissingCredentials

The file does not exist.

opencode_auth_file classmethod

opencode_auth_file(path: str | Path | None = None, providers: tuple[str, ...] | list[str] = ()) -> Credentials

Use an opencode auth.json (from opencode auth login).

At materialize time the file is parsed, filtered to providers and passed to opencode as the OPENCODE_AUTH_CONTENT environment variable; no auth file is written to the run home.

Parameters:

Name Type Description Default
path str | Path | None

The auth file. Defaults to ~/.local/share/opencode/auth.json.

None
providers tuple[str, ...] | list[str]

Provider keys to keep (for example ["opencode"]). Empty keeps all.

()

Returns:

Type Description
Credentials

An opencode_auth_file credential.

Raises:

Type Description
MissingCredentials

The file does not exist.

from_host classmethod

from_host(harness: str) -> Credentials

Use the host CLI's own login at its default location.

Equivalent to claude_host_login(), codex_auth_file() or opencode_auth_file().

Parameters:

Name Type Description Default
harness str

"claude", "codex" or "opencode".

required

Returns:

Type Description
Credentials

The matching credential.

Raises:

Type Description
UnknownHarness

harness is not one of the three.

MissingCredentials

The host login file does not exist.

opencode_auth_content

opencode_auth_content() -> str

Return the auth file as JSON text, filtered to providers (used for opencode_auth_file).

Raises:

Type Description
MissingCredentials

The file cannot be read or parsed, or lacks a requested provider.

Stack dataclass

Stack(root: Path, name: str, version: str, description: str, harnesses: tuple[str, ...] | None, default_models: dict[str, str], agent_name: str, identity: str, skills: tuple[Path, ...], mcp_servers: dict[str, dict], hooks: tuple[HookDef, ...], store: StoreEntry | None = None)

A harness-neutral agent: one identity plus skills, MCP servers and hooks.

Load it from a config/ directory with Stack.load. A stack is read-only: every run copies it into its own run home (home/stack/) and builds the harness config from it, so many runs can share one stack. Layout and validation rules: docs/concepts/stacks.md.

Attributes:

Name Type Description
root Path

Absolute path of the stack directory.

name str

stack.json name.

version str

stack.json version.

description str

stack.json description (empty if absent).

harnesses tuple[str, ...] | None

stack.json harnesses compatibility list, or None for any harness.

default_models dict[str, str]

stack.json default_models (harness -> model). Informational only: PHD never reads it; Spec.model is always required.

agent_name str

File stem of the single agents/*.md file.

identity str

Text of that file; becomes the start of the system prompt.

skills tuple[Path, ...]

Skill directories under skills/ (each has a SKILL.md), sorted by name.

mcp_servers dict[str, dict]

.mcp.json mcpServers, unresolved (placeholders intact).

hooks tuple[HookDef, ...]

Parsed hooks/hooks.json entries.

store StoreEntry | None

Where the stack lives in the stack store, or None for Stack.load(dir).

ref property

ref: str

"<name>@<version>"; recorded as RunResult.stack.

load classmethod

load(root: str | Path) -> Stack

Load and validate a stack directory.

Parameters:

Name Type Description Default
root str | Path

The stack directory (~ is expanded). Only directories are supported.

required

Returns:

Type Description
Stack

The loaded stack.

Raises:

Type Description
StackInvalid

Missing or malformed stack.json; not exactly one agents/*.md; a skill folder without SKILL.md; malformed .mcp.json or hooks/hooks.json.

HookUnsupported

A hook names an event outside the neutral set.

Example
stack = Stack.load("tests/fixtures/stack")
stack.ref            # 'fixture-helper@0.1.0'

check_harness

check_harness(harness: str) -> None

Raise StackIncompatible if harnesses is set and excludes harness.

content_hash

content_hash() -> str

Return a SHA-256 over every file in the stack, as "sha256:<hex>".

Files are visited in sorted order; each contributes its POSIX relative path and raw bytes (no line-ending normalization). Skipped, relative to the stack root: anything named .git or __pycache__ (a folder, so its files, or a file) and *.pyc files. These are what stack assembly leaves out when it copies; other dot-folders and dot-files such as .mcp.json are hashed. The dispatcher computes it at plan time and records it as RunResult.stack_hash.

HookDef dataclass

HookDef(event: str, command: str, tool: str | None = None, timeout_s: float = 30.0)

One neutral hook from hooks/hooks.json.

Attributes:

Name Type Description
event str

"session_start", "pre_tool", "post_tool" or "stop".

command str

A shell command line. May contain ${stack} (the run's copy of the stack, shell-quoted) and ${env:NAME} (from Spec.secrets).

tool str | None

Neutral tool to match ("shell", "read", "write", "edit", "web_fetch", "web_search", "mcp:<server>[/<tool>]"), from the JSON match.tool; None matches every tool.

timeout_s float

Seconds the hook command may run. Default 30.

as_dict

as_dict() -> dict

Return the hook as a plain dict with keys event, command, tool, timeout_s.


Next: Dispatcher ยท See also: API overview, Stacks