entry

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: 35 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 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

View Source
const (
	ErrKindNoKey       = "no_key"       // no credential configured
	ErrKindCanceled    = "canceled"     // caller aborted the call
	ErrKindTimeout     = "timeout"      // deadline hit
	ErrKindAuth        = "auth"         // 401/403 — key rejected
	ErrKindNotFound    = "not_found"    // 404 — wrong endpoint/model id
	ErrKindBadRequest  = "bad_request"  // 400 — provider rejected the payload
	ErrKindRateLimited = "rate_limited" // 429 after retries
	ErrKindUnavailable = "unavailable"  // 5xx after retries
	ErrKindUnreachable = "unreachable"  // transport failure after retries
	ErrKindGeneric     = "generic"      // anything else
)

Error-kind labels a ClassifyError (and APIErrorKind's verdicts) carries. They double as i18n suffixes: entry.hints.<kind> is the troubleshooting text a surface expands under the error.

View Source
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.

View Source
const ToolNameTaskBudget = "task_budget"

ToolNameTaskBudget is the wire name of the budget-declaration tool: the call a model makes when the round needs more dispatches than the engine's derived limit allows. Like task_submit it lives here so the tool loop can recognize the call by name without importing the assembly package.

View Source
const ToolNameTaskSubmit = "task_submit"

ToolNameTaskSubmit is the wire name of the native task-dispatch bridge tool — the call an entry model emits when a turn should become a task. It lives here rather than in askengine (which imports this package and builds the tool spec) so classification code can recognize the call without a package cycle, and so a rename has one edit point.

Variables

View Source
var ErrNoKey = errors.New("entry: no model api_key configured")

ErrNoKey is returned when no API key is configured.

View Source
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 APIErrorKind added in v0.1.0

func APIErrorKind(err error) (kind string, status int)

APIErrorKind classifies any model-call error — raw (statusError family) or wrapped (ClassifyError) — into the ErrKind* vocabulary plus the HTTP status the provider answered, if one exists. Surfaces that only see the error (rather than the ClassifyError wrapper) get the same mapping WrapAPIError applied. The second result is 0 when no response arrived.

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

func ContainsDSMLToolCall(s string) bool

ContainsDSMLToolCall reports whether s carries DSML tool-call markup in either pipe variant, opening or closing.

func EnsureAPIError added in v0.1.0

func EnsureAPIError(err error, locs ...i18n.Locale) error

EnsureAPIError applies WrapAPIError only to genuine model-call failures that are not already classified — the idempotent form an outer boundary calls without knowing which inner layer the error escaped from.

func FastPathPrompt added in v0.0.8

func FastPathPrompt(asciiOnly bool, loc ...i18n.Locale) string

FastPathPrompt returns a minimal system prompt for pure conversation & conceptual answering.

func IsFatalModelError added in v0.0.8

func IsFatalModelError(err error) bool

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 IsLocalEndpoint added in v0.1.0

func IsLocalEndpoint(base string) bool

IsLocalEndpoint reports whether reaching base needs no internet: loopback, a private/link-local address (a LAN model box, a self-hosted gateway), a .local/.lan name, or a single-label host ("ollama", "gpu-box") that only a LAN resolver can answer. A model behind any of those keeps answering during an internet outage, so the offline gate must not wait on its behalf.

func IsModelCallError added in v0.1.0

func IsModelCallError(err error) bool

IsModelCallError reports whether err came out of a model call (provider answer, transport failure, missing credential, deadline) rather than from the machinery around it — the boundary wrap uses it to re-dress only model failures, so a storage or routing error keeps its own message instead of being relabeled "entry model call failed".

func IsModelConfigError added in v0.1.0

func IsModelConfigError(err error) bool

IsModelConfigError reports whether err names a problem the user can fix in the model settings — no key, a rejected key, a bad endpoint, a retired model id — rather than a transient outage worth waiting out. Surfaces that offer a "fix your model config" affordance (the web console's error bubble) key on this so the CTA lands exactly where it helps; a ClassifyError unwraps to the same verdict, so raw and user-facing errors classify alike.

func ResolveContextWindow added in v0.1.0

func ResolveContextWindow(model config.ModelConfig) int

ResolveContextWindow resolves the advertised context window (tokens) a model config lands on: the declared context_window wins, then the provider/detected catalogue row — the same chain NewClient applies at build time. Exported so callers that never construct a client (replay budget sizing) can still scale to the model. 0 when nothing knows.

func Speak

func Speak(ctx context.Context, text string) error

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

func StripDSMLToolCalls(text string) string

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

func StripThinking(s string) string

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

func ValidatePlanSpec(p *PlanSpec) error

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

func ValidateTaskSpec(t *TaskSpec) error

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

func ValidateToolCall(tc *ToolCall) error

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 WithOfflineHook added in v0.1.0

func WithOfflineHook(ctx context.Context, fn func(OfflineNote)) context.Context

WithOfflineHook attaches fn to ctx. The retry loops call it when the gate enters and leaves a wait. A nil fn is a no-op.

func WithRetryHook added in v0.1.0

func WithRetryHook(ctx context.Context, fn func(RetryNote)) context.Context

WithRetryHook attaches fn to ctx. The retry loops in streamWithRetry, completeWithRetry and completeOpenAI call it once per scheduled backoff, before sleeping. A nil fn is a no-op — most callers (tests, batch tools) have nothing to report to.

func WithSessionID added in v0.1.1

func WithSessionID(ctx context.Context, id string) context.Context

WithSessionID scopes one call's conversation. Callers that know the thread (the console's chat, the REPL's session) pass it so the provider sees one session per conversation; callers that do not leave it unset and the client's own id stands.

func WrapAPIError

func WrapAPIError(err error, locs ...i18n.Locale) error

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. Already-classified input is returned untouched so a boundary re-wrap (the ask engine's catch-all) cannot flatten a specific kind into "generic".

Types

type ClassifyError

type ClassifyError struct {
	UserMsg string // what to show the user
	Err     error  // underlying cause

	// Kind is the machine-readable failure class (the ErrKind* constants).
	// Surfaces map it to their own troubleshooting copy — the TUI's foldable
	// hint block, the console's <details> section — instead of parsing
	// UserMsg back apart.
	Kind string
	// Status is the HTTP status the provider answered with, when the failure
	// was a response (429, 400, 5xx…). 0 for transport-level failures that
	// never got an answer.
	Status int
	// Detail carries the provider's own rejection reason when one rode along
	// in the response body — bounded like UserMsg's appended detail.
	Detail string
}

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 WithAcceptanceCandidates added in v0.1.2

func WithAcceptanceCandidates(cands []contract.Candidate) ClassifyOption

WithAcceptanceCandidates tells the entry model which verification checks the workspace already declares. The model selects; it never authors a command. Duplicates and empty entries are dropped, and the list is capped so the prompt stays a shortlist rather than a menu.

func WithAgentRoster added in v0.1.1

func WithAgentRoster(names []string) ClassifyOption

WithAgentRoster records the thread's team pick so the entry model can name the user's own agents instead of inventing them. Names are trimmed, empty entries dropped, duplicates removed, order preserved.

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 one of four wire dialects, selected by the config's api_type: Anthropic Messages, OpenAI Chat Completions, OpenAI Responses, or Google Generative AI. 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) Complete

func (c *Client) Complete(ctx context.Context, system, user string) (string, error)

Complete runs one non-streaming call and returns the model's text.

func (*Client) CompleteTurns

func (c *Client) CompleteTurns(ctx context.Context, system string, turns []Turn) (string, error)

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

func (c *Client) ContextWindow() int

ContextWindow returns the advertised context length in tokens, or 0 when unknown.

func (*Client) EstimateCost added in v0.0.8

func (c *Client) EstimateCost(in, out int64) float64

EstimateCost calculates the estimated USD cost for the given input and output tokens.

func (*Client) Key added in v0.1.1

func (c *Client) Key() string

Key identifies this client for health bookkeeping: wire dialect, endpoint and model. Two registry aliases of the same model id on different endpoints (or dialects) are different keys, so one provider's outage does not cool down the other. The provider label and the credential are deliberately absent: neither changes what the request does to the endpoint, and a rotated key must not alias or reset the record.

func (*Client) ListModels added in v0.0.8

func (c *Client) ListModels(ctx context.Context) ([]ModelInfo, error)

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

func (c *Client) ModelName() string

ModelName returns the configured model id, for metric labels.

func (*Client) Pricing added in v0.0.8

func (c *Client) Pricing() providers.Pricing

Pricing returns the configured pricing structure.

func (*Client) Provider added in v0.0.8

func (c *Client) Provider() string

Provider returns the provider catalogue ID, or empty for a custom endpoint.

func (*Client) SetDiskCache added in v0.0.4

func (c *Client) SetDiskCache(dc *DiskCache)

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

func (c *Client) SetPricing(p providers.Pricing)

SetPricing updates the client's pricing model.

func (*Client) SetPromptCaching added in v0.0.4

func (c *Client) SetPromptCaching(enabled bool)

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.

func (*Client) Usage added in v0.0.4

func (c *Client) Usage() Usage

Usage returns the client's cumulative token consumption across every successful call since construction. Providers that do not report usage contribute zero.

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

func NewDiskCache(db *sql.DB) *DiskCache

NewDiskCache builds a disk cache over an already-migrated database. A nil db yields a disabled cache (all operations are no-ops).

func (*DiskCache) Get added in v0.0.4

func (c *DiskCache) Get(ctx context.Context, ns, k1, k2 string, dst any) bool

Get loads the cached value for (ns, k1, k2) into dst. It reports false on a miss, an expired row, or any storage/decode failure — every failure path is a miss, never an error.

func (*DiskCache) Put added in v0.0.4

func (c *DiskCache) Put(ctx context.Context, ns, k1, k2 string, v any)

Put stores v under (ns, k1, k2) and periodically evicts rows past the TTL. Both statements are best-effort; a failed write only costs a future miss.

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 OfflineNote added in v0.1.0

type OfflineNote struct {
	// Waiting is true on entering the wait and false when the link is back.
	Waiting bool
	// Elapsed is how long the gate waited; meaningful only when Waiting is
	// false (it is zero on entry).
	Elapsed time.Duration
}

OfflineNote describes one state change of the offline gate: entering the wait, or coming out of it once the link returned. It exists so a surface can say "the network is down, waiting" instead of letting the turn look stalled — and, on the way out, report how long the outage cost.

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

func ParseOutput(raw string) (Output, error)

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

func (o Output) ToolCalls() []*ToolCall

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

type PromptLayers struct {
	MemoryRules bool
	TaskExample bool
}

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
	// AgentRoster is the thread's team pick — the agents the user chose for
	// this conversation, in the order they picked them. It is shown to the
	// model because a roster the model cannot see is a roster it will
	// contradict: asked to "test the agents I picked", an entry model that
	// only knows the node's capability card invented claude_code, codex and
	// deepseek_harness for a thread whose team was deepseek_harness and
	// opencode, and pinned each task to an agent the thread had excluded.
	// Empty means "no pick" (the scheduler routes by capability).
	AgentRoster []string
	// AcceptanceCandidates are the verification entry points the workspace
	// already declares (Makefile targets, package scripts, toolchain
	// defaults, CI steps). The model selects from this list for
	// spec.acceptance; it never invents a command. Empty means "no project
	// in view" and the task will be reported unverified.
	AcceptanceCandidates []contract.Candidate
}

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 NewRegistry

func NewRegistry() *Registry

NewRegistry builds an empty registry.

func (*Registry) Copy added in v0.0.8

func (r *Registry) Copy() *Registry

Copy returns a shallow copy of the registry (same Tool values), so a caller can attach per-request tools without mutating the shared registry.

func (*Registry) Lookup

func (r *Registry) Lookup(name string) (Tool, bool)

Lookup returns a tool by name.

func (*Registry) Register

func (r *Registry) Register(t Tool)

Register adds a tool, replacing any existing tool with the same name.

func (*Registry) Specs

func (r *Registry) Specs() []ToolSpec

Specs returns all registered tools in their wire form, sorted by name so the request is deterministic.

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 RetryNote added in v0.1.0

type RetryNote struct {
	// Attempt is the upcoming retry's 1-based index inside the budget (1 is
	// the first retry after the initial attempt failed).
	Attempt int
	// MaxAttempts is the retry budget for this call — Attempt counts to it.
	MaxAttempts int
	// Delay is the backoff about to be slept before the retry fires.
	Delay time.Duration
	// Err is the failure being retried — a *statusError/*retryableError for a
	// provider answer (429/5xx), a *transientError for a transport drop.
	Err error
}

RetryNote describes one transport retry the client is about to sleep through: which retry this is inside the call's budget, how long the backoff lasts, and why the previous attempt failed. It exists so a surface can show "rate limited, retrying in Ns" on its status line — without it a provider answering 429/5xx sits silently behind the spinner for the whole backoff ladder, which reads as a hang rather than a retry.

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

func Supervise(ctx context.Context, c *Client, intent, result string) (SuperviseVerdict, error)

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"`
	// AllowAgents narrows the agent pool for this task to the named agents —
	// the thread's team pick, filled by the ask engine from the composer's
	// roster. It lives in spec for the same reason as ToolsPolicy: spec_json
	// is what persists on the row and what a delegated task carries to the
	// executor, so the restriction survives a hop to another node instead of
	// being a submitter-side suggestion. Empty means no restriction.
	AllowAgents []string `json:"allow_agents,omitempty"`
	// PermissionMode is the conversation's permission policy that created
	// this task (defense.ModeManual, ModePlan, …). Empty means auto: the
	// thread never picked one, and the executor's ordinary tier gate applies.
	PermissionMode string `json:"permission_mode,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"`
	// Acceptance is the machine-checkable contract: commands and artifact
	// assertions the orchestrator runs itself after the agent claims done.
	// It lives here because spec_json persists on the row and crosses the
	// wire, so a delegated task is verified by the same criteria on the
	// executor. Empty means no contract: the task cannot be "verified".
	Acceptance []contract.Check `json:"acceptance,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 ToolUse

type ToolUse struct {
	ID    string
	Name  string
	Input map[string]any
}

ToolUse is one tool invocation the model emitted in a response.

type Transcript

type Transcript struct {
	OK      bool
	Text    string
	Timeout bool
	Err     string
}

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

type TriageResult struct {
	IsFastPath bool
	Reason     string
}

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.

func (Usage) Sub added in v0.0.4

func (u Usage) Sub(other Usage) Usage

Sub returns u minus other, clamped at zero per component — the consumption that happened between two Usage snapshots.

func (Usage) Total added in v0.0.4

func (u Usage) Total() int64

Total is the combined input+output token count.

Jump to

Keyboard shortcuts

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