harness

package
v0.9.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 12, 2026 License: MIT Imports: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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 Available

func Available(h Harness) (path string, ok bool)

Available finds the first of the harness's runner binaries on PATH.

func EnabledSet added in v0.6.0

func EnabledSet(ids []string) map[string]bool

EnabledSet turns a list of enabled harness ids into a lookup set.

func ResolveModel added in v0.6.0

func ResolveModel(m model.Model, enabled map[string]bool) (harnessID, cliModelID string, ok bool)

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

func ValidateAllowlist(models []model.Model, allowlist []string, enabled map[string]bool) error

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 NewClaude

func NewClaude() *Claude

NewClaude returns the builtin Claude Code harness.

func (Claude) CLI

func (b Claude) CLI() []string

func (Claude) EnvKeys

func (b Claude) EnvKeys() []string

func (*Claude) Exhausted added in v0.8.0

func (c *Claude) Exhausted(stdout []byte) bool

Exhausted reports whether stdout describes a run that ran out of budget.

func (Claude) ID

func (b Claude) ID() string

func (Claude) Name

func (b Claude) Name() string

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

func (c *Claude) RuntimeError(stdout []byte, exitCode int, timedOut bool) string

RuntimeError classifies claude's output; see streamRuntimeError.

func (*Claude) ScanTurns added in v0.8.2

func (c *Claude) ScanTurns(line []byte) []transcript.Turn

ScanTurns projects one stream-json line onto the transcript vocabulary; see scanStreamTurns.

func (*Claude) ScanUsage

func (c *Claude) ScanUsage(line []byte) (int, bool)

ScanUsage reads the output-token count off one live stream line; see scanStreamUsage.

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 NewCodex added in v0.6.0

func NewCodex() *Codex

NewCodex returns the builtin Codex harness.

func (Codex) CLI added in v0.6.0

func (b Codex) CLI() []string

func (Codex) EnvKeys added in v0.6.0

func (b Codex) EnvKeys() []string

func (Codex) ID added in v0.6.0

func (b Codex) ID() string

func (Codex) Name added in v0.6.0

func (b Codex) Name() string

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

func (c *Codex) RuntimeError(stdout []byte, exitCode int, timedOut bool) string

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) ScanTurns added in v0.8.2

func (c *Codex) ScanTurns(line []byte) []transcript.Turn

ScanTurns projects one `codex exec --json` line onto the transcript vocabulary. Codex reports items only on completion, so a tool call and its output arrive together and are split back into the call and result turns the rest of the pipeline expects.

func (*Codex) ScanUsage added in v0.6.0

func (c *Codex) ScanUsage(line []byte) (int, bool)

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) CLI added in v0.7.0

func (b Copilot) CLI() []string

func (Copilot) EnvKeys added in v0.7.0

func (b Copilot) EnvKeys() []string

func (Copilot) ID added in v0.7.0

func (b Copilot) ID() string

func (Copilot) Name added in v0.7.0

func (b Copilot) Name() string

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

func (c *Copilot) RuntimeError(stdout []byte, exitCode int, timedOut bool) string

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) ScanTurns added in v0.8.2

func (c *Copilot) ScanTurns(line []byte) []transcript.Turn

ScanTurns projects one copilot event line onto the transcript vocabulary.

Messages only, deliberately: copilot ships disabled (see the Copilot type comment), and its tool-invocation event names are not pinned anywhere this repo can verify. Guessing at them would produce a transcript that silently omits or mislabels what the agent ran, which is worse than one that plainly carries only the prose. Widen this — with a captured stream to check against — when the copilot runner is enabled.

func (*Copilot) ScanUsage added in v0.7.0

func (c *Copilot) ScanUsage(line []byte) (int, bool)

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 NewFake

func NewFake() *Fake

NewFake returns the builtin fake harness.

func (Fake) CLI

func (b Fake) CLI() []string

func (Fake) EnvKeys

func (b Fake) EnvKeys() []string

func (Fake) ID

func (b Fake) ID() string

func (Fake) Name

func (b Fake) Name() string

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

func (f *Fake) RuntimeError(stdout []byte, exitCode int, timedOut bool) string

RuntimeError classifies the fixture exactly as Claude classifies live output.

func (*Fake) ScanTurns added in v0.8.2

func (f *Fake) ScanTurns(line []byte) []transcript.Turn

ScanTurns projects fixture lines exactly as Claude projects live ones, so a replayed fixture produces a real transcript end to end.

func (*Fake) ScanUsage

func (f *Fake) ScanUsage(line []byte) (int, bool)

ScanUsage scans fixture lines exactly as Claude scans live ones.

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.

func All

func All() []Harness

All returns the builtin harness set.

func ByID

func ByID(id string) (Harness, bool)

ByID returns the builtin harness with the given id, if any.

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 TurnScanner added in v0.8.2

type TurnScanner interface {
	// ScanTurns returns the turns one stream line carries, in order, or nil
	// for a line that carries none. One line can yield several: a single
	// claude assistant event may hold text, thinking, and tool-use blocks.
	//
	// It reports raw text; bounding, redaction, and sequencing belong to the
	// caller's transcript.Recorder.
	ScanTurns(line []byte) []transcript.Turn
}

TurnScanner is the optional capability of projecting the live output stream onto the harness-neutral conversation vocabulary; it powers the transcript the status page replays. A harness without it simply produces no transcript.

Each CLI's stream is shaped differently — claude nests content blocks under an assistant message, codex flattens them into typed items, copilot emits one event per message — so normalising here is the only place the difference can be absorbed once.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL