Documentation
¶
Overview ¶
Package harness abstracts the coding-agent CLIs patchy drives. A harness builds the argv for one prompted run (PromptSpec), the runner package executes it, and the harness parses the CLI's stream-json stdout back into an AgentResult — harnesses never touch os/exec themselves, so every caller can be tested against captured output.
Four harnesses register: Claude (the claude CLI, patchy's default agent), Codex (the codex CLI, driving OpenAI models), Copilot (the copilot CLI, which brokers both vendors' models and so is every model's fallback rather than any model's preferred harness) and Fake (replays a fixture file through cat, for tests and the agent-runner's --fake mode).
Index ¶
- Constants
- func Available(h Harness) (path string, ok bool)
- func EnabledSet(ids []string) map[string]bool
- func ResolveModel(m model.Model, enabled map[string]bool) (harnessID, cliModelID string, ok bool)
- func ValidateAllowlist(models []model.Model, allowlist []string, enabled map[string]bool) error
- type AgentResult
- type BudgetReporter
- type Claude
- func (b Claude) CLI() []string
- func (b Claude) EnvKeys() []string
- func (c *Claude) Exhausted(stdout []byte) bool
- func (b Claude) ID() string
- func (b Claude) Name() string
- func (c *Claude) ParseResult(stdout []byte) (AgentResult, bool)
- func (c *Claude) PromptSpec(ws string, req PromptRequest) runner.CommandSpec
- func (c *Claude) RuntimeError(stdout []byte, exitCode int, timedOut bool) string
- func (c *Claude) ScanUsage(line []byte) (int, bool)
- type Codex
- func (b Codex) CLI() []string
- func (b Codex) EnvKeys() []string
- func (b Codex) ID() string
- func (b Codex) Name() string
- func (c *Codex) ParseResult(stdout []byte) (AgentResult, bool)
- func (c *Codex) PromptSpec(ws string, req PromptRequest) runner.CommandSpec
- func (c *Codex) RuntimeError(stdout []byte, exitCode int, timedOut bool) string
- func (c *Codex) ScanUsage(line []byte) (int, bool)
- type Copilot
- func (b Copilot) CLI() []string
- func (b Copilot) EnvKeys() []string
- func (b Copilot) ID() string
- func (b Copilot) Name() string
- func (c *Copilot) ParseResult(stdout []byte) (AgentResult, bool)
- func (c *Copilot) PromptSpec(ws string, req PromptRequest) runner.CommandSpec
- func (c *Copilot) RuntimeError(stdout []byte, exitCode int, timedOut bool) string
- func (c *Copilot) ScanUsage(line []byte) (int, bool)
- type Fake
- func (b Fake) CLI() []string
- func (b Fake) EnvKeys() []string
- func (b Fake) ID() string
- func (b Fake) Name() string
- func (f *Fake) ParseResult(stdout []byte) (AgentResult, bool)
- func (f *Fake) PromptSpec(ws string, req PromptRequest) runner.CommandSpec
- func (f *Fake) RuntimeError(stdout []byte, exitCode int, timedOut bool) string
- func (f *Fake) ScanUsage(line []byte) (int, bool)
- type Harness
- type PromptRequest
- type Sandbox
- type Usage
- type UsageScanner
Constants ¶
const FakeFixtureEnv = "PATCHY_FAKE_FIXTURE"
FakeFixtureEnv names the environment variable pointing at the stream-json fixture file the Fake harness replays.
Variables ¶
This section is empty.
Functions ¶
func EnabledSet ¶ added in v0.6.0
EnabledSet turns a list of enabled harness ids into a lookup set.
func ResolveModel ¶ added in v0.6.0
ResolveModel picks the harness that runs m given the enabled harness set, and the CLI model-id string that harness's --model flag expects. The model's preferred harness wins when it is enabled and supports the model; otherwise the first enabled supporting harness in registry order, so resolution is deterministic. As a last resort the fake harness runs any model when enabled (dev/e2e), reporting the model's bare id as the CLI id it will ignore.
func ValidateAllowlist ¶ added in v0.6.0
ValidateAllowlist checks that every allowlist entry is a known canonical model id that resolves to an enabled harness. It returns a joined error naming every unknown id and every id no enabled harness can run, or nil when the allowlist is fully covered.
Types ¶
type AgentResult ¶
type AgentResult struct {
FinalText string
SessionID string // the session id the CLI reports on its result event
NumTurns int
Usage *Usage // includes CostUSD from total_cost_usd; nil when unreported
IsError bool
Subtype string
Errors []string
}
AgentResult is the parsed terminal result of one agent run.
type BudgetReporter ¶ added in v0.8.0
type BudgetReporter interface {
// Exhausted reports whether stdout describes a run that hit its turn or
// token limit rather than failing.
Exhausted(stdout []byte) bool
}
BudgetReporter is the optional capability of distinguishing a run that exhausted its budget from one that malfunctioned. Both are runtime errors; only the first is the agent doing as it was told until the limit stopped it, and callers report them differently.
type Claude ¶
type Claude struct {
// contains filtered or unexported fields
}
Claude drives the `claude` CLI (Claude Code).
func (*Claude) Exhausted ¶ added in v0.8.0
Exhausted reports whether stdout describes a run that ran out of budget.
func (*Claude) ParseResult ¶
func (c *Claude) ParseResult(stdout []byte) (AgentResult, bool)
ParseResult reads the terminal result event from claude's stream-json output; see parseStreamResult.
func (*Claude) PromptSpec ¶
func (c *Claude) PromptSpec(ws string, req PromptRequest) runner.CommandSpec
PromptSpec builds the headless claude invocation for one prompted run. stream-json with --verbose emits one JSON event per line, which is what ParseResult and ScanUsage parse. Optional request fields append their flag only when set, in a stable order.
func (*Claude) RuntimeError ¶
RuntimeError classifies claude's output; see streamRuntimeError.
type Codex ¶ added in v0.6.0
type Codex struct {
// contains filtered or unexported fields
}
Codex drives the `codex` CLI (OpenAI Codex), the alternative harness for running the agent stages on OpenAI models.
func (*Codex) ParseResult ¶ added in v0.6.0
func (c *Codex) ParseResult(stdout []byte) (AgentResult, bool)
ParseResult digests the codex event stream: the final answer is the concatenated agent messages, the session id is the thread id, and the turn count and usage accumulate over completed turns. Output with no terminal turn event (plain text, crash mid-stream) returns the raw stdout as FinalText with ok=false, matching the interface contract.
func (*Codex) PromptSpec ¶ added in v0.6.0
func (c *Codex) PromptSpec(ws string, req PromptRequest) runner.CommandSpec
PromptSpec builds the headless codex invocation for one prompted run. `codex exec --json` emits one JSON event per line, which is what ParseResult and ScanUsage parse. Codex's own Landlock/Seatbelt sandbox is always disabled: patchy confines the agent at the pod layer (no network egress beyond the model API, no credentials, locked-down securityContext), where codex's kernel sandbox is redundant and unavailable anyway.
codex exec has no equivalents for MaxTurns or a pre-assigned SessionID, so those request fields do not map; budget and timeout enforcement stay with the runner, and the session id is read back from the stream's thread.started event instead. The neutral Sandbox posture is intentionally not rendered: codex's read-only/workspace-write modes are enforced by bubblewrap, which this image does not ship, and enabling it would mean relaxing the pod's RuntimeDefault seccomp profile — it gates the user-namespace and mount syscalls bwrap needs (verified on-cluster: userns clone is EPERM under RuntimeDefault, works under Unconfined). That is not a trade worth making to prevent writes in a pod that already has no egress, no credentials, a read-only rootfs, and a workspace discarded after the run — so --sandbox stays danger-full-access for every posture. AddDirs is likewise unmapped (codex 0.145 gained --add-dir; wiring it is a follow-up). SystemPromptAppend has no system-prompt channel either and is folded into the prompt so its instructions still reach the agent.
func (*Codex) RuntimeError ¶ added in v0.6.0
RuntimeError detects a codex run that produced no agent output (auth blocked, crash, failed turn) so it is reported distinctly from a run whose report merely needs judging. A run that emitted any agent message is usable regardless of exit code — a partial answer, not an error.
func (*Codex) ScanUsage ¶ added in v0.6.0
ScanUsage reads the output-token count off one live stream line. Codex reports usage only on turn.completed events, so the budget accumulator sums per-turn totals; within a turn the budget cannot fire early, but a multi-turn session over budget is still killed between turns.
type Copilot ¶ added in v0.7.0
type Copilot struct {
// contains filtered or unexported fields
}
Copilot drives GitHub's agentic Copilot CLI (`copilot -p`, the non-interactive runner — not the older `gh copilot` suggest/explain extension). It is the one harness that is not vendor-native: Copilot brokers both vendors' models, so it can run any model in the registry, and it is every model's fallback rather than any model's preferred harness.
Its credential is the reason for that ordering. claude and codex take a model API key scoped to inference; copilot authenticates with a GitHub token (COPILOT_GITHUB_TOKEN/GH_TOKEN/GITHUB_TOKEN), which is a forge credential in a pod whose entire isolation model rests on never holding one. PromptSpec therefore disables the built-in GitHub MCP server on every run so nothing in the agent can spend that token against the GitHub API, and the egress policy for a copilot pod admits only the Copilot endpoints. The token is still the broadest credential any agent pod carries, so the runner ships disabled and an operator opts into it deliberately.
func NewCopilot ¶ added in v0.7.0
func NewCopilot() *Copilot
NewCopilot returns the builtin Copilot harness.
func (*Copilot) ParseResult ¶ added in v0.7.0
func (c *Copilot) ParseResult(stdout []byte) (AgentResult, bool)
ParseResult digests the copilot event stream: the final answer is the concatenated assistant messages, the session id and exit code come off the terminal result event, and the turn count and usage accumulate over the stream. Output with no result event (an auth failure, which copilot reports as plain text before the stream ever starts, or a crash mid-stream) returns the raw stdout as FinalText with ok=false, matching the interface contract.
func (*Copilot) PromptSpec ¶ added in v0.7.0
func (c *Copilot) PromptSpec(ws string, req PromptRequest) runner.CommandSpec
PromptSpec builds the headless copilot invocation for one prompted run. --output-format json emits the session-event stream as JSONL, one object per line, which is what ParseResult and ScanUsage read; --allow-all-tools is what the CLI requires for a non-interactive run and --no-ask-user keeps the agent from stalling on a question nobody will answer.
Three flags exist for the pod rather than the prompt. --disable-builtin-mcps stops the bundled github-mcp-server from spending the GitHub token the CLI authenticated with (see the type comment). --no-remote and --no-remote-export keep the session off GitHub's web and mobile surfaces: patchy's sessions carry unremediated vulnerability detail, which must not leave the pod through a side channel the operator never opted into. --no-auto-update is belt and braces over the image's COPILOT_AUTO_UPDATE=false — the rootfs is read-only and the version is pinned.
MaxTurns does not map: copilot bounds work by AI credits and autopilot continues, neither of which is a turn ceiling, so the budget and timeout stay with the runner exactly as they do for codex. SystemPromptAppend has no system-prompt channel either and is folded into the prompt so its instructions still reach the agent.
func (*Copilot) RuntimeError ¶ added in v0.7.0
RuntimeError detects a copilot run that produced no agent output (auth blocked, crash, failed session) so it is reported distinctly from a run whose report merely needs judging. A run that emitted any assistant message is usable regardless of exit code — a partial answer, not an error.
The auth path is why the no-result case is an error rather than the "degenerate but usable" plain text the claude harness tolerates: copilot validates its token against the GitHub API before opening the stream and prints a plain-text failure, so stdout with no result event in it is a run that never started.
func (*Copilot) ScanUsage ¶ added in v0.7.0
ScanUsage reads the output-token count off one live stream line. Copilot reports usage per model call on assistant.usage, so the budget accumulator sees every call rather than only turn boundaries — a runaway single turn is killed mid-flight, which the codex stream cannot do.
type Fake ¶
type Fake struct {
// contains filtered or unexported fields
}
Fake is a stand-in harness for tests and the agent-runner's --fake mode: it replays a captured stream-json fixture through cat instead of invoking an agent, and parses it with the same stream-json helpers as Claude, so everything downstream of PromptSpec is exercised for real. Unix-only (it shells out to /bin/cat's argv convention); the real deployments it fakes run in Linux pods anyway.
func (*Fake) ParseResult ¶
func (f *Fake) ParseResult(stdout []byte) (AgentResult, bool)
ParseResult parses the fixture exactly as Claude parses live output.
func (*Fake) PromptSpec ¶
func (f *Fake) PromptSpec(ws string, req PromptRequest) runner.CommandSpec
PromptSpec ignores the request's prompt and flags and replays the fixture named by FakeFixtureEnv; ws and Env still land on the spec so runner-side behavior (workspace, environment) stays faithful.
func (*Fake) RuntimeError ¶
RuntimeError classifies the fixture exactly as Claude classifies live output.
type Harness ¶
type Harness interface {
ID() string // registry key, e.g. "claude"
Name() string // human name, e.g. "Claude Code"
CLI() []string // runner binary candidates, in preference order
EnvKeys() []string // credential env vars, in preference order
// PromptSpec builds the headless command for one prompted run in workspace ws.
PromptSpec(ws string, req PromptRequest) runner.CommandSpec
// ParseResult extracts the terminal result from the CLI's full stdout.
// ok is false when the output carried no terminal result event (plain
// text, crash mid-stream); the AgentResult then carries the raw stdout as
// FinalText and nothing else.
ParseResult(stdout []byte) (res AgentResult, ok bool)
// RuntimeError returns a short reason when the agent run did not complete
// usably (auth blocked, crash, budget exhausted, error envelope), or ""
// when it did. A run that reports an error is reported as one even if it
// also produced text: a partial answer from a run that died is not a
// result, and treating it as one hides the cause behind whatever the
// stage checks next.
RuntimeError(stdout []byte, exitCode int, timedOut bool) string
}
Harness is the required surface every agent CLI implements. A harness drives a model — it does not own one; the model a run targets is supplied as a harness-specific CLI id on the PromptRequest.
type PromptRequest ¶
type PromptRequest struct {
Prompt string
Model string // harness-specific model id
SystemPromptAppend string // appended to the CLI's system prompt when set
SessionID string // pre-assigned UUID → claude --session-id
MaxTurns int // agent-turn ceiling; 0 leaves the CLI default
Sandbox Sandbox // filesystem/exec posture; each harness renders it natively
AddDirs []string // extra directories the agent may access
Env []string // extras appended to os.Environ() by the runner
}
PromptRequest describes one prompted agent run, harness-agnostically; the harness maps it onto its CLI's flags.
type Sandbox ¶ added in v0.6.0
type Sandbox int
Sandbox is the filesystem/execution posture a run requires, declared harness-neutrally so agentrun states intent once and each harness renders it in its own vocabulary: claude as an allow/deny tool grammar, codex (once the pod's kernel sandbox is confirmed) as a --sandbox mode backed by mounted execpolicy rules. A harness that has no way to express a posture renders it as its default — the request is advisory, not a guarantee every CLI can keep.
const ( // SandboxDefault imposes no tool policy: the CLI's own defaults apply. It // is the zero value, so a bare PromptRequest stays unrestricted. SandboxDefault Sandbox = iota // SandboxReadOnly is the investigation posture: read the tree and write // only the report — no source edits, no mutating commands, no network tools. SandboxReadOnly // SandboxWorkspaceWrite is the remediation posture: edit the workspace // freely; network tools stay denied. SandboxWorkspaceWrite )
type Usage ¶
type Usage struct {
InputTokens *int // fresh (uncached) input only
CacheReadTokens *int
CacheCreationTokens *int
OutputTokens *int
CostUSD *float64
}
Usage is the harness-reported consumption of one agent session. Fields are nil where the CLI does not report them. InputTokens is the fresh (uncached) input only; cache reads and writes are reported separately so a multi-turn session's cheap cache traffic does not inflate the headline input figure.
type UsageScanner ¶
type UsageScanner interface {
// ScanUsage returns the output-token count reported by one stream line
// (claude: assistant events' message.usage.output_tokens), ok=false
// otherwise.
ScanUsage(line []byte) (outputTokens int, ok bool)
}
UsageScanner is the optional capability of reading token usage off the live output stream; it powers the caller's output-token budget kill switch.