providers

package
v0.31.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 19 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 providers holds one thin adapter per external coding-agent CLI.

A provider knows three things and nothing else:

  • how to build the argv for its CLI (Argv),
  • how the prompt reaches that CLI (PromptDelivery),
  • how to read a finished run's captured output back into a Result (Parse).

It does not spawn processes, touch the filesystem, or record state — that is internal/engine's job (G2.5). Keeping the parsers pure is what lets every one of them be pinned against captured CLI bytes in testdata/ (checklist rule 21).

Ported from orchestrator/dispatcher.py. Where this package and that file disagree, the Python is the specification and the divergence is written down both here and in docs/brainstorm/go-migration-notes.md.

Index

Constants

View Source
const (
	StepStart = "start"
	StepText  = "text"
	StepTool  = "tool"
	StepError = "error"
	StepEnd   = "end"
)

The kinds of Step. StepStart opens an attempt (claude's `init`, codex's `thread.started`; opencode has none), so a reader of a log that several attempts appended to can show the last one alone.

Variables

View Source
var ErrNotPorted = errors.New("provider not implemented yet")

ErrNotPorted marks a backend the Python orch supports but the Go rewrite has not reached yet. Distinguished from an unknown name so the engine can tell "you asked for something that does not exist" from "not yet", and so a half-finished rewrite fails loudly rather than silently doing nothing.

Empty since G3.4 ported the last four backends. Kept, with its test, because the distinction it draws is what the engine's error message depends on; a sixth backend added to model.Backend before its adapter exists lands here.

View Source
var GeminiStreamJSON = sync.OnceValue(probeGeminiStreamJSON)

GeminiStreamJSON is whether the installed gemini has `--output-format stream-json`, which reports a run's tokens (#543). Probed once per process from `gemini --help`: an older gemini rejects the flag, and a dispatch that cannot start is worse than one whose spend is estimated. A var so tests can pin it.

Functions

func CodexModelsCachePath added in v0.31.0

func CodexModelsCachePath() string

CodexModelsCachePath is the model catalog codex keeps in its home: $CODEX_HOME/models_cache.json, ~/.codex/models_cache.json when CODEX_HOME is unset. codex refreshes it from its server as it runs, so it carries the reasoning efforts each model takes now (#576), which the catalog bundled with the CLI can lag. Reading it is a file read: no exec, no network.

func CodexRolloutPattern added in v0.31.0

func CodexRolloutPattern(sessionsDir, threadID string) string

CodexRolloutPattern is the glob that finds a thread's rollout under sessionsDir, whatever day codex filed it under (the directory is the local date the session started, which need not be the date orch saw). "" for an id that is not a plain id.

func CodexSessionsDir added in v0.31.0

func CodexSessionsDir(getenv func(string) string) string

CodexSessionsDir is where codex keeps its rollouts: $CODEX_HOME/sessions, else ~/.codex/sessions. "" when neither variable is set.

func HeadlessEnv

func HeadlessEnv(b model.Backend) []string

HeadlessEnv is the environment a backend's CLI needs, on top of the operator's, to run unattended in a task's worktree. Only gemini needs any.

gemini 0.59 refuses a directory it was not told to trust (exit 55, testdata/gemini/0.59.0/untrusted-directory.log), and every dispatch runs in a fresh worktree beside the repo, never inside a folder the operator trusted. GEMINI_CLI_TRUST_WORKSPACE=true lifts that gate the way claude's acceptEdits and codex's approval flags already open the same door; it is an environment variable rather than `--skip-trust` because a gemini that predates it ignores the variable but would reject the flag.

func IsVersionDrift

func IsVersionDrift(res Result) bool

IsVersionDrift reports whether res looks like the backend rejected the cli_model, i.e. whether the reap loop should retry with RouteEntry.FallbackCLIModel. Port of is_version_drift_error.

func NewSessionID

func NewSessionID() string

NewSessionID mints the per-dispatch session id claude correlates retries by.

Python generates this inside ClaudeBackend.build_cmd and then digs it back out of the argv with `_extract_session_id`. Go moves generation to the caller so Argv stays pure and testable; the engine calls this once per dispatch and puts the result in Request.SessionID.

func ParseCodexEfforts added in v0.31.0

func ParseCodexEfforts(raw []byte) map[string][]string

ParseCodexEfforts reads a codex model catalog — models_cache.json, or the same `models` array `codex debug models` prints — into each model slug's supported reasoning efforts, in the catalog's order. A catalog it cannot read, or one with no efforts at all, is nil: the caller falls back to the levels every model takes rather than trusting a partial answer.

Types

type AgyProvider

type AgyProvider struct{}

AgyProvider adapts the `agy` CLI (Antigravity). Port of dispatcher.py's AgyBackend.

agy emits a single JSON object on stdout under `--output-format json`, not JSONL. It reports token counts but no USD figure, so cost is always zero and the dashboard's pricing.yaml estimates spend from the tokens.

func (AgyProvider) Argv

func (AgyProvider) Argv(req Request) []string

Argv returns the argv for `agy --output-format json [--agent <a>] --model <m> [--effort <e>] --print <prompt>`.

`--agent` is passed only when the route names one. Issue #88 sent `--agent executor` on every dispatch, because agy 1.2's default persona was a coordinator that delegated instead of executing. agy 1.4 has no `executor` ("unknown agent \"executor\" (no custom agents are available)", testdata/agy/1.4.2/unknown-agent.json) and its default runs the prompt in-process, edits included, so a hard-coded agent failed every dispatch (#382).

`--print` MUST stay last: its value is the prompt, parsed positionally, so any flag after it is swallowed into the prompt text.

`--print-timeout` is deliberately absent — the engine supervises the child with its own SIGTERM/SIGKILL deadline, and a second timeout owned by the CLI would race it.

`--effort` is emitted only when the route sets it (issue #87): base-name Gemini models require an effort tier, while suffix-baked ones (`gemini-3.7-flash-high`) reject it.

func (AgyProvider) ExtractCost

func (AgyProvider) ExtractCost(output []byte) (cost float64, tokensIn, tokensOut int)

ExtractCost reports the token counts in a captured agy log; the USD figure is always zero because agy does not price the turn.

func (AgyProvider) ModelsArgv

func (AgyProvider) ModelsArgv() []string

ModelsArgv is `agy models`.

func (AgyProvider) Name

func (AgyProvider) Name() model.Backend

func (AgyProvider) Parse

func (AgyProvider) Parse(exitCode int, output []byte) Result

Parse reads agy's JSON envelope. A run succeeds only when the process exited 0 AND the envelope says `status: "SUCCESS"`.

func (AgyProvider) ParseModels

func (AgyProvider) ParseModels(out []byte) []string

ParseModels reads `agy models`: `id<TAB>display name` per line.

func (AgyProvider) PromptDelivery

func (AgyProvider) PromptDelivery() PromptDelivery

PromptDelivery is PromptArg: the prompt is the value of `--print`.

type ClaudeProvider

type ClaudeProvider struct{}

ClaudeProvider adapts the `claude` CLI. Port of dispatcher.py's ClaudeBackend.

The CLI streams one JSON event per line under `--output-format stream-json` — what the agent says and every tool it calls, as it happens, which is what lets the dashboard follow a running task — and ends with the envelope it used to print alone under `--output-format json`: `type: "result"`, same fields. A run counts as a success only when the process exited 0 AND the envelope says `is_error: false` AND `subtype: "success"` — all three, because 2.1.269 will happily exit non-zero with `subtype: "success"` on an API error (see testdata/claude/2.1.269/unrecognized-model.log).

func (ClaudeProvider) Argv

func (ClaudeProvider) Argv(req Request) []string

Argv returns the argv for `claude -p --output-format stream-json --verbose ...`.

The order is the Python's, flag for flag, except the output format: Python asked for `json`, which writes nothing until the run ends, so a dispatch could not be followed while it ran. `stream-json` requires `--verbose` under `-p`. `--add-dir .` is the literal dot: the engine passes the real directory as the child's working directory, and the flag grants explicit write access to it as defence in depth.

Two departures from build_cmd, both because Argv is pure:

  • The session id comes from the Request instead of being minted here and dug back out of the argv afterwards. An empty SessionID omits the flag and lets the CLI pick its own, so a caller that forgets loses retry correlation rather than emitting a broken `--session-id ""`.
  • The budget comes from the Request instead of a config dict stored on the adapter. Python looks for `claude_max_budget_usd` and then `budget.per_dispatch_usd`; resolving which one wins is the engine's job now, and this package never sees internal/config.

func (ClaudeProvider) Distribution

func (ClaudeProvider) Distribution() Distribution

Distribution is @anthropic-ai/claude-code; the native install updates itself.

func (ClaudeProvider) ExtractCost

func (c ClaudeProvider) ExtractCost(output []byte) (cost float64, tokensIn, tokensOut int)

ExtractCost reports the spend and token counts in a captured claude log, without deciding whether the run succeeded. Port of extract_cost, kept exported because the engine's budget gate reads a log it did not parse.

func (ClaudeProvider) Name

func (ClaudeProvider) Name() model.Backend

func (ClaudeProvider) Parse

func (c ClaudeProvider) Parse(exitCode int, output []byte) Result

Parse reads the JSON envelope out of a finished run's captured output.

func (ClaudeProvider) PromptDelivery

func (ClaudeProvider) PromptDelivery() PromptDelivery

type CodexProvider

type CodexProvider struct{}

CodexProvider adapts the `codex` CLI. Port of dispatcher.py's CodexBackend.

codex >= 0.148 streams JSONL events to **stdout** under `--json`; the `-o` file holds only the last message, in markdown. So Parse reads the captured log, not the artefact file — dispatcher.py says the same in a comment above CodexBackend.wait_result, and the G2.4 brief's "`exec --json -o` with JSONL" describes the older schema.

A run succeeds when the process exited 0, no event is an error, and the last `turn.*` event is `turn.completed`. The pre-0.148 schema (`task_complete`, `step_finish`) is gone and is not accepted.

func (CodexProvider) Argv

func (CodexProvider) Argv(req Request) []string

Argv returns the argv for `codex exec --skip-git-repo-check --json ...`.

`-C .` is the literal dot, as with claude's `--add-dir`: the engine sets the child's working directory.

`-s` / `--sandbox` is deliberately absent. `--approve-for-me` already implies the workspace-write sandbox, and codex >= 0.148 rejects the two together ("cannot be used with --approve-for-me").

Python writes a `__OUTPUT__<task id>.codex.json` placeholder here that its spawn step rewrites in place. Go takes the resolved path in the Request instead; DefaultOutputPath builds the value Python's spawn would have produced.

func (CodexProvider) DefaultOutputPath

func (CodexProvider) DefaultOutputPath(logsDir, taskID string) string

DefaultOutputPath is where codex's `-o` artefact goes: beside the dispatch log, one file per dispatch. logsDir is the engine's `state/logs`.

func (CodexProvider) Distribution

func (CodexProvider) Distribution() Distribution

Distribution is @openai/codex.

func (CodexProvider) ExtractCost

func (CodexProvider) ExtractCost(output []byte) (cost float64, tokensIn, tokensOut int)

ExtractCost reports the token counts in a captured codex log. Port of extract_cost; see sumCodexUsage on why the USD figure is always zero.

func (CodexProvider) ModelsArgv

func (CodexProvider) ModelsArgv() []string

ModelsArgv is `codex debug models`, codex's model catalog as JSON. It reads no network; the catalog ships with the CLI.

func (CodexProvider) Name

func (CodexProvider) Name() model.Backend

func (CodexProvider) Parse

func (CodexProvider) Parse(exitCode int, output []byte) Result

Parse reads the JSONL event stream from a finished run's captured output.

func (CodexProvider) ParseModels

func (CodexProvider) ParseModels(out []byte) []string

ParseModels reads the catalog's slugs that codex shows (visibility "list"); the hidden ones are codex's own (its reviewer, reserved slugs).

func (CodexProvider) PromptDelivery

func (CodexProvider) PromptDelivery() PromptDelivery

type CodexSession added in v0.31.0

type CodexSession struct {
	// Quota is the newest token_count's rate_limits: the plan's 5-hour
	// (primary) and weekly (secondary) windows, which count every use of the
	// account, not only orch's. nil when the rollout reported none.
	Quota []QuotaWindow
	// Model and Effort are what the last turn ran with, from its
	// turn_context: the model codex resolved and the reasoning effort,
	// "" when codex recorded none (no effort was set). exec --json names
	// neither (#580).
	Model, Effort string
}

CodexSession is what codex wrote about one run in its session rollout.

func ParseCodexRollout added in v0.31.0

func ParseCodexRollout(b []byte) CodexSession

ParseCodexRollout reads a rollout's JSONL. Lines that do not parse are skipped, as in the exec log: codex may still be appending to it.

type Distributed

type Distributed interface {
	Distribution() Distribution
}

Distributed is the optional half of a Provider whose CLI has a release feed orch can read. agy and muse have none: their latest version is unknown, and unknown is never a warning.

type Distribution

type Distribution struct {
	// NPM is the package on the npm registry: where the latest version is
	// read, and what `npm install -g` updates.
	NPM string
	// Brew is the Homebrew formula (or "--cask <name>").
	Brew string
	// Self is the CLI's own update command, for the copy its install script
	// puts under a path containing SelfPath; "" when it has none.
	Self     string
	SelfPath string
}

Distribution is where a CLI's releases are published and how each way of installing it is updated (#448). orch only prints these; the operator runs them.

type Failure

type Failure string

Failure is the coarse category of a failed dispatch, and is what the reap loop's retry policy keys on. Ported from dispatcher.py's FailureClass; the string values are the same lower-snake ones, because they are written into event rows and read by the dashboard.

const (
	FailureIDSpoof      Failure = "id_spoof"      // agent called task-finish.sh with the wrong id
	FailureTimeout      Failure = "timeout"       // exceeded estimateHours * multiplier
	FailureRateLimit    Failure = "rate_limit"    // 429 / "rate limit" / "too many requests"
	FailurePermission   Failure = "permission"    // auth denied — retrying will not help
	FailureBudget       Failure = "budget"        // spend cap hit — retrying burns more
	FailureVersionDrift Failure = "version_drift" // backend rejected the requested cli_model
	FailureTransient    Failure = "transient"     // 5xx / UnknownError / err_xxxxxxxx
	FailureParser       Failure = "parser"        // our own Parse could not read the output
	FailureOther        Failure = "other"         // unknown — conservative default, retry once
)

func Classify

func Classify(res Result) Failure

Classify maps a failed Result to a Failure. Pure: no I/O, no mutation.

Order matters and is the Python's order. Checks keyed on markers orch sets itself (ErrorMessage) run first, then specific CLI-output markers, then generic ones, then the conservative default. Callers pass any Result; successful ones are not special-cased, because the reap loop only asks about failures.

Divergence from the G2.4 brief, which sketched this as a per-provider `Classify(exit int, stderr []byte)` method: in Python it is one module-level function shared by every backend, and it reads ErrorMessage and the stdout tail, not just stderr. Splitting it per provider would invite five copies that drift, and dropping ErrorMessage would break the two highest-priority classes outright — both ID_SPOOF and TIMEOUT are set by orch, never printed by a CLI.

type GeminiProvider

type GeminiProvider struct{}

GeminiProvider adapts the `gemini` CLI. Port of dispatcher.py's GeminiBackend.

A gemini with `--output-format stream-json` (0.59 has it) is run with it when the engine's probe finds it, and reports its real tokens (#543). An older one prints plain text with no usage at all: its tokens are zero and Estimated, and the engine estimates them from the prompt and output size (engine.spendRow). Either way pricing.yaml prices the tokens; gemini reports no dollar figure.

func (GeminiProvider) Argv

func (GeminiProvider) Argv(req Request) []string

Argv returns the argv for `gemini -p <prompt> --model <model>`.

There is no working-directory flag. Python sets `PWD` in the child's environment on top of the usual working directory; that is the engine's half of the contract, not the argv's.

func (GeminiProvider) Distribution

func (GeminiProvider) Distribution() Distribution

Distribution is @google/gemini-cli.

func (GeminiProvider) ExtractCost

func (GeminiProvider) ExtractCost(output []byte) (cost float64, tokensIn, tokensOut int)

ExtractCost reports the token counts of a stream-json run; the USD figure is always zero, since gemini reports none and pricing.yaml prices the tokens.

func (GeminiProvider) Name

func (GeminiProvider) Name() model.Backend

func (GeminiProvider) Parse

func (GeminiProvider) Parse(exitCode int, output []byte) Result

Parse reports success purely from the exit code, and quotes the last non-empty line as the failure reason.

That last line is what carries the diagnosis in practice: an unauthenticated gemini 0.59.0 exits 41 with a single line naming the three environment variables it would accept (testdata/gemini/0.59.0/auth-error.log).

func (GeminiProvider) PromptDelivery

func (GeminiProvider) PromptDelivery() PromptDelivery

PromptDelivery is PromptArg: gemini takes the prompt as the value of `-p`, and the engine closes the child's stdin.

type ModelLister

type ModelLister interface {
	// ModelsArgv is the argv that prints the model list. It spends nothing
	// and opens no session.
	ModelsArgv() []string
	// ParseModels returns the model ids in out, in the CLI's order, as a
	// route's cli_model names them. Output it cannot read gives none.
	ParseModels(out []byte) []string
}

ModelLister is the optional half of a Provider whose CLI can say which models it runs now (#397): opencode, agy and codex. claude, gemini and muse have no such command, and their packaged routes stay as they are.

Pure like the rest of the package: ModelsArgv is what to exec, ParseModels reads its stdout. Running it — with a timeout, on PATH — is the caller's.

type MuseProvider

type MuseProvider struct{}

MuseProvider adapts the `muse` CLI (Muse Code, #395).

`muse exec --json` streams JSONL envelopes keyed by `payload_type` rather than `type`. The run's verdict is the last `run.terminal.*` envelope — a background workflow can wake the session and end it more than once — whose payload says `terminal: "completed"` or `"failed"` with a `reason`, and carries the final answer in `text`. Usage and the subscription allowance come in `run.usage`. muse reports no USD figure, so pricing.yaml estimates spend from the tokens, as for agy.

func (MuseProvider) Argv

func (MuseProvider) Argv(req Request) []string

Argv returns the argv for `muse exec --json --prompt-file <p> --workspace <cwd> --worktree off ...`.

orch owns the worktree, hence `--worktree off`. Headless, the default approval mode hangs on the first shell call, so approvals are off and the agent may not ask the user anything. `--disable-sandbox` because muse's bwrap sandbox fails where unprivileged user namespaces are restricted (Ubuntu's apparmor_restrict_unprivileged_userns, testdata sandbox-denied.jsonl), and would keep the agent from writing the project's orch.db outside the workspace even where it works.

func (MuseProvider) Name

func (MuseProvider) Name() model.Backend

func (MuseProvider) Parse

func (MuseProvider) Parse(exitCode int, output []byte) Result

Parse reads muse's JSONL stream. A run succeeds when the process exited 0 and the last run_terminal says "completed".

func (MuseProvider) PromptDelivery

func (MuseProvider) PromptDelivery() PromptDelivery

PromptDelivery is PromptFile: muse 1.4.12 reads no prompt from stdin ("missing prompt") and wants a regular file for --prompt-file, so /dev/stdin is refused too.

type OpencodeProvider

type OpencodeProvider struct{}

OpencodeProvider adapts the `opencode` CLI. Port of dispatcher.py's OpencodeBackend.

opencode streams JSONL events to stdout under `--format json`. A run succeeds when the process exited 0, no event is a `type:"error"`, and the last `step_finish` carries a reason outside opencodeFailureReasons — any other reason ("stop", "length", provider-specific values) is a completed run.

func (OpencodeProvider) Argv

func (OpencodeProvider) Argv(req Request) []string

Argv returns the argv for `opencode run --format json --auto --dir <abs>`.

`--dir` takes Request.Cwd rather than the literal dot claude and codex use: opencode resolves file writes against $PWD or its own project detection and ignores the child's working directory, so the value has to be absolute.

Route.CLIModel goes in verbatim, prefix included. Router entries embed the provider prefix themselves (`google/gemini-2.5-pro`); there is no separate provider field to join. See the note in docs/brainstorm/go-migration-notes/sonnet-2.md about that prefix not resolving against opencode 1.18.30 on an unauthenticated machine.

func (OpencodeProvider) Distribution

func (OpencodeProvider) Distribution() Distribution

Distribution is opencode-ai; its install script's copy has `opencode upgrade`.

func (OpencodeProvider) ExtractCost

func (OpencodeProvider) ExtractCost(output []byte) (cost float64, tokensIn, tokensOut int)

ExtractCost reports cost and token counts in a captured opencode log.

func (OpencodeProvider) ModelsArgv

func (OpencodeProvider) ModelsArgv() []string

ModelsArgv is `opencode models`.

func (OpencodeProvider) Name

func (OpencodeProvider) Parse

func (OpencodeProvider) Parse(exitCode int, output []byte) Result

Parse reads the JSONL event stream from a finished run's captured output.

func (OpencodeProvider) ParseModels

func (OpencodeProvider) ParseModels(out []byte) []string

ParseModels reads `opencode models`: one `provider/model` per line.

func (OpencodeProvider) PromptDelivery

func (OpencodeProvider) PromptDelivery() PromptDelivery

type PromptDelivery

type PromptDelivery int

PromptDelivery says how a provider's CLI wants the prompt.

const (
	// PromptStdin pipes the prompt file's bytes into the child's stdin.
	// claude, codex and opencode all take the prompt this way.
	PromptStdin PromptDelivery = iota
	// PromptArg passes the prompt text as a CLI argument. gemini and agy
	// need this; neither is ported yet.
	PromptArg
	// PromptFile hands the CLI the path of the prompt file the engine wrote,
	// in Request.PromptPath. muse needs this: it reads no prompt from stdin.
	PromptFile
)

type Provider

type Provider interface {
	// Name is the model_router.yaml `backend:` literal this adapter serves.
	Name() model.Backend

	// PromptDelivery says whether Argv expects Request.PromptText to be set.
	PromptDelivery() PromptDelivery

	// Argv returns the argv to exec. Pure: same Request, same argv. Never
	// contains shell metacharacters — the engine execs directly, no shell.
	Argv(req Request) []string

	// Parse turns a finished run's exit code and captured output into a
	// Result. Pure, total, and never returns an error: unreadable output is
	// itself a Result, carrying the ErrorMessage that Classify maps to
	// FailureParser. Cost and tokens are still extracted from output that
	// failed, because a failed run has usually already been paid for.
	Parse(exitCode int, output []byte) Result
}

Provider is the adapter contract. One implementation per external CLI.

The G2.4 brief sketched this as `Argv(prompt, route, budgetUSD) []string` and `Parse(stdout []byte) (Result, error)`; both changed to match what dispatcher.py actually does. See Request (argv inputs are not just a prompt, a route and a budget) and Parse (the exit code decides success, and a parse failure is a Result, not an error).

func Get

func Get(name model.Backend) (Provider, error)

Get returns the adapter for a router entry's backend.

Python's get_backend raises ValueError for an unknown name; the split between ErrNotPorted and "unknown backend" is new, and exists only while the rewrite is mid-flight.

type QuotaWindow

type QuotaWindow struct {
	// Window is the provider's own name for it ("five_hour", "seven_day").
	Window string `json:"window"`
	// Utilization is the used fraction, 0 to 1.
	Utilization float64 `json:"utilization"`
	// ResetsAt is when the window resets, Unix seconds; 0 when not given.
	ResetsAt int64 `json:"resets_at"`
}

QuotaWindow is one usage window of a provider's subscription, as the provider reported it: how much of it is used and when it resets.

type Request

type Request struct {
	// TaskID is the id of the task being dispatched. Only used to name
	// per-dispatch artefacts; no provider puts it in the argv today.
	TaskID string

	// Route is the resolved model_router.yaml entry for this task.
	Route model.RouteEntry

	// Cwd is the absolute directory the CLI runs in. Providers that take an
	// explicit directory flag read it from here; the engine also passes it
	// to the child process itself.
	Cwd string

	// OutputPath is where a provider that writes a separate artefact file
	// should point its flag (codex's `-o`). The engine builds it with the
	// provider's own DefaultOutputPath helper. Empty means "no artefact".
	OutputPath string

	// PromptText is only read by providers whose PromptDelivery is
	// PromptArg. Providers on PromptStdin ignore it.
	PromptText string

	// PromptPath is the rendered prompt file. Only read by providers whose
	// PromptDelivery is PromptFile; the engine fills it from the dispatch.
	PromptPath string

	// SessionID correlates retries in the CLI's own session store. Only
	// claude takes one. nil means "let the CLI pick"; see ClaudeProvider.Argv.
	SessionID string

	// BudgetUSD is the per-dispatch spend cap to hand the CLI, when the
	// operator configured one. nil omits the flag entirely.
	BudgetUSD *float64

	// Settings is a claude settings JSON to load on top of the ones the CLI
	// finds itself — the project root's, for a worktree that lacks them
	// because git ignores .claude/ (#231). Only claude reads it; empty omits
	// the flag.
	Settings string

	// WritableDirs are directories outside Cwd the agent must be able to
	// write: the one holding the project's orch.db, so a sandboxed CLI can
	// report its task done or blocked (#387). Only codex sandboxes writes
	// to its workspace; it gets one --add-dir per entry.
	WritableDirs []string

	// StreamJSON asks the CLI for its structured output. Only gemini reads
	// it (`--output-format stream-json`, #543): a gemini that predates the
	// flag rejects it, so the engine sets this from a probe of the installed
	// CLI (GeminiStreamJSON) rather than always.
	StreamJSON bool
}

Request is everything a provider needs to build an argv for one dispatch.

Python's `Backend.build_cmd(task, route)` takes the whole Task and reaches into module state for the rest (ClaudeBackend stores a config dict on the instance; CodexBackend writes a `__OUTPUT__` placeholder into the argv that `spawn` rewrites afterwards). A struct of plain values instead keeps Argv pure and keeps this package off internal/config (checklist rule 14, and the stricter rule in the G2.4 brief: providers import model only).

type Result

type Result struct {
	ExitCode int
	Success  bool
	CostUSD  float64
	// TokensIn counts every input token, cache reads and writes included;
	// CacheReadTokens and CacheCreationTokens say how much of it was which.
	TokensIn            int
	CacheReadTokens     int
	CacheCreationTokens int
	// TokensOut counts every output token, reasoning included;
	// ReasoningTokens says how much of it was reasoning, when the CLI says
	// (codex, opencode, agy; #417).
	TokensOut       int
	ReasoningTokens int

	// Stdout is the captured log — stdout and stderr merged, because that is
	// how the engine spawns children (dispatcher.py: `stderr=STDOUT`). Claude's
	// is the log minus its stream-json events, which are the agent's work
	// rather than claude's verdict (see withoutStreamEvents).
	Stdout string
	// Stderr is populated only when the engine captures stderr separately.
	// Both Python and the providers here leave it empty; Classify still
	// reads it so the engine can fill it in without touching this package.
	Stderr string

	// Text is the model's final answer, as the CLI reports it: claude's
	// `result`, codex's last `agent_message`, opencode's text parts of the
	// last message, agy's `response`, and gemini's assistant messages (its
	// whole stdout on success when it ran without stream-json: plain text,
	// so nothing separates the answer from the CLI's own notices). Empty when the CLI reported none. The engine does
	// not read it; `orch ci review` parses a verdict out of it.
	Text string

	// ErrorMessage is the operator-facing reason the dispatch failed, and is
	// the first thing Classify looks at. Python types it `str | None`; the
	// empty string is the None.
	ErrorMessage string

	// Estimated marks a run whose backend reported activity but no token
	// usage, so downstream spend rows can tell missing telemetry apart from
	// genuinely zero-cost work. opencode sets it when a run reported no
	// numbers (Issue #8); gemini does when it ran without stream-json and
	// printed no usage at all (#543). The engine then estimates the tokens
	// from the prompt and output size (engine.spendRow).
	Estimated bool

	// PermissionDenials are the tool calls the CLI refused without asking,
	// as `Tool` or `Bash(command)`. A run can succeed with some; one that
	// could do nothing looks the same from its exit code (#231). claude and
	// agy report them (agy as its denied_actions' display names, #383).
	PermissionDenials []string

	// Quota is the subscription usage the CLI reported during the run, newest
	// report wins: claude's rate_limit_event carries its 5-hour and weekly
	// windows. nil when the CLI says nothing — every other backend today.
	Quota []QuotaWindow

	// QuotaExhausted is true when the CLI reported its subscription out of
	// quota during the run (claude's rate_limit_event), and QuotaResetsAt is
	// when that ends, Unix seconds, 0 when not given. The engine fails a
	// route with `failover` over to its next provider on it (#439).
	QuotaExhausted bool
	QuotaResetsAt  int64

	// SessionID is the CLI's own id for the run, when its output names one:
	// codex's thread.started thread_id, which names the session rollout
	// file the engine reads the quota from afterwards (#577). "" when the
	// output carries none.
	SessionID string

	// EffectiveModel, EffectiveEffort and EffectiveServiceTier are what the
	// CLI says it actually ran, which may differ from the route orch asked
	// for (#580): codex's session rollout names the model and the effort
	// (the engine fills those in), and its exec log says when it dropped a
	// service tier the model does not offer ("default" then). "" is
	// unknown, never the declared value copied over.
	EffectiveModel, EffectiveEffort, EffectiveServiceTier string
}

Result is the terminal state of one dispatch. Ported from dispatcher.py's DispatchResult.

Two of Python's fields are deliberately absent: `files_touched` (the dispatcher leaves it empty and the main loop fills it from `git diff`, so it belongs to the engine, not here) and `should_retry_with_fallback` (the reap loop derives it from Classify, so storing it invites the two disagreeing).

type Step

type Step struct {
	Kind string `json:"kind"`
	// Tool is the tool's name in the CLI's own words (claude's `Read`,
	// opencode's `read`, codex's `shell`); empty unless Kind is StepTool.
	Tool string `json:"tool,omitempty"`
	// Detail is what the step was about — the file, the command, the text —
	// cut to maxStepDetail runes.
	Detail string `json:"detail,omitempty"`
}

A Step is one thing an agent did, read off one line of its streamed log: what the dashboard shows under a running task. It is a reading aid, not a record — nothing decides anything on it, so a line it does not recognise is simply no step.

func ActivityOf

func ActivityOf(line []byte) []Step

ActivityOf reads one line of a dispatch log — claude's stream-json, codex's `--json`, opencode's `--format json` — into the steps it records. The formats do not share a `type` value that means different things, so the line says which CLI wrote it; gemini and agy write one object at the end and yield nothing until then. A line that is not a JSON object yields nothing: stderr, or the partial line a tail started in.

Jump to

Keyboard shortcuts

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