Documentation
¶
Overview ¶
Package askengine is the unified entry engine shared by `panda ask` (CLI) and the web panel: one prompt in, three intents out — answer (pure LLM reply), tool_call (memory tools, executed and fed back), task (submitted to the node network, locally or delegated). It owns the whole pipeline — config, storage, memory injection, tool registry, entry model client, and the optional P2P scheduler core — so both front-ends run exactly the same classification and execution path with zero duplicated logic.
Index ¶
- Variables
- type ApprovalRequest
- type ApprovalState
- type AskScope
- type Engine
- func (e *Engine) ApprovalState(sessionID, project string) ApprovalState
- func (e *Engine) Ask(ctx context.Context, prompt string, authorize bool) (*Result, error)
- func (e *Engine) AskTurns(ctx context.Context, history []entry.Turn, prompt, workDir string, ...) (res *Result, err error)
- func (e *Engine) AskTurnsScoped(ctx context.Context, history []entry.Turn, prompt string, scope AskScope, ...) (res *Result, err error)
- func (e *Engine) AskTurnsSession(ctx context.Context, history []entry.Turn, ...) (res *Result, err error)
- func (e *Engine) AwaitPlanOutcome(ctx context.Context, planID string, cb StreamCallbacks) *Result
- func (e *Engine) CancelTask(ctx context.Context, taskID string) ([]string, error)
- func (e *Engine) CardPath() string
- func (e *Engine) ClearApproval(sessionID, project string) error
- func (e *Engine) Close()
- func (e *Engine) DialPeer(ctx context.Context, addr string) error
- func (e *Engine) EnqueueTask(ctx context.Context, in core.TaskInput, q core.QueueSpec) (core.Task, error)
- func (e *Engine) Locale() i18n.Locale
- func (e *Engine) MCPCommand() string
- func (e *Engine) ModelConfig() config.ModelConfig
- func (e *Engine) MutateConfig(fn func(*config.Config))
- func (e *Engine) MutateConfigErr(fn func(*config.Config) error) error
- func (e *Engine) PlanStages(ctx context.Context, planID string) ([]core.Task, error)
- func (e *Engine) Project() (string, string)
- func (e *Engine) ReadConfig(fn func(*config.Config))
- func (e *Engine) RejectTask(ctx context.Context, taskID, reason string) error
- func (e *Engine) ReloadCard(path string) error
- func (e *Engine) RememberApproval(sessionID, project, scope, decision string) error
- func (e *Engine) ResumeApproved(ctx context.Context, taskID, workDir string, cb StreamCallbacks, ...) *Result
- func (e *Engine) SetLocale(loc i18n.Locale)
- func (e *Engine) SetMCPCommand(ctx context.Context, cmd string) error
- func (e *Engine) SetModel(mc config.ModelConfig) error
- func (e *Engine) SetOnReview(fn func(core.Task))
- func (e *Engine) SetProject(name, workDir string)
- func (e *Engine) SetProjectApprovalPolicy(project, mode, scope string) error
- func (e *Engine) SetRouterPolicy(injection config.InjectionConfig, routing config.RoutingConfig)
- func (e *Engine) StartPlan(ctx context.Context, p plan.Plan, q core.QueueSpec) (string, error)
- func (e *Engine) SummarizeTurns(ctx context.Context, evicted []entry.Turn) (string, error)
- func (e *Engine) TaskStore() *core.TaskStore
- func (e *Engine) WorkPath() string
- type Options
- type Progress
- type ProgressKind
- type Result
- type StreamCallbacks
Constants ¶
This section is empty.
Variables ¶
var ErrApprovalDenied = errors.New("tier-2 execution denied by a remembered approval decision")
ErrApprovalDenied marks a refusal that came from a remembered deny — the gate answered "no" before a task existed, so callers can surface it as a policy refusal (HTTP 409, a denied turn) instead of a generic failure.
Functions ¶
This section is empty.
Types ¶
type ApprovalRequest ¶ added in v0.0.7
type ApprovalRequest struct {
TaskID string
Title string
Intent string
Reason string // the executor's authorization-refusal message
Project string // the task's project — the scope a project-level "remember" writes to
Scope string // the resolved default remember scope (once|session|project)
}
ApprovalRequest describes a tier-2 (irreversible) action awaiting the user's consent at the inline approval gate: the task the entry model routed and the executor's refusal reason. It is what an OnApproval callback renders and what a NeedsApproval Result carries back for a caller that prompts out-of-band.
type ApprovalState ¶ added in v0.0.9
type ApprovalState struct {
Mode string `json:"mode"` // effective normalized mode
Scope string `json:"scope"` // default remember scope
Decision string `json:"decision"` // remembered answer, "" when none
DecisionScope string `json:"decision_scope"` // where the decision lives: session|project|""
Project string `json:"project"`
}
ApprovalState is the effective approval policy for (sessionID, project) as a surface sees it — what the /approval command and the panel render.
type AskScope ¶ added in v0.0.8
type AskScope struct {
Project string
WorkDir string
// Mode is the slash-prefix interaction mode the user picked for this turn
// ("goal", "plan", "spec"); empty leaves classification to the model.
Mode string
// SessionID keys the conversation a remembered "session" approval belongs
// to — the REPL's active session, a panel chat's id. Empty means the
// session-less bucket (a bare REPL, `panda ask`), whose decisions live and
// die with the process.
SessionID string
// AmbientProject falls back to the engine's ambient (entered) project
// when Project is empty — the compatibility default for CLI callers that
// do not pin a project per ask. Exported so scoped callers outside this
// package (panel sessions) can make the same choice explicitly.
AmbientProject bool
// Node pins this ask's classified task to a preferred executor node
// (id or name). A model-emitted spec.node always wins — the scope value
// is the composer's explicit pick, used when the model leaves routing
// to the scheduler. Plans are unaffected: per-stage routing is the
// point of a pipeline, so a flat node pin would defeat it.
Node string
}
AskScope is immutable context attached to one ask. Project and WorkDir are threaded through every classified and tool-call task path instead of mutating the Engine's ambient project or the scheduler Core's default directory.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine is the long-lived unified entry engine. It is safe for concurrent Ask calls (the entry client and registry are; the scheduler core is).
func New ¶
New builds an engine from cfg: opens storage, wires memory stores and the tool registry, connects the entry model client, optionally loads the capability card (creating the scheduler core and dialing peers once so the first classification already sees remote capabilities), and optionally spawns the MCP server. An Options.MCPCommand of "" falls back to config.yaml's mcp.command, so a configured server needs no CLI flag.
func (*Engine) ApprovalState ¶ added in v0.0.9
func (e *Engine) ApprovalState(sessionID, project string) ApprovalState
ApprovalState resolves the gate context for one (session, project) pair.
func (*Engine) Ask ¶
Ask runs one prompt through the unified entry model. A tool_call intent is executed (memory/MCP tools) and its result fed back, converging to a final answer or task; a task is submitted through the scheduler core (local or delegated) and its outcome returned.
func (*Engine) AskTurns ¶
func (e *Engine) AskTurns(ctx context.Context, history []entry.Turn, prompt, workDir string, authorize bool, cb StreamCallbacks) (res *Result, err error)
AskTurns is the backward-compatible session-aware entry point. Callers that own explicit project context should use AskTurnsScoped.
func (*Engine) AskTurnsScoped ¶ added in v0.0.8
func (e *Engine) AskTurnsScoped(ctx context.Context, history []entry.Turn, prompt string, scope AskScope, authorize bool, cb StreamCallbacks) (res *Result, err error)
AskTurnsScoped is the session-aware ask with request-scoped project/workspace.
func (*Engine) AskTurnsSession ¶ added in v0.0.9
func (e *Engine) AskTurnsSession(ctx context.Context, history []entry.Turn, prompt, workDir, mode, sessionID string, authorize bool, cb StreamCallbacks) (res *Result, err error)
AskTurnsSession is AskTurnsScoped plus the session id a remembered "session" approval binds to. "" degrades to the session-less bucket.
func (*Engine) AwaitPlanOutcome ¶ added in v0.0.11
AwaitPlanOutcome re-enters the stage watch for a plan that is already running — the post-approval path. Approving a parked stage resumes that one task; the pipeline behind it (next stages, their verdict) still needs the same follow startClassifiedPlan installed at submit, or the turn ends at the resumed stage's receipt while the plan runs on unreported. Returns nil when the plan id resolves to no board a watch could mean.
func (*Engine) CancelTask ¶ added in v0.0.8
CancelTask cancels taskID and its subtree through the scheduler core when the engine has one, so the cancel reaches remote executors too. Without the core (or when the scheduler is down to a plain store) it degrades to the local row update — the same behaviour the direct store call had.
The engine's core is an ephemeral sibling of the kernel daemon's: it shares the task database, and its bus connections are the dialed peers, so forwardCancelDownstream can deliver the task_cancel the daemon would have sent had the cancel arrived on the wire.
func (*Engine) CardPath ¶ added in v0.0.7
CardPath returns the capabilities.yaml the engine's scheduler was built from — the file /card edits and reloads.
func (*Engine) ClearApproval ¶ added in v0.0.9
ClearApproval forgets remembered decisions for (sessionID, project): the session bucket plus the project row's stored answer. Both, so "forget" really forgets no matter which scope the user last remembered into.
func (*Engine) Close ¶
func (e *Engine) Close()
Close releases the engine's resources (DB handle, scheduler core, MCP server). The engine must not be used afterwards.
func (*Engine) DialPeer ¶ added in v0.0.7
DialPeer dials addr on the engine's scheduler right now — /nodes add's live-connect path, so a peer freshly appended to the config joins this session without a restart. The connection registers itself (hello exchange) on success; the caller decides whether to wait or dial in the background.
func (*Engine) EnqueueTask ¶ added in v0.0.2
func (e *Engine) EnqueueTask(ctx context.Context, in core.TaskInput, q core.QueueSpec) (core.Task, error)
EnqueueTask routes a directly-created task (the panel's board "new task" form, `panda task add`) through the async queue: it lands in queued and the scheduler starts it when resources allow. Needs a capability card, like task submission.
The same tier-2 verdict the ask loop resolves applies here: the task's own project supplies the effective mode, a remembered project approve supplies consent without a prompt, a remembered deny refuses before the row exists, "always" still parks every tier-2 task for a foreground decision. Session remembers cannot apply — the linked session does not exist yet (the board creates it after a successful enqueue).
func (*Engine) MCPCommand ¶
MCPCommand returns the current MCP server command ("" = disabled).
func (*Engine) ModelConfig ¶
func (e *Engine) ModelConfig() config.ModelConfig
ModelConfig returns the engine's current model configuration.
func (*Engine) MutateConfig ¶ added in v0.0.10
MutateConfig applies fn to the engine's shared config under the write lock. Front ends alias e.cfg (the REPL's r.cfg is the same pointer) and use this for every post-init field write, so ask/tool goroutines reading those fields under the read lock never observe a torn mutation.
func (*Engine) MutateConfigErr ¶ added in v0.0.10
MutateConfigErr is MutateConfig for fallible mutations — typically a config-file persist paired with the in-memory write. Running the file I/O inside the lock serializes it with every other surface's mutate (REPL /model, panel settings saves) so concurrent writers cannot interleave a read-modify-write of config.yaml into a lost update.
func (*Engine) PlanStages ¶ added in v0.0.6
PlanStages returns every stage of one plan, for following a run.
func (*Engine) ReadConfig ¶ added in v0.0.10
ReadConfig runs fn under the read lock — the read half of MutateConfig, for callers that need several fields observed as one consistent snapshot. A nil cfg skips fn: no config loaded means nothing to snapshot.
func (*Engine) RejectTask ¶ added in v0.0.11
RejectTask fails a reviewed task and propagates the rejection to the remote executor holding its delegated review copy, on the same cancel path CancelTask uses. Without the forward the executor's copy stayed in review and a local approve there would run work the origin explicitly denied.
func (*Engine) ReloadCard ¶ added in v0.0.7
ReloadCard hot-swaps the scheduler's capability card (the /card edit path): the core re-reads the file, rebuilds its router, re-registers, and tells connected peers. The engine's own cardPath is what the system_status tool reports, so it moves too. Errors when the engine runs cardless — there is nothing to reload.
func (*Engine) RememberApproval ¶ added in v0.0.9
RememberApproval stores a tier-2 answer at the given scope. "session" keeps it in memory, dying with the process (a REPL's lifetime, a panel chat's); "project" persists it on the project row where every later session finds it; "once" writes nothing. decision is approve|deny.
func (*Engine) ResumeApproved ¶ added in v0.0.7
func (e *Engine) ResumeApproved(ctx context.Context, taskID, workDir string, cb StreamCallbacks, answers ...string) *Result
ResumeApproved accepts or re-runs a reviewed task under the caller's context. workDir optionally overrides the persisted task directory for an active originating session; progress is bridged from the same core event stream as initial foreground submission.
func (*Engine) SetLocale ¶ added in v0.0.8
SetLocale updates the active user locale for this engine.
func (*Engine) SetMCPCommand ¶
SetMCPCommand hot-swaps the stdio MCP server at runtime (the settings page): a new registry is built (memory + system + reminder tools), the new server spawned and its tools imported, then the swap happens atomically. An empty command disables MCP. A failed spawn leaves the previous registry and server serving. The ctx spawns the new server; the engine's own lifetime is unchanged.
func (*Engine) SetModel ¶
func (e *Engine) SetModel(mc config.ModelConfig) error
SetModel hot-swaps the entry model client at runtime (the settings page): a failed build leaves the previous client serving.
func (*Engine) SetOnReview ¶ added in v0.0.9
SetOnReview installs the callback fired when a task enters review — i.e. when work is waiting on a human decision. It is attached to the store the scheduler core actually transitions tasks on (and re-attached across card reloads), so an embedder's notification path cannot silently miss a pending approval. The callback must not block; it may not decide the approval, only announce it.
func (*Engine) SetProject ¶ added in v0.0.8
SetProject names the ambient project for the tasks this engine submits, and the directory they run in. Both may be empty, which is "not in a project".
func (*Engine) SetProjectApprovalPolicy ¶ added in v0.0.9
SetProjectApprovalPolicy writes a project's mode/scope overrides through the engine's own project store, so CLI and panel callers do not need a second handle to the same table. Empty fields keep their current values — a caller setting only the scope must not wipe the mode.
func (*Engine) SetRouterPolicy ¶ added in v0.0.8
func (e *Engine) SetRouterPolicy(injection config.InjectionConfig, routing config.RoutingConfig)
SetRouterPolicy re-applies the injection and routing policy to the engine's scheduler core, so a policy edited at runtime (the console's settings view) takes effect without a restart. A no-op on an engine with no card, which has no router to configure.
func (*Engine) StartPlan ¶ added in v0.0.6
StartPlan hands a multi-stage plan to the scheduler core, which creates one task per stage and releases the ones with no dependencies. It is the plan plane's only entry point outside the daemon's own completion hooks: without it the flagship cross-device pipeline — develop where a coding agent lives, train where the GPU lives, report where the user is — was reachable only from a test. Needs a capability card for the same reason task submission does: a plan whose stages cannot be routed is a plan that cannot start.
func (*Engine) SummarizeTurns ¶ added in v0.0.10
SummarizeTurns compresses evicted history into a running digest. evicted may begin with the previous digest's synthetic turn; the model is asked to fold it forward so the result replaces it, not appends to it. Returns ("", nil) when no model client is configured — callers then degrade to a hard trim.
type Options ¶
type Options struct {
// CardPath points at capabilities.yaml. When empty, the engine derives the
// path from config or the default location and lazily initializes the
// scheduler on the first task dispatch or card mutation, so a missing
// CardPath no longer restricts the engine to answers and memory tools.
CardPath string
// MCPCommand is an optional space-separated stdio MCP server command
// whose tools are imported into the registry.
MCPCommand string
// QueueTasks routes classified tasks through the async queue (core.Enqueue)
// instead of blocking inline submission: the task lands in queued and the
// queue scheduler starts it when resources allow — the panel's mode, where
// progress streams into the session. The CLI keeps inline (blocking) mode.
QueueTasks bool
// ReplyASCII makes the entry model answer in English/ASCII. Set it when
// the client runs on a bare Linux console whose font has no CJK glyphs
// (Chinese replies would otherwise render as diamonds).
ReplyASCII bool
// Locale specifies the user's preferred language (en, zh-CN, etc.).
// When empty, it is detected from the environment or config.
Locale i18n.Locale
// AsyncPeers dials configured peers in the background instead of waiting
// for the dials (and a settle window) before New returns. Interactive
// surfaces (the REPL) want this: an offline peer's dial timeout is
// routine in a long-lived session, not worth dead air before the banner.
// One-shot callers (panda ask) leave it off — their routing decision runs
// immediately and needs the conns settled first.
AsyncPeers bool
// MeshNode makes the engine a full network participant whenever it owns
// the node row (no daemon running): the WS listener comes up on
// network.listen_addr, configured peers get reconnect keepalives via
// SyncPeers, and LAN discovery gains auto-dial. `panda web` and the
// panel sidecar set it — both are long-lived, and without it a web-only
// node is an island: it could drain the queue but never be dialed, and
// a dropped peer edge stayed dead until restart. Interactive seats keep
// it off: the flap a short-lived REPL causes on peers outweighs the
// benefit (and a co-resident daemon makes the row borrowed anyway).
MeshNode bool
// ConfigPath is the file cfg was loaded from — the same path the caller
// passed to config.Load. It joins the sandbox's write-deny set so a
// sandboxed subprocess cannot rewrite the node's own configuration.
// Empty resolves like config.Load does (flag > env > user > system).
ConfigPath string
// Logger defaults to a warn-level stderr handler.
Logger *slog.Logger
}
Options tunes how the engine is built.
type Progress ¶ added in v0.0.6
type Progress struct {
Kind ProgressKind
Name string
Model string
Round int
Budget int
}
Progress is one structured progress event: the action, and the name of what it acts on (a task title, a plan goal, a tool name). The engine deliberately holds no locale — the CLI translates these through internal/i18n and the panel through the browser's language, from the same event.
Round/Budget locate a supervision step inside its loop ("round 2/5"): set on exec/judge milestones when the trace event carries them, zero otherwise. Renderers stay silent about single-round runs (Budget ≤ 1).
type ProgressKind ¶ added in v0.0.6
type ProgressKind string
ProgressKind names what the engine is about to do.
const ( ProgressTask ProgressKind = "task" // submitting a classified task ProgressPlan ProgressKind = "plan" // starting a multi-stage plan ProgressTool ProgressKind = "tool" // running a tool // The following are lifecycle milestones bridged from the scheduler core's // trace events while a synchronous Submit blocks — so the CLI shows the run // advancing (routing → executing → judging) instead of a frozen spinner. ProgressRoute ProgressKind = "route" // scheduler picked a node ProgressExec ProgressKind = "exec" // the agent/adapter started running ProgressJudge ProgressKind = "judge" // a supervision round is evaluating the result // ProgressWait is the round following a task the queue parked — its link // is not live yet, so the work has not started. Name carries the observed // state ("queued", "dispatched"), emitted on entering the wait and on // every state change, so the card keeps advancing while the round waits // instead of sitting frozen at the dispatch. ProgressWait ProgressKind = "wait" )
type Result ¶
type Result struct {
// Kind is "answer", "task" or "plan" — the final converged intent.
Kind string
// Answer carries the model's text reply when Kind == "answer".
Answer string
// Note is an incidental model note emitted alongside a tool call.
Note string
// Thought is the model's reasoning/thinking chain before producing the result.
Thought string
// Task fields, valid when Kind == "task".
TaskID string
TaskTitle string // for conversation history: "the task that ran" in one line
TaskState string
OK bool
Stdout string
Stderr string
ExitCode int
// Deferred marks a parked-for-delivery outcome: the approval was
// accepted into an outbox because the executor's link is down, so the
// correct rendering is "queued for delivery" with exit 0 — not a
// failure. Mirrors TaskResultPayload.Deferred.
Deferred bool
Agent string
Model string
Injected bool
// Executor is the node that actually ran the task — this node's id for a
// local run, the peer's id for a delegated one. Empty when the result
// never reached an executor (route miss, early failure).
Executor string
// WorkDir is the workspace the executor ran in (the derived directory,
// not the submitter's pin) — carried on the wire so the origin can
// locate the produced files on the machine that made them.
WorkDir string
// RouteFallback names the peer the task was routed to before the link
// failed at send time and it ran locally instead. Empty for a clean
// local run or a real delegation — non-empty means Executor's local id
// understates the user's intent ("on the Mac") and the report should say
// so. The marker lives in the task's audit events (EvRouteFallback).
RouteFallback string
// Question carries the agent's clarification when the task parked in
// review on a PANDA_QUESTION marker (core §4.3): the surface should show
// it verbatim — it is the one thing standing between the task and done.
Question string
// FilesChanged lists the workdir-relative paths the run touched — the
// result's footprint, so a surface can show what moved instead of trusting
// the agent's prose.
FilesChanged []string
// EntryModel is the model that served this ask's entry calls (triage,
// classify, answer stream) — the configured primary, or the fallback the
// circuit breaker routed to mid-ask. UI surfaces render it next to the
// execution attribution so "which model did what" is never a guess.
EntryModel string
// Report is the LLM-generated summary of the task outcome. It is filled
// by SummarizeResult after every inline task (success or failure) so the
// user sees a human-readable summary instead of raw stdout/stderr. A
// model failure leaves it empty, and the caller falls back to raw output.
Report string
// Plan fields, valid when Kind == "plan". A plan is asynchronous by nature —
// its stages run on other machines, in waves — so the call returns as soon as
// the stages exist and the first wave is released; PlanID is how the caller
// follows it from there.
PlanID string
PlanGoal string
PlanStages []core.Task
// Warning is a non-fatal advisory the surface should print — currently
// "no queue consumer is running" when the plan's stages were parked but
// nothing on this node will drain them. It does not change OK.
Warning string
// Cost of this ask, as reported by the entry model's provider (zero for
// providers that report no usage). The CLI shows them on its closing status
// line; the panel bills them through RecordDelegationMetric.
InputTokens int64
OutputTokens int64
Latency time.Duration
Cost float64
// NeedsApproval is set on a task Result when execution refused for lack of
// tier-2 (irreversible) consent and the caller supplied no OnApproval
// callback: the task is parked in review and Approval carries what a person
// must sign off on. A caller whose UI cannot answer a synchronous callback
// (the termios REPL, whose interrupt watcher owns the terminal mid-ask)
// reads this after the ask returns, prompts on its own event loop, and calls
// ResumeApproved. When OnApproval is set the engine consults it inline and
// this stays false.
NeedsApproval bool
Approval *ApprovalRequest
// Denied is set when a remembered "deny" answered the tier-2 gate before
// the task existed: nothing was created and no prompt was shown. Kind
// stays "task" so the refusal renders where a task card would have been.
Denied bool
// ConsentSource records which remembered scope supplied the consent when
// one did ("session" or "project"), so surfaces can show the task ran on
// a standing answer rather than a fresh prompt.
ConsentSource string
}
Result is the outcome of one Ask call.
type StreamCallbacks ¶
type StreamCallbacks struct {
OnDelta func(text string)
OnReasoning func(text string)
OnStatus func(text string)
OnProgress func(Progress)
// OnApproval is consulted when an inline task refuses for lack of tier-2
// (irreversible) consent and the approval mode is not "never". Returning
// true re-runs the task authorized in the same round-trip (ResumeApproved);
// returning false leaves it parked in review. A nil callback means the
// caller cannot answer synchronously: the engine returns a NeedsApproval
// Result instead, for the caller to handle on its own event loop.
OnApproval func(ApprovalRequest) bool
// GetSteer is polled at the start of each round to consume user steering ideas
// injected at runtime, appending them to conversation turns.
GetSteer func() string
}
StreamCallbacks receives live progress while an ask converges. OnDelta delivers answer text incrementally (streaming); OnReasoning delivers the model's chain-of-thought live (display-only, kept out of the answer and history per D14); OnStatus delivers one-line progress notes (tool calls, task submission) as ready-made English prose, and OnProgress delivers the same events structured, for a caller that owns a locale and wants to phrase them itself. Set whichever fits — OnProgress wins when both are present.