askengine

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2026 License: MIT Imports: 39 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

This section is empty.

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
}

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

type AskScope struct {
	Project string
	WorkDir string
	// contains filtered or unexported fields
}

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

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

Config returns the engine's loaded configuration.

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) through the async queue: it lands in queued and the scheduler starts it when resources allow. Needs a capability card, like task submission.

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

func (e *Engine) ResumeApproved(ctx context.Context, taskID, workDir string, cb StreamCallbacks) *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) 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) 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) 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
	// 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
	// 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
}

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