runtime

package
v0.54.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 38 Imported by: 0

Documentation

Index

Constants

View Source
const (

	// PiInferenceGatewayConfigFile is the file the extension reads from
	// $PI_CODING_AGENT_DIR.
	PiInferenceGatewayConfigFile = "inference-gateway.json"

	// MaxPiGatewayModelsFileBytes bounds a committed models_file.
	MaxPiGatewayModelsFileBytes = 256 << 10
)

Inference gateway route on pi (ADR 0137). The pi-inference-gateway extension registers provider "gateway"; the runner renders its config file, inference-gateway.json, from the inference.gateway block, so only the model list comes from the repository. The rendered file alone does not make the endpoint and auth header runner-owned: the extension merges its INFERENCE_GATEWAY_* environment over the file (the env wins for authHeader and defaultApi, and can add models or rename the provider), so the runner must also control that environment when it launches pi.

View Source
const DefaultAgentPrompt = "Run the agent task"

DefaultAgentPrompt is the prompt handed to the agent CLI when RunParams does not override it. It is deliberately content-free: the actual task comes from the agent definition selected with --agent, so every runtime adapter can pass the same string.

View Source
const DefaultDebugLogName = "agent-debug.log"

DefaultDebugLogName is the local debug-log filename for runtimes that do not implement DebugLogNamer.

View Source
const EnvDataTrustedPathVar = envDataTrustedPathVar

EnvDataTrustedPathVar names the read-only trusted PATH EnvDataLoad records before .env is read. A probe runs its own tools with it, so a PATH that .env sets cannot choose them.

View Source
const (
	// PiInferenceGatewayLocalConfigFile is the extension's local overlay.
	// It is merged over inference-gateway.json and can replace baseUrl and
	// headers, so a run with a block refuses it.
	PiInferenceGatewayLocalConfigFile = "inference-gateway.local.json"
)

Variables

This section is empty.

Functions

func AgentDefinitionModel added in v0.40.0

func AgentDefinitionModel(path string) string

AgentDefinitionModel reads the frontmatter `model:` from a Claude-style agent definition. It returns "" when the file has no frontmatter, names no model, or cannot be read or parsed: the caller then falls back to the runtime default, which is what the run does today when nothing names a model. A definition that cannot be read at all fails the run later, in Bootstrap, with a better message than this function could give.

func BuiltinAliasModel added in v0.48.0

func BuiltinAliasModel(runtimeName, model string, configAliases map[string]string) string

BuiltinAliasModel returns the model id runtimeName runs model on through its built-in alias table, or "" when it has none: model is not a bare alias that runtime maps, or the repo retargets it with models.aliases (the plan block shows that remap itself). Claude Code maps the aliases in claudeAliasDefaults (fable stays on Claude Code's own table); pi maps those in piModelAliases.

func DebugLogNameFor added in v0.37.0

func DebugLogNameFor(candidates ...any) string

DebugLogNameFor returns the debug-log filename from the first candidate that implements DebugLogNamer with a non-empty name (callers pass the Backend's Runtime and TranscriptHandler), falling back to DefaultDebugLogName.

func DiscoverPersonas added in v0.54.0

func DiscoverPersonas(skillDirs []string, agentName string) ([]RegisteredPersona, []SkippedPersona)

DiscoverPersonas runs the pi/codex persona discovery over skillDirs for the agent agentName and returns the registered personas, in the order discovery returns them (sorted by name), and the skipped files.

func EffectiveModel added in v0.40.0

func EffectiveModel(runModel, agentModel string) string

EffectiveModel returns the model a run will actually ask the runtime for: the value the runner resolved (flag > env > agents: entry > harness `model:`), or, when the runner resolved none, the agent definition's frontmatter `model:`. An empty result means neither named one and the runtime's own default applies.

This is the single fallback chain. PiRuntime.Run builds `--model` from it and NeedsOpenAIProvider decides from it whether the run needs the OpenAI run-scoped provider, so the two cannot disagree about which model a run will call — a disagreement would either strand a frontmatter-pinned OpenAI agent without a credential or attach a live OpenAI credential to a run that never calls OpenAI (#6920).

func EnvDataControlLines added in v0.49.0

func EnvDataControlLines() []string

EnvDataControlLines are the runner-written .env lines the launch-time loader understands, in the order the runner writes them: the PATH capture, the .env.d loop, the PATH restore and the iteration.env read. internal/cli writes these exact lines (its tests check they agree) as shell for the agent's own shells; the loader interprets each as data.

func EnvDataLoad added in v0.49.0

func EnvDataLoad(envFile string) string

EnvDataLoad is envDataLoad for the runner's in-sandbox probes in internal/cli (the pre-agent context scan and the GitHub preflight), which read the run's environment from .env before they run a command (#8574). The probe shell pins no CLI, so it records the trusted PATH itself (envDataTrustedPin), and no extra names are dropped.

func GenAISystemFor added in v0.44.0

func GenAISystemFor(rt Runtime, model, agentModel string, aliases map[string]string) string

GenAISystemFor returns the OTEL GenAI provider identity for rt and the given model. A ProviderResolver is preferred; otherwise System() is used.

func HomeAgentsMDPath added in v0.44.0

func HomeAgentsMDPath(rt Runtime) string

HomeAgentsMDPath returns rt's HomeAgentsMDPath, or "" for runtimes that read AGENTS.md themselves.

func ImplicitFallbackModels added in v0.48.0

func ImplicitFallbackModels(model string, configAliases map[string]string) []string

ImplicitFallbackModels returns the built-in fallback chain for model, or nil when there is none. Only a bare alias that resolves to its built-in default has one: a pinned id or provider/id spec fails loudly when it is not served (#7026), and an alias the repo retargets with models.aliases keeps the repo's choice with no implicit chain behind it. The returned slice is a copy.

func NeedsGatewayRoute added in v0.47.0

func NeedsGatewayRoute(backend, runModel, agentModel string, configAliases map[string]string) bool

NeedsGatewayRoute reports whether the parent's effective model on the named backend resolves to the gateway provider. On pi it uses the same resolution buildPiRunCommand gates on (provider prefix, case-folded, models.aliases, the FULLSEND_PI_PROVIDER default for a bare id). On codex the gateway/ prefix alone decides, as in translateCodexModel: codex consults no alias table. On Claude Code it uses the model buildRunCommand passes (claudeGatewayModel). pi, codex and Claude Code carry the route.

func NeedsOpenAIProvider added in v0.40.0

func NeedsOpenAIProvider(backend, runModel, agentModel string, configAliases map[string]string) bool

NeedsOpenAIProvider reports whether a run on the named backend with the given effective model needs the OpenAI run-scoped provider — the runner creates one only then, so a harness may declare the openai provider for every runtime without forcing an OpenAI credential on runs that never call OpenAI (#6920).

codex speaks only the OpenAI Responses API, so it needs one for every model except a gateway/ one, which reaches the inference gateway through the runner's gateway provider instead (ADR 0137, NeedsGatewayRoute). pi is multi-provider: it needs one exactly when the effective model resolves to its openai provider, which is the same resolution buildPiRunCommand gates on (provider prefix, the FULLSEND_PI_PROVIDER default for a bare id). Every other backend — Claude Code on Vertex, the test runtimes — needs none.

runModel is what the runner resolved (flag > env > agents: entry > harness `model:`) and agentModel the agent definition's frontmatter `model:`; both are passed rather than one pre-resolved value so a caller cannot resolve them differently from the runtime's own launch path — see EffectiveModel. configAliases is the repo's models.aliases (nil if unset), threaded through so an alias remapped to an openai id resolves to the same provider here as it does in buildPiRunCommand.

func PiGatewayTokenSeed added in v0.47.0

func PiGatewayTokenSeed(configDir string) string

PiGatewayTokenSeed is the POSIX sh fragment that writes the placeholder the sandbox environment carries for INFERENCE_GATEWAY_API_KEY into the gateway token file under configDir, atomically via rename. It runs at iteration start, before the agent-writable .env is sourced (and before the run command clears the INFERENCE_GATEWAY_* family), and the runner re-runs it through `sandbox exec` after every token refresh. A value that is not a gateway placeholder fails the run: a real token in the sandbox environment would mean the provider path was bypassed.

The iteration-start seed and a refresher's re-seed can overlap (only the latter holds the sandbox lock), so each writer uses its own temp file, named by its shell's pid, and removes it if the write fails. The write goes through orderedSeedWrite, so an iteration-start seed that stalls cannot replace a newer placeholder a re-seed already wrote.

func PiOpenAIAuthSeed added in v0.38.0

func PiOpenAIAuthSeed(configDir string) string

PiOpenAIAuthSeed is the POSIX sh fragment that writes the placeholder the sandbox environment carries for OPENAI_API_KEY into pi's auth.json under configDir (atomically, via rename — pi locks and re-reads the file). It runs at iteration start, before the agent-writable .env is sourced, and the runner re-runs it through `sandbox exec` after every credential refresh, once the sandbox has observed the new generation: an exec'd shell's environment holds the current placeholder, so the runner never needs to know the opaque revision. A value that is not a gateway placeholder fails the run: a real key in the sandbox environment would mean the provider path was bypassed, and forwarding it would defeat the design.

The iteration-start seed and a refresher's re-seed can overlap (only the latter holds the sandbox lock), so, as PiGatewayTokenSeed does, each writer uses its own temp file, named by its shell's pid, and removes it if the write fails. The write goes through orderedSeedWrite, so a seed holding an older generation leaves a newer one in place instead of replacing it. Leaving it is not a failure here.

func RenderPiGatewayConfig added in v0.47.0

func RenderPiGatewayConfig(g config.InferenceGatewayConfig, modelsFile []byte) ([]byte, []string, error)

RenderPiGatewayConfig renders the runner-owned inference-gateway.json for a pi run that uses gateway/ models. The model list comes from the block's inline models, or from modelsFile (the committed models_file's bytes, read from the same ref as config.yaml) when the block names one. The runner sets baseUrlEnv and authHeader itself. It returns the rendered bytes and the sorted gateway model ids, which also feed sub-agent model resolution.

A block with no model list is an error here: pi runs with PI_OFFLINE=1, so the extension never discovers models from the gateway.

func SeedReplacing added in v0.47.1

func SeedReplacing(seed string, previous ...string) string

SeedReplacing returns seed, a fragment built on orderedSeedWrite, run so that it first records previous, the placeholders the re-seed retires, as rotated out. The refresher knows them from the rotations it observed; a seed holding one may not have written yet, and without this record that seed would not be recognized as stale (fullsend#8311). previous holds the placeholder the file named and any generation the refresher saw in the sandbox whose own hand-off failed before it was recorded: a later rotation retires those too. Empty entries are dropped; with none left, seed is returned unchanged.

func SetPiGatewayRun added in v0.47.0

func SetPiGatewayRun(sandboxName string, run *PiGatewayRun)

SetPiGatewayRun registers the gateway setup for a sandbox. Call it before Bootstrap: Bootstrap writes the config file and the sub-agent model allowlist from it. A nil run clears the registration.

func TerminateStrayProcesses added in v0.42.0

func TerminateStrayProcesses(sandboxName string, w io.Writer)

TerminateStrayProcesses sweeps the sandbox after the runner ended an iteration at its budget. OpenShell's exec timeout drops the relay and leaves the command running under PID 1, so without this the agent keeps spending and writing until the sandbox is deleted (#7042). Warning-only, like the between-iteration sweep.

func ValidateCodexModel added in v0.45.0

func ValidateCodexModel(model string) error

ValidateCodexModel reports whether model is one fullsend's codex integration can serve. Empty, a Claude alias, or a provider prefix other than openai/ or gateway/ are errors; the message names both ways to set a valid id. Used by `agent new` so `--runtime codex` cannot generate a harness the runtime will refuse (#7264). A gateway/ model is accepted by shape: whether an inference.gateway block applies is known only at run time.

func ValidatePiGatewayModelsFile added in v0.47.0

func ValidatePiGatewayModelsFile(data []byte) (map[string]any, error)

ValidatePiGatewayModelsFile parses a committed models_file (the extension's own config format) and returns its providers.gateway entry. The file must hold exactly one provider, "gateway", carrying only models, include, exclude and defaultApi, with at least one model, and every model must set its own api. include, exclude and defaultApi are accepted for compatibility with the extension's format but only affect discovered models, so they do nothing on an offline pi run. Endpoint, credential, header, discovery and fallback keys are refused: the runner owns them, and discovery is off under PI_OFFLINE.

func ValidatePiGatewayPluginEnv added in v0.47.0

func ValidatePiGatewayPluginEnv(plugins []PluginInput) error

ValidatePiGatewayPluginEnv is the run-time check that applies when a block applies: no declared plugin may set an INFERENCE_GATEWAY_* env key (the runner owns that family), and no plugin may load the inference-gateway extension itself (the runner loads it by path). It is deliberately not part of the static harness deny-list, which every harness is held to and which would break the local guide.

func WantsClaudeMDBridge added in v0.37.0

func WantsClaudeMDBridge(rt Runtime) bool

WantsClaudeMDBridge reports whether rt wants the CLAUDE.md→AGENTS.md bridge file; false for runtimes that do not implement ContextBridger.

Types

type AgentEvent added in v0.31.0

type AgentEvent interface {
	// contains filtered or unexported methods
}

AgentEvent is the normalized event interface for runtime-agnostic rendering. Each concrete event type implements this with a no-op marker method.

type Backend

type Backend struct {
	Runtime
	Transcripts TranscriptHandler
}

Backend pairs the active runtime with its transcript/debug artifact handler.

func Default

func Default() Backend

Default returns the Claude Code backend. Prefer ResolveFromPerRepoConfig for config-aware selection.

func Resolve added in v0.30.0

func Resolve(name string) (Backend, error)

Resolve returns the agent backend for the given runtime name.

func ResolveForAgent added in v0.38.0

func ResolveForAgent(agents []config.AgentEntry, repoRuntime, agent string) (Backend, bool, error)

ResolveForAgent selects the runtime backend for one agent: the agents: entry's runtime when set, else repoRuntime (the repo-wide runtime: key, "claude" when empty). The boolean reports whether the per-agent entry decided. Both values are validated against config.ValidRuntimes so an agents: entry cannot activate a stub runtime any more than the repo-wide key can.

func ResolveFromPerRepoConfig added in v0.30.0

func ResolveFromPerRepoConfig(cfg config.PerRepoConfigReader) (Backend, error)

ResolveFromPerRepoConfig selects the runtime backend from per-repo config. The runtime name is validated against config.ValidRuntimes before resolution so that stub runtimes registered in Resolve for dev/testing cannot be activated through config files.

type BehaviourOpResult added in v0.30.0

type BehaviourOpResult struct {
	Description string `json:"description"`
	Success     bool   `json:"success"`
	Error       string `json:"error,omitempty"`
	// HTTPStatus and ResponseBody are recorded by http_probe only. The
	// body is capped at httpProbeBodyLimit bytes, with every JWT-shaped
	// substring replaced by httpProbeJWTRedaction; BodyHadJWT records that
	// one was there, so a custody assertion can still fail on it.
	HTTPStatus   int    `json:"http_status,omitempty"`
	ResponseBody string `json:"response_body,omitempty"`
	BodyHadJWT   bool   `json:"body_had_jwt,omitempty"`
}

BehaviourOpResult records the outcome of one scripted operation.

type BehaviourOperation added in v0.30.0

type BehaviourOperation struct {
	Description string `yaml:"description" json:"description"`
	Op          string `yaml:"op" json:"op"`
	Args        string `yaml:"args" json:"args"`
	Content     string `yaml:"content,omitempty" json:"content,omitempty"`
	// ExpectFail marks a step the scenario expects to fail, such as a fetch
	// the sandbox must block. Its failure is still recorded but does not
	// make the run exit non-zero.
	ExpectFail bool `yaml:"expect_fail,omitempty" json:"expect_fail,omitempty"`
	// http_probe fields (#8280). Fixed fields only — the op is not a
	// general HTTP client. When they are empty, http_probe parses Args as
	// "METHOD URL HEADER_ENV [BODY]" (see ParseHTTPProbeArgs).
	Method    string `yaml:"method,omitempty" json:"method,omitempty"`
	URL       string `yaml:"url,omitempty" json:"url,omitempty"`
	HeaderEnv string `yaml:"header_env,omitempty" json:"header_env,omitempty"`
	Body      string `yaml:"body,omitempty" json:"body,omitempty"`
}

BehaviourOperation is a single scripted step for the dummy runtime.

type BehaviourResults added in v0.30.0

type BehaviourResults struct {
	Operations []BehaviourOpResult `json:"operations"`
}

BehaviourResults is written to output/behaviour-results.json in the sandbox.

type BehaviourScript added in v0.30.0

type BehaviourScript struct {
	Ops []BehaviourOperation `yaml:"ops"`
}

BehaviourScript is the YAML committed to .fullsend/behaviour/current-scenario.yaml.

func LoadBehaviourScript added in v0.30.0

func LoadBehaviourScript(path string) (*BehaviourScript, error)

LoadBehaviourScript reads and parses a behaviour scenario script from disk.

type BootstrapInput

type BootstrapInput interface {
	SandboxName() string
	// AgentPath returns the local filesystem path to the agent definition file.
	// For cached agents this may be a content-addressed path with a generic basename.
	AgentPath() string
	// AgentName returns the logical agent name (e.g. "review") used to construct
	// the destination filename as {name}.md inside the sandbox. Populated from
	// the CLI positional argument; must not be empty in production (enforced by
	// cobra arg validation in cmd/fullsend).
	AgentName() string
	SkillDirs() []string
	// Plugins returns the harness's declared plugin directories (ADR 0094),
	// each tagged with the runtime format it is in. A runtime loads the
	// entries of its own kind and names and skips the rest.
	Plugins() []PluginInput
	// ModelAliases returns the per-repo model alias overrides from
	// .fullsend/config.yaml (models.aliases). A nil map means no overrides.
	// Used by the pi runtime to thread the overrides into sub-agent dispatch
	// so children resolve aliases the same way the parent does (#7020).
	ModelAliases() map[string]string
	// AgentSubagents returns the per-agent subagents map from the merged
	// config agents: entry for this run's agent. Keys are persona names
	// (or "default"); values are model references (nil = tombstone).
	// Used by the pi runtime to resolve each persona's model (#7031).
	AgentSubagents() map[string]*string
	// ParentModel returns the model this run's agent actually runs on --
	// after the agents: entry, --model and the alias remap -- or "" when
	// the caller does not know it. The pi runtime adds it to the set a
	// persona's model is checked against, so a persona pinned to the
	// parent's own model is accepted even when that model is outside the
	// alias table (#7031).
	ParentModel() string
	// Effort returns the reasoning effort the run's agent runs at (the
	// harness effort after the agents: entry and --effort, the value Run
	// receives as RunParams.Effort), or "" when none is set. The codex
	// runtime binds it as every native child's effort (#8836).
	Effort() string
	// OpenAIProviderAttached reports whether the run-scoped OpenAI
	// provider was created for this run (the harness declares an
	// openai-type provider and the run needs it, parent or child — see
	// runtime.NeedsOpenAIProvider and runtime.OpenAIChildren).
	// OPENAI_API_KEY is only present in the sandbox when this is true, so
	// the pi runtime uses it to decide whether a pre-configured child
	// naming the openai provider can be trusted (#7981): trusting it
	// otherwise would admit a persona Bootstrap cannot actually serve.
	OpenAIProviderAttached() bool
}

BootstrapInput is the portable contract every runtime needs to provision agent content into the sandbox. Implementations live outside this package (runner adapter, tests).

type ClaudeRuntime

type ClaudeRuntime struct{}

ClaudeRuntime implements Runtime using the Claude Code CLI.

func (ClaudeRuntime) Bootstrap

func (r ClaudeRuntime) Bootstrap(input BootstrapInput) error

func (ClaudeRuntime) ClearGatewayRun added in v0.47.0

func (r ClaudeRuntime) ClearGatewayRun(sandboxName string)

ClearGatewayRun implements GatewayRouteRuntime.

func (ClaudeRuntime) ClearIterationArtifacts

func (r ClaudeRuntime) ClearIterationArtifacts(sandboxName string) error

ClearIterationArtifacts terminates processes the previous iteration left running (see killStrayProcesses), then removes its outputs and transcripts so artifacts are per-iteration.

func (ClaudeRuntime) ConfigDir

func (ClaudeRuntime) ConfigDir() string

func (ClaudeRuntime) DebugLogName added in v0.37.0

func (ClaudeRuntime) DebugLogName() string

DebugLogName implements DebugLogNamer: the local artifact for --debug output.

func (ClaudeRuntime) EmitTranscriptErrors

func (ClaudeRuntime) EmitTranscriptErrors(w io.Writer, summaries []TranscriptError)

func (ClaudeRuntime) EnvExports

func (r ClaudeRuntime) EnvExports() []string

func (ClaudeRuntime) ExtractDebugLog

func (r ClaudeRuntime) ExtractDebugLog(sandboxName, localPath, debug string) error

func (ClaudeRuntime) ExtractTranscripts

func (r ClaudeRuntime) ExtractTranscripts(sandboxName, agentLabel, outputDir string) error

func (ClaudeRuntime) GatewayCredentialSeed added in v0.47.0

func (r ClaudeRuntime) GatewayCredentialSeed() CredentialSeed

GatewayCredentialSeed implements GatewayRouteRuntime: the gateway placeholder key, the token file seed and the token file the oidc mode's apiKeyHelper prints. The api-key mode never re-seeds (its credential is not rotated), so the seed only ever runs for oidc.

func (ClaudeRuntime) Name

func (ClaudeRuntime) Name() string

func (ClaudeRuntime) NeedsClaudeMDBridge added in v0.37.0

func (ClaudeRuntime) NeedsClaudeMDBridge() bool

NeedsClaudeMDBridge implements ContextBridger. Claude Code auto-loads CLAUDE.md but not AGENTS.md, so AGENTS.md-only repos need the pointer file.

func (ClaudeRuntime) ParseTranscriptErrors

func (ClaudeRuntime) ParseTranscriptErrors(transcriptDir string) []TranscriptError

func (ClaudeRuntime) ParseTranscriptFile added in v0.27.0

func (ClaudeRuntime) ParseTranscriptFile(path string) (TranscriptError, bool)

func (ClaudeRuntime) PrepareGatewayRun added in v0.47.0

func (r ClaudeRuntime) PrepareGatewayRun(sandboxName string, run GatewayRun) error

PrepareGatewayRun implements GatewayRouteRuntime: it records the gateway base URL and auth mode for the sandbox. Claude Code needs no model list.

func (ClaudeRuntime) Run

func (r ClaudeRuntime) Run(ctx context.Context, params RunParams, printer *ui.Printer, start time.Time, metrics *RunMetrics) (int, error)

func (ClaudeRuntime) System added in v0.25.0

func (ClaudeRuntime) System() string

System returns the OTEL GenAI provider identity. Claude Code serves a single model vendor — it speaks the Anthropic API and has no Vertex, OpenAI or Gemini path — so the system is the vendor ("anthropic"), not the runtime name.

func (ClaudeRuntime) WorkspaceDir

func (ClaudeRuntime) WorkspaceDir() string

type CodexRuntime added in v0.40.0

type CodexRuntime struct{}

CodexRuntime drives the Codex agent runtime (openai/codex, CLI `codex`, pinned in the sandbox image by CODEX_VERSION). Bootstrap (codex_bootstrap.go) translates the Claude-style agent definition into a runner-owned config.toml and installs the sandbox hook scripts behind an adapter codex invokes from hooks.json (codex_config.go); Run (codex_run.go) executes `codex exec --json` against a run-scoped OpenAI provider whose bearer token comes from a runner-seeded file, and normalizes the stream via parseCodexStream (codex_progress.go); transcripts are codex's rollout session JSONL files (codex_transcript.go). Selectable with `runtime: codex` in per-repo config or on an `agents:` entry (#6920, ADR 0099).

func (CodexRuntime) Bootstrap added in v0.40.0

func (r CodexRuntime) Bootstrap(input BootstrapInput) error

Bootstrap prepares the runner-owned codex config directory for one agent run: the agent body as developer_instructions in config.toml, the auth script for the run-scoped OpenAI provider, skills, the hook scripts plus the fullsend adapter and hooks.json when the harness enables security, and the manifest Run reads. It also preflights the pinned codex binary so a broken image fails here rather than as a silent zero-turn run.

func (CodexRuntime) ClearGatewayRun added in v0.47.0

func (r CodexRuntime) ClearGatewayRun(sandboxName string)

ClearGatewayRun implements GatewayRouteRuntime.

func (CodexRuntime) ClearIterationArtifacts added in v0.40.0

func (r CodexRuntime) ClearIterationArtifacts(sandboxName string) error

ClearIterationArtifacts terminates processes the previous iteration left running (see killStrayProcesses), then removes its outputs, the rollout sessions and the debug log so transcripts and output files are per-iteration.

func (CodexRuntime) ConfigDir added in v0.40.0

func (CodexRuntime) ConfigDir() string

ConfigDir returns the codex config directory inside the sandbox. It is exported to the agent process as CODEX_HOME (see EnvExports) and lives outside the cloned repo tree so the target repo cannot pre-seed it and workspace resets do not clear it. It is not a permission boundary: the agent process runs as the same user, so the runner-written files under it must be checksum-guarded before each launch rather than trusted.

func (CodexRuntime) DebugLogName added in v0.40.0

func (CodexRuntime) DebugLogName() string

DebugLogName implements DebugLogNamer: the local artifact for codex's stderr trace output.

func (CodexRuntime) EmitTranscriptErrors added in v0.40.0

func (CodexRuntime) EmitTranscriptErrors(w io.Writer, summaries []TranscriptError)

func (CodexRuntime) EnvExports added in v0.40.0

func (r CodexRuntime) EnvExports() []string

EnvExports pins codex's config location to the runner-owned path. codex refuses to start when CODEX_HOME does not exist, so Bootstrap must create the directory as well; the sandbox image bakes the same value as an ENV default for ad-hoc invocations (images/sandbox/Containerfile). codex keeps its other hygiene settings (update check, analytics, telemetry) in config.toml rather than the environment, so there is nothing else here.

func (CodexRuntime) ExtractDebugLog added in v0.40.0

func (r CodexRuntime) ExtractDebugLog(sandboxName, localPath, debug string) error

ExtractDebugLog downloads the stderr capture Run writes when debug is on. codex exec has no debug flag of its own: its tracing goes to stderr behind the RUST_LOG filter, and Run redirects that to this file.

It gets the same pattern redaction as the other artifacts. codex logs at error level by default and raises to whatever RUST_LOG asks for, so this file carries request bodies, hook output and command text — the same material output.jsonl does, and it is uploaded the same way.

func (CodexRuntime) ExtractTranscripts added in v0.40.0

func (r CodexRuntime) ExtractTranscripts(sandboxName, agentLabel, outputDir string) error

ExtractTranscripts downloads codex's rollout session files (written under the runner-owned $CODEX_HOME/sessions/YYYY/MM/DD/, one per thread) into outputDir, with the same path containment as the Claude and pi handlers. The root thread's rollout is saved as <agentLabel>-<basename>; a child thread's (its session_meta names a parent_thread_id) as <agentLabel>-sub<seq>-<role>.jsonl, where seq counts the kept child rollouts in ascending basename order and role is the child's agent_role when it is a legal persona name or explore, else codexGenericRole.

Only `.jsonl` is collected. codex writes the running session's rollout uncompressed and compresses older ones in place (codex-rs/thread-store/src/local/helpers.rs), so a `.jsonl.zst` is never the current iteration's transcript — and the sessions directory is agent-writable, so trusting that suffix meant a plaintext file *named* `x.jsonl.zst` shipped as an artifact that codexRedactFile declined to rewrite. Extension is not evidence of content: the suffix is excluded and every candidate's first line must parse as a codex rollout envelope before it is kept.

ClearIterationArtifacts empties the sessions directory between iterations, so in practice this finds the current run's rollout.

func (CodexRuntime) GatewayCredentialSeed added in v0.47.0

func (r CodexRuntime) GatewayCredentialSeed() CredentialSeed

GatewayCredentialSeed implements GatewayRouteRuntime: the gateway placeholder key, the token file seed and the token file.

func (CodexRuntime) HomeAgentsMDPath added in v0.44.0

func (r CodexRuntime) HomeAgentsMDPath() string

HomeAgentsMDPath is $CODEX_HOME/AGENTS.md. codex skips a project's own AGENTS.md while the project is untrusted, which it always is here, but loads this one as user instructions regardless of trust.

func (CodexRuntime) Name added in v0.40.0

func (CodexRuntime) Name() string

func (CodexRuntime) OpenAIAuthFile added in v0.40.0

func (r CodexRuntime) OpenAIAuthFile() string

OpenAIAuthFile implements runtime.OpenAICredentialSeeder: the runner-owned file codex's auth command prints. codex caches the token for refresh_interval_ms and then re-runs the command, so re-seeding this file is what lets a running iteration follow a credential refresh — the same role pi's auth.json plays, and for the same reason (OpenShell 0.0.115 pins a revision-scoped placeholder to the generation it was issued for and refuses the unrevisioned alias, so the process environment cannot carry a placeholder that survives a refresh; a file the process re-reads can).

func (CodexRuntime) OpenAIAuthSeed added in v0.40.0

func (r CodexRuntime) OpenAIAuthSeed() string

OpenAIAuthSeed implements runtime.OpenAICredentialSeeder: the POSIX sh fragment that writes the placeholder the sandbox environment carries for OPENAI_API_KEY into the token file, atomically via rename so the auth command never reads a half-written file. The write goes through orderedSeedWrite, with a per-writer temp file, so an iteration-start seed that stalls cannot replace a newer placeholder a re-seed already wrote.

It runs at iteration start, before the agent-writable .env is sourced, and the runner re-runs it through `sandbox exec` after every credential refresh once the sandbox has observed the new generation: an exec'd shell's environment holds the current placeholder, so the runner never needs to know the opaque revision. A value that is not a gateway placeholder fails the run — a real key in the sandbox environment would mean the provider path was bypassed, and forwarding it would defeat the design (ADR 0092).

func (CodexRuntime) ParseTranscriptErrors added in v0.40.0

func (CodexRuntime) ParseTranscriptErrors(transcriptDir string) []TranscriptError

ParseTranscriptErrors scans every JSONL file in transcriptDir and reports those whose run ended in error.

Only the tee'd `exec --json` capture (output.jsonl) yields a verdict: codex's rollout session files are a different envelope, which parseCodexTranscriptFile recognises and skips rather than misreading. That is the same division pi has — the stream capture is the runner's exit-code override input — with the difference that pi can also judge its session files. Classifying a rollout is tracked for a follow-up; the run's verdict does not depend on it, because Run already returns 1 on a stream-reported error.

func (CodexRuntime) ParseTranscriptFile added in v0.40.0

func (CodexRuntime) ParseTranscriptFile(path string) (TranscriptError, bool)

ParseTranscriptFile is the runner's exit-0 override input: the tee'd `exec --json` stream.

func (CodexRuntime) PrepareGatewayRun added in v0.47.0

func (r CodexRuntime) PrepareGatewayRun(sandboxName string, run GatewayRun) error

PrepareGatewayRun implements GatewayRouteRuntime: it registers the gateway provider's base_url for the sandbox, so Bootstrap renders the fullsend-gateway provider and Run can select it. Neither the block's model list nor its models_file is rendered: the model is pinned by --model, and codex's own GET /v1/models is denied by the gateway profile.

func (CodexRuntime) ProviderFor added in v0.47.0

func (CodexRuntime) ProviderFor(model, agentModel string, _ map[string]string) string

ProviderFor returns "gateway" for a gateway/ model, which the inference gateway serves (ADR 0137), and "" otherwise, so GenAISystemFor falls back to System().

func (CodexRuntime) Run added in v0.40.0

func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Printer, start time.Time, metrics *RunMetrics) (int, error)

Run executes one agent iteration and normalizes codex's `exec --json` stream into AgentEvents. The stream's verdict overrides a zero exit code, as it does for pi, so a failed turn fails the run whatever codex exits.

func (CodexRuntime) System added in v0.40.0

func (CodexRuntime) System() string

System returns the OTEL GenAI provider identity of codex's direct route: it speaks the OpenAI Responses API, so the system is the vendor ("openai"), not the runtime name.

func (CodexRuntime) WorkspaceDir added in v0.40.0

func (CodexRuntime) WorkspaceDir() string

type ContextBridger added in v0.37.0

type ContextBridger interface {
	NeedsClaudeMDBridge() bool
}

ContextBridger is an optional Runtime extension for runtimes that only auto-load CLAUDE.md (not AGENTS.md) into their system context. When it reports true and the target repo has AGENTS.md but no CLAUDE.md, the runner injects a minimal CLAUDE.md pointer so the agent is not context-blind. Runtimes that read AGENTS.md natively should not implement it (or return false).

type CredentialSeed added in v0.47.0

type CredentialSeed struct {
	PlaceholderEnv string
	Seed           string
	File           string
}

CredentialSeed is one credential route's in-sandbox seed (ADR 0092, ADR 0137): the env var the run-scoped provider's placeholder reaches the sandbox in, the POSIX sh fragment that writes that placeholder into a runner-owned file the agent re-reads per request, and that file's absolute sandbox path. The runner re-runs Seed through `sandbox exec` after every refresh of the route's provider, once the sandbox hands out the new generation under PlaceholderEnv, and greps File for it.

Each route names its own triple, so one run that uses two routes (a pi run with openai/ and gateway/ models) keeps two independent refresh handoffs. A zero CredentialSeed means the runtime has no seed for the route: the provider is still created and refreshed, but nothing is re-seeded in the sandbox.

func OpenAIRouteSeed added in v0.47.0

func OpenAIRouteSeed(rt Runtime) CredentialSeed

OpenAIRouteSeed returns the OpenAI route's seed for rt (OpenAICredentialSeeder), or a zero seed when rt has none or its seeder returns an empty fragment.

func (CredentialSeed) IsZero added in v0.47.0

func (s CredentialSeed) IsZero() bool

IsZero reports whether the route has no seed fragment.

type DebugLogNamer added in v0.37.0

type DebugLogNamer interface {
	DebugLogName() string
}

DebugLogNamer is an optional extension a runtime or TranscriptHandler implements to name the local debug-log artifact the runner writes per iteration (e.g. "claude-debug.log"). Runtimes without it get DefaultDebugLogName.

type DummyPlaybackRuntime added in v0.39.0

type DummyPlaybackRuntime struct {
	ExecFn      sandboxExecFunc
	UploadFn    sandboxUploadFunc
	GitCommitFn gitCommitFunc
}

DummyPlaybackRuntime replays canned agent results from an ordered playlist. Each invocation serves the result at the current index, writes result.json to output/agent-result.json, copies any companion files into the workspace, and advances the index via a git commit+push.

ExecFn, UploadFn, and GitCommitFn are optional test overrides; production uses sandbox.Exec, sandbox.UploadFile, and a real git commit+push. Forge API calls (reading/updating the tracking comment) go through RunParams.ForgeClient — per the forge-abstraction rule, this runtime must not shell out to `gh`/`glab` itself.

func (DummyPlaybackRuntime) Bootstrap added in v0.39.0

func (r DummyPlaybackRuntime) Bootstrap(input BootstrapInput) error

func (DummyPlaybackRuntime) ClearIterationArtifacts added in v0.39.0

func (r DummyPlaybackRuntime) ClearIterationArtifacts(sandboxName string) error

ClearIterationArtifacts sweeps stray processes (dummy-playback execs run in the real sandbox, so it gets the same between-iteration hygiene as the agent runtimes), then removes the previous iteration's output.

func (DummyPlaybackRuntime) ConfigDir added in v0.39.0

func (DummyPlaybackRuntime) ConfigDir() string

func (DummyPlaybackRuntime) EmitTranscriptErrors added in v0.39.0

func (DummyPlaybackRuntime) EmitTranscriptErrors(w io.Writer, summaries []TranscriptError)

func (DummyPlaybackRuntime) EnvExports added in v0.39.0

func (DummyPlaybackRuntime) EnvExports() []string

func (DummyPlaybackRuntime) ExtractDebugLog added in v0.39.0

func (DummyPlaybackRuntime) ExtractDebugLog(_ string, _ string, _ string) error

func (DummyPlaybackRuntime) ExtractTranscripts added in v0.39.0

func (DummyPlaybackRuntime) ExtractTranscripts(_ string, _ string, _ string) error

func (DummyPlaybackRuntime) Name added in v0.39.0

func (DummyPlaybackRuntime) ParseTranscriptErrors added in v0.39.0

func (DummyPlaybackRuntime) ParseTranscriptErrors(_ string) []TranscriptError

func (DummyPlaybackRuntime) ParseTranscriptFile added in v0.39.0

func (DummyPlaybackRuntime) ParseTranscriptFile(_ string) (TranscriptError, bool)

func (DummyPlaybackRuntime) Run added in v0.39.0

func (r DummyPlaybackRuntime) Run(ctx context.Context, params RunParams, printer *ui.Printer, _ time.Time, _ *RunMetrics) (int, error)

func (DummyPlaybackRuntime) System added in v0.39.0

func (DummyPlaybackRuntime) System() string

func (DummyPlaybackRuntime) WorkspaceDir added in v0.39.0

func (DummyPlaybackRuntime) WorkspaceDir() string

type DummyRuntime added in v0.30.0

type DummyRuntime struct {
	ExecFn         sandboxExecFunc
	UploadFn       sandboxUploadFunc
	WriteResultsFn writeBehaviourResultsFunc
	HostGitFn      hostGitFunc
	// contains filtered or unexported fields
}

DummyRuntime executes scripted operations in the real OpenShell sandbox. ExecFn, UploadFn, WriteResultsFn, and HostGitFn are optional test overrides; production uses sandbox.Exec, sandbox.Upload, writeBehaviourResults, and runHostGit.

func (DummyRuntime) Bootstrap added in v0.30.0

func (r DummyRuntime) Bootstrap(input BootstrapInput) error

func (DummyRuntime) ClearIterationArtifacts added in v0.30.0

func (r DummyRuntime) ClearIterationArtifacts(sandboxName string) error

ClearIterationArtifacts sweeps stray processes (the dummy runtime's ops run in the real sandbox, so it gets the same between-iteration hygiene as the agent runtimes), then removes the previous iteration's output.

func (DummyRuntime) ConfigDir added in v0.30.0

func (DummyRuntime) ConfigDir() string

func (DummyRuntime) EmitTranscriptErrors added in v0.30.0

func (DummyRuntime) EmitTranscriptErrors(w io.Writer, summaries []TranscriptError)

func (DummyRuntime) EnvExports added in v0.30.0

func (DummyRuntime) EnvExports() []string

func (DummyRuntime) ExtractDebugLog added in v0.30.0

func (DummyRuntime) ExtractDebugLog(_ string, _ string, _ string) error

func (DummyRuntime) ExtractTranscripts added in v0.30.0

func (DummyRuntime) ExtractTranscripts(_ string, _ string, _ string) error

func (DummyRuntime) Name added in v0.30.0

func (DummyRuntime) Name() string

func (DummyRuntime) ParseTranscriptErrors added in v0.30.0

func (DummyRuntime) ParseTranscriptErrors(_ string) []TranscriptError

func (DummyRuntime) ParseTranscriptFile added in v0.30.0

func (DummyRuntime) ParseTranscriptFile(_ string) (TranscriptError, bool)

func (DummyRuntime) Run added in v0.30.0

func (r DummyRuntime) Run(ctx context.Context, params RunParams, printer *ui.Printer, _ time.Time, _ *RunMetrics) (int, error)

func (DummyRuntime) System added in v0.30.0

func (DummyRuntime) System() string

func (DummyRuntime) WorkspaceDir added in v0.30.0

func (DummyRuntime) WorkspaceDir() string

type ErrorEvent added in v0.31.0

type ErrorEvent struct {
	ErrorType string
	Message   string
}

ErrorEvent is emitted when the runtime reports an error.

type EventRenderer added in v0.31.0

type EventRenderer struct {
	// contains filtered or unexported fields
}

EventRenderer renders normalized AgentEvent values to a Printer. It tracks block state (text/thinking) so transitions between event types produce clean output boundaries.

func NewEventRenderer added in v0.31.0

func NewEventRenderer(printer *ui.Printer) *EventRenderer

NewEventRenderer creates a renderer that writes to the given printer.

func (*EventRenderer) Handle added in v0.31.0

func (r *EventRenderer) Handle(evt AgentEvent)

Handle dispatches a single AgentEvent to the appropriate rendering method.

type GatewayRouteRuntime added in v0.47.0

type GatewayRouteRuntime interface {
	PrepareGatewayRun(sandboxName string, run GatewayRun) error
	ClearGatewayRun(sandboxName string)
	GatewayCredentialSeed() CredentialSeed
}

GatewayRouteRuntime is implemented by runtimes that carry the inference gateway route. The runner calls PrepareGatewayRun before Bootstrap when a block applies and the run resolves a gateway/ model, and ClearGatewayRun when the run ends. GatewayCredentialSeed names the route's placeholder env key, seed fragment and credential file, which the runner's gateway refresher re-runs after each token refresh.

pi, codex and Claude Code implement it. Runtimes without the route do not implement the interface, and the runner refuses a gateway/ model on them.

type GatewayRun added in v0.47.0

type GatewayRun struct {
	// Block is the resolved, complete inference.gateway block.
	Block config.InferenceGatewayConfig
	// ModelsFile is the committed models_file's bytes, read from the same
	// ref as config.yaml; nil when the block has no models_file.
	ModelsFile []byte
	// BaseURL is the gateway URL the runtime's client calls: the origin
	// plus the url's path prefix, if any (config.GatewayURL.BaseURL), with
	// no trailing slash. The client adds /v1/... under it.
	BaseURL string
}

GatewayRun is the runtime-neutral per-run inference gateway setup the runner hands a runtime when an inference.gateway block applies (ADR 0137, #8280).

type HTTPProbe added in v0.47.0

type HTTPProbe struct {
	Method    string `json:"method"`
	URL       string `json:"url"`
	HeaderEnv string `json:"header_env"`
	Body      string `json:"body,omitempty"`
}

HTTPProbe holds the validated fields of one http_probe op.

func ParseHTTPProbeArgs added in v0.47.0

func ParseHTTPProbeArgs(args string) (HTTPProbe, error)

ParseHTTPProbeArgs splits the compact table form "METHOD URL HEADER_ENV [BODY]" (whitespace-separated; BODY is the untouched remainder, so it may contain spaces) and validates the result.

func (HTTPProbe) Validate added in v0.47.0

func (p HTTPProbe) Validate() error

Validate checks the probe's fixed fields.

type HomeInstructionsBridger added in v0.44.0

type HomeInstructionsBridger interface {
	HomeAgentsMDPath() string
}

HomeInstructionsBridger is implemented by runtimes that do not read the target repo's AGENTS.md natively and load instructions from a file of their own instead. HomeAgentsMDPath is where the runner copies the repo's AGENTS.md (or the injected org-level one) inside the sandbox.

type InitEvent added in v0.31.0

type InitEvent struct {
	Model   string
	Version string
	// SessionID is the runtime's session id when the stream reports one
	// (Claude Code's init event); empty otherwise.
	SessionID string
}

InitEvent is emitted once at stream start with runtime metadata.

type ModelFallbackEvent added in v0.48.0

type ModelFallbackEvent struct {
	From    string
	To      string
	Trigger string
}

ModelFallbackEvent reports that the runtime itself switched models mid-session: Claude Code's --fallback-model chain answering for a model that failed. From is the model that failed, To the one that took over.

type ModelUsage added in v0.42.0

type ModelUsage struct {
	Requests                 int     `json:"requests"`
	InputTokens              int     `json:"input_tokens"`
	OutputTokens             int     `json:"output_tokens"`
	CacheCreationInputTokens int     `json:"cache_creation_input_tokens"`
	CacheReadInputTokens     int     `json:"cache_read_input_tokens"`
	CostUSD                  float64 `json:"cost_usd"`
}

ModelUsage is one model's token and cost contribution to a run. Requests counts the agent invocations attributed to the model (one for the parent iteration, one per sub-agent call); the claude runtime has no source for it and leaves it zero.

func (*ModelUsage) Add added in v0.42.0

func (u *ModelUsage) Add(other ModelUsage)

Add accumulates other into u.

type OpenAICredentialSeeder added in v0.40.0

type OpenAICredentialSeeder interface {
	OpenAIAuthSeed() string
	OpenAIAuthFile() string
}

OpenAICredentialSeeder is implemented by runtimes that read the OpenAI credential placeholder from a runner-owned file the runner re-seeds after every refresh (ADR 0092). OpenAIAuthSeed returns the POSIX sh fragment that writes the sandbox's current OPENAI_API_KEY placeholder into that file, failing closed when the value is not a gateway placeholder; OpenAIAuthFile returns the file's absolute sandbox path, used to verify the seed after a refresh.

The placeholder cannot simply be read from the process environment: it is revision-scoped on OpenShell 0.0.110+ and pinned to the credential generation it was issued for, so a process started before a refresh holds a placeholder the gateway will no longer resolve. A file the agent process re-reads per request is what lets a running iteration follow a refresh.

A runtime that returns "" from OpenAIAuthSeed is treated as having no seeder: the run-scoped provider is still created and refreshed, but no in-sandbox re-seed is attempted. Runtimes with no OpenAI path at all (Claude Code, dummy) do not implement the interface.

type OpenCodeRuntime added in v0.37.0

type OpenCodeRuntime struct{}

OpenCodeRuntime drives the OpenCode agent runtime (anomalyco/opencode), selected with `runtime: opencode` (#6035, unbound-force#510). Bootstrap translates the Claude-style agent into an OpenCode agent; Run executes `opencode run --format json` and normalizes its ndjson stream.

OpenCode reads AGENTS.md natively, so it needs no ContextBridger. Project config discovery is disabled (see EnvExports), which also drops project AGENTS.md discovery; the run prelude re-attaches it via openCodeInstructionsConfig.

func (OpenCodeRuntime) Bootstrap added in v0.37.0

func (r OpenCodeRuntime) Bootstrap(input BootstrapInput) error

Bootstrap prepares the runner-owned config dir for one agent run: the translated agent at agent/<name>.md, harness skills, and the dir scaffold. It preflights the opencode binary so a broken image fails here rather than as a silent zero-turn run.

It installs no hooks: OpenCode has no native PreToolUse/PostToolUse hooks, and the plugin adapter that bridges security.HookPlan is #515.

func (OpenCodeRuntime) ClearIterationArtifacts added in v0.37.0

func (r OpenCodeRuntime) ClearIterationArtifacts(sandboxName string) error

ClearIterationArtifacts terminates processes the previous iteration left running, then removes its outputs and the debug log so transcripts and output files are per-iteration (mirrors PiRuntime.ClearIterationArtifacts).

func (OpenCodeRuntime) ConfigDir added in v0.37.0

func (OpenCodeRuntime) ConfigDir() string

ConfigDir returns the runner-owned OpenCode config directory (OPENCODE_CONFIG_DIR). It lives outside the cloned repo so the target repo cannot pre-seed it and a workspace reset does not clear it (#515). No ".opencode" suffix is needed: OPENCODE_CONFIG_DIR itself counts as a config dir (config/config.ts:425).

The dir is root-owned 0775 (group sandbox) because the run prelude writes opencode.json here each iteration. Lockdown to 0750 with all writes via openshell is deferred to #7824.

func (OpenCodeRuntime) DebugLogName added in v0.48.0

func (OpenCodeRuntime) DebugLogName() string

DebugLogName implements DebugLogNamer.

func (OpenCodeRuntime) EmitTranscriptErrors added in v0.37.0

func (OpenCodeRuntime) EmitTranscriptErrors(w io.Writer, summaries []TranscriptError)

func (OpenCodeRuntime) EnvExports added in v0.37.0

func (r OpenCodeRuntime) EnvExports() []string

EnvExports pins OpenCode's config discovery to the runner-owned dir and exports the variables Bootstrap and Run rely on.

OPENCODE_CONFIG_CONTENT (Vertex provider + permission policy) and GOOGLE_APPLICATION_CREDENTIALS (WIF credential file) come from the harness; Run restores their pristine values after reading the agent-writable .env. The policy must ALLOW the tools a read-only agent needs: headless `opencode run` has no TTY and auto-rejects any permission request config does not pre-resolve (run.ts:795-808), so a bare "deny" fails every tool call. Write-path denial is unbound-force#515.

func (OpenCodeRuntime) ExtractDebugLog added in v0.37.0

func (r OpenCodeRuntime) ExtractDebugLog(sandboxName, localPath, debug string) error

ExtractDebugLog downloads OpenCode's stderr capture written when --debug is set.

func (OpenCodeRuntime) ExtractTranscripts added in v0.37.0

func (r OpenCodeRuntime) ExtractTranscripts(sandboxName, agentLabel, outputDir string) error

ExtractTranscripts downloads the tee'd output.jsonl into outputDir as <agentLabel>-output.jsonl, with the same path containment as the Claude and pi handlers.

func (OpenCodeRuntime) Name added in v0.37.0

func (OpenCodeRuntime) Name() string

func (OpenCodeRuntime) ParseTranscriptErrors added in v0.37.0

func (OpenCodeRuntime) ParseTranscriptErrors(transcriptDir string) []TranscriptError

ParseTranscriptErrors scans every JSONL file in transcriptDir (the extracted output.jsonl tee) and reports those whose stream ended in error.

func (OpenCodeRuntime) ParseTranscriptFile added in v0.37.0

func (OpenCodeRuntime) ParseTranscriptFile(path string) (TranscriptError, bool)

ParseTranscriptFile is the runner's exit-0 override input: the tee'd --format json stream. It replays the ndjson through parseOpenCodeStream and reports the synthesized ResultEvent's verdict.

func (OpenCodeRuntime) Run added in v0.37.0

func (r OpenCodeRuntime) Run(ctx context.Context, params RunParams, printer *ui.Printer, start time.Time, metrics *RunMetrics) (int, error)

Run executes one agent iteration and normalizes OpenCode's --format json stream into AgentEvents. A stream that reports an error overrides a 0 exit code, as in pi.

func (OpenCodeRuntime) System added in v0.37.0

func (OpenCodeRuntime) System() string

System returns the fallback OTEL GenAI provider identity. OpenCode is multi-provider and does not implement ProviderResolver yet (#1935), so the system is the runtime itself rather than a model vendor.

func (OpenCodeRuntime) WorkspaceDir added in v0.37.0

func (OpenCodeRuntime) WorkspaceDir() string

type PiChild added in v0.46.0

type PiChild struct {
	Source     string
	Spec       string
	Configured bool
}

PiChild is one configured pi child whose model resolves to a provider the runner must prepare for (openai, or a Vertex provider). Source says where the model came from ("subagents.x", "subagents.default", or a persona's frontmatter) and Spec is the resolved "<provider>/<id>". Configured is true for a subagents entry: the repo asked for that model, so a run that cannot serve it must fail. A persona's own frontmatter model is not configured that way; it is refused later, at Bootstrap or dispatch.

func GatewayChildren added in v0.47.0

func GatewayChildren(backend, agentPath string, subagentsCfg map[string]*string, skillDirs []string, agentName string, configAliases map[string]string) []PiChild

GatewayChildren lists the configured pi children whose model resolves to the gateway provider, resolved exactly as Bootstrap resolves them (see OpenAIChildren).

func OpenAIChildren added in v0.45.0

func OpenAIChildren(backend, agentPath string, subagentsCfg map[string]*string, skillDirs []string, agentName string, configAliases map[string]string) []PiChild

OpenAIChildren lists the configured pi children whose model resolves to the openai provider: a repo `subagents.<persona>` entry, `subagents.default`, or a discovered persona's own frontmatter `model:` (#7981). It resolves them exactly as Bootstrap does — the same persona discovery, the same model table built from the agent definition's model and models.aliases, the same resolver — so the runner's provider gate, its pre-sandbox check and the children's openai allowlist cannot drift.

NeedsOpenAIProvider answers only for the parent. pi is multi-provider per child, so a Vertex parent with an OpenAI persona needs the run-scoped OpenAI provider too. The list is empty for every backend other than pi (codex has no children; the rest never need the provider) and for an agent without the Agent tool, which dispatches no children. A model an Agent call names at dispatch time is not covered: it is not known before the sandbox starts.

func VertexChildren added in v0.46.0

func VertexChildren(backend, agentPath string, subagentsCfg map[string]*string, skillDirs []string, agentName string, configAliases map[string]string) []PiChild

VertexChildren lists the configured pi children whose model resolves to a Vertex provider (anthropic-vertex, google-vertex, xai-vertex). The runner fails a non-Vertex parent before the sandbox when a subagents entry is among them and no Vertex credential reaches the sandbox (#7980).

func (PiChild) String added in v0.46.0

func (c PiChild) String() string

type PiGatewayRun added in v0.47.0

type PiGatewayRun struct {
	// Config is the rendered inference-gateway.json (RenderPiGatewayConfig).
	Config []byte
	// ModelIDs are the gateway model ids RenderPiGatewayConfig returned;
	// they become the manifest's ProviderModels["gateway"].
	ModelIDs []string
	// BaseURL is the gateway endpoint exported as INFERENCE_GATEWAY_BASE_URL.
	BaseURL string
	// TokenFile is the sandbox path of the gateway token, exported as
	// INFERENCE_GATEWAY_TOKEN_FILE. Required: validatePiGatewayRun refuses
	// a run without it.
	TokenFile string
	// ConfigFile is the sandbox path of the rendered config, exported as
	// INFERENCE_GATEWAY_CONFIG_FILE for the parent.
	ConfigFile string
}

PiGatewayRun is the per-run inference gateway setup a block applies.

type PiRuntime added in v0.37.0

type PiRuntime struct{}

PiRuntime drives the pi agent runtime (earendil-works/pi, CLI `pi`, pinned in the sandbox image). Bootstrap (pi_bootstrap.go) translates the Claude-style agent definition and installs the sandbox hook scripts behind a pi extension; Run (pi_run.go) executes `pi --print --mode json` and normalizes the stream via parsePiStream (pi_progress.go); transcripts are pi's session JSONL files (pi_transcript.go). Selected per org/repo with `runtime: pi` (#6464).

func (PiRuntime) Bootstrap added in v0.37.0

func (r PiRuntime) Bootstrap(input BootstrapInput) error

Bootstrap prepares the runner-owned pi config directory for one agent run: agent body as APPEND_SYSTEM.md, locked-down settings.json, skills, the hook scripts plus the fullsend hook extension when the harness enables security, and the manifest Run reads. It also preflights the pinned pi binary so a broken image fails here rather than as a silent zero-turn run.

func (PiRuntime) ClearGatewayRun added in v0.47.0

func (r PiRuntime) ClearGatewayRun(sandboxName string)

ClearGatewayRun implements GatewayRouteRuntime.

func (PiRuntime) ClearIterationArtifacts added in v0.37.0

func (r PiRuntime) ClearIterationArtifacts(sandboxName string) error

ClearIterationArtifacts terminates processes the previous iteration left running (see killStrayProcesses), then removes its outputs and sessions so transcripts and output files are per-iteration. The sessions glob also takes the sub-agent session dirs (sessions/agent-<seq>/); the Agent extension's usage file lives outside them and is named explicitly, or a retry would re-count the first iteration's children.

func (PiRuntime) ConfigDir added in v0.37.0

func (PiRuntime) ConfigDir() string

ConfigDir returns the pi config directory inside the sandbox. It is exported to the agent process as PI_CODING_AGENT_DIR (see EnvExports) and lives outside the cloned repo tree so the target repo cannot pre-seed it and workspace resets do not clear it. It is not a permission boundary: the agent process runs as the same user and pi loads extensions from <dir>/extensions/, which is why Run passes --no-extensions and names the runner-supplied extensions explicitly. Session JSONL storage is <dir>/sessions (PI_CODING_AGENT_SESSION_DIR, also passed as --session-dir).

func (PiRuntime) DebugLogName added in v0.37.0

func (PiRuntime) DebugLogName() string

DebugLogName implements DebugLogNamer.

func (PiRuntime) EmitTranscriptErrors added in v0.37.0

func (PiRuntime) EmitTranscriptErrors(w io.Writer, summaries []TranscriptError)

func (PiRuntime) EnvExports added in v0.37.0

func (r PiRuntime) EnvExports() []string

EnvExports pins pi's config and session locations to runner-owned paths, disables all startup network traffic (update checks, package update checks, telemetry) and disables the module loader's on-disk transpile cache. PI_OFFLINE does not affect the inference call itself; PI_TELEMETRY=0 additionally drops pi's provider attribution headers. Var names/semantics per earendil-works/pi docs/environment-variables.md (PI_CODING_AGENT_DIR, PI_CODING_AGENT_SESSION_DIR, PI_OFFLINE, PI_SKIP_VERSION_CHECK, PI_TELEMETRY) — re-verify against that doc when PI_VERSION moves. The sandbox image bakes the same values as ENV defaults for ad-hoc invocations (images/sandbox/Containerfile).

JITI_FS_CACHE is not pi's own variable but jiti's, the loader pi imports every `-e` module through (createJiti in core/extensions/loader.ts passes no fsCache, so jiti resolves it from JITI_FS_CACHE, then JITI_CACHE, then true). jiti probes for a node_modules directory next to the module that created it — the bundled chunk under <pi>/dist/bundle/chunks/ in the published package, so <pi>/dist/bundle/chunks/node_modules/.cache/jiti — and falls back to $TMPDIR/jiti; in the sandbox image pi is root-installed and ships no such directory, so it is /tmp/jiti — writable by the agent and persistent across iterations. A cache entry is validated only against a ` /* v9-<hash of the source> */` trailer, so a body rewritten with the trailer left in place executes while the source file is untouched: that is a way around both the extension tree-hash preflight (piExtensionsGuard) and the hook adapter's SHA-256 check (piHooksGuard), neither of which can see it. Setting the variable to false makes jiti ignore any planted entry and create no cache directory at all (verified on pi 0.84.4, and jiti is still 2.7.0 at the pinned 0.85.0 — internal/runtime/testdata/pi/jiti-cache-check.sh reproduces both halves). Run re-exports these after the agent-writable .env is sourced, so the agent cannot switch the cache back on, and harness validation reserves the JITI_* family from extension env.

The cache is one lever of several: the rest of jiti's environment (JITI_ALIAS above all, which remaps a module specifier to another file) is cleared outright right after .env, on every provider path — see piLoaderEnvNames in pi_run.go.

func (PiRuntime) ExtractDebugLog added in v0.37.0

func (r PiRuntime) ExtractDebugLog(sandboxName, localPath, debug string) error

ExtractDebugLog downloads pi's stderr capture written when --debug is set.

func (PiRuntime) ExtractTranscripts added in v0.37.0

func (r PiRuntime) ExtractTranscripts(sandboxName, agentLabel, outputDir string) error

ExtractTranscripts downloads pi's session JSONL files (written under the runner-owned sessions dir, possibly nested by working directory) into outputDir as <agentLabel>-<basename>, with the same path containment as the Claude handler. Sub-agent sessions (sessions/agent-<seq>/, written by the children fullsend-agent.js spawns) are saved as <agentLabel>-sub<seq>-<basename>, and the extension's usage file alongside them.

func (PiRuntime) GatewayCredentialSeed added in v0.47.0

func (r PiRuntime) GatewayCredentialSeed() CredentialSeed

GatewayCredentialSeed implements GatewayRouteRuntime: the gateway placeholder key, the token file seed and the token file.

func (PiRuntime) Name added in v0.37.0

func (PiRuntime) Name() string

func (PiRuntime) OpenAIAuthFile added in v0.40.0

func (r PiRuntime) OpenAIAuthFile() string

OpenAIAuthFile implements OpenAICredentialSeeder: pi's auth.json inside the sandbox, which the runner greps for the new placeholder to confirm a re-seed landed.

func (PiRuntime) OpenAIAuthSeed added in v0.40.0

func (r PiRuntime) OpenAIAuthSeed() string

OpenAIAuthSeed implements OpenAICredentialSeeder: the fragment that seeds pi's auth.json with the sandbox's current OPENAI_API_KEY placeholder. The runner runs it through `sandbox exec` after every credential refresh; Run emits the same fragment at iteration start.

func (PiRuntime) ParseTranscriptErrors added in v0.37.0

func (PiRuntime) ParseTranscriptErrors(transcriptDir string) []TranscriptError

ParseTranscriptErrors scans every JSONL file in transcriptDir (the extracted session files and, when present, the tee'd output.jsonl) and reports those whose last run ended in error.

func (PiRuntime) ParseTranscriptFile added in v0.37.0

func (PiRuntime) ParseTranscriptFile(path string) (TranscriptError, bool)

ParseTranscriptFile is the runner's exit-0 override input: the tee'd --mode json stream. It also understands pi session files so ParseTranscriptErrors can use it on extracted sessions.

func (PiRuntime) PrepareGatewayRun added in v0.47.0

func (r PiRuntime) PrepareGatewayRun(sandboxName string, run GatewayRun) error

PrepareGatewayRun implements GatewayRouteRuntime: it renders the runner-owned inference-gateway.json from the block and registers the run for the sandbox (SetPiGatewayRun), with the token file under the pi config dir.

func (PiRuntime) ProviderFor added in v0.44.0

func (PiRuntime) ProviderFor(model, agentModel string, aliases map[string]string) string

ProviderFor returns the serving-endpoint provider of the model pi will call: the lowercase prefix of translatePiModel, the same value the run command and NeedsOpenAIProvider already branch on. A Claude id on Vertex is "anthropic-vertex", a Grok id is "xai-vertex", Gemini is "google-vertex", GPT is "openai". The publisher ("anthropic", "xai") is not used: two runs of the same publisher model through different endpoints are different inference paths.

func (PiRuntime) Run added in v0.37.0

func (r PiRuntime) Run(ctx context.Context, params RunParams, printer *ui.Printer, start time.Time, metrics *RunMetrics) (int, error)

Run executes one agent iteration and normalizes pi's --mode json stream into AgentEvents. pi exits 0 on model error in json mode, so the stream's verdict overrides the exit code (#2786/#5361).

When the requested model is an alias, Run attempts each model in its fallback chain — FallbackModels when set, else the alias's built-in chain (ImplicitFallbackModels, #8426) — until one succeeds or returns a non-model error. A Vertex 404 ("Publisher model not found") or 403 ("data sharing not enabled") on an aliased model triggers the next fallback; all other errors are terminal, as is an attempt where the model already answered. Fallbacks on another pi provider are dropped (piFallbackChain), and the whole chain shares params.Timeout. Pinned explicit ids (provider/id or bare catalog ids) never fall back (#7026).

func (PiRuntime) System added in v0.37.0

func (PiRuntime) System() string

System is the no-resolver fallback required by Runtime. Pi always has a serving endpoint (ProviderFor uses translatePiModel, which defaults a bare/empty model to anthropic-vertex/opus), so agent spans must go through ProviderFor / GenAISystemFor and never this value (#7245).

func (PiRuntime) WorkspaceDir added in v0.37.0

func (PiRuntime) WorkspaceDir() string

type PlaybackEntry added in v0.39.0

type PlaybackEntry struct {
	// Result is the subdirectory name under .fullsend/results/ that contains
	// this entry's result.json and optional companion files.
	Result string
}

PlaybackEntry is a single entry in a playback playlist, used by the Gherkin step definitions to build the playlist before committing it.

type Playlist added in v0.39.0

type Playlist struct {
	Current int      `yaml:"current"`
	Results []string `yaml:"results"`
}

Playlist is the YAML committed to .fullsend/results/playlist.yaml. Results are 1-indexed: current=1 serves results[0].

type PluginErrorEvent added in v0.46.0

type PluginErrorEvent struct {
	Plugin  string
	Type    string
	Path    string
	Message string
}

PluginErrorEvent reports a plugin the runtime failed to load at startup. Only the Claude parser emits it, once per entry of the init event's plugin_errors. Type is the runtime's error category (an open set); Path is empty when the runtime does not name a directory (Claude Code before 2.1.283, or an entry that is not a --plugin-dir load failure).

type PluginInput added in v0.42.0

type PluginInput struct {
	Name   string
	Path   string
	Kind   pluginformat.Kind
	Env    map[string]string
	PiArgs []string
}

PluginInput is one declared plugin: a host directory to upload, the sandbox name it is uploaded as, the format the directory is in, and the environment and pi options the harness gave it. Name is optional — the path basename is used when empty.

func (PluginInput) SandboxName added in v0.42.0

func (p PluginInput) SandboxName() string

SandboxName is the directory name the plugin takes in the sandbox: Name when set, else the path basename.

type ProviderResolver added in v0.44.0

type ProviderResolver interface {
	ProviderFor(model, agentModel string, aliases map[string]string) string
}

ProviderResolver is an optional Runtime extension for multi-provider backends. ProviderFor returns the OTEL GenAI provider identity (gen_ai.system / gen_ai.provider.name) for the model that run will call, using the same resolution as the inference request. model is the runner- resolved value (flag > env > agents: entry > harness model:); agentModel is the agent definition's frontmatter model: and is only consulted when model is empty (no runner-resolved model); aliases are the repo's models.aliases. The identity is the serving endpoint (the pi provider prefix after translatePiModel), not the model publisher: a Claude id on Vertex is "anthropic-vertex", not "anthropic". That matches how the run authenticates and which catalog a downstream consumer should look up. Single-vendor runtimes omit this; GenAISystemFor falls back to System().

Return a non-empty lowercase provider identifier (alphanumeric plus hyphen, e.g. "anthropic-vertex", "openai"). Return "" to fall back to System().

type RegisteredPersona added in v0.54.0

type RegisteredPersona struct {
	Name string
	// SkillDir is the skill directory the file was found in, as passed in.
	SkillDir string
	// Path is the file's host path.
	Path string
	// Data is the file's raw bytes.
	Data []byte
	// Frontmatter is the raw YAML between the fences; nil without one.
	Frontmatter []byte
}

RegisteredPersona is one sub-agents/*.md file that pi and codex discovery registers (discoverPersonas). The runner's persona manifest lists exactly these (#6158).

type RepoDirInput added in v0.44.0

type RepoDirInput interface {
	RepoDir() string
}

RepoDirInput is implemented by bootstrap inputs that know the target repository's path inside the sandbox. The codex runtime requires it: the project's trust level is pinned in the config it renders.

type ResultEvent added in v0.31.0

type ResultEvent struct {
	NumTurns                 int
	TotalCostUSD             float64
	IsError                  bool
	ErrorMessage             string
	Subtype                  string
	InputTokens              int
	OutputTokens             int
	ReasoningTokens          int
	CacheCreationInputTokens int
	CacheReadInputTokens     int
	// PerModelUsage breaks the token totals and cost down by model id.
	// Only the claude parser fills it (from the result's modelUsage); it is
	// nil otherwise.
	PerModelUsage map[string]ModelUsage
}

ResultEvent is emitted once at stream end with final metrics.

type RetryEvent added in v0.31.0

type RetryEvent struct {
	Attempt    int
	MaxRetries int
	DelayMs    int
	Error      string
}

RetryEvent is emitted when the runtime retries an API call.

type RunMetrics

type RunMetrics struct {
	ToolCalls                atomic.Int32
	NumTurns                 int     `json:"num_turns"`
	TotalCostUSD             float64 `json:"total_cost_usd"`
	InputTokens              int     `json:"input_tokens"`
	OutputTokens             int     `json:"output_tokens"`
	ReasoningTokens          int     `json:"reasoning_tokens"`
	CacheCreationInputTokens int     `json:"cache_creation_input_tokens"`
	CacheReadInputTokens     int     `json:"cache_read_input_tokens"`
	Model                    string  `json:"model"`
	// PerModelUsage breaks the totals above down by the model spec that
	// spent them. Runtimes that dispatch sub-agents fill it — pi's Agent
	// tool with one entry per child model plus the parent's own, claude
	// with one entry per model id from the result's modelUsage — so a run
	// whose cost is dominated by children is legible in metrics.json;
	// runtimes without sub-agents leave it nil and the totals stand alone.
	PerModelUsage map[string]ModelUsage `json:"per_model_usage,omitempty"`
	// FallbackFrom lists, in the order they were tried, the models the run
	// moved off before Model took over (#8426): models the Vertex project
	// did not serve, and on Claude Code any model its own --fallback-model
	// handling left (a "model_fallback" event, for example on overload).
	// Empty when the first model ran.
	FallbackFrom []string `json:"fallback_from,omitempty"`
	// FallbackReasons says why the run moved off each FallbackFrom entry,
	// at the same index: "not_served" when the runner retried because the
	// Vertex project does not serve the model, "claude_code:<trigger>"
	// when Claude Code switched itself (its model_fallback trigger, for
	// example "claude_code:last_resort"). Add entries with recordFallback
	// so the two stay aligned.
	FallbackReasons []string `json:"fallback_reasons,omitempty"`
}

RunMetrics collects execution statistics from stream parsing.

type RunParams

type RunParams struct {
	SandboxName   string
	AgentBaseName string
	Model         string
	Effort        string
	// FallbackModels is the ordered overload/retirement fallback chain
	// (FULLSEND_FALLBACK_MODELS). Claude Code passes it as --fallback-model;
	// runtimes without the capability ignore it with a warning. On Claude
	// Code and pi it also replaces an alias's built-in chain
	// (ImplicitFallbackModels) when the alias is not served.
	FallbackModels []string
	RepoDir        string
	// HostRepoDir is the runner-side path of the target repository, the
	// directory uploaded into the sandbox at RepoDir. The dummy runtime's
	// checkout_branch op runs its git remote access there, because
	// sandboxes cannot fetch from the forge; other runtimes ignore it.
	HostRepoDir string
	FullsendDir string
	// PluginDirs are the sandbox-side directories Claude Code is pointed at
	// with --plugin-dir, one per Claude-format plugin the runner uploaded.
	PluginDirs []string
	// Plugins are the harness's declared plugins (host paths and formats),
	// the same list Bootstrap received. PiRuntime.Run re-hashes the pi-format
	// entries to render the sandbox preflight; other runtimes ignore them.
	Plugins []PluginInput
	Debug   string
	// HooksSettingsPath, if set, is passed as --settings so Claude Code
	// loads the runner's hook wiring regardless of its working directory.
	HooksSettingsPath string
	Timeout           time.Duration
	OutputPath        string           // if set, tee stream-json stdout to this file
	OnEvent           func(AgentEvent) // if non-nil, called with normalized events during Run
	// Prompt overrides DefaultAgentPrompt. The validation loop sets it on a
	// retry iteration to inject the previous iteration's failure so the agent
	// can self-correct instead of re-running blindly. See #1050, #6494.
	//
	// Every Runtime implementation MUST honour this field, falling back to
	// DefaultAgentPrompt when it is empty. A runtime that ignores it turns
	// validation_loop.feedback_mode into a silent no-op for every harness
	// that selects that runtime, which is indistinguishable from the blind
	// retries this field exists to remove. Runtime support is tracked in the
	// key support matrix in docs/runtimes.md.
	Prompt string
	// Forge is the forge platform identifier ("github" or "gitlab").
	// Empty defaults to "github". Used by runtimes that need
	// forge-specific environment variable resolution.
	Forge string
	// ModelAliases holds per-repo model alias overrides from
	// .fullsend/config.yaml models.aliases (#6882). When a harness or
	// agent model value is an alias key present in this map, the
	// runtime translates it to the mapped id before passing it to the
	// underlying CLI. An empty or nil map means no overrides; the
	// runtime's compiled-in alias table is used as-is.
	ModelAliases map[string]string
	// ForgeClient is an authenticated forge.Client for the current Forge
	// platform, used by runtimes that need to call forge APIs from the
	// orchestrator process itself (as opposed to the agent's own tool use
	// inside the sandbox). Per the forge-abstraction rule (AGENTS.md,
	// docs/contributing/forge-abstraction.md), any such call must go
	// through this client rather than shelling out to `gh`/`glab`. May be
	// nil when no token could be resolved; callers must treat that as
	// "forge operations unavailable" rather than failing outright, mirroring
	// the fail-closed-but-non-fatal handling already used for the playback
	// tracking comment.
	ForgeClient forge.Client
}

RunParams configures a single agent invocation inside the sandbox.

type Runtime

type Runtime interface {
	Name() string
	// System returns a fallback OTEL GenAI provider identity (gen_ai.system /
	// gen_ai.provider.name) when the runtime does not implement
	// ProviderResolver. Single-vendor runtimes return the model vendor
	// (e.g. "anthropic"). Multi-provider runtimes must implement
	// ProviderResolver so the agent span reports the serving endpoint for
	// the model actually used (#7245); System() is then unused on agent
	// spans. Kept on the runtime so telemetry stays runtime-agnostic rather
	// than hardcoding a vendor in the CLI (ADR 0050).
	System() string
	ConfigDir() string
	WorkspaceDir() string
	EnvExports() []string
	Bootstrap(input BootstrapInput) error
	Run(ctx context.Context, params RunParams, printer *ui.Printer, start time.Time, metrics *RunMetrics) (exitCode int, err error)
	ClearIterationArtifacts(sandboxName string) error
}

Runtime is an agent execution backend (LLM tool-use loop) inside the sandbox.

type SandboxHooksBootstrap added in v0.37.0

type SandboxHooksBootstrap interface {
	SandboxHookConfig() security.SandboxHookConfig
}

SandboxHooksBootstrap is an optional BootstrapInput extension carrying the runtime-neutral sandbox tool hook configuration (Tirith, SSRF, canary, secret redaction, ...). Runtimes type-assert for it in Bootstrap and, when present, install the hook scripts from security.HookFiles and wire them through their native mechanism (Claude Code: settings.json; other runtimes: their own plugin/extension) following security.HookPlan. Runtimes that do not implement it install no sandbox tool hooks — see docs/runtimes.md.

type SkippedPersona added in v0.54.0

type SkippedPersona struct {
	Path   string
	Reason string
}

SkippedPersona is a sub-agents/*.md file discovery did not register.

func (SkippedPersona) String added in v0.54.0

func (s SkippedPersona) String() string

String is the warning pi prints for a skipped persona.

type TextEvent added in v0.31.0

type TextEvent struct {
	Text string
}

TextEvent carries an incremental assistant text delta.

type ThinkingEvent added in v0.31.0

type ThinkingEvent struct {
	Text string
}

ThinkingEvent carries an incremental thinking text delta.

type TokensEvent added in v0.31.0

type TokensEvent struct {
	InputTokens     int
	OutputTokens    int
	ReasoningTokens int
	CacheRead       int
	CacheWrite      int
}

TokensEvent carries incremental token usage counters.

type ToolResultEvent added in v0.44.0

type ToolResultEvent struct {
	ID        string
	Result    string
	IsError   bool
	Partial   bool
	Oversized bool
}

ToolResultEvent carries the result of a completed tool invocation. ID is the tool call identifier from the runtime stream (matches ToolUseEvent.ID); Result is the raw result text; IsError reports a failed call, as set on the wire; Partial reports that non-text content (for example image blocks) was skipped while flattening, so Result is a fragment of what the wire carried; Oversized reports that the result's stream line exceeded streamBufSize and was skipped, so only ID is known — Result is empty and IsError is unknown, not false. Only the Claude runtime emits it today — see the runtime support matrix in docs/runtimes.md.

type ToolUseEvent added in v0.31.0

type ToolUseEvent struct {
	ID        string
	Name      string
	Summary   string
	Arguments string
}

ToolUseEvent reports a tool call. The Claude Code parser emits it when it reads the line carrying the call's complete arguments (written ahead of the call's result; the tool may already be running by then); the pi, codex and OpenCode parsers emit it when the call has finished — codex once per changed path of a file_change item, so one apply_patch can yield several. Not every call yields one: a Claude Code server_tool_use block on an assistant line (the path production takes) and a tool_use line beyond streamBufSize emit nothing. ID is the tool call identifier from the runtime stream; it is empty when the parser passes none through — pi and codex (#7414), OpenCode, and a Claude Code server-side tool reported from stream_event blocks, whose result never arrives as a tool_result. Name is the raw tool name from the runtime stream. Summary is a one-line context string from extractSafeContext; it is empty for tools not recognized by that function. Arguments is the call's input as the stream carried it: JSON text, unredacted, for the Level 3 content collector only — the renderer does not print it. It is not checked here: input assembled from stream_event deltas stops growing at maxToolInputSize and can be incomplete JSON. Empty when the wire carried no input, and from the pi and codex parsers (#7414) and the OpenCode parser.

type TranscriptError

type TranscriptError struct {
	Source       string
	IsError      bool
	ErrorMessage string
	Subtype      string
}

TranscriptError holds extracted error information from a runtime transcript.

func (TranscriptError) DisplayMessage added in v0.37.0

func (te TranscriptError) DisplayMessage() string

DisplayMessage returns the sanitized, bounded message for a transcript error: ErrorMessage with ANSI escapes, control characters, and GHA workflow command markers stripped, or the subtype fallback when it sanitizes to empty (both fields are omitempty in the transcript). ErrorMessage is truncated at parse time; Subtype is not, so the fallback applies the same truncateError bound before sanitizing. Every sink that renders a transcript error — GHA annotations, the CLI console, span status and events — goes through this one method so the treatments agree.

type TranscriptHandler

type TranscriptHandler interface {
	ExtractTranscripts(sandboxName, agentLabel, outputDir string) error
	ExtractDebugLog(sandboxName, localPath, debug string) error
	ParseTranscriptErrors(transcriptDir string) []TranscriptError
	// ParseTranscriptFile parses a single JSONL transcript or output file
	// and returns the last result event, if any. Use this to check a tee'd
	// output.jsonl for is_error:true without scanning an entire directory.
	ParseTranscriptFile(path string) (TranscriptError, bool)
	EmitTranscriptErrors(w io.Writer, summaries []TranscriptError)
}

TranscriptHandler extracts runtime conversation artifacts from the sandbox and surfaces errors in operator-facing logs (e.g. GitHub Actions annotations). Implementations are runtime-specific (Claude stream-json today).

Jump to

Keyboard shortcuts

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