Documentation
¶
Overview ¶
Package entry implements the unified entry model (design doc §7): one model call classifies a user request as an answer, a controlled tool call, a structured task, or a multi-stage plan. The model never performs side effects — the Go core validates and executes whatever the model emits.
Index ¶
- Constants
- Variables
- func BuildPrompt(opts PromptOptions) string
- func ContainsDSMLToolCall(s string) bool
- func FastPathPrompt(asciiOnly bool, loc ...i18n.Locale) string
- func IsFatalModelError(err error) bool
- func Speak(ctx context.Context, text string) error
- func StripDSMLToolCalls(text string) string
- func StripThinking(s string) string
- func SummarizeResult(ctx context.Context, c *Client, title, intent string, ok bool, exitCode int, ...) (string, error)
- func ValidatePlanSpec(p *PlanSpec) error
- func ValidateTaskSpec(t *TaskSpec) error
- func ValidateToolCall(tc *ToolCall) error
- func VoiceDir() string
- func WrapAPIError(err error, locs ...i18n.Locale) error
- type ClassifyError
- type ClassifyOption
- type Client
- func (c *Client) Complete(ctx context.Context, system, user string) (string, error)
- func (c *Client) CompleteTurns(ctx context.Context, system string, turns []Turn) (string, error)
- func (c *Client) CompleteTurnsWithTools(ctx context.Context, system string, turns []Turn, tools []ToolSpec) (Response, error)
- func (c *Client) ContextWindow() int
- func (c *Client) EstimateCost(in, out int64) float64
- func (c *Client) ListModels(ctx context.Context) ([]ModelInfo, error)
- func (c *Client) ModelName() string
- func (c *Client) Pricing() providers.Pricing
- func (c *Client) Provider() string
- func (c *Client) SetDiskCache(dc *DiskCache)
- func (c *Client) SetPricing(p providers.Pricing)
- func (c *Client) SetPromptCaching(enabled bool)
- func (c *Client) StreamTurnsWithTools(ctx context.Context, system string, turns []Turn, tools []ToolSpec, ...) (Response, error)
- func (c *Client) Usage() Usage
- type ContentBlock
- type DiskCache
- type Kind
- type ModelInfo
- type Output
- func Classify(ctx context.Context, c *Client, devices []ledger.Node, memory, user string) (Output, error)
- func ClassifyStreamWithTools(ctx context.Context, c *Client, devices []ledger.Node, memory string, ...) (Output, error)
- func ClassifyTurns(ctx context.Context, c *Client, devices []ledger.Node, memory string, ...) (Output, error)
- func ClassifyTurnsWithTools(ctx context.Context, c *Client, devices []ledger.Node, memory string, ...) (Output, error)
- func ParseOutput(raw string) (Output, error)
- type PlanSpec
- type PlanStageSpec
- type PromptLayers
- type PromptOptions
- type Registry
- type Requires
- type ResourceProfile
- type Response
- type SuperviseVerdict
- type TaskSpec
- type TaskSpecDetail
- type Tool
- type ToolCall
- type ToolSpec
- type ToolUse
- type Transcript
- type TriageResult
- type Turn
- type Usage
Constants ¶
const ( VerdictDone = "done" VerdictContinue = "continue" VerdictReview = "review" )
Supervise verdict statuses. Done/Continue are the two judgments the model may emit; Review is produced by Supervise itself when the model answers without a usable verdict — or when the model is unreachable (review P1-6) — and asks the caller to park the task for a human.
Variables ¶
var ErrNoKey = errors.New("entry: no model api_key configured")
ErrNoKey is returned when no API key is configured.
var ErrNoModel = errors.New("model not configured: set model.provider or model.base_url (run `panda init` or `panda model add`)")
ErrNoModel is returned by NewClient when the config names neither a built-in provider nor an endpoint: there is no default vendor, so an unconfigured node must fail loudly instead of silently phoning one.
Functions ¶
func BuildPrompt ¶
func BuildPrompt(opts PromptOptions) string
BuildPrompt assembles the layered system prompt: the resident routing core, the optional layers ChooseLayers picks from the history, then the device capability summary (stable prefix end) and the user-memory wall (volatile tail).
func ContainsDSMLToolCall ¶ added in v0.0.8
ContainsDSMLToolCall reports whether s carries DSML tool-call markup in either pipe variant, opening or closing.
func FastPathPrompt ¶ added in v0.0.8
FastPathPrompt returns a minimal system prompt for pure conversation & conceptual answering.
func IsFatalModelError ¶ added in v0.0.8
IsFatalModelError reports whether an error from the model client indicates that the provider or endpoint failed in an unrecoverable manner (unauthorized 401, forbidden/quota 403, not found 404, rate limited 429 after retries, 5xx server outage, or connection unreachable), making fallback to an alternate model candidate desirable. User context cancellation (context.Canceled) is NOT considered a fatal model error.
func Speak ¶
Speak speaks text via the TTS sidecar. A missing driver is returned as an error, not fatal. The text is stripped of Markdown first — emphasis markers, fences and table pipes read as noise ("星号星号", "反引号") when spoken, so the pipeline always renders answers to prose before TTS.
func StripDSMLToolCalls ¶ added in v0.0.8
StripDSMLToolCalls removes DSML tool-call markup from text, keeping the prose around it: everything before the first opening marker, plus anything after the final closing tool_calls/invoke tag. Text without markup is returned unchanged.
func StripThinking ¶ added in v0.0.7
StripThinking is the exported form of stripThinkingBlock for callers outside the entry package: the last-chance backstop that runs where model text is about to be persisted (the ask engine's Result assembly), so a provider path added without the per-parse strip still cannot leak chain-of-thought into session history or a stored task result.
func SummarizeResult ¶ added in v0.0.7
func SummarizeResult(ctx context.Context, c *Client, title, intent string, ok bool, exitCode int, stdout, stderr string, loc ...i18n.Locale) (string, error)
SummarizeResult asks the entry model to produce a user-facing summary of a task's outcome. It is the dedicated "report after execution" call: the engine invokes it after every inline task (success or failure) so the user sees a human-readable summary instead of raw stdout/stderr. A model failure degrades gracefully — the caller falls back to raw output, so the summary never blocks result delivery (review: LLM 汇报必须可降级).
Identical task outcomes are served from the client's disk cache when present.
func ValidatePlanSpec ¶ added in v0.0.6
ValidatePlanSpec checks the shape of a model-emitted plan: the fields the converter needs, and the two mistakes a model actually makes — a stage with no id (so nothing can depend on it) and a duplicate id (so a Needs reference is ambiguous). Dependency correctness itself — dangling needs, cycles — is the plan package's job, checked once against the real Plan rather than twice against two representations.
func ValidateTaskSpec ¶
ValidateTaskSpec checks a task emitted by the model for the fields the core needs before it can be persisted and routed. It returns an error describing the first problem; the model output is never trusted verbatim.
func ValidateToolCall ¶
ValidateToolCall checks a tool invocation. The tool name must be present; the Go core's tool whitelist (not this package) decides whether the named tool is actually allowed to run.
func VoiceDir ¶ added in v0.0.9
func VoiceDir() string
VoiceDir returns the directory the current process resolves voice sidecars from. The self-updater uses it to refresh the packaged scripts beside the running binary without re-deriving the resolution rules.
func WrapAPIError ¶
WrapAPIError converts a model-call error into a user-friendly ClassifyError. The message is actionable, not generic: a rejected key says to fix the key, a wrong endpoint says to fix base_url/model, rate limits and outages say to wait — so the user knows what to do instead of retrying blind. loc is the reply locale of the ask that failed (PromptOptions.UserLocale); omitting it falls back to the process default, matching the pre-locale behaviour.
Types ¶
type ClassifyError ¶
ClassifyError wraps a model/parse failure with a user-friendly message. The entry layer must never fail silently — an API error surfaces a clear explanation, and a malformed structured output degrades to an answer rather than erroring out (see ParseOutput).
func (*ClassifyError) Error ¶
func (e *ClassifyError) Error() string
func (*ClassifyError) Unwrap ¶
func (e *ClassifyError) Unwrap() error
type ClassifyOption ¶ added in v0.0.2
type ClassifyOption func(*PromptOptions)
ClassifyOption tweaks the system prompt the Classify* entry points build.
func WithASCIIOnly ¶ added in v0.0.2
func WithASCIIOnly() ClassifyOption
WithASCIIOnly makes the entry model answer in English/ASCII (for terminals that cannot render CJK).
func WithLocale ¶ added in v0.0.8
func WithLocale(loc i18n.Locale) ClassifyOption
WithLocale sets the user language preference for prompt construction.
func WithRequestMode ¶ added in v0.0.9
func WithRequestMode(mode string) ClassifyOption
WithRequestMode records the slash-prefix mode the user chose for the turn (/goal, /plan, /spec). Unknown values are ignored.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client talks to an Anthropic-compatible Messages API or an OpenAI-compatible Chat Completions API, selected by the config's api_type. It is small and dependency-free so the core daemon does not pull in an SDK.
func NewClient ¶
func NewClient(model config.ModelConfig) (*Client, error)
NewClient builds a client from the model config. An empty baseURL falls back to the named provider's catalogue endpoint; with neither provider nor base_url the config is unconfigured and NewClient fails with ErrNoModel — callers must not mistake a built-in default for the user's own choice. The endpoint must be HTTPS so the API key never travels cleartext (M2); loopback http stays allowed for a local dev model, matching the guard the commander applies to adapter endpoints (D7).
func (*Client) CompleteTurns ¶
CompleteTurns runs one call with a conversation history and no tools, returning the model's text. It is the answer/fallback path; the tool path is CompleteTurnsWithTools.
func (*Client) CompleteTurnsWithTools ¶
func (c *Client) CompleteTurnsWithTools(ctx context.Context, system string, turns []Turn, tools []ToolSpec) (Response, error)
CompleteTurnsWithTools runs one call with a conversation history and an optional tool set, returning both text and any tool_use blocks. It dispatches on the configured api type; the Anthropic path leaves tool_choice unset: the Messages API defaults to "auto" when tools are present, and DeepSeek's Anthropic endpoint rejects the string "auto" (it wants the internally-tagged object form). Omitting it is simpler and correct.
func (*Client) ContextWindow ¶ added in v0.0.8
ContextWindow returns the advertised context length in tokens, or 0 when unknown.
func (*Client) EstimateCost ¶ added in v0.0.8
EstimateCost calculates the estimated USD cost for the given input and output tokens.
func (*Client) ListModels ¶ added in v0.0.8
ListModels fetches the provider's model catalogue. The endpoint is derived from the provider override or the configured api type (see listModelsEndpoint); the response is the OpenAI "data":[{"id":…}] form. It needs an API key unless the provider is no-auth (a local Ollama).
func (*Client) ModelName ¶ added in v0.0.4
ModelName returns the configured model id, for metric labels.
func (*Client) Provider ¶ added in v0.0.8
Provider returns the provider catalogue ID, or empty for a custom endpoint.
func (*Client) SetDiskCache ¶ added in v0.0.4
SetDiskCache attaches the disk cache used for entry-model decision reuse (classify / supervise). A nil cache disables it.
func (*Client) SetPricing ¶ added in v0.0.8
SetPricing updates the client's pricing model.
func (*Client) SetPromptCaching ¶ added in v0.0.4
SetPromptCaching toggles provider-native prompt-cache markers on outgoing requests. Enabled by default; see Client.promptCache.
func (*Client) StreamTurnsWithTools ¶
func (c *Client) StreamTurnsWithTools(ctx context.Context, system string, turns []Turn, tools []ToolSpec, onDelta func(string), onReasoning func(string)) (Response, error)
StreamTurnsWithTools runs one call with a conversation history, an optional tool set, and a text-delta callback: answer text is delivered live as the provider streams it, while tool_use blocks and the final Response are accumulated and returned at the end. It is the streaming counterpart of CompleteTurnsWithTools and dispatches on the configured api type.
type ContentBlock ¶
type ContentBlock struct {
Type string `json:"type"` // text | thinking | tool_use | tool_result
Text string `json:"text,omitempty"` // text
Thinking string `json:"thinking,omitempty"` // thinking content (Anthropic wire format)
Signature string `json:"signature,omitempty"` // thinking signature
ID string `json:"id,omitempty"` // tool_use id
Name string `json:"name,omitempty"` // tool_use name
Input map[string]any `json:"input,omitempty"` // tool_use input
ToolUseID string `json:"tool_use_id,omitempty"` // tool_result linkage
Content string `json:"content,omitempty"` // tool_result content
}
ContentBlock is a structured content block in a message or response. It covers the Messages API vocabulary PANDA uses: text/thinking (responses) and tool_use/tool_result (both directions).
func (ContentBlock) MarshalJSON ¶ added in v0.0.2
func (b ContentBlock) MarshalJSON() ([]byte, error)
MarshalJSON emits only the fields each block type carries on the wire. Crucially, a tool_use block ALWAYS carries "input" (an empty object for a no-argument tool): the Anthropic Messages schema requires the field, and strict Anthropic-compatible providers (e.g. DeepSeek's /anthropic endpoint) reject the request with a 400 when map omitempty drops the empty input. Similarly, a thinking block ALWAYS carries "thinking" (not "text"), as strict Anthropic-compatible providers reject with "missing field `thinking`" otherwise.
type DiskCache ¶ added in v0.0.4
type DiskCache struct {
// contains filtered or unexported fields
}
DiskCache is a small SQLite-backed cache for entry-model decisions (intent classification, supervise verdicts). One row is one decision, namespaced by ns and keyed by two SHA-256 hashes — the prompt side and the device-snapshot / result side — so a changed input naturally lands on a different key and misses. Hits skip the LLM call entirely.
The table is created by storage migration v11 (entry_cache). Failures are deliberately best-effort: a cache that cannot be read or written degrades to a plain uncached call, never an error for the user.
func NewDiskCache ¶ added in v0.0.4
NewDiskCache builds a disk cache over an already-migrated database. A nil db yields a disabled cache (all operations are no-ops).
type Kind ¶
type Kind string
Kind is the entry model's top-level output category.
const ( // KindAnswer is a plain natural-language reply. KindAnswer Kind = "answer" // KindToolCall requests a controlled tool invocation. KindToolCall Kind = "tool_call" // KindTask requests a persistent, multi-step or cross-device task. KindTask Kind = "task" // KindPlan requests a multi-stage pipeline: several tasks whose ordering and // data flow matter, each routed to whichever node suits it. A single task // cannot express "develop where the coding agent lives, train where the GPU // lives, report back through the device the user is holding", so a request // that needs different machines for different steps becomes this instead. KindPlan Kind = "plan" )
type ModelInfo ¶ added in v0.0.8
type ModelInfo struct {
ID string `json:"id"`
}
ModelInfo is one entry in a provider's model catalogue.
type Output ¶
type Output struct {
Kind Kind
Answer string // KindAnswer
Tool *ToolCall // KindToolCall — the first call (kept for simple consumers)
Tools []*ToolCall // KindToolCall — every call the model emitted this round
Task *TaskSpec // KindTask
Plan *PlanSpec // KindPlan
Note string // text emitted alongside the tool call(s) (KindToolCall)
}
Output is the parsed result of one entry-model call. Exactly one of Answer/Tool/Task/Plan is populated, matching Kind. Note carries content the executor does not act on — text emitted alongside a tool call — so callers can surface it rather than drop it.
func Classify ¶
func Classify(ctx context.Context, c *Client, devices []ledger.Node, memory, user string) (Output, error)
Classify runs the unified entry model once with no tools and returns the parsed Output. It is the answer/fallback entry point; the tool path is ClassifyTurnsWithTools.
func ClassifyStreamWithTools ¶
func ClassifyStreamWithTools(ctx context.Context, c *Client, devices []ledger.Node, memory string, turns []Turn, registry *Registry, onDelta func(string), onReasoning func(string), opts ...ClassifyOption) (Output, error)
ClassifyStreamWithTools is ClassifyTurnsWithTools with live text streaming: answer deltas are delivered to onDelta as the provider emits them, while the parsed Output is returned once complete. Chain-of-thought from a provider's separate reasoning field is delivered to onReasoning live (display-only, kept out of Output per D14); pass nil to ignore it. A cache hit delivers the stored answer as one delta; structured outputs (task/tool_call) never stream, same as the live path.
func ClassifyTurns ¶
func ClassifyTurns(ctx context.Context, c *Client, devices []ledger.Node, memory string, turns []Turn, opts ...ClassifyOption) (Output, error)
ClassifyTurns is Classify with a conversation history and no tools.
func ClassifyTurnsWithTools ¶
func ClassifyTurnsWithTools(ctx context.Context, c *Client, devices []ledger.Node, memory string, turns []Turn, registry *Registry, opts ...ClassifyOption) (Output, error)
ClassifyTurnsWithTools runs the entry model with a conversation history and a tool registry. A native tool_use response becomes a KindToolCall output; a text response falls through to the existing JSON/prose parsing (answer/task). Identical inputs (turns, memory, devices, tool roster) are served from the disk cache without an LLM call.
func ParseOutput ¶
ParseOutput turns raw model text into a validated Output. The model may emit JSON for tool_call/task or plain prose for answer. Anything that is not a valid tool_call/task JSON object falls back to KindAnswer (never a silent error for the user — design doc §7.4).
func (Output) ToolCalls ¶ added in v0.0.9
ToolCalls returns every call the model emitted this round. Models emit several tool_use blocks per response for batch operations ("cancel these 5 tasks"), and the loop must honour all of them in one round: executing only the first burns one round per call until the round budget runs out on work that was fully specified up front.
type PlanSpec ¶ added in v0.0.6
type PlanSpec struct {
Goal string `json:"goal"`
Stages []PlanStageSpec `json:"stages"`
}
PlanSpec is the structured multi-stage payload the model emits for KindPlan. It is deliberately a mirror of internal/plan.Plan rather than that type itself: the plan package imports this one (a stage's resources are an entry.ResourceProfile), so the dependency can only run one way. The plan package converts a validated PlanSpec into its own Plan.
type PlanStageSpec ¶ added in v0.0.6
type PlanStageSpec struct {
ID string `json:"id"`
Title string `json:"title"`
Intent string `json:"intent"`
Requires []string `json:"requires"`
Needs []string `json:"needs"`
Node string `json:"node,omitempty"`
Resources ResourceProfile `json:"resource_profile"`
}
PlanStageSpec is one stage of a model-emitted plan. Requires and Resources are the same routing vocabulary a single task uses, so a stage is matched to a node by the existing scoring — the GPU stage cannot land on the Pi because of what it declares here. Node is the hard pin ("在 Mac 上做"): a stage carrying it may only run on that node — the requires match alone is a coincidence across a fleet where every machine advertises the same agent.
type PromptLayers ¶ added in v0.0.4
PromptLayers selects the optional prompt sections for one classification call: the memory governance rules join once the session has actually used a memory tool, and the verbose task JSON example joins once a task recently appeared in the conversation. The resident core always carries the compact routing rules and task skeleton, so a first-call classification needs neither optional layer.
func ChooseLayers ¶ added in v0.0.4
func ChooseLayers(turns []Turn) PromptLayers
ChooseLayers is the pure injection decision: given the conversation turns so far, which optional prompt sections does this call need? Memory-tool activity is scanned across the whole history (once the session is a memory session it stays one); task activity only within the recent window.
type PromptOptions ¶
type PromptOptions struct {
Devices []ledger.Node // capability directory snapshot (may be empty)
Memory string // Hermes memory summary (may be empty; capped)
// History is the conversation so far; ChooseLayers reads it to decide
// which optional prompt layers (memory rules, task example) to attach.
History []Turn
// ASCIIOnly asks the model to reply in plain-English ASCII. Set when the
// client is a bare Linux console: its PSF font has no CJK glyphs, so any
// Chinese in the reply renders as replacement diamonds.
ASCIIOnly bool
// UserLocale indicates the target UI/prompt language preference.
UserLocale i18n.Locale
// RequestMode is the interaction mode the user picked for this turn with
// a slash prefix: "goal" (refine the goal before acting), "plan" (emit a
// staged plan), or "spec" (write a detailed specification). Empty means
// the classifier decides on its own.
RequestMode string
}
PromptOptions carries the dynamic parts of the system prompt.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry is the set of tools the entry model may call, keyed by name.
func (*Registry) Copy ¶ added in v0.0.8
Copy returns a shallow copy of the registry (same Tool values), so a caller can attach per-request tools without mutating the shared registry.
type Requires ¶
type Requires struct {
Abilities []string `json:"abilities"`
}
Requires lists the abilities a task needs (design doc §7.3).
type ResourceProfile ¶
type ResourceProfile struct {
CPU int `json:"cpu"`
RAMGB float64 `json:"ram_gb"`
GPUVRAMGB float64 `json:"gpu_vram_gb"`
DurationHint string `json:"duration_hint"` // short | long
}
ResourceProfile is a coarse resource hint, not a safety rating (design doc §7.3; complexity/risk are recorded but do not auto-switch model tiers in MVP).
type Response ¶
type Response struct {
Text string
ToolUses []ToolUse
Truncated bool
// Reasoning is the model's chain-of-thought captured from a SEPARATE wire
// field — Anthropic thinking blocks, OpenAI-compat delta.reasoning_content —
// never from inlined <think> tags in Text. It is display-only scratch: the
// streaming path surfaces it live via a reasoning sink, and it is kept out
// of Text and out of session history (D14). Callers must not persist it.
Reasoning string
}
Response is the parsed result of one completion call: the textual answer plus any tool_use blocks the model emitted (a model may return text alongside a tool call, or only a tool call). Truncated reports that the provider stopped at max_tokens, so the text is incomplete.
type SuperviseVerdict ¶ added in v0.0.3
type SuperviseVerdict struct {
// Status is "done" (the task is complete), "continue" (work remains), or
// "review" (no verdict could be obtained — hand it to a human).
Status string `json:"status"`
// Reason is a one-line justification for the verdict.
Reason string `json:"reason"`
// Followup is, for a "continue" verdict, the remaining work and the next
// step for the following agent. Empty for "done".
Followup string `json:"followup"`
}
SuperviseVerdict is the outcome of a post-execution completion check: did the agent's result actually satisfy the task, or does work remain?
func Supervise ¶ added in v0.0.3
Supervise asks the configured entry model whether an agent's result fully satisfies the task described by intent (which carries the success criteria). A model that answers without producing a verdict returns VerdictReview: unverified work is handed to a human rather than silently promoted to done. An unreachable model also parks the task for review (review P1-6): the project's primary guarantee is that only work meeting its success definition ever reaches done, and a supervisor outage is precisely when nothing can be verified — degrading to done then would silently accept every agent task while the endpoint is unhealthy. Parking keeps the terminal state honest; a human can approve (or re-run) once the supervisor recovers. The error still travels to the caller, which logs it. Parked verdicts are never cached — a re-run under a healthy supervisor judges from scratch.
type TaskSpec ¶
type TaskSpec struct {
Title string `json:"title"`
Project string `json:"project"`
ContextType string `json:"context_type"`
Requires Requires `json:"requires"`
Spec TaskSpecDetail `json:"spec"`
Complexity float64 `json:"complexity"`
Risk string `json:"risk"`
Resources ResourceProfile `json:"resource_profile"`
// ToolsPolicy is the per-task tool-face override. Empty means "use the
// global routing.tools_policy"; "minimal" keeps the safe whitelist;
// "extended" lifts it so the agent's native skills, MCP and sub-agent
// tools are reachable. The entry model sets this based on the task's
// complexity and risk: high-complexity tasks that need the agent's
// full capability set can request extended without operator intervention
// at the routing layer. The engine copies it into Spec.ToolsPolicy so it
// rides spec_json to the executor; this outer field only exists for the
// model's emit shape.
ToolsPolicy string `json:"tools_policy,omitempty"`
// MaxTurns is the per-task agent turn cap the entry model may request for
// a task whose complexity needs more (or fewer) rounds than the adapter
// default. Copied into Spec.MaxTurns for the same reason as ToolsPolicy.
MaxTurns int `json:"max_turns,omitempty"`
}
TaskSpec is the structured task payload the model emits for KindTask (design doc §7.3).
type TaskSpecDetail ¶
type TaskSpecDetail struct {
Scope string `json:"scope"`
Target string `json:"target"`
Node string `json:"node,omitempty"` // preferred node id/name; empty lets the scheduler choose
Constraints []string `json:"constraints"`
SuccessDefinition string `json:"success_definition"`
// ToolsPolicy / MaxTurns live here (not on the outer TaskSpec) because
// spec_json is what persists on the task row and crosses the wire in
// TaskDelegatePayload — an outer-field-only override would evaporate at
// toTaskInput's marshal and never reach the executor.
ToolsPolicy string `json:"tools_policy,omitempty"`
MaxTurns int `json:"max_turns,omitempty"`
// ActionSpec is the hardware/software actuator dispatch (§7.2): when the
// request drives a declared actuator (a hardware:* ability on a device),
// the model names the target actuator, the action verb and the scalar
// parameters the actuator's driver placeholders need. It lives inside
// spec for the same reason as ToolsPolicy — spec_json is what reaches the
// executor, where SubstituteActionSpec fills {action}/{param:<name>}.
ActionSpec *ledger.ActionSpec `json:"action_spec,omitempty"`
}
TaskSpecDetail captures what to do, where, and how to verify success.
type Tool ¶
type Tool struct {
Name string
Description string
Schema map[string]any // JSON Schema for the tool's input arguments
// Tier grades the tool's side effect on the defense scale (see
// internal/defense: 1 reversible, 2 irreversible). 0 (unset) is
// fail-closed — the gate treats it as Tier 2 — so a tool with state
// effects must declare itself to run unattended: read-only and memory
// tools declare Tier 1; tools that mutate node/card/task state declare
// Tier 2 and run only under an explicit authorization for the ask.
Tier int
Run func(ctx context.Context, args map[string]any) (string, error)
}
Tool is a callable tool the entry model may invoke. Name/Description/Schema are what the model sees (the Anthropic tool schema); Run executes the call and returns a short user-facing result. The model never performs side effects — the registry's Run is the only thing that acts on a tool call.
type ToolCall ¶
type ToolCall struct {
ID string `json:"id,omitempty"`
Tool string `json:"tool"`
Arguments map[string]any `json:"arguments"`
}
ToolCall is a validated tool invocation request. ID carries the tool_use id when the call came from native tool_use (so the loop can reply with a matching tool_result); it is empty for the text-JSON fallback path.
type ToolSpec ¶
type ToolSpec struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema map[string]any `json:"input_schema"`
}
ToolSpec describes one tool the model may call (Anthropic Messages API shape).
type Transcript ¶
Transcript is one captured utterance: the wake word fired and the speech that followed was transcribed. OK is false (with Err set) when a sidecar is unavailable — a missing key or driver degrades, it never crashes the caller.
Timeout separates the two very different reasons OK can be false. Nobody spoke is the normal outcome of a listening round and the caller should simply go around again; a broken sidecar will break identically on the next round, so a caller that cannot tell them apart either spins a hot loop respawning python or reports a missing driver as silence.
func Listen ¶
func Listen(ctx context.Context, durationS float64) Transcript
Listen blocks until the wake word fires (or durationS elapses), then captures and transcribes the utterance. It drives wake.py then stt.py. VAD is deliberately NOT in this chain yet: each sidecar opens its own microphone stream, so a vad.py gate would consume the start of the utterance and leave stt.py with silence. VAD belongs in a single-stream capture (wake + VAD + ASR sharing one audio feed), which is a hardware-phase follow-up.
type TriageResult ¶ added in v0.0.8
TriageResult indicates whether a prompt should take the fast conversational path.
func FastTriage ¶ added in v0.0.8
func FastTriage(prompt string, history []Turn) TriageResult
FastTriage analyzes user prompt to check if it's a simple query that does not require cluster device topology scanning, heavy JSON task schema, or external tools.
type Turn ¶
type Turn struct {
Role string // "user" | "assistant"
Content string // plain text (used when Blocks is empty)
Blocks []ContentBlock // structured blocks for tool_use/tool_result
}
Turn is one conversation turn for multi-turn classification.
type Usage ¶ added in v0.0.4
type Usage struct {
InputTokens int64 `json:"input_tokens"`
OutputTokens int64 `json:"output_tokens"`
}
Usage is the provider-reported token consumption of one or more calls.