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
- func StatusText(p Progress) string
- func WithHardwarePlanConsent(ctx context.Context) context.Context
- type ApprovalRequest
- type ApprovalState
- type AskScope
- type DispatchedTask
- 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) ClearModel()
- func (e *Engine) Close()
- func (e *Engine) ContextWindow() int
- func (e *Engine) ContinueReviewed(ctx context.Context, taskID, note string, cb StreamCallbacks) *Result
- func (e *Engine) DeleteTaskNote(ctx context.Context, taskID, sender string) error
- func (e *Engine) DialPeer(ctx context.Context, addr string) error
- func (e *Engine) EditTaskNote(ctx context.Context, taskID, sender, text string, attachments []string) error
- func (e *Engine) EnqueueTask(ctx context.Context, in core.TaskInput, q core.QueueSpec) (core.Task, string, error)
- func (e *Engine) FetchArtifact(ctx context.Context, source, taskID, hash string) (artifact.Manifest, 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) PromoteTaskNote(ctx context.Context, taskID, sender string) (status, warning string, err error)
- 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) SendTaskMessage(ctx context.Context, taskID, text string, inject bool) (status, warning string, err error)
- func (e *Engine) SendTaskNote(ctx context.Context, taskID, text string, attachments []string, inject bool) (TaskNoteResult, error)
- 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
- type TaskNoteResult
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 ¶
func StatusText ¶ added in v0.1.0
StatusText phrases one progress event as one-line English prose — the fallback wording surfaces use when they did not bind OnProgress, and the wire text the panel re-localizes for the browser from the same event.
func WithHardwarePlanConsent ¶ added in v0.1.4
WithHardwarePlanConsent scopes explicit plan-stage authorization to one authenticated hardware request. The marker grants nothing on its own: the request must also supply authorize=true and pass the normal approval policy. Ordinary asks deliberately keep their existing per-stage consent behavior.
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
// Agents is the thread's roster: the agent names this conversation is
// allowed to hand work to. It is copied into every classified task's spec
// (allow_agents) and enforced at routing time on whichever node executes
// the task, so it constrains plans, sub-agents and remote hops alike
// rather than being a hint the model may ignore. Empty means no
// restriction — the scheduler routes by capability, as before.
Agents []string
// PermissionMode is the conversation's permission policy (defense.Mode*:
// auto, manual, edits, plan, bypass). It rides every tool gate and is
// copied into each classified task's spec so the executor — possibly a
// peer — applies the same policy. Empty reads as auto.
PermissionMode string
// Acceptance is the user's own contract for any task this ask produces
// (CLI --accept). It is appended to the classified task's spec and, unlike
// a model-selected check, bypasses the project shortlist: the user is the
// authority on how their own work is judged.
Acceptance []contract.Check
// Side marks a side-channel ask: a multi-turn conversation beside the main
// thread whose history is a fork-point snapshot. It narrows this ask on
// three axes — the prompt says the history is reference only, the tool face
// drops to a read-only subset (no task_submit, no task_budget, no mutation
// tools), and a classification that still lands on a task or plan is
// answered with a fixed note instead of being executed. None of the three is
// sufficient alone: the prompt is a hint the model may disobey, and the tool
// face only covers dispatch that goes through tools.
Side bool
// SideTurns is the side channel's own conversation so far. It replays AFTER
// the boundary marker, which is what keeps two things apart that would
// otherwise read as one: the main thread's history (history above, reference
// only) and the question-and-answer the user actually had with this channel.
// Only meaningful with Side.
SideTurns []entry.Turn
}
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 DispatchedTask ¶ added in v0.1.4
type DispatchedTask struct {
TaskID string `json:"task_id"`
TaskTitle string `json:"title,omitempty"`
TaskState string `json:"state,omitempty"`
}
DispatchedTask is one row of a fan-out: a task this ask enqueued, named the way the transcript names it. It carries only what a surface needs to draw a receipt — the row itself is read back through the task API, which is where state, traces and the employee's face live.
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) ClearModel ¶ added in v0.1.4
func (e *Engine) ClearModel()
ClearModel drops the live client and the fallbacks, leaving the engine in the model-less state New builds for a node that carries no key: the task surface (enqueue/cancel/plan) keeps working and only the ask path reports ErrNoModel.
SetModel cannot express this — NewClient refuses an unconfigured entry — so deleting the last model would otherwise leave the removed credential in the client slot and every following ask would still be dialed against the row the user just deleted. Config, engine and UI would disagree in the worst way: the page says nothing is configured while turns keep reaching the old endpoint.
func (*Engine) ContextWindow ¶ added in v0.1.0
ContextWindow returns the serving model's advertised context window in tokens, or 0 when it is unknown (no reachable client, or a model the catalogue does not size). Callers scale prompt-side budgets — like the history replay window — to it.
func (*Engine) ContinueReviewed ¶ added in v0.1.0
func (e *Engine) ContinueReviewed(ctx context.Context, taskID, note string, cb StreamCallbacks) *Result
ContinueReviewed requeues a follow-up-parked task: the supervised round budget ran out mid-work (needs_followup) and the operator chose "keep going" over accept-half or throw-away. The call only marks the row — the store's queue scheduler runs the continuation, which is what lets a CLI or console continue work a daemon owns. The optional note travels as a steer-grade board note that leads the continued round's intent.
func (*Engine) DeleteTaskNote ¶ added in v0.1.0
DeleteTaskNote drops a pending note from the board.
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) EditTaskNote ¶ added in v0.1.0
func (e *Engine) EditTaskNote(ctx context.Context, taskID, sender, text string, attachments []string) error
EditTaskNote rewrites a pending note. Errors carry the reason the store refused (unknown row, already read, terminal task, remote executor) so the surface can map them onto an HTTP status without guessing.
func (*Engine) EnqueueTask ¶ added in v0.0.2
func (e *Engine) EnqueueTask(ctx context.Context, in core.TaskInput, q core.QueueSpec) (core.Task, string, 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 warn result carries a localized advisory when the task was accepted but this store has no live queue consumer — the row is durable and runs once a consumer starts, but a silent "queued" that never moves is the worst possible failure mode to surface as success.
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) FetchArtifact ¶ added in v0.1.4
func (e *Engine) FetchArtifact(ctx context.Context, source, taskID, hash string) (artifact.Manifest, error)
FetchArtifact pulls a task's output artifact from the node that ran it into this node's pool. A task report travels back as a hash and the bytes stay where they were made until someone asks — so this is what "bring it here so I can look at it" calls, for the console's preview or a stage that needs the files.
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) PromoteTaskNote ¶ added in v0.1.0
func (e *Engine) PromoteTaskNote(ctx context.Context, taskID, sender string) (status, warning string, err error)
PromoteTaskNote escalates a queued note to an inject without posting a second row — the second-Enter path. The returned status is the same "interrupted"/"queued" pair SendTaskNote reports.
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) SendTaskMessage ¶ added in v0.1.0
func (e *Engine) SendTaskMessage(ctx context.Context, taskID, text string, inject bool) (status, warning string, err error)
SendTaskMessage delivers a user message into a task — the two send modes (steer.go). Queue posts a durable advisory the agent reads at its next supervision round; inject additionally aborts the in-flight round when one is live so the message leads the next one as a directive. The returned token is "interrupted" (a running turn was aborted), "queued" (the message waits for the next round — or the task's first run), and callers localize it for their surface.
The warning mirrors EnqueueTask: a task still queued with no consumer on this store never reaches a round, so a note delivered to it is durable but unread — say so instead of reporting a silent success.
func (*Engine) SendTaskNote ¶ added in v0.1.0
func (e *Engine) SendTaskNote(ctx context.Context, taskID, text string, attachments []string, inject bool) (TaskNoteResult, error)
SendTaskNote is SendTaskMessage with attachments and the landed slot. The text and the files travel together: the store appends one `@path` line per attachment to the body, so the agent reads a self-contained note.
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
// unless AwaitQueued is also set.
QueueTasks bool
// AwaitQueued turns queue-mode submission back into a synchronous-looking
// round: after Enqueue the ask follows the row through awaitSettled until
// it settles, bridging the consumer's persisted timeline into the turn's
// progress. Execution then belongs to the queue scheduler — resource-keyed
// (project:<name> serializes same-worktree tasks, disjoint projects run in
// parallel up to max_concurrent_tasks) and process-death-safe (the row is
// scheduled, so a dead submitter strands nothing). Interactive surfaces
// (REPL/TUI, panda ask) set it alongside QueueTasks; the panel leaves it
// off for receipt semantics. ctx ending mid-wait detaches the watch only —
// the task keeps running and the front end's task watcher announces the
// outcome, the same detach the inline wait's parked-task path has.
AwaitQueued 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
// LocalOnly marks a process that writes to the store and exits: `panda
// task add`, `task send`, `task continue`. Such a command needs the
// schema, the card and the task store — not a network presence. Opening
// the LAN-discovery socket for the milliseconds between argv and exit
// buys nothing (nobody can pair with a process that is already gone) and
// costs real things: a wildcard UDP bind on every short command, a
// `bind: address already in use` warning when several run at once or a
// daemon holds the port, and a one-shot peer dial whose conns are torn
// down before a single hello completes. LocalOnly skips both; everything
// a write needs (schema, store, card, identity key) still happens.
LocalOnly 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
// Detail qualifies the milestone without a locale: for a spawn it is
// the parallel-mode descriptor — "isolated" for a private-copy child,
// the comma-joined lane paths for a scoped one, "" for the default
// whole-project claim; for an offline milestone it is "waiting" or
// "resumed". Renderers phrase it in their own language.
Detail string
// Retry fields, valid when Kind == ProgressRetry: Attempt/MaxAttempt are
// the retry's position inside the call's budget, Delay the backoff about
// to be slept, Status the provider's HTTP answer (0 on transport failure),
// Reason the entry.ErrKind* class. Delay doubles as the outage's length on
// a resumed ProgressOffline.
Attempt int
MaxAttempt int
Delay time.Duration
Status int
Reason string
// InputTokens/OutputTokens are the ask's cumulative token counts, valid
// when Kind == ProgressUsage. Estimated marks OutputTokens as a
// character-based estimate rather than the provider's own count: surfaces
// render it with a "~" so a live guess is never mistaken for the bill.
InputTokens int64
OutputTokens int64
Estimated bool
}
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 // ProgressClarify means the ask is waiting on the user's choice card. ProgressClarify ProgressKind = "clarify" // 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 // ProgressSpawn is the fan-out milestone: a running agent emitted a // PANDA_DELEGATE request and the runtime spawned a causal child task for // it. It makes parallel decomposition visible — several in a row read as // the orchestrator dispatching sub-agents, not as repeated routing noise. ProgressSpawn ProgressKind = "spawn" // a delegate child task was spawned 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" // ProgressRetry is emitted each time a model call schedules a transport // retry (429, 5xx, network drop): Attempt counts to MaxAttempt while // Delay is the backoff about to be slept, Status the HTTP answer the // provider gave (0 when no response arrived), and Reason the machine // error class (entry.ErrKind*). Without it a rate-limited provider sits // behind a motionless spinner for the whole retry ladder. ProgressRetry ProgressKind = "retry" // ProgressOffline is emitted while the offline gate (entry/offline.go) // waits for a lost link: Detail is "waiting" on entering the wait and // "resumed" once the network answered again, Delay how long the outage // lasted, Name the model whose call stalled. It is a separate kind from // ProgressRetry on purpose — "the link is down" and "the provider failed" // are different problems, and a surface that shows the second for the // first sends the user to the wrong page. ProgressOffline ProgressKind = "offline" // ProgressAgentText carries one block of the delegated agent's own prose // (or an errored tool result) verbatim in Detail. It is live display // material, not a lifecycle milestone: a task that runs for twenty // minutes must show the work happening, not a frozen spinner. ProgressAgentText ProgressKind = "agent_text" // ProgressUsage reports the ask's cumulative token consumption while it // runs: InputTokens/OutputTokens are the totals so far across every model // call this ask made. Output may be a character-based estimate on // dialects that report usage only at end-of-stream; the final event of a // turn always carries the provider's real numbers. Surfaces render it next // to the clock instead of waiting for the closing result line. ProgressUsage ProgressKind = "usage" )
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
// Dispatched names every task this ask enqueued, in dispatch order, when a
// single round fanned out several `task_submit` calls. The task fields
// above still describe the last one — the receipt this Result has always
// carried — so a surface that draws one card keeps working unchanged. A
// round that dispatched exactly one task leaves this empty: the receipt
// already says everything there is to say.
Dispatched []DispatchedTask
// 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
// QuestionSpec is the structured option set the agent offered alongside
// the question (the same shape the entry model uses before a task). A
// surface with a choice card renders it; Question stays the text form.
QuestionSpec *entry.ClarifySpec
// 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
// Verified and Verification carry the delivery contract's verdict:
// "verified" when every selected check ran and passed, "failed" when one
// did not, "partial" when some were skipped, "" when the task carried no
// contract. A done task with an empty or non-verified verdict is exactly
// what a surface must not present as an unqualified success.
Verified bool
Verification 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
// NeedsClarification is set when a pre-execution clarify round could not
// be answered inline (no OnQuestion callback, or the model asked twice).
// Clarification carries the questions and Answer a human-readable
// rendering, so a surface without a choice card can show what is needed
// and take the answer as the next user turn.
NeedsClarification bool
Clarification *entry.ClarifySpec
// 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
// OnQuestion renders a pre-execution clarify round and blocks until the
// user answers. ok=false means the user cancelled (the engine returns the
// cancelled context). A nil callback means this surface cannot show a
// choice card: the engine returns the question as a NeedsClarification
// Result for the caller to render and answer in its own event loop.
OnQuestion func(entry.ClarifySpec) ([]entry.ClarifyAnswer, 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
// OnSteerConsumed fires once per idea GetSteer handed over, with the round
// that will carry it. A surface that accepted a note has only proved it
// reached a channel; this is the proof the model will see it, and without
// it "已注入" is a claim the caller cannot back up — the last round of a
// turn can start and finish before anything polls the channel again.
OnSteerConsumed func(text string, round int)
// OnTaskRow fires once, with the id of the task row this turn created,
// before that task executes. The Result carries the same id, but it
// arrives after the work is over — far too late for a surface that wants
// to type into the running task (queue on the first Enter, inject on the
// second). Nil for callers that only read the outcome.
OnTaskRow func(taskID 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.
type TaskNoteResult ¶ added in v0.1.0
type TaskNoteResult struct {
Sender string `json:"sender"`
Seq int64 `json:"seq"`
Status string `json:"status"`
Warning string `json:"warning,omitempty"`
}
TaskNoteResult is the outcome of one note into a task: the board slot it occupies (so the caller can edit, drop or promote that exact row), how it landed, and the advisory the surface should show beside the outcome.