Documentation
¶
Overview ¶
SPDX-License-Identifier: AGPL-3.0-or-later
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
- Variables
- func AdapterDir() string
- func AdapterOutputContractFailure(text string) bool
- func AdapterSupportsRestricted(adapter string) bool
- func AdapterUnavailable(text string) bool
- func AgentHardTimeout() time.Duration
- func AgentName(ctx context.Context) string
- func AgentTimeout() time.Duration
- func ApplyFromConfig(cfg *config.Config, configPath, cardPath string) string
- func Authorized(ctx context.Context) bool
- func ContextOverflow(text string) bool
- func DropAgentSession(ctx context.Context, agent, adapter string)
- func EffectiveBaseURL(model config.ModelConfig) string
- func InjectionNotice(d InjectionDecision, agent string) string
- func IsAuthenticationSetupRequired(s string) bool
- func IsAuthorizationRefusal(stderr string) bool
- func IsModelConfigFailure(text string) bool
- func ModelCredsWithheld(ctx context.Context) bool
- func ParseActionSpec(specJSON string) (*ledger.ActionSpec, error)
- func ProtectedPaths(cfg *config.Config, configPath, cardPath string) []string
- func RemoteTask(ctx context.Context) bool
- func Restricted(ctx context.Context) bool
- func ResumeAdapter(ctx context.Context) string
- func ResumeID(ctx context.Context) string
- func SecretReadDenyPaths(cfg *config.Config, configPath, cardPath string) []string
- func SessionMode(ctx context.Context) bool
- func SetAgentTimeout(d time.Duration)
- func SetNativeTimeout(d time.Duration)
- func SetSandboxConfig(sc config.SandboxConfig, protected, secretReads []string) string
- func SetSilenceTimeout(d time.Duration)
- func SubstituteActionSpec(p *Plan, spec *ledger.ActionSpec, intent string) error
- func TaskID(ctx context.Context) string
- func WithAgentCommand(ctx context.Context, cmd string) context.Context
- func WithAgentEvents(ctx context.Context, fn AgentEventFunc) context.Context
- func WithAgentName(ctx context.Context, name string) context.Context
- func WithAgentTimeout(ctx context.Context, d time.Duration) context.Context
- func WithAuthorized(ctx context.Context) context.Context
- func WithChildRPC(ctx context.Context, url, token, attempt string) context.Context
- func WithComplexity(ctx context.Context, c float64) context.Context
- func WithExecutionProfiles(ctx context.Context, sink func(AdapterExecutionProfile)) context.Context
- func WithHarnessOutcomes(ctx context.Context, sink func(HarnessOutcome)) context.Context
- func WithImmediateCoordination(ctx context.Context) context.Context
- func WithIncrementalPrompt(ctx context.Context, full, delta, session, adapter string) context.Context
- func WithMCPConfig(ctx context.Context, doc string) context.Context
- func WithMaxTurns(ctx context.Context, n int) context.Context
- func WithModelCredsWithheld(ctx context.Context) context.Context
- func WithProgress(ctx context.Context, fn ProgressFunc) context.Context
- func WithPromptObserver(ctx context.Context, fn PromptObserver) context.Context
- func WithRecoveryModel(ctx context.Context, failed Result) context.Context
- func WithRemoteTask(ctx context.Context) context.Context
- func WithRestricted(ctx context.Context) context.Context
- func WithResultSchema(ctx context.Context, schema string) context.Context
- func WithResume(ctx context.Context, sessionID, adapter string) context.Context
- func WithSessionMode(ctx context.Context) context.Context
- func WithSubagent(ctx context.Context) context.Context
- func WithTaskID(ctx context.Context, taskID string) context.Context
- func WithToolsPolicy(ctx context.Context, policy string) context.Context
- type AdapterExecutionProfile
- type AdapterRequest
- type AgentCandidate
- type AgentCheck
- type AgentConcurrency
- type AgentEvent
- type AgentEventFunc
- type AgentResult
- type AgentSessions
- type Executor
- type FileContext
- type HarnessOutcome
- type InjectionDecision
- type InjectionKind
- type NativeResult
- type Plan
- type ProbeSpec
- type ProbeVerdict
- type ProfileCapabilities
- type ProgressFunc
- type PromptObserver
- type Result
- type Router
- func (r *Router) Agent(name string) (ledger.Agent, bool)
- func (r *Router) AgentDispatchable(name string, ag ledger.Agent) bool
- func (r *Router) AgentUsableReason(name string, ag ledger.Agent) (bool, string)
- func (r *Router) AgentViable(name string, ag ledger.Agent) bool
- func (r *Router) Card() ledger.Card
- func (r *Router) CheckAgent(name string, ag ledger.Agent) AgentCheck
- func (r *Router) DispatchRoute(required []string, traits ...string) (Plan, error)
- func (r *Router) DispatchTaskRoute(required []string, task TaskRouting) (Plan, error)
- func (r *Router) Execute(ctx context.Context, plan Plan, prompt string, cwd string, authorized bool) Result
- func (r *Router) InjectedModelEndpoint(name, adapter string) (string, string)
- func (r *Router) InjectionDecision(name, adapter string) InjectionDecision
- func (r *Router) MatchActuator(required []string) (ledger.ActuatorProfile, bool)
- func (r *Router) MatchAgent(required []string) (string, ledger.Agent, bool)
- func (r *Router) MatchManual(required []string) (ledger.ManualAbility, bool)
- func (r *Router) MatchNative(required []string) (ledger.NativeAbility, bool)
- func (r *Router) PandaTools() bool
- func (r *Router) PinnedAgentName(req string) (name string, pinned, known bool)
- func (r *Router) PlanUnusableReason(p Plan) string
- func (r *Router) PlanUsable(p Plan) bool
- func (r *Router) ProbeAgentFresh(name string, ag ledger.Agent) (ProbeVerdict, time.Duration)
- func (r *Router) RankAgents(required []string) []AgentCandidate
- func (r *Router) RetryAgent(name string)
- func (r *Router) RosterOnCard(names []string) []string
- func (r *Router) Route(required []string) (Plan, error)
- func (r *Router) SetAdapterProcessRunner(...)
- func (r *Router) SetAdapterRunner(fn func(ctx context.Context, adapter, prompt, cwd string) AgentResult)
- func (r *Router) SetAgentBlocked(fn func(name string) bool)
- func (r *Router) SetAgentProber(fn func(name string, ag ledger.Agent) bool)
- func (r *Router) SetConcurrency(g *AgentConcurrency)
- func (r *Router) SetEndpointProber(fn func(spec ProbeSpec) ProbeVerdict)
- func (r *Router) SetMCPPassthrough(command string)
- func (r *Router) SetPolicy(injection config.InjectionConfig, routing config.RoutingConfig)
- func (r *Router) SetSelfConfigPath(path string)
- func (r *Router) ToolsPolicy() string
- func (r *Router) WithAgents(names []string) *Router
- func (r *Router) WithConfig(card ledger.Card, model config.ModelConfig, injection config.InjectionConfig, ...) *Router
- type TaskRouting
- type UsageDetail
Constants ¶
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 ¶
ErrAdapterUnavailable prefixes every failure that means "this node cannot spawn this agent at all" — the script is not where the install layout says it should be, the interpreter is missing, or the path names something that is not a file. It exists as a message prefix rather than only an error value because the diagnosis has to survive the trip through AgentResult.Result → Result.Stderr → bus.TaskResultPayload.Stderr, where no error chain is left to unwrap. AdapterUnavailable is the matcher for that trip.
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 AdapterOutputContractFailure ¶ added in v0.1.7
AdapterOutputContractFailure reports whether a failure text means the CLI ran and streamed, but its transcript could not be reduced to an answer — the adapter's parser and the CLI's wire schema disagree, or the "endpoint" it dialled was not an API at all.
It is a deterministic verdict about *this build talking to this endpoint*: the identical bytes will arrive again, so the orchestrator's bounded retry buys three identical failures (pi's three attempts, ~7s each, all with "unrecognized event schema"). The row stops here and the reason is the operator's next step, which is the same shape as AdapterUnavailable: a fix to the environment, not a re-run.
func AdapterSupportsRestricted ¶ added in v0.0.10
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 AdapterUnavailable ¶ added in v0.1.6
AdapterUnavailable reports whether a failure text means the agent could never have started on this node, so retrying cannot change the outcome and a human review of the *work* would be reviewing nothing.
The patterns cover the two ways that happens in practice: adapterScript's own verdict (which carries the sentinel), the interpreter-missing result the spawn site returns with exit 127, and the interpreter's report when the script path does not resolve — the last for rows recorded before adapterScript existed, including the ones already sitting in a database's task_events.
func AgentHardTimeout ¶ added in v0.0.6
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
AgentName reads the card agent name WithAgentName attached — "" when none.
func AgentTimeout ¶ added in v0.1.4
AgentTimeout reports the advertised per-execution budget (before the wind-down grace). The orchestration layer reads it to decide whether a task's own declared shape warrants a longer budget than the global one.
func ApplyFromConfig ¶ added in v0.1.5
ApplyFromConfig installs the node-wide base policy for cfg — the one call the daemon and the embedded engine make at startup, and the one a settings surface repeats when sandbox.mode changes at runtime. Both halves of the deny list come from the same cfg/configPath/cardPath triple, so a runtime switch covers exactly what a restart would. Returns the backend in effect ("" when the mode is off or the platform has none).
func Authorized ¶ added in v0.1.4
Authorized reports whether a human consented to this run's operations.
func ContextOverflow ¶ added in v0.0.7
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
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 IsAuthenticationSetupRequired ¶ added in v0.1.7
IsAuthenticationSetupRequired recognizes a short CLI login diagnostic.
func IsAuthorizationRefusal ¶ added in v0.0.4
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 IsModelConfigFailure ¶ added in v0.1.6
IsModelConfigFailure reports a provider answer that names the model itself: the endpoint does not serve this id to the credential the CLI is configured with. It is the one class of 400 a blind re-run cannot improve — the CLI, the endpoint and the model id are unchanged, so the answer is identical — and the fix lives in the agent's own model configuration (a CLI config file, a provider switch), never in the task text. Callers use it to skip the retry budget and to say so in the review card instead of filing the park as "the prompt needs changing".
Matched on the provider's own vocabulary rather than the HTTP status: a bare 400 also covers malformed requests and context overflows, which are a different story with a different fix.
func ModelCredsWithheld ¶ added in v0.0.11
ModelCredsWithheld reports whether the execution context withholds this node's model credentials from the adapter subprocess env.
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
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
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
Restricted reports whether the context asks for a read-only agent run.
func ResumeAdapter ¶ added in v0.1.0
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
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
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
SessionMode reports whether the context asks for session execution.
func SetAgentTimeout ¶ added in v0.0.6
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
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
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 WithAgentCommand ¶ added in v0.0.10
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
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
WithAgentTimeout attaches a per-task agent execution timeout to the context; runAdapterProcess honours it over the global SetAgentTimeout value.
func WithAuthorized ¶ added in v0.1.4
WithAuthorized tells the adapter that a human consented to this run's irreversible operations. An adapter that gates its own tool calls (claude --permission-prompts none auto-denies anything its permission mode does not allow) lifts that posture only when this is set — otherwise an approval from OpenPanda can never reach the CLI, and the task parks in review again with the same question (issue #165).
func WithChildRPC ¶ added in v0.1.7
WithChildRPC supplies an ephemeral capability to the MCP subprocess. Never write the token into project files, activity transcripts or wire payloads.
func WithComplexity ¶ added in v0.1.0
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 WithExecutionProfiles ¶ added in v0.1.6
func WithExecutionProfiles(ctx context.Context, sink func(AdapterExecutionProfile)) context.Context
WithExecutionProfiles installs a trusted process-boundary sink separately from adapter-authored NDJSON. An adapter cannot spoof an authoritative configuration observation by emitting an event with the same name.
func WithHarnessOutcomes ¶ added in v0.1.7
func WithHarnessOutcomes(ctx context.Context, sink func(HarnessOutcome)) context.Context
func WithImmediateCoordination ¶ added in v0.1.7
func WithIncrementalPrompt ¶ added in v0.1.7
func WithIncrementalPrompt(ctx context.Context, full, delta, session, adapter string) context.Context
WithIncrementalPrompt keeps full recovery input available at the actual adapter attempt, where resume affinity (including fallback) is known.
func WithMCPConfig ¶ added in v0.0.10
WithMCPConfig attaches the passthrough MCP config document. Empty is a no-op.
func WithMaxTurns ¶ added in v0.0.10
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
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 WithPromptObserver ¶ added in v0.1.7
func WithPromptObserver(ctx context.Context, fn PromptObserver) context.Context
func WithRecoveryModel ¶ added in v0.1.7
WithRecoveryModel lets a new Panda recovery instruction resume Claude's checkpoint with injected credentials. It does not replay the old prompt.
func WithRemoteTask ¶ added in v0.0.10
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
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
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
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
WithSessionMode asks the adapter to keep the agent process alive across turns. Only set for adapters whose registry entry declares Capabilities.SupportsSession.
func WithSubagent ¶ added in v0.1.5
WithSubagent marks an orchestrated child, independently of the CLI's native internal delegation tools (whose policy remains owned by that CLI).
func WithTaskID ¶ added in v0.0.9
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
WithToolsPolicy attaches the normalized tools policy to an execution context. The orchestration layer sets it on the execution context to request a narrower tool face for a task. The Router enforces the operator's global policy as a ceiling before dispatching to any adapter.
Types ¶
type AdapterExecutionProfile ¶ added in v0.1.6
type AdapterExecutionProfile struct {
HarnessAttemptID string `json:"harness_attempt_id,omitempty"`
Coordination string `json:"coordination"`
Version int `json:"version"`
Observation string `json:"observation"`
Agent string `json:"agent"`
Adapter string `json:"adapter"`
CWD string `json:"cwd"`
Transport string `json:"transport"`
AdapterPath string `json:"adapter_path,omitempty"`
AdapterSHA256 string `json:"adapter_sha256,omitempty"`
SandboxMode string `json:"sandbox_mode"`
SandboxBackend string `json:"sandbox_backend"`
SandboxNetwork bool `json:"sandbox_network"`
ExternalToolPolicy string `json:"external_tool_policy"`
NativeToolAccess string `json:"native_tool_access"`
NativeSettings string `json:"native_settings_policy"`
ModelPreference string `json:"model_preference,omitempty"`
ModelInjection bool `json:"model_injection"`
RequestedEffort string `json:"requested_effort,omitempty"`
NativeModel string `json:"native_model"`
NativeEffort string `json:"native_effort"`
NativeConfig string `json:"native_config"`
NativeVersion string `json:"native_version"`
ToolsPolicy string `json:"requested_tools_policy,omitempty"`
Restricted bool `json:"restricted"`
Authorized bool `json:"authorized"`
ResumeRequested bool `json:"resume_requested"`
TimeoutS int `json:"timeout_s"`
MaxTurns int `json:"requested_max_turns,omitempty"`
DeclaredCapabilities *ProfileCapabilities `json:"declared_capabilities,omitempty"`
}
AdapterExecutionProfile is a control-plane observation, NOT an assertion about the CLI's effective model/tools/configuration. It intentionally excludes prompts, argv templates, MCP bodies, provider URLs, env values and credentials.
type AdapterRequest ¶
type AdapterRequest struct {
Model string `json:"model,omitempty"`
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"`
// Authorized carries the operator's tier-2 consent (a foreground
// approval, --authorize, or a bypass session) to the adapter. Adapters
// that gate their own tool calls use it to lift that posture for this
// run; adapters without such a gate ignore it. Never set together with
// Restricted — consent is what removes the read-only face.
Authorized bool `json:"authorized,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
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 AgentConcurrency ¶ added in v0.1.5
type AgentConcurrency struct {
// contains filtered or unexported fields
}
AgentConcurrency counts subprocess calls, not parked parent orchestrators. It is shared by router snapshots so hot model changes cannot reset capacity.
func NewAgentConcurrency ¶ added in v0.1.5
func NewAgentConcurrency() *AgentConcurrency
func (*AgentConcurrency) Configure ¶ added in v0.1.5
func (g *AgentConcurrency) Configure(capacity int, r config.RoutingConfig, d config.DelegationConfig)
func (*AgentConcurrency) YieldTask ¶ added in v0.1.7
func (g *AgentConcurrency) YieldTask(ctx context.Context, taskID string) func()
YieldTask frees only the identified live adapter's permit while its MCP call awaits children. The resume closure observes cancellation and a concurrently exited adapter; it cannot release a newer run's permit or double-count one.
type AgentEvent ¶ added in v0.0.10
type AgentEvent struct {
HarnessAttemptID string `json:"-"`
// 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"`
// ContextTokens is the request-scoped context footprint an adapter
// reports on its "context" event: the prompt tokens of the newest model
// call (uncached input plus cache reads and writes). The result
// envelope's own usage is cumulative for the run, so it cannot answer
// "how full is the agent's window" — this is the only per-request
// number the CLIs report. Model is the id that served the request, when
// the adapter knows it. Both are display metadata for the console's
// context gauge; 0/"" when the run never reported them.
ContextTokens int `json:"context_tokens,omitempty"`
Model string `json:"model,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"`
// WorkObserved is trusted Go-side tool activity, never adapter-authored.
WorkObserved bool `json:"-"`
// OpenCode can mint an empty session before its provider accepts a fresh run.
ProviderStartupFailure bool `json:"provider_startup_failure,omitempty"`
// RescueError is set by the router, not by the adapter.
RescueError string `json:"-"`
}
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 ¶
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.
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 HarnessOutcome ¶ added in v0.1.7
A task attempt can run several harnesses, including a second attempt with the same harness after model injection. Their IDs are independent of task leases.
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 ¶
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
// When availability displaces the top-ranked agent, retain the decision for the task trace.
FallbackFrom string
FallbackReason 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
// contains filtered or unexported fields
}
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
// Status is the HTTP status the probe received, 0 when no response
// arrived. Routing ignores it (a 4xx still proves the service answers
// API-shaped requests), but a diagnostic surface needs it: "reachable"
// and "reachable, but it rejected this request" are different sentences,
// and Detail alone forces the caller to parse a string.
Status int
}
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 ProfileCapabilities ¶ added in v0.1.6
type ProfileCapabilities struct {
Restricted bool `json:"restricted"`
Session bool `json:"session"`
Skills bool `json:"skills"`
MCP bool `json:"mcp"`
Subagents bool `json:"subagents"`
StructuredOutput bool `json:"structured_output"`
}
These are registry declarations, not probes of installed CLI features.
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 PromptObserver ¶ added in v0.1.7
type Result ¶
type Result struct {
// NoProviderWork is local dispatch evidence used before handing off to a peer.
NoProviderWork bool `json:"-"`
OK bool
ExitCode int
Stdout string
Stderr string
Tokens int
Cost float64
NeedManual bool
// ResumeRejected is computed at the adapter boundary, never trusted from
// adapter-authored JSON. It permits one full-input cold recovery.
ResumeRejected 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
// FallbackFrom names the agent the plan pinned when Agent is a substitute,
// and FallbackReason is why that agent never answered. Both are empty when
// the plan's own agent ran. They exist because the substitution is only
// honest if it can be explained: a thread that says "deepseek_harness
// answered" under a task titled "…claude_code" reads as the reply having
// been swapped out, unless the sentence also carries the cause.
FallbackFrom string
FallbackReason 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"`
// RescueError is the native provider error that triggered model injection.
RescueError string
// 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) AgentDispatchable ¶ added in v0.0.9
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
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
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) 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) DispatchRoute ¶ added in v0.1.7
DispatchRoute chooses a primary and fallback chain from the agents that can receive this task now. Route is the static card lookup used for previews.
func (*Router) DispatchTaskRoute ¶ added in v0.1.7
func (r *Router) DispatchTaskRoute(required []string, task TaskRouting) (Plan, error)
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
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 ¶
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
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
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
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
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
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).
The score starts with average capability coverage (1 exact / 0.9 token- subset), discounted by cost tier plus a preferred-agent bonus. Matching a card specialty increases it by half; a not_for match halves it. Health demotes the rank 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) RetryAgent ¶ added in v0.1.7
RetryAgent lets an operator explicitly probe an executor before its automatic dispatch cooldown expires. It does not change capability or permission checks.
func (*Router) RosterOnCard ¶ added in v0.1.1
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 ¶
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
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
SetAgentProber overrides the agent availability probe. Test seam: suites with a fake adapter runner normally pair it with an always-available probe.
func (*Router) SetConcurrency ¶ added in v0.1.5
func (r *Router) SetConcurrency(g *AgentConcurrency)
SetConcurrency installs the core-owned gate before publishing a router.
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
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 configures an unpublished router. Runtime callers use WithConfig instead of mutating a snapshot held by active tasks.
func (*Router) SetSelfConfigPath ¶ added in v0.0.9
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
ToolsPolicy reports the normalized agent tools policy the router runs adapters under (config routing.tools_policy).
func (*Router) WithAgents ¶ added in v0.1.0
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.
func (*Router) WithConfig ¶ added in v0.1.5
func (r *Router) WithConfig(card ledger.Card, model config.ModelConfig, injection config.InjectionConfig, routing config.RoutingConfig) *Router
WithConfig publishes an independent policy snapshot while preserving the process runner, test hooks and shared concurrency accounting. Default methods are bound at call time so cloned routers never execute against stale policy.
type TaskRouting ¶ added in v0.1.7
TaskRouting describes the work separately from hard capability requirements.
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.