entry

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT Imports: 16 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, or a structured task. The model never performs side effects — the Go core validates and executes whatever the model emits.

Index

Constants

This section is empty.

Variables

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

ErrNoKey is returned when no API key is configured.

Functions

func BuildPrompt

func BuildPrompt(opts PromptOptions) string

BuildPrompt assembles the system prompt with the device capability summary and user-memory placeholder filled in.

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 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 WrapAPIError

func WrapAPIError(err error) 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.

Types

type ClassifyError

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

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).

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. A zero baseURL/model falls back to config defaults, so callers can pass config.Default().Model. 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) StreamTurnsWithTools

func (c *Client) StreamTurnsWithTools(ctx context.Context, system string, turns []Turn, tools []ToolSpec, onDelta 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
	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.

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"
)

type Output

type Output struct {
	Kind   Kind
	Answer string    // KindAnswer
	Tool   *ToolCall // KindToolCall
	Task   *TaskSpec // KindTask
	Note   string    // dropped text / extra tool_use (KindToolCall)
}

Output is the parsed result of one entry-model call. Exactly one of Answer/Tool/Task is populated, matching Kind. Note carries content the executor does not act on — text emitted alongside a tool call and any tool_use after the first — 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), 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.

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).

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).

type PromptOptions

type PromptOptions struct {
	Devices []ledger.Node // capability directory snapshot (may be empty)
	Memory  string        // Hermes memory summary (may be empty; capped)
	// 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
}

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) 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
}

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) or "continue" (work remains).
	Status string
	// Reason is a one-line justification for the verdict.
	Reason string
	// Followup is, for a "continue" verdict, the remaining work and the next
	// step for the following agent. Empty for "done".
	Followup string
}

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). On a call failure it fails open toward "done" — verification is a safety net, not a gate, and a broken supervisor must not stall a finished task.

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"`
}

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"`
}

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

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

Jump to

Keyboard shortcuts

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