agent

package
v0.141.0 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 15 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 agent provides the agent registry, command-template rendering, the adapter that turns a job request into an executable argv, and a detect probe. See plan §9 (P3), §6.1 (AgentConfig) and §11 (security: keep argv, never build a shell string).

Index

Constants

View Source
const (
	// HealthUnknown means the window holds no evidence at all: no job was run, so
	// nothing can be claimed about the provider. It is NOT "healthy" — a listing must
	// show it as unknown, and a pre-dispatch substitution treats it as acceptable
	// (never having failed is not a reason to move work away).
	HealthUnknown = "unknown"
	// HealthHealthy means the agent ran jobs in the window and is not degraded.
	HealthHealthy = "healthy"
	// HealthDegraded means the window saw at least DegradedAfter transient failures
	// that the agent has not recovered from with RecoverAfterOK successes.
	HealthDegraded = "degraded"
)

Agent health states (SUP-01 P3).

View Source
const (
	// TypeCLIAgent renders Command + Args templates with the job prompt.
	TypeCLIAgent = "cli-agent"
	// TypeExec runs a request-supplied argv verbatim (no prompt/template).
	TypeExec = "exec"
	// TypeACPAgent launches an Agent Client Protocol server (Command + Args are its
	// launch argv) and drives one prompt turn over its stdio. The prompt travels
	// over the protocol, so Args never carry {{prompt}}. See internal/acp and
	// internal/runner/acp.
	TypeACPAgent = "acp-agent"
)

Agent type identifiers (AgentConfig.Type).

View Source
const ExecAgentKey = config.BuiltinExecAgentKey

ExecAgentKey is the reserved key of the built-in exec agent. It is always available without a config declaration, mirroring the built-in "local" runner. Being built-in does NOT bypass a project's allowed_agents allowlist (see CheckAllowed and plan §11).

View Source
const FallbackSessionCapture = `(?i)(?:^|[\s"'])(?:--resume|resume|--session[-_]?id)[=\s]+["']?([A-Za-z0-9][A-Za-z0-9._-]{7,127})["']?`

FallbackSessionCapture is the GENERIC session_capture a cli-agent gets when neither the built-in table nor the operator's config says otherwise (AGT-04): the id is whatever follows a `--resume` / `--session-id` spelling, so a brand-new cli-agent is续接-able the day it is declared instead of the day someone writes a regex for it. jcode's exit banner is the case that motivated it (真机采样 2026-09-22, job 20260922-201228-becdd0e9):

Session hamster - to resume:
  jcode --resume session_hamster_1790079148520_bc5cb0d44153fe56

— a non-uuid id, which all three built-in regexes miss.

The token class is deliberately wide (`[A-Za-z0-9][A-Za-z0-9._-]{7,127}`) to cover a uuid, a `ses_01H9…` ULID-style id and a `session_<host>_<ts>_<rand>` id. Two guards keep it off prose, and neither can be expressed in the pattern itself:

  • the capture only reads the LAST 4KB of log/stream output (internal/job), since a real banner is an exit banner;
  • a captured placeholder (`<session_id>`, `SESSION_ID`, `your-session-id`, …) is dropped by internal/job.acceptableSessionID.
View Source
const McpServerNameDefault = "gofer"

McpServerNameDefault is the codex config block name of the gofer MCP server (`[mcp_servers.<name>]` in codex config.toml). It is the server whose per-server env we override via `-c mcp_servers.<name>.env.<KEY>=<VALUE>` (see McpEnvInjectArgs). The convention is "gofer"; an agent may override it with AgentConfig.McpServerName when its codex config uses a different block name.

Variables

View Source
var (
	FallbackSessionResume            = []string{"--resume", "{{session_id}}", "-p", "{{prompt}}"}
	FallbackSessionResumeInteractive = []string{"--resume", "{{session_id}}"}
)

FallbackSessionResume / FallbackSessionResumeInteractive are the resume argv a cli-agent with no session_resume gets (AGT-04): capturing an id is only half of `job resume`, and `--resume <id>` (+ `-p <prompt>` for a batch run) is the shape claude/omp/jcode share. An agent whose syntax differs either has a built-in entry (codex's `exec resume`) or writes one line of config.

Functions

func CheckAllowed

func CheckAllowed(cfg allowedAgentsLookup, projectKey, agentKey string) error

CheckAllowed verifies that agentKey is listed in the project's allowed_agents. The built-in exec agent is NOT exempt: a project must list "exec" in its allowed_agents for exec to be usable (plan §11 — built-in does not bypass the project allowlist). Returns an error when the project is unknown or the agent is not allowed.

func GlobalArgs

func GlobalArgs(ac config.AgentConfig) []string

GlobalArgs returns command-wide options that must precede a CLI subcommand in a RESUME argv (the initial argv uses only an explicit global_args). Explicit global_args wins. For existing configurations that kept those options in args, infer the prefix before the first token used as the batch resume subcommand (for example codex's "exec"). Configs with an unknown resume shape are left unchanged rather than guessing which positional token is a subcommand.

func HasBuiltinTemplate

func HasBuiltinTemplate(key string) bool

HasBuiltinTemplate reports whether key names a definition gofer ships — one of the built-in agent templates, or the reserved `exec` agent that needs no `agents:` entry at all.

A console needs it to tell the two meanings of "delete this agent" apart (WEB-04③ V1.1): deleting an operator's OVERRIDE of a built-in key does not remove a capability, it restores the built-in definition (the key comes back on the next resolve), while deleting a purely custom key removes it. The flag is deliberately about the TEMPLATE TABLE and not about whether the entry is currently injected: an operator override is a normal declared agent, and the fallback is exactly what happens to it.

func HealthState

HealthState classifies an agent's recent-job aggregate. The rule:

  • no job in the window → unknown (no evidence);
  • transient failures >= degraded_after AND fewer than recover_after_ok successes since the last of them → degraded;
  • otherwise → healthy.

A zero/negative threshold reads as "unset" and falls back to the documented default (config.EffectiveAgentHealth resolves them normally; this keeps a hand-built config from producing a nonsensical verdict such as "0 failures is already degraded").

func IsFallbackCapture

func IsFallbackCapture(reSrc string) bool

IsFallbackCapture reports whether reSrc is the generic AGT-04 fallback rather than an agent's own (built-in or configured) session_capture. Two behaviours key off it: the fallback reads only the TAIL of a log/stream (internal/job, the live pty capture), and a capture it produced is reported as `by: "fallback"` in the job.session_captured event.

func McpEnvInjectArgs

func McpEnvInjectArgs(ac config.AgentConfig, env map[string]string) []string

McpEnvInjectArgs renders codex `-c mcp_servers.<name>.env.<KEY>=<VALUE>` config overrides that push each env entry onto the gofer MCP child that codex spawns (gap①, issue 7z6j). codex starts MCP stdio servers with a SANITISED env and does NOT inherit the codex process env, so env injected into the codex process (c0f355a's runReq.Env → cmd.Env) never reaches the MCP child. Routing the same entries through codex's per-server `-c` override makes them land on the MCP child's env, so e.g. `--role supervisor`'s GOFER_AGENT_ROLE=supervisor lets the child's gofer MCP self-register role=supervisor.

It returns nil unless the agent uses codex-style `-c` config overrides AND env is non-empty — so a plain codex job (no role.env) is unaffected, and non-codex agents (e.g. claude's `--append-system-prompt`) are never touched. Keys are sorted for a deterministic rendered command. Each entry yields TWO argv elements (`-c`, `mcp_servers.<name>.env.<KEY>=<VALUE>`), mirroring SystemInject: argv is preserved element-wise and never shell-joined (SR403); codex parses the `-c` value as TOML with a raw-literal fallback, so a bare value survives intact.

Secret boundary: only the caller-supplied env (job.Env / role.env) is passed here. The MCP connection token must live in codex config.toml (`[mcp_servers.<name>].env`) — it is NEVER rendered here, so no secret enters the persisted rendered command (SR403/SR805).

func Modes

func Modes(ac config.AgentConfig) (batch, interactive bool)

Modes reports whether an agent supports batch and interactive execution.

Batch is every agent that is not declared interactive-only: exec agents and any cli-agent without the legacy `interactive: true`. A cli-agent whose args carry no {{prompt}} is still a batch agent — wrappers that take the prompt from stdin/env, or probes like `go env`, have always run that way and the only thing the old reverse gate rejected was `interactive: true`. Interactive is `interactive_args` (an empty list means a bare TUI launch) or the legacy flag, whose args ARE the interactive argv.

func NDJSONProjectorFor

func NDJSONProjectorFor(key string, a config.AgentConfig) string

NDJSONProjectorFor resolves the built-in event projector for an agent: by agent key first, then by the base name of Command (lower-cased, .exe stripped), the same fallback builtinSessionDefaults / the ndjson keep list use. An agent with no built-in projector gets the generic one, which projects nothing on its own (the whitelist is its only filter).

func Render

func Render(tmplArgs []string, vars Vars) []string

Render substitutes placeholders in each template argument INDEPENDENTLY and returns a fresh argv slice. This is the core security invariant (plan §11): the argv array is preserved element-by-element and is NEVER joined into a single shell string, so a prompt containing spaces/quotes stays one argv element and is never re-tokenised by a shell.

Example: tmplArgs ["exec", "{{prompt}}"] with Prompt=`fix "x" now` renders to ["exec", `fix "x" now`] — still two argv elements.

func Resolve

func Resolve(cfg *config.Config, d Detector) (*config.Config, map[string]DetectResult)

Resolve is the SINGLE entry point for "detect the host's agent CLIs, then merge the built-in templates into a config". Every assembly path funnels through it — core.Build, core.ReloadWith, and the core-less registries in internal/commands — so `gofer agent list`, /v1/agents, the MCP tools and a worker's advertised caps can never disagree about which agents exist on a box.

IRON RULE (P2): an ESCAPE-HATCH agent — one the operator declared in the config — is NEVER removed because a probe failed. Only TEMPLATE-INJECTED agents are detect-gated. A name clash is won by the escape hatch ENTIRELY: a template is injected only when its key does not exist, and no field-level merge is ever done (Interactive/NoRawCmd are plain bools, so "unset" and "explicit false" cannot be told apart and a partial merge would silently flip them).

Resolve mutates cfg IN PLACE and returns it, so the one *config.Config pointer that the core, the registries and the project write-back path all share stays a single object. It runs before that pointer is published to any atomic snapshot, so it adds no concurrent write.

Idempotent: keys injected by a previous Resolve are stripped first and re-gated from scratch, so resolve∘resolve == resolve. Without that, a second pass would read a previously injected template as an operator declaration and silently promote it to an un-gated escape hatch — i.e. the detect gate would only ever apply on the first pass.

The second return carries the detect result for EVERY probed agent (templates and escape hatches alike): it is the one detect pass per config, and the source T5's availability cache is meant to be fed from. Callers that do not need it discard it.

func ResolveAgent

func ResolveAgent(cfg *config.Config, key string) (config.AgentConfig, bool)

ResolveAgent resolves an agent config for key against a config snapshot, with the same built-in "exec" semantics as Registry.Get. It lets callers that already hold a config snapshot (e.g. job.Service.validate) resolve an agent from that exact snapshot rather than the registry's (possibly concurrently reloaded) pointer.

func SessionCompatible

func SessionCompatible(aKey string, a config.AgentConfig, bKey string, b config.AgentConfig) bool

SessionCompatible reports whether a session started by agent a can be continued by agent b: the same agent always can; different agents only when both sit in one session family.

func SessionFamily

func SessionFamily(key string, ac config.AgentConfig) string

SessionFamily returns the family an agent belongs to, or "" when it shares its session store with no other agent. A CLI agent not listed by key falls back to its command's base name (a renamed `claude` wrapper stays in the family); an ACP agent is only in a family when listed by key.

An explicit `session_family` on the agent wins over the built-in table (and joins agents the table knows nothing about, e.g. a self-built CLI agent and its ACP front-end sharing one store). Family names compare case-insensitively.

func ValidateConfig

func ValidateConfig(cfg *config.Config) error

ValidateConfig checks mode combinations shared by server and worker loading.

func WithModelArgs

func WithModelArgs(tmpl, modelArgs []string) []string

WithModelArgs returns tmpl with modelArgs spliced in right before the first argument that holds {{prompt}} (N1 §B), or appended at the end when no argument does (an interactive / interactive-resume shape). Empty modelArgs returns tmpl unchanged, so a job that names no model renders byte-for-byte what it always did. The result is a fresh slice; tmpl is never modified.

Types

type BuildOptions

type BuildOptions struct {
	AllowEmptyPrompt bool
	Interactive      bool     // select interactive_args when building an interactive job
	AgentArgs        []string // extra args appended to cli-agent argv (§14)
	// ReadOnly appends the agent's resolved read-only args to a cli-agent's argv
	// (agent config read_only_args, filled from the built-in table) — the flag is what
	// actually puts the CLI in its sandbox. Admission has already refused the request
	// when the agent has no read-only mode, so an empty list here appends nothing.
	ReadOnly bool
	// Model is the model the job asked for (N1 §B). Empty leaves the argv untouched.
	// A cli-agent splices its model_args (carrying {{model}}) before the prompt
	// argument; an agent without model_args is an error rather than a silent drop.
	Model string
	// FromSession is the earlier session a new one inherits context from (gofer-f4z8,
	// `job run --from-session`). Empty leaves the argv untouched. A cli-agent appends
	// its rendered from_session_args right after the args template (before AgentArgs);
	// an agent without from_session_args is an error rather than a silent drop.
	FromSession string
}

BuildOptions adjusts request resolution for paths with different admission semantics. The default zero value preserves the public Build behaviour.

type DetectResult

type DetectResult struct {
	Available bool
	Version   string
	Error     string
}

DetectResult reports an agent's availability.

Available is decided by lookPathProbe and by NOTHING else: it never depends on a child process' exit code. Version is best-effort — a failed or hung version probe costs the version string and NEVER the availability.

Error carries the reason an agent is unavailable (unknown key / no command / not on PATH). It is left empty when Available is true: consumers must read Available, not the presence of an error.

type Detector

type Detector interface {
	Detect(agents map[string]config.AgentConfig) map[string]DetectResult
}

Detector probes which agent CLIs are actually installed on THIS host. It is the injection seam that lets the real probe be swapped for a hermetic fake, which is what keeps `go test ./...` independent of whatever CLIs happen to sit on the developer's PATH (see core.WithAgentDetector / NoopDetector).

Contract:

  • Detect is called AT MOST ONCE per Resolve, and gets EVERY candidate agent in one call — so an implementation is free to fan out in parallel and enforce a single overall budget rather than a per-agent one.
  • It must never panic and never block indefinitely. A failed probe is reported as Available=false with an Error, never as a returned error.
  • A key missing from the returned map is read as unavailable.

func DefaultDetector

func DefaultDetector() Detector

DefaultDetector returns the Detector every production assembly path uses when the caller injects none.

type NoopDetector

type NoopDetector struct{}

NoopDetector reports every agent unavailable without touching the host: no PATH lookup, no child process. Inject it wherever template materialization must not depend on what happens to be installed — every test that builds a Core, and any caller that must stay hermetic.

With it, Resolve injects NOTHING; the operator's declared agents are untouched (the iron rule keeps escape hatches regardless of any probe outcome), so a config resolves to exactly the agent set it declared.

func (NoopDetector) Detect

Detect implements Detector.

type Registry

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

Registry exposes the agents declared in a loaded config plus the built-in exec agent. It is read-only over *config.Config.

The config AND the availability cache are held behind ONE atomic.Pointer so SIGHUP-driven hot-reload (C3) can atomically swap both without locking the read paths. Each read takes one snapshot so a concurrent Reload cannot tear a single call — and, because the two live in the same snapshot, a reader can never pair a new config with the previous config's detect results.

func NewRegistry

func NewRegistry(cfg *config.Config) *Registry

NewRegistry builds an agent registry over cfg with a COLD availability cache. Callers that already ran a detect pass (core.Build, via agent.Resolve) must use NewRegistryWith so the results are cached instead of re-probed per request.

func NewRegistryWith

func NewRegistryWith(cfg *config.Config, avail map[string]DetectResult) *Registry

NewRegistryWith builds an agent registry over cfg and SEEDS its availability cache with avail — the second return of agent.Resolve, i.e. the results of the one detect pass that already ran for this config.

This is what keeps GET /v1/agents and the MCP ListAgents tool free of child processes: both are read paths over this cache, and ListAgents in particular is a tool an agent calls repeatedly. Passing a nil avail here still counts as seeded (a Detector ran and reported nothing — e.g. NoopDetector in tests); pass through NewRegistry to declare that no detect pass ran at all.

func (*Registry) Availability

func (r *Registry) Availability() map[string]DetectResult

Availability returns the availability of EVERY agent in the registry WITHOUT spawning a child process per call: it serves the results of the ONE detect pass that already ran for the current config (core.Build / core.ReloadWith → agent.Resolve → NewRegistryWith/ReloadWith).

This is the read path GET /v1/agents and the MCP ListAgents tool sit on. Both used to run a live probe per agent PER REQUEST — ListAgents especially, which an agent calls over and over, and whose cost scales with the agent count that P2's template injection is about to grow.

Freshness: the cache turns over with the config snapshot, so a CLI installed after the process started shows up on the next reload (SIGHUP / `gofer worker reload`), which re-runs the detect pass. It does NOT self-refresh on a timer — availability is a display/report fact, never an admission gate.

Two invariants keep this cache from EVER producing a false negative (an installed agent reported as missing — which is how an agent silently vanishes from a caps view):

  • A COLD cache (registry built outside core: the core-less CLI paths, tests) is probed live once and memoized — never read as "everything unavailable".
  • An exec-type agent is available by construction (no external CLI to find), so it is answered from lookPathProbe regardless of what the cache holds — a hermetic Detector (NoopDetector) must not be able to report the BUILT-IN exec agent gone.

The returned map is a fresh copy; callers may keep or mutate it freely.

func (*Registry) Build

func (r *Registry) Build(agentKey, prompt string, cmd []string, vars Vars) (Resolved, error)

Build turns a single job request into an executable Resolved form. The argv-preserving contract of Render (plan §11) is upheld: nothing is ever joined into a shell string.

Parameters (P4's JobRequest is not built yet, so adapter takes plain inputs):

  • agentKey: which configured/built-in agent to use.
  • prompt: the prompt text for cli-agent agents.
  • cmd: the request-supplied argv for exec agents (argv[0] is the command). Ignored for cli-agent agents.
  • vars: placeholder values for cli-agent template rendering. Prompt is taken from the prompt parameter (vars.Prompt is overwritten to keep them consistent).

func (*Registry) BuildWithOptions

func (r *Registry) BuildWithOptions(agentKey, prompt string, cmd []string, vars Vars, opts BuildOptions) (Resolved, error)

BuildWithOptions is Build with explicit resolution options. The agent is resolved against the registry's CURRENT config pointer, so a caller that must stay pinned to one config snapshot for a whole operation uses BuildFrom instead (see its doc).

func (*Registry) Detect

func (r *Registry) Detect(agentKey string) DetectResult

Detect reports one agent's availability, for DISPLAY paths (`gofer agent detect`, GET /v1/agents, the MCP ListAgents tool). It shares the availability rule with the batch Detector (lookPathProbe) so a box can never report an agent as usable in one view and unusable in another.

Semantics:

  • Unknown agent -> Available=false with an error.
  • exec agent -> Available=true, always (no external CLI to probe).
  • Any other agent -> Available=true iff its command resolves on PATH. A missing detect block is NOT a reason to report unavailable: it used to be, which reported an installed CLI as unusable purely because the operator had written no detect stanza.
  • Version -> best-effort, bounded; failure leaves it empty, never flips Available. Never panics.

func (*Registry) Get

func (r *Registry) Get(key string) (config.AgentConfig, bool)

Get returns the agent config for key. The built-in "exec" agent resolves even when the config does not declare it. The second return is false for an unknown key.

func (*Registry) Injected

func (r *Registry) Injected() map[string]bool

Injected reports which agent keys of the current snapshot were materialized from a BUILT-IN template rather than declared by the operator (see config.MarkInjectedAgents / agent.Resolve). The read paths that LIST agents surface it so a console can say why an agent the operator never wrote is there — /v1/agents otherwise shows built-in and declared agents as one undifferentiated set. nil means none (a config assembled without the template pass, e.g. tests).

func (*Registry) List

func (r *Registry) List() map[string]config.AgentConfig

List returns every agent keyed by name (config-declared plus built-in exec).

func (*Registry) Names

func (r *Registry) Names() []string

Names returns all agent keys (config-declared plus the built-in exec), sorted for stable output. The built-in exec is included even if not declared.

func (*Registry) Reload

func (r *Registry) Reload(newCfg *config.Config)

Reload atomically swaps the registry's config to newCfg (C3 hot-reload), leaving the availability cache COLD (lazily re-probed). Callers on the reload path already hold fresh detect results (core.ReloadWith) and must use ReloadWith instead.

func (*Registry) ReloadWith

func (r *Registry) ReloadWith(newCfg *config.Config, avail map[string]DetectResult)

ReloadWith atomically swaps BOTH the config and the availability cache (C3 hot-reload). The two are swapped as one snapshot, so a reader concurrent with the swap sees either the old config with its old detect results or the new config with its new ones — never a mix.

This is how a newly installed CLI becomes visible: the reload runs one fresh detect pass (core.ReloadWith → agent.Resolve) and its results land here.

type Resolved

type Resolved struct {
	Command string
	Args    []string
	Env     map[string]string
}

Resolved is the executable form of one job request: the command to run, its argv (excluding command), and the agent-config-level env. The runner (P4) layers process env on top of Env; the adapter returns only the agent's own env so callers control the merge order.

func BuildFrom

func BuildFrom(cfg *config.Config, agentKey, prompt string, cmd []string, vars Vars, opts BuildOptions) (Resolved, error)

BuildFrom is BuildWithOptions against an EXPLICIT config snapshot instead of the registry's (concurrently swappable) config pointer — the Build-side counterpart of ResolveAgent.

It exists so an operation that consults the config more than once resolves every fact from ONE version of it: job.Service.Submit validates the request against a config snapshot taken at entry and must build the executable argv from that same snapshot. Going through the registry there would let a reload landing mid-submit produce a job that passed the OLD policy but executes the NEW agent's command.

type ResumeCaps

type ResumeCaps struct {
	// SessionResume: a non-interactive CLI resume template exists (`--resume -p`).
	SessionResume bool
	// SessionResumeInteractive: an interactive (pty) resume template exists.
	SessionResumeInteractive bool
	// LoadSession: an ACP agent that can reload a session (session/load).
	LoadSession bool
	// FromSession: a NEW session can inherit an earlier one's context
	// (`job run --from-session`, gofer-f4z8) — a cli-agent with from_session_args.
	FromSession bool
	// Family is SessionFamily(key, ac).
	Family string
}

ResumeCaps is how an agent's session can be continued; it feeds GET /v1/agents so a client can grey out resume forms that would be rejected.

func ResumeCapabilities

func ResumeCapabilities(key string, ac config.AgentConfig) ResumeCaps

ResumeCapabilities summarises how ac's sessions can be continued.

type Vars

type Vars struct {
	Prompt    string
	Cwd       string
	JobID     string
	ResultDir string
	SessionID string
	// SystemPrompt feeds {{system_prompt}} in an agent's SystemInject template
	// (E35 role injection, e.g. claude --append-system-prompt).
	SystemPrompt string
	// Text feeds {{text}} in an agent's DeliverCommand (the web message typed to a
	// live session, already carrying the reply prefix).
	Text string
	// Model feeds {{model}} in an agent's ModelArgs (N1 §B).
	Model string
	// FromSession feeds {{from_session}} in an agent's FromSessionArgs (gofer-f4z8):
	// the earlier session the new one inherits its context from.
	FromSession string
}

Vars holds the values substituted into command-template placeholders. See plan §9 (P3): first-phase placeholders are {{prompt}} {{cwd}} {{job_id}} {{result_dir}}. SessionID feeds {{session_id}} for session inject/resume templates (session-capture §5.1/§6.4).

Jump to

Keyboard shortcuts

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