commander

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: AGPL-3.0 Imports: 34 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 commander implements the three-tier capability execution: native (deterministic commands, no model), agent (AI CLI via adapter), and manual (human-notified). Design doc §6.

Index

Constants

View Source
const DefaultNativeTimeout = 5 * time.Minute

DefaultNativeTimeout is the built-in per-command budget NewExecutor ships with. The operator's timeouts.native_s knob replaces THIS value only — an explicit WithTimeout is a deliberate bound the global default must not stretch (a 30s probe command would otherwise inherit a 30m ceiling).

Variables

This section is empty.

Functions

func AdapterDir added in v0.0.3

func AdapterDir() string

AdapterDir returns the directory the current process resolves adapter scripts from. The self-updater uses it to install updated adapter scripts beside the running binary without re-deriving the resolution rules.

func AdapterSupportsRestricted added in v0.0.10

func AdapterSupportsRestricted(adapter string) bool

AdapterSupportsRestricted reports whether the named adapter can honor a read-only run. The answer comes from the agent registry's capability declaration (Capabilities.SupportsRestricted), not a local table, so the allowlist cannot drift from the manifest that describes the adapter. Unknown adapters get false — a miss means refuse.

func AgentHardTimeout added in v0.0.6

func AgentHardTimeout() time.Duration

AgentHardTimeout reports the enforced wall-clock limit for one agent execution. A task's lease must exceed it, or the lease monitor force-fails work that is still legitimately running — see core.Core.SetTimeouts.

func AgentName added in v0.0.10

func AgentName(ctx context.Context) string

AgentName reads the card agent name WithAgentName attached — "" when none.

func ContextOverflow added in v0.0.7

func ContextOverflow(text string) bool

ContextOverflow reports whether a failure text looks like the agent's context window overflowing. Exported for the orchestration layer, which gives such failures one compressed retry and then parks them in review.

func DropAgentSession added in v0.1.0

func DropAgentSession(ctx context.Context, agent, adapter string)

DropAgentSession evicts the live session-mode process an agent's pool may hold for (agent, adapter): the next turn then spawns a fresh conversation instead of reusing the evicted one's transcript. The context-overflow recovery uses this — a pooled session replays the very transcript that just overflowed. No-op without a pool or live session.

func EffectiveBaseURL added in v0.0.8

func EffectiveBaseURL(model config.ModelConfig) string

EffectiveBaseURL returns the endpoint base URL to use for injection.

func InjectionNotice added in v0.0.2

func InjectionNotice(d InjectionDecision, agent string) string

InjectionNotice renders the one-line announcement prepended to a task's output whenever a model injection happens, so the user always sees what was injected and why (no secrets included).

Deliberately one short line, one language: it is a footnote on someone else's output. The endpoint drops its scheme (the full URL is in the audit log and the model_injection event) and the reason collapses to the config value that caused it — the old form duplicated the whole sentence in English and Chinese, which buried the agent's actual answer.

func IsAuthorizationRefusal added in v0.0.4

func IsAuthorizationRefusal(stderr string) bool

IsAuthorizationRefusal reports whether a failure string carries the tier-2 authorization refusal. The retry loop uses it to skip pointless re-runs: a policy refusal is deterministic — another attempt cannot produce consent.

func ModelCredsWithheld added in v0.0.11

func ModelCredsWithheld(ctx context.Context) bool

ModelCredsWithheld reports whether the execution context withholds this node's model credentials from the adapter subprocess env.

func NativeTimeout added in v0.0.11

func NativeTimeout() time.Duration

NativeTimeout reports the effective process-global native budget; zero when unset (callers fall back to the executor's own timeout).

func ParseActionSpec added in v0.0.9

func ParseActionSpec(specJSON string) (*ledger.ActionSpec, error)

ParseActionSpec extracts the action_spec block from a task's spec JSON. A spec without one yields nil, nil — the actuator's {intent} substitution still applies, and a command needing {action}/{param:...} then fails substitution with a clear error instead of executing literal braces.

func ProtectedPaths added in v0.0.10

func ProtectedPaths(cfg *config.Config, configPath, cardPath string) []string

ProtectedPaths builds the node-state deny list shared by the daemon and the embedded engine (askengine): the database + WAL directory, the memory and skills stores, the artifact pool, the config and card files, and the arbitration shadow tree — bookkeeping the drift detector and audit chain verify, so a sandboxed subprocess must never be able to rewrite it.

func RemoteTask added in v0.0.10

func RemoteTask(ctx context.Context) bool

RemoteTask reports whether the execution context carries a remote-origin task (set by the orchestration layer before Execute).

func Restricted added in v0.0.10

func Restricted(ctx context.Context) bool

Restricted reports whether the context asks for a read-only agent run.

func ResumeAdapter added in v0.1.0

func ResumeAdapter(ctx context.Context) string

ResumeAdapter reads the adapter that minted the attached handle — "" when none, or when the producer is unknown (a legacy row). Tests use it to pin that the handle travels with its mint tag, which is what lets buildAdapterRequest decide per attempt instead of per round.

func ResumeID added in v0.0.9

func ResumeID(ctx context.Context) string

ResumeID reads the session id WithResume attached — "" when none. The adapter runner and tests use it to observe what the supervision loop threaded through.

func SecretReadDenyPaths added in v0.1.0

func SecretReadDenyPaths(cfg *config.Config, configPath, cardPath string) []string

SecretReadDenyPaths lists the node-owned files a sandboxed process must not read under strict mode: the config and capability card beside it, the SQLite database and its WAL/SHM siblings (the node key pairs live in the settings table), and the subscription OAuth token store. Only the files, never their parent directories — the work trees share those.

func SessionMode added in v0.0.10

func SessionMode(ctx context.Context) bool

SessionMode reports whether the context asks for session execution.

func SetAgentTimeout added in v0.0.6

func SetAgentTimeout(d time.Duration)

SetAgentTimeout retunes the agent-adapter execution budget. A deep-learning stage legitimately runs far longer than a code edit, so the limit has to be operator-tunable rather than a compile-time constant. Values under a minute are ignored as misconfiguration. Process-global: call it during startup, before any task executes.

func SetNativeTimeout added in v0.0.11

func SetNativeTimeout(d time.Duration)

SetNativeTimeout applies the configured native-command budget. Zero or negative leaves executors on their built-in default (5m), so an unconfigured fleet behaves exactly as before.

func SetSandboxConfig added in v0.0.10

func SetSandboxConfig(sc config.SandboxConfig, protected, secretReads []string) string

SetSandboxConfig installs the node-wide base policy from config plus the node's own protected state paths (database, memory, card, config file — the bookkeeping the drift detector and audit chain rely on). Returns the backend name actually in effect ("" when the mode is off or the platform has no backend) so the caller can log it.

func SetSilenceTimeout added in v0.0.8

func SetSilenceTimeout(d time.Duration)

SetSilenceTimeout retunes the progress silence limit. 0 means disabled — the config layer maps an explicit silence_s: -1 to that; an unset key now arrives as DefaultSilenceS instead, since a wedged adapter emitting nothing for minutes is a corpse worth killing, not a worker worth waiting on.

func SubstituteActionSpec added in v0.0.9

func SubstituteActionSpec(p *Plan, spec *ledger.ActionSpec, intent string) error

SubstituteActionSpec fills an actuator plan's placeholders from spec and intent, in place. It is a no-op for non-actuator plans. A spec naming a different actuator than the plan resolved is rejected — executing another actuator's command with this spec's parameters would act on hardware the task never asked for.

func TaskID added in v0.0.9

func TaskID(ctx context.Context) string

TaskID reads the task ID WithTaskID attached — "" when none.

func WithAgentCommand added in v0.0.10

func WithAgentCommand(ctx context.Context, cmd string) context.Context

WithAgentCommand attaches a command template to the execution context; runAdapterProcess copies it into AdapterRequest.Cmd for adapters that read it (generic.py). Empty is a no-op.

func WithAgentEvents added in v0.0.10

func WithAgentEvents(ctx context.Context, fn AgentEventFunc) context.Context

WithAgentEvents attaches a structured-event sink to an execution context. Adapters emit {"type":"event",…} NDJSON on stderr alongside the progress notes; runAdapterProcess parses and forwards them here. Nil/absent = the events are parsed out of diagnostics and dropped.

func WithAgentName added in v0.0.10

func WithAgentName(ctx context.Context, name string) context.Context

WithAgentName attaches the card agent name to the execution context; runAdapterDefault reads it for name-aware registry lookups. Empty is a no-op.

func WithAgentTimeout added in v0.0.7

func WithAgentTimeout(ctx context.Context, d time.Duration) context.Context

WithAgentTimeout attaches a per-task agent execution timeout to the context; runAdapterProcess honours it over the global SetAgentTimeout value.

func WithComplexity added in v0.1.0

func WithComplexity(ctx context.Context, c float64) context.Context

WithComplexity attaches the entry classifier's complexity score to the execution context; runAdapterProcess copies it into AdapterRequest.Complexity. Adapters that pick among several models (opencode's free/paid roster) read it to prefer their free tier on simple tasks. Non-positive is a no-op — 0 means the task was never scored.

func WithEffort added in v0.0.10

func WithEffort(ctx context.Context, effort string) context.Context

WithEffort attaches a reasoning-effort level (e.g. "high"); adapters without an effort flag ignore it. Empty is a no-op.

func WithMCPConfig added in v0.0.10

func WithMCPConfig(ctx context.Context, doc string) context.Context

WithMCPConfig attaches the passthrough MCP config document. Empty is a no-op.

func WithMaxTurns added in v0.0.10

func WithMaxTurns(ctx context.Context, n int) context.Context

WithMaxTurns attaches a per-task agent turn cap to the execution context; runAdapterProcess copies it into AdapterRequest.MaxTurns. Non-positive is a no-op — the adapter then falls back to its own default.

func WithModelCredsWithheld added in v0.0.11

func WithModelCredsWithheld(ctx context.Context) context.Context

WithModelCredsWithheld marks the execution context as carrying a task whose trust-zone admission tier withholds this node's model credentials (trust.AcceptPolicy.ModelCreds == withhold).

func WithProgress added in v0.0.2

func WithProgress(ctx context.Context, fn ProgressFunc) context.Context

WithProgress attaches a compact progress-note sink to an execution context: the agent's one-line status notes ("Bash: ls -la", "subagent: Explore") the orchestration layer records on the task timeline. Nil = notes are parsed out of diagnostics and dropped.

func WithRemoteTask added in v0.0.10

func WithRemoteTask(ctx context.Context) context.Context

WithRemoteTask marks the execution context as carrying a remote-origin task. Execute uses it to hold agent plans to the restricted tool face whenever the task arrived unconsented.

func WithRestricted added in v0.0.10

func WithRestricted(ctx context.Context) context.Context

WithRestricted asks the adapter subprocess to run with only read-capable tools. Adapters without a restricted mode must never receive it — the execAgent loop filters on AdapterSupportsRestricted before spawning.

func WithResultSchema added in v0.0.10

func WithResultSchema(ctx context.Context, schema string) context.Context

WithResultSchema attaches the JSON Schema for the run's structured output; adapters whose CLI lacks the flag ignore it and the marker protocol remains the fallback. Empty is a no-op.

func WithResume added in v0.0.7

func WithResume(ctx context.Context, sessionID, adapter string) context.Context

WithResume attaches an agent session id to the execution context; runAdapterProcess copies it into AdapterRequest.Resume. Empty is a no-op. adapter names the producer's adapter file ("opencode.py"): a session handle is only meaningful to the adapter that minted it, so a supervision round whose plan (or fallback chain) lands on a different adapter must not be offered the foreign handle — opencode answering "Expected a string starting with ses" to a claude UUID, then cold-starting and re-burning the whole run on every retry, is exactly the failure this prevents. An empty adapter means the producer is unknown (a legacy row); the offer stands.

func WithSessionMode added in v0.0.10

func WithSessionMode(ctx context.Context) context.Context

WithSessionMode asks the adapter to keep the agent process alive across turns. Only set for adapters whose registry entry declares Capabilities.SupportsSession.

func WithSystemPrompt added in v0.0.10

func WithSystemPrompt(ctx context.Context, text string) context.Context

WithSystemPrompt attaches the static protocol/system rider text the adapter passes to the CLI's append-system-prompt flag. Empty is a no-op.

func WithTaskID added in v0.0.9

func WithTaskID(ctx context.Context, taskID string) context.Context

WithTaskID attaches an OpenPanda task ID to the execution context; runAdapterProcess injects PANDA_TASK_ID into the spawned process environment and sets task_id in the adapter request JSON.

func WithToolsPolicy added in v0.0.7

func WithToolsPolicy(ctx context.Context, policy string) context.Context

WithToolsPolicy attaches the normalized tools policy to an execution context. The orchestration layer sets it on the execution context to override with a per-task policy from the task spec; the Router applies its global policy (routing.tools_policy) only when the context carries no task-level policy yet, so a per-task override always takes precedence.

Types

type AdapterRequest

type AdapterRequest struct {
	Prompt   string `json:"prompt"`
	TimeoutS int    `json:"timeout_s"`
	CWD      string `json:"cwd,omitempty"`
	// Resume carries the agent session id a previous run returned, so a
	// follow-up round (the supervision loop's "continue" verdict) resumes the
	// agent's own conversation instead of cold-starting on the bare follow-up
	// text. Adapters without session support ignore it.
	Resume string `json:"resume,omitempty"`
	// ToolsPolicy grades the tool face the adapter runs with: minimal (or
	// empty) keeps the adapter's safe whitelist; extended lifts it so the
	// agent's native skills, sub-agent tooling and project MCP servers are
	// reachable. Set by the Router from routing.tools_policy.
	ToolsPolicy string `json:"tools_policy,omitempty"`
	// Restricted asks for the adapter's read-only mode and OUTRANKS
	// ToolsPolicy: an unconsented remote task on an operator who chose
	// extended still gets no shell. Only adapters whose registry entry
	// declares Capabilities.SupportsRestricted ever see it set.
	Restricted bool `json:"restricted,omitempty"`
	// TaskID carries the OpenPanda task ID that this process executes for.
	// Used for causal subagent tree linkage and subtask dispatch.
	TaskID string `json:"task_id,omitempty"`
	// Cmd is the argv template a generic adapter expands ({prompt}
	// placeholder). It comes from the card's agents.<name>.command field, so
	// a node can wire a new CLI without shipping a bespoke adapter script.
	Cmd string `json:"cmd,omitempty"`
	// MaxTurns is a per-task agent turn cap from the task spec
	// (spec.max_turns). Adapters without a turn-limit flag ignore it; those
	// that have one apply it instead of their own default.
	MaxTurns int `json:"max_turns,omitempty"`
	// SystemPrompt is appended to the agent's own system prompt
	// (--append-system-prompt on claude): the static protocol riders ride
	// there so the user prompt carries only the task and the stable prefix
	// caches across rounds. Ignored by adapters without the flag.
	SystemPrompt string `json:"system_prompt,omitempty"`
	// ResultSchema is a JSON Schema the run's final reply validates against
	// (claude --json-schema): status/question/delegate_requests arrive
	// parsed instead of as text markers. Empty = no structured contract.
	ResultSchema string `json:"result_schema,omitempty"`
	// MCPConfig is a ready-made {"mcpServers":{…}} document for CLIs that
	// take an MCP config flag (claude --mcp-config): the passthrough servers
	// ride the request instead of a .mcp.json written into the work dir.
	MCPConfig string `json:"mcp_config,omitempty"`
	// MaxBudgetUSD caps the run's spend inside the harness where the CLI
	// supports it (claude --max-budget-usd). 0 = unset.
	MaxBudgetUSD float64 `json:"max_budget_usd,omitempty"`
	// Effort names the CLI's reasoning-effort level (claude --effort).
	Effort string `json:"effort,omitempty"`
	// Complexity is the task's 0–1 difficulty score from the entry
	// classifier (§7.3). Adapters that pick among several served models
	// (opencode) read it to prefer their free tier on simple tasks.
	// 0 = unset — unclassified work gets the adapter's default ordering.
	Complexity float64 `json:"complexity,omitempty"`
	// Session asks the adapter to keep the agent process alive across
	// turns: the request is followed by line-framed {"type":"user","text"}
	// turn inputs and each turn produces one result envelope (Phase 6).
	Session bool `json:"session,omitempty"`
}

AdapterRequest is written to the adapter's stdin.

type AgentCandidate added in v0.0.2

type AgentCandidate struct {
	Name  string
	Agent ledger.Agent
	Score float64
}

AgentCandidate is one scored agent match produced by RankAgents.

type AgentCheck added in v0.0.9

type AgentCheck struct {
	// Usable is the dispatch verdict — the same check routing applies.
	Usable bool
	// Reason explains the first failing check in fixable terms ("" when
	// Usable): missing cli, no credentials, unreachable endpoint.
	Reason string
	// ModelSrc is where the run's model comes from:
	// "own" (agent credentials), "injected" (panda's model), "self"
	// (self-contained), or "none" (no usable source).
	ModelSrc string
	// Model is the injected model name; only set when ModelSrc == "injected".
	Model string
	// Endpoint is the provider base URL the run would hit ("" = undeterminable).
	Endpoint string
	// Reachable is the cached endpoint verdict; meaningful only when
	// Endpoint != "".
	Reachable bool
	// Detail is the probe's short status ("http 200", "http 503", dial error)
	// — operator-facing, never carries credentials.
	Detail string
	// Rejected is true when the endpoint refused the definitive credential
	// (bad key or empty quota) — the fix is credentials, not connectivity.
	Rejected bool
}

AgentCheck is the user-facing dispatch-readiness report for one agent: whether it would accept a task right now, why not when it would not, which model source the run would use, and the provider endpoint it would hit. It backs `panda agents test`, where the reason must name the fix.

type AgentEvent added in v0.0.10

type AgentEvent struct {
	// Ev is the block kind: "text" | "thinking" | "tool_use" |
	// "tool_result" | adapter-specific extensions.
	Ev string `json:"ev"`
	// ID is the block's own id (tool_use blocks), Parent the enclosing
	// tool_use id for sub-agent content.
	ID     string `json:"id,omitempty"`
	Parent string `json:"parent,omitempty"`
	// Name is the tool name for tool_use; ToolUseID the call a tool_result
	// answers.
	Name      string `json:"name,omitempty"`
	ToolUseID string `json:"tool_use_id,omitempty"`
	// Text/Thinking/Content carry the block's body (bounded by the adapter
	// and hard-capped again here); Input is the tool_use argument object.
	Text     string          `json:"text,omitempty"`
	Thinking string          `json:"thinking,omitempty"`
	Content  string          `json:"content,omitempty"`
	Input    json.RawMessage `json:"input,omitempty"`
	IsError  bool            `json:"is_error,omitempty"`
	// Adapter names the adapter file that produced the event — stamped by
	// the process wrapper, never parsed off the wire, so control-plane
	// consumers (session-checkpoint persistence) can attribute a minted
	// handle to the adapter that must later resume it.
	Adapter string `json:"adapter,omitempty"`
}

AgentEvent is one structured activity block the adapter streamed back — a text/thinking/tool_use/tool_result block from the harness's event feed. Parent carries the enclosing tool_use id when the block ran inside a sub-agent (e.g. a Claude Task call), which is what lets the display layer nest the delegation tree.

type AgentEventFunc added in v0.0.10

type AgentEventFunc func(AgentEvent)

AgentEventFunc receives one structured agent-activity event. It is the transcript channel — every block the harness emitted — where ProgressFunc is the compact status line.

func AgentEvents added in v0.0.10

func AgentEvents(ctx context.Context) AgentEventFunc

AgentEvents reads the structured-event sink WithAgentEvents attached — nil when none.

type AgentResult

type AgentResult struct {
	OK        bool         `json:"ok"`
	Result    string       `json:"result"`
	Stderr    string       `json:"stderr"`
	ExitCode  int          `json:"exit_code"`
	Tokens    int          `json:"tokens"`
	Cost      float64      `json:"cost"`
	Usage     *UsageDetail `json:"usage"`
	SessionID string       `json:"session_id"`
	Model     string       `json:"model,omitempty"`
	Injected  bool         `json:"injected,omitempty"`
	// Structured is the harness's validated structured output (claude
	// --json-schema → structured_output), passed through verbatim. When the
	// schema carries the panda protocol fields (status/question/
	// delegate_requests) the run loop reads them here instead of parsing
	// markers out of prose.
	Structured json.RawMessage `json:"structured,omitempty"`
	// SubagentStats is the harness's own delegation fan-out summary
	// (claude's result.subagent_stats) — how many sub-agents the run
	// spawned, by type. Passthrough for observability.
	SubagentStats json.RawMessage `json:"subagent_stats,omitempty"`
	// SessionDead marks a session-mode result whose adapter process is
	// gone. The session teardown marker (cmd.Wait) races the envelope
	// when the adapter kills the CLI on its way out, so a failed turn
	// needs the in-band verdict to drive the one-shot fallback.
	SessionDead bool `json:"session_dead,omitempty"`
}

AgentResult is what an adapter returns. Every field carries its wire name explicitly: Go's untagged fallback matches keys case-insensitively but NOT underscore-insensitively, so without the tags "exit_code" would silently drop — adapter-reported 124/127/2 would all decode as 0.

type AgentSessions added in v0.0.10

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

AgentSessions holds the session-mode adapter processes one task opened — keyed by adapter so a plan whose fallback chain crosses adapters keeps one session per CLI. The pool's context is the task's execution context: a task abort cancels every live session without waiting on turn boundaries.

func WithSessionPool added in v0.0.10

func WithSessionPool(ctx context.Context) (context.Context, *AgentSessions)

WithSessionPool attaches a session pool to the execution context and returns both; the caller defers pool.CloseAll() so no adapter process outlives the task.

func (*AgentSessions) CloseAll added in v0.0.10

func (p *AgentSessions) CloseAll()

CloseAll kills every live session. Idempotent; called when the task's supervision loop finishes — whatever the verdict.

type Executor

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

Executor runs native commands with a timeout and captures output. It never invokes an LLM — native commands are deterministic by contract.

func NewExecutor

func NewExecutor() *Executor

NewExecutor creates a native executor. Default timeout 5m, no working dir.

func (*Executor) Run

func (e *Executor) Run(ctx context.Context, command string, args ...string) NativeResult

Run executes a command and returns its result. ctx may carry a shorter deadline than the effective timeout; the operator's native_s knob (when set) replaces the executor's built-in default, never an explicit WithTimeout bound.

func (*Executor) WithDir

func (e *Executor) WithDir(dir string) *Executor

WithDir sets the working directory for commands.

func (*Executor) WithTimeout

func (e *Executor) WithTimeout(d time.Duration) *Executor

WithTimeout sets the command timeout.

type FileContext

type FileContext struct {
	Type   string            `json:"type"`
	Repo   string            `json:"repo,omitempty"`
	Branch string            `json:"branch,omitempty"`
	Commit string            `json:"commit,omitempty"`
	Scope  []string          `json:"scope,omitempty"`
	Env    map[string]string `json:"env,omitempty"`
}

FileContext is the file-type task context (design doc §12.5). It records repo identity plus optional scope so the executor knows what to touch.

func (*FileContext) Hash

func (fc *FileContext) Hash() string

Hash returns a reproducible SHA-256 of the context (excluding volatile paths). Used as the context_store key and pointer hit check.

type InjectionDecision added in v0.0.2

type InjectionDecision struct {
	Inject  bool
	Reason  string
	Model   string        // model name injected (empty when Inject is false)
	BaseURL string        // endpoint injected (empty when Inject is false)
	Kind    InjectionKind // why it injected; empty when Inject is false
}

InjectionDecision is the outcome of the model-injection policy check for one agent adapter: whether panda overrides the agent's model endpoint via env, and a secret-free human-readable reason for announcements/audit.

type InjectionKind added in v0.1.1

type InjectionKind string

InjectionKind classifies why an injection happened, in the compact form the task-output notice prints. The full sentence lives in Decision.Reason, which is audit and event material — the notice is a one-line footnote on the agent's own output, so it carries the config value, not prose.

const (
	// InjectionKindAuto is the "agent had no credentials of its own" path.
	InjectionKindAuto InjectionKind = "auto"
	// InjectionKindAlways is the injection.model=always override.
	InjectionKindAlways InjectionKind = "always"
	// InjectionKindRescue is the failure-time retry: the agent's own model
	// failed with a provider/auth error, so panda's model ran the second
	// attempt.
	InjectionKindRescue InjectionKind = "rescue"
)

type NativeResult

type NativeResult struct {
	OK       bool
	ExitCode int
	Stdout   string
	Stderr   string
}

NativeResult is the outcome of a deterministic command.

type Plan

type Plan struct {
	Kind    string // native | agent | manual
	Ability string
	Command string
	Args    []string
	Tier    int // native command tier (defense §16)
	Agent   string
	Adapter string
	Notify  string
	// Alternates lists the remaining matching agents in score order. When
	// the primary agent's CLI is unavailable at execution time, execAgent
	// falls back through this chain.
	Alternates []string
	// ActuatorID is set when the plan resolves to a card actuator (§7.2):
	// the command is that actuator's driver invocation, and the run path
	// substitutes its {intent}/{action}/{param:<name>} placeholders from the
	// task's action_spec before execution. Empty for ordinary plans.
	ActuatorID string
}

Plan describes how to execute a task on this node.

type ProbeSpec added in v0.0.9

type ProbeSpec struct {
	Endpoint string // resolved provider base URL
	APIType  string // "anthropic" | "openai" | "responses" — request shape
	APIKey   string // optional; auth proves more than connectivity when present
	Model    string // model name when known; a wrong name still earns a 4xx
	// KeyDefinitive marks APIKey as literally the credential the run sends —
	// an env var, an inline token, the injected key — not a possibly-stale
	// OAuth access token extracted from an auth store the CLI would refresh.
	// Only a definitive key lets a 401/402/403 verdict mean "the run
	// would fail the same way"; without one that response just proves the
	// service is up.
	KeyDefinitive bool
	// RejectionHint carries a secret-free reason the harness's own state
	// recorded against this endpoint's credential — e.g. hermes's
	// credential_pool marking a provider "exhausted / INSUFFICIENT_BALANCE".
	// When the probe itself cannot authenticate (the secret lives in a
	// keyring), the hint corroborates an auth-class 4xx into a rejection:
	// the endpoint refusing AND the harness recording a credential failure
	// is conclusive where either alone is not.
	RejectionHint string
}

ProbeSpec describes the model call a run would actually make: which endpoint, which wire protocol, and — when panda can see it — the credential and model name the run would use. APIKey is sent to the endpoint only; it is never logged, cached, or included in reports.

type ProbeVerdict added in v0.0.9

type ProbeVerdict struct {
	// OK means the model service answered and — when a definitive credential
	// was probed — did not reject it.
	OK bool
	// Detail is the short secret-free status: "http 200", "http 503", or the
	// transport error text.
	Detail string
	// Rejected is true when the endpoint refused the definitive credential
	// (401/402/403): the service is up but the run would fail on
	// auth or quota — a different fix than a dead route.
	Rejected bool
	// Unknown is true when the probe drew no answer within its deadline. That
	// single outcome carries no information about the agent: the route may be
	// dead, or alive and queued behind its own upstream, and nothing observed
	// distinguishes the two. Routing must not disqualify on it. A refused
	// connect or an unknown host is NOT unknown — that is a deterministic
	// answer that nothing serves this address, and it still disqualifies.
	Unknown bool
}

ProbeVerdict is the outcome of one model-endpoint probe.

func ProbeModel added in v0.0.9

func ProbeModel(spec ProbeSpec) (ProbeVerdict, time.Duration)

ProbeModel performs a fresh, uncached minimal-request check and reports the verdict plus the observed latency. Interactive diagnostics ("agents test", "doctor") need what the network looks like now, not a verdict from half a minute ago; the fresh result is written back into the cache so the printed verdict matches the one routing would use next.

type ProgressFunc added in v0.0.2

type ProgressFunc func(note, kind string)

ProgressFunc receives one adapter progress note (a short human-readable line, e.g. "Bash: du -ah | sort -rh") as the agent works. The kind parameter tags typed events: "" for ordinary tool notes, "subagent" when the agent spawns a sub-agent (Claude's Task tool), etc. The orchestration layer records the kind so the task timeline shows the delegation chain.

type Result

type Result struct {
	OK         bool
	ExitCode   int
	Stdout     string
	Stderr     string
	Tokens     int
	Cost       float64
	NeedManual bool
	// Agent is the agent that actually executed (may differ from the plan's
	// primary when the fallback chain kicked in). Empty for non-agent plans
	// and when no candidate was usable at all.
	Agent string
	// Adapter is the adapter file that ran ("opencode.py") — the owner of
	// SessionID's wire shape. Persisted alongside the session handle so a
	// later round offers resume only to the adapter that minted it.
	Adapter string
	// Usage is the structured token breakdown the adapter reported (nil when
	// the adapter is a plain-text one); SessionID is the agent session a
	// follow-up round can resume (empty when the adapter has none).
	Usage     *UsageDetail
	SessionID string
	Model     string `json:"model,omitempty"`
	Injected  bool   `json:"injected,omitempty"`
	// Structured carries the harness's validated structured output when the
	// run used a result schema — the parsed protocol fields the run loop
	// prefers over text markers. SubagentStats is the harness's own
	// delegation fan-out summary (claude's result.subagent_stats).
	Structured    json.RawMessage `json:"structured,omitempty"`
	SubagentStats json.RawMessage `json:"subagent_stats,omitempty"`
}

Result is the normalized execution result (design doc P0-33).

type Router

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

Router matches a task's required abilities against a node's capability card and produces an execution plan (native command / agent adapter / manual notification).

func NewRouter

func NewRouter(card ledger.Card, executor *Executor, model config.ModelConfig, injection config.InjectionConfig, routing config.RoutingConfig) *Router

NewRouter builds a router from this node's capability card. The model config is injected into agent adapter subprocesses only as the injection policy allows (default auto: agent-native credentials win); routing honors the preferred-agents bonus and falls back across scored candidates.

func (*Router) Agent added in v0.0.8

func (r *Router) Agent(name string) (ledger.Agent, bool)

Agent returns the agent definition by name, or ok=false.

func (*Router) AgentDispatchable added in v0.0.9

func (r *Router) AgentDispatchable(name string, ag ledger.Agent) bool

AgentDispatchable reports whether an agent is ready to receive a task right now: statically viable (AgentViable) AND able to reach the model endpoint its run would actually use. The second check is what catches the "configured but cannot connect" case — a provider outage, a broken egress route, a dead relay host — before the task blocks inside the adapter.

func (*Router) AgentUsableReason added in v0.0.11

func (r *Router) AgentUsableReason(name string, ag ledger.Agent) (bool, string)

AgentUsableReason is AgentDispatchable with the first failure's reason attached — the diagnostic form (doctor, debug logs). An empty reason means usable.

func (*Router) AgentViable added in v0.0.5

func (r *Router) AgentViable(name string, ag ledger.Agent) bool

AgentViable reports whether an agent can actually execute on this machine: the adapter runtime exists, its CLI resolves on PATH, AND it can reach a model — either its own credentials (registry manifest) or panda's configured model via injection. An installed-but-locked-out CLI (e.g. claude.exe without login state on a node with no model key) fails only after minutes of runtime hang; probing viability up front keeps both the local fallback chain and the capability summary peers route on from ever selecting such an agent.

func (*Router) Card added in v0.0.8

func (r *Router) Card() ledger.Card

Card returns the router's underlying capability card.

func (*Router) CheckAgent added in v0.0.9

func (r *Router) CheckAgent(name string, ag ledger.Agent) AgentCheck

CheckAgent produces the dispatch-readiness report for one agent.

func (*Router) Execute

func (r *Router) Execute(ctx context.Context, plan Plan, prompt string, cwd string, authorized bool) Result

Execute runs the plan and returns a formatted result. authorized is the user's explicit consent to run Tier-2 (irreversible) commands; a Tier-2 native command without it is refused before execution.

func (*Router) InjectedModelEndpoint added in v0.1.1

func (r *Router) InjectedModelEndpoint(name, adapter string) (string, string)

InjectedModelEndpoint returns the model name and endpoint this node would inject into the named agent, resolved through the per-agent pin (injection.agents) and the adapter's dialect. The failure-time rescue needs it: the policy decision said "don't inject", so it carries no endpoint of its own, and falling back to the node model's URL would announce an endpoint the retry never used whenever that agent pins its own.

func (*Router) InjectionDecision added in v0.0.2

func (r *Router) InjectionDecision(name, adapter string) InjectionDecision

InjectionDecision evaluates the configured injection.model strategy for the adapter that drives an agent. It never logs or returns secrets — only the model name and endpoint, which are not sensitive.

Strategy (injection.model):

  • never: no injection, unconditionally.
  • always: always inject the panda model endpoint (legacy behavior).
  • auto: inject only when the agent carries no model credentials of its own (env vars, login state / config files — both from the agent's registry credential manifest) AND panda has a model key configured; otherwise the agent's native model wins.

name is the card's agent entry ("claude_code"), adapter its script ("claude_code.py"); both go to agents.Lookup so a generic.py custom CLI resolves to no manifest instead of borrowing zcode's.

func (*Router) MatchActuator added in v0.0.9

func (r *Router) MatchActuator(required []string) (ledger.ActuatorProfile, bool)

MatchActuator finds a card actuator whose id satisfies any of required (§7.1). Actuators live on the card's own list — not in card.Native — so they need their own matcher; the ability namespace is shared, which is what makes a required "hardware:gpio_servo" route here at all.

func (*Router) MatchAgent

func (r *Router) MatchAgent(required []string) (string, ledger.Agent, bool)

MatchAgent finds the best-scoring configured agent that satisfies any of required — either by name ("agent:<name>", the form the device summary advertises) or by one of its declared capabilities. Scoring is capability match × cost_tier discount plus the preferred-agents bonus (see RankAgents); the deterministic tie-break keeps repeated runs stable.

func (*Router) MatchManual

func (r *Router) MatchManual(required []string) (ledger.ManualAbility, bool)

MatchManual finds a manual ability whose id matches any of required.

func (*Router) MatchNative

func (r *Router) MatchNative(required []string) (ledger.NativeAbility, bool)

Match finds the first native ability whose id matches any of required.

func (*Router) PandaTools added in v0.0.9

func (r *Router) PandaTools() bool

PandaTools reports whether the openpanda self-management server is enabled (routing.panda_tools). Still gated on the extended tools policy by the caller.

func (*Router) PinnedAgentName added in v0.1.1

func (r *Router) PinnedAgentName(req string) (name string, pinned, known bool)

PinnedAgentName reports whether req is an "agent:<name>" requirement and, if so, the registry key it names on this router's card. known is false when the pin names no agent the card carries — an uninstalled CLI or one this node never registered — so a caller can tell "not a pin" from "a pin this node cannot honour" instead of treating both as "no opinion".

func (*Router) PlanUnusableReason added in v0.1.0

func (r *Router) PlanUnusableReason(p Plan) string

PlanUnusableReason explains why PlanUsable said no: one "name: reason" pair per rejected candidate. The gate used to fail with a generic "cli/ credentials/endpoint check failed", which is useless to the operator when the real cause is a 429 from the provider behind the agent — the reason names the failing check (missing cli, no model, endpoint unreachable, quota/auth rejected) so the fix is obvious. "" means the plan is usable.

func (*Router) PlanUsable added in v0.0.9

func (r *Router) PlanUsable(p Plan) bool

PlanUsable reports whether the plan can be dispatched for execution on this node right now. Native/manual plans have no agent dependency and always pass; an agent plan needs at least one candidate — primary or alternate — that is dispatchable (viable + endpoint reachable). localMatch and the run path gate on this so a node whose harnesses are all installed-but-dead declines the task fast and the scheduler fails over to a healthy peer.

func (*Router) ProbeAgentFresh added in v0.0.9

func (r *Router) ProbeAgentFresh(name string, ag ledger.Agent) (ProbeVerdict, time.Duration)

ProbeAgentFresh resolves the endpoint this agent's run would use and probes it uncached — the live counterpart of CheckAgent's cached verdict, for diagnostics that report the network as it is now. name is the card's agent entry, needed to resolve the registry record for generic.py custom CLIs.

func (*Router) RankAgents added in v0.0.2

func (r *Router) RankAgents(required []string) []AgentCandidate

RankAgents scores every agent that satisfies any of required and returns the candidates sorted by descending score (ties broken by name, so the choice stays deterministic across map iteration orders).

Score = capability match (1.0 exact / 0.9 token-subset) × cost_tier discount + preferred-agents bonus, halved while the agent sits in a transient-failure cooldown (agenthealth.go). A requirement of the form "agent:<name>" pins that exact agent — an explicit user choice never fans out to substitutes.

A roster (WithAgents) filters the pool before any of that: an agent outside the thread's team is not a candidate at all, including one named by an "agent:<name>" pin the model emitted. Inside the roster, an agent that declares none of the required abilities still scores allowedFloor — the team is an instruction, so the smallest roster of one employee must run the work rather than fail to route.

func (*Router) RosterOnCard added in v0.1.1

func (r *Router) RosterOnCard(names []string) []string

RosterOnCard returns the entries of names this node's capability card actually carries. A thread's team can legitimately name agents that only a peer has (the pick is mesh-wide), so an executor needs to know whether the team it was handed can be staffed HERE before it routes: WithAgents degrades to the unrestricted card when none of the names resolve, which silently re-staffs a task the user scoped to agents this machine does not have.

func (*Router) Route

func (r *Router) Route(required []string) (Plan, error)

Route picks the best way to execute required capabilities on this node. Priority: native > agent > manual (design doc §6.4) — except an explicit `agent:<name>` pin: a bare native or actuator command can never satisfy a demand for an agent run, so letting MatchNative win on a sibling capability token silently drops the pin. requires ["agent:x","git"] used to run `git status` and report the task done without the agent ever starting.

func (*Router) SetAdapterProcessRunner added in v0.0.8

func (r *Router) SetAdapterProcessRunner(fn func(ctx context.Context, adapter, prompt, cwd string, env []string) AgentResult)

SetAdapterProcessRunner swaps the process runner (test seam).

func (*Router) SetAdapterRunner

func (r *Router) SetAdapterRunner(fn func(ctx context.Context, adapter, prompt, cwd string) AgentResult)

SetAdapterRunner overrides the agent adapter invocation. It is a test seam: suites that need to exercise agent execution without spawning a real LLM CLI (e.g. scope-drift interception in core) inject a fake here.

func (*Router) SetAgentBlocked added in v0.1.1

func (r *Router) SetAgentBlocked(fn func(name string) bool)

SetAgentBlocked injects the agent circuit-breaker predicate: it reports whether the node's breaker currently holds this agent open. Ranking demotes such an agent (never excludes it). The core owns the breaker and wires this at construction; a router without it ranks exactly as before.

func (*Router) SetAgentProber added in v0.0.2

func (r *Router) SetAgentProber(fn func(name string, ag ledger.Agent) bool)

SetAgentProber overrides the agent availability probe. Test seam: suites with a fake adapter runner normally pair it with an always-available probe.

func (*Router) SetEndpointProber added in v0.0.9

func (r *Router) SetEndpointProber(fn func(spec ProbeSpec) ProbeVerdict)

SetEndpointProber overrides the model-endpoint reachability probe. Test seam: unit tests must never depend on real network state.

func (*Router) SetMCPPassthrough added in v0.0.7

func (r *Router) SetMCPPassthrough(command string)

SetMCPPassthrough sets the stdio MCP server (argv string, empty disables) that extended-policy agent runs expose — on the adapter request for flag-capable CLIs, via a work-dir .mcp.json for discovery-only CLIs. The ask engine's own MCP client is independent of this; the passthrough only concerns what the delegated agent CLIs may discover.

func (*Router) SetPolicy added in v0.0.2

func (r *Router) SetPolicy(injection config.InjectionConfig, routing config.RoutingConfig)

SetPolicy swaps the injection/routing policy after construction (the core builds its router before the full config is wired through).

func (*Router) SetSelfConfigPath added in v0.0.9

func (r *Router) SetSelfConfigPath(path string)

SetSelfConfigPath records the daemon's --config path so the passthrough document can hand it to `panda mcp`. Empty means the self-tools server falls back to the same default discovery every CLI command uses.

func (*Router) ToolsPolicy added in v0.0.7

func (r *Router) ToolsPolicy() string

ToolsPolicy reports the normalized agent tools policy the router runs adapters under (config routing.tools_policy).

func (*Router) WithAgents added in v0.1.0

func (r *Router) WithAgents(names []string) *Router

WithAgents returns a copy of the router whose agent pool is limited to names — a chat thread's roster, chosen in the composer. Native commands and actuators are deliberately untouched: the roster answers "which agent may take this work", not "may this declared command run".

Names this node does not carry are ignored, and when none of them are present the router comes back unchanged. That is the honest degradation: a roster of employees who work on another machine must not strand the task here with "no route" when this node has hands of its own.

type UsageDetail added in v0.0.7

type UsageDetail struct {
	InputTokens      int `json:"input_tokens"`
	OutputTokens     int `json:"output_tokens"`
	CacheReadTokens  int `json:"cache_read_tokens"`
	CacheWriteTokens int `json:"cache_write_tokens"`
}

UsageDetail is the structured token breakdown an adapter reports alongside the flat Tokens total: the total feeds the existing pipeline unchanged, the breakdown feeds observability (agent_usage task events) so input, output and cache traffic can be told apart.

Jump to

Keyboard shortcuts

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