askengine

package
v0.0.10 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: AGPL-3.0 Imports: 41 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 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

Constants

This section is empty.

Variables

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

func New(ctx context.Context, cfg *config.Config, opts Options) (*Engine, error)

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

func (e *Engine) Ask(ctx context.Context, prompt string, authorize bool) (*Result, error)

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) AskTurnsMode added in v0.0.9

func (e *Engine) AskTurnsMode(ctx context.Context, history []entry.Turn, prompt, workDir, mode string, authorize bool, cb StreamCallbacks) (res *Result, err error)

AskTurnsMode is AskTurns plus the slash-prefix interaction mode the user picked (/goal, /plan, /spec). "" is exactly AskTurns.

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 AskTurnsMode plus the session id a remembered "session" approval binds to. "" degrades to AskTurnsMode's session-less bucket.

func (*Engine) CancelTask added in v0.0.8

func (e *Engine) CancelTask(ctx context.Context, taskID string) ([]string, error)

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

func (e *Engine) CardPath() string

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

func (e *Engine) ClearApproval(sessionID, project string) error

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

func (e *Engine) DialPeer(ctx context.Context, addr string) error

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) Locale added in v0.0.8

func (e *Engine) Locale() i18n.Locale

Locale returns the active user locale for this engine.

func (*Engine) MCPCommand

func (e *Engine) MCPCommand() string

MCPCommand returns the current MCP server command ("" = disabled).

func (*Engine) MaintainPeers

func (e *Engine) MaintainPeers(ctx context.Context)

MaintainPeers keeps redialing configured peers in the background until ctx ends — for long-lived embedders (the web panel). Short-lived CLI asks skip it: New's one-shot dial plus waitForPeers already covers them.

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

func (e *Engine) MutateConfig(fn func(*config.Config))

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

func (e *Engine) MutateConfigErr(fn func(*config.Config) error) error

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

func (e *Engine) PlanStages(ctx context.Context, planID string) ([]core.Task, error)

PlanStages returns every stage of one plan, for following a run.

func (*Engine) Project added in v0.0.8

func (e *Engine) Project() (string, string)

Project reports the ambient project and its work dir.

func (*Engine) ReadConfig added in v0.0.10

func (e *Engine) ReadConfig(fn func(*config.Config))

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) ReloadCard added in v0.0.7

func (e *Engine) ReloadCard(path string) error

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

func (e *Engine) RememberApproval(sessionID, project, scope, decision string) error

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

func (e *Engine) SetLocale(loc i18n.Locale)

SetLocale updates the active user locale for this engine.

func (*Engine) SetMCPCommand

func (e *Engine) SetMCPCommand(ctx context.Context, cmd string) error

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

func (e *Engine) SetOnReview(fn func(core.Task))

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

func (e *Engine) SetProject(name, workDir string)

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

func (e *Engine) SetProjectApprovalPolicy(project, mode, scope string) error

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

func (e *Engine) StartPlan(ctx context.Context, p plan.Plan, q core.QueueSpec) (string, error)

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

func (e *Engine) SummarizeTurns(ctx context.Context, evicted []entry.Turn) (string, error)

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.

func (*Engine) TaskStore added in v0.0.8

func (e *Engine) TaskStore() *core.TaskStore

TaskStore returns the task store on the engine's database, for callers that need read-level access (reference resolution) without a scheduler core.

func (*Engine) WorkPath

func (e *Engine) WorkPath() string

WorkPath returns the configured work directory — the project workspace panel sessions execute in. It lets the panel pin non-repo sessions to the work path so the memory wall (§17.2) holds for them too.

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

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

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

func (*Result) Tokens added in v0.0.6

func (r *Result) Tokens() int64

Tokens is the ask's total token count (input + output), 0 when the provider reports no usage.

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.

Jump to

Keyboard shortcuts

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