runtime

package
v1.4.11 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 29 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

This file implements shell-style argument tokenization for prompt templates (US-001, #331). A template invocation like

/component Button "click handler"

arrives at the expander as the raw string `Button "click handler"`; the expander needs positional args ($1, $@, ...), so the string must be split into ["Button", "click handler"] honoring shell quoting rules: double and single quotes group a single argument, surrounding quotes are stripped, and internal whitespace is preserved.

Rather than hand-roll a tokenizer, we reuse a mature shell-quoting library (github.com/kballard/go-shellquote), per the project's "reuse rather than reinvent" rule.

This file implements the context-budget reminder provider: the last link of the budget tooling. When the conversation has used most of the model's window, the provider injects one <system-reminder> per threshold crossing (a notice at <=10% remaining, an escalated warning at <=3%) so the model can land the current work and size the next steps to the room it actually has.

Like every reminder it is ephemeral: injected only into that turn's request, never persisted, never compacted. The provider is stateless — it reads the run's live budget state from the context the loop published, so registering it once per session works for every run, parent or sub-agent, and the once-per-crossing ladder lives in the shared state.

Checkpoint persistence for the "infinite context" feature (#480). A checkpoint is a distilled summary of a conversation *prefix* — everything up to a watermark message index — persisted as a Markdown memory file so a later run can reload the collapsed context instead of replaying (and re-tokenizing) the whole transcript.

The file lives at <memoryRoot>/sessions/<sessionID>/checkpoint.md and carries the repo's standard YAML frontmatter (name/description/metadata.type) with the checkpoint bookkeeping (watermark, createdAt, covered message count) under metadata; the Summary is the Markdown body. This mirrors the memory-file convention (see internal/memory, TypeCheckpoint = "checkpoint") so the memory indexer can pick these files up unchanged.

This file provides the persistence primitives plus the summarize→Checkpoint bridge; the run loop calls both through writeCompactionCheckpoint, which logs-and-continues on a write failure rather than aborting the turn.

This file implements the layered configuration system (US-023, #42), the golder port of pi/zero's config resolution. A resolved Config is produced by merging partial layers in precedence order:

default < global < project < environment/CLI

Each layer is a *ConfigLayer whose fields are pointers, so "unset" (nil) is distinguishable from "set to the zero value" — only set fields override lower layers (field-level replacement, no deep merge). The final Config is validated: an unknown thinking level or tool-execution mode is a hard error, as is a malformed layer file.

This file implements the headless / stdio run modes (US-020, FR-18): a non-interactive driver that runs the agent loop over a single prompt for scripting and CI. Two output modes are supported, mirroring pi's print-mode and rpc/stream-json protocols:

  • PrintMode: run the loop to completion and write only the final assistant text to the output (the "-p / --print" mode).
  • StreamJSONMode: serialize every AgentEvent as a line-delimited JSON object as it is emitted (the "--output-format stream-json" mode), so a parent process can consume the run incrementally.

The run's success/failure is reported as a returned error so the CLI can map it to a process exit code: a run whose final assistant message carries stopReason error/aborted, or whose stream result errors, is a failure.

This file implements pi's two-layer agent loop (US-006, FR-1). It strings together streaming assistant responses, batch tool execution, and the loop's six hooks with control flow kept faithful to pi's runLoop:

  • Inner loop: one turn = stream an assistant response → execute its tool calls → feed the results back, repeating until an assistant message has no tool calls (a natural turn end).
  • Outer loop: after the inner loop settles, pull getFollowUpMessages; if any are returned they become the next pending input and the inner loop runs again, otherwise the run ends.

Per-turn hooks after each turn_end: getSteeringMessages (pulled after tool execution and injected before the next turn), prepareNextTurn (may swap context / model / thinkingLevel), shouldStopAfterTurn (true ⇒ agent_end + exit). Two stop reasons are handled specially: length (the response was truncated by the token cap) fails every tool call so the model resends (failToolCallsFromTruncatedMessage); error / aborted end the run immediately.

agentLoop starts a fresh run from a prompt already appended to the context.

This file implements system-prompt assembly (US-021, #40), the golder port of pi's prompt construction. A run's system prompt is built from three layers, in order:

  1. a base instruction (who the agent is and how it should behave),
  2. an environment block (working directory, OS/arch, current date),
  3. the user-wide AGENTS.md under the state root (when present), and
  4. every project AGENTS.md found on the path from a root directory down to the working directory, concatenated general-to-specific.

The AGENTS.md ordering mirrors zero/pi's monorepo behavior: a repo-root AGENTS.md states broad conventions, and a nested package's AGENTS.md refines them, so the more specific file appears later and takes precedence in the model's reading.

This file implements the general system-reminder dynamic context injection mechanism (US-002, FR-1/FR-2), golder's port of Claude Code's per-turn <system-reminder> injection.

A reminder is EPHEMERAL background context (the current todo list, a file that changed under the working directory, a budget warning) that should be visible to the model on the turn it matters, but must never pollute the durable conversation history. Two properties follow from that:

  • Not user instructions. Reminder bodies are wrapped in <system-reminder> tags with a preamble stating they are background context from the harness, not a request from the user (the pi / Claude Code semantic convention).
  • Ephemeral. Reminders are injected only into the per-turn LLM request via the existing TransformContext seam, which shapes a COPY of the message list for the request and is never written back to AgentContext.Messages. Because they never enter the persisted message list they cannot be saved to the session file and cannot be folded into a compaction summary (compaction only ever sees AgentContext.Messages).

The mechanism is a registry of ReminderProviders. Each provider is consulted every turn and may decline (ok == false) so a reminder only appears when its condition holds. RunConfig.Reminders wires the registry into the loop.

This file implements DrainStream (architecture deepening ①): the single place that consumes a loop EventStream. The streaming-text delta accounting (track how many bytes of the current assistant message have been surfaced, emit only the new suffix) and the message_update-vs-turn_end dispatch were previously hand-rolled in three places — the REPL, the headless driver, and the sub-agent tool. Each consumer now supplies callbacks and shares one drain loop, so a bug in the delta arithmetic or the dispatch has exactly one home.

This file implements declarative skills (US-028, #45): a skill is a markdown file with a YAML frontmatter block (mirrors SKILL.md) that names a reusable capability. Loading a skill parses its metadata (name, description, optional tool allow-list and model) and its markdown body (the skill's system prompt), then materializes it as a sub-agent tool — so invoking a skill runs its body as the system prompt of a child agent loop, reusing the SubAgentTool abstraction rather than introducing a second execution path. Each skill's description is surfaced in the parent's capability list so the model can choose to delegate to it.

This file implements slash-commands (US-029, #45): typed "/name" shortcuts a user invokes in the REPL. Commands come from four sources — built-in registrations, user markdown templates, skills and plugins (the Source* constants) — resolved with a fixed priority:

  • Built-in commands are registered at compile time via RegisterBuiltin (from init() in the fork's own code). They are always available.
  • User commands are declarative markdown templates loaded from a directory (mirrors the .../commands/*.md convention): the file name is the command name and the body is a prompt template that may reference $ARGUMENTS.

Conflict rule: same-name commands resolve by priority tier (built-in > project > global > package > settings > CLI); the higher tier wins and the loser is reported via Shadowed. Built-ins are load-bearing and always win. Within a tier, the last-added command overrides earlier ones (a re-load).

Plugins extend the set through the plugin package (SourcePlugin) rather than a second mechanism, and a fork can add built-ins via init() registration; the MCP client is not implemented, so nothing is sourced from MCP.

This file implements streamAssistantResponse (US-003): it shapes the context into a provider request, resolves the API key dynamically, drives the provider stream, and back-fills the partial assistant message into the context while emitting message_start / message_update / message_end events.

This file implements sub-agent orchestration (US-027, #45) with an optional process-isolation mode (US-019, #135).

A sub-agent is a full agent loop with its own AgentContext (independent system prompt, message history and tool set), launched by the parent through a normal tool call. The child runs to completion and its final assistant text is fed back to the parent as the tool result - so from the parent loop's perspective a sub-agent is just another tool.

Two isolation modes are supported, selected by SubAgentSpec.Isolation:

  • Goroutine (default): the child loop runs in-process in a goroutine sharing the parent process, matching the original "single-process goroutine" decision.
  • Process: the parent spawns a fresh golder subprocess (golder --subagent-rpc) and delegates the run over stdio JSON-RPC (reusing internal/jsonrpc). The child runs in a separate process, so a crash or resource leak in the child cannot affect the parent loop; a crash is surfaced as a tool error. The subprocess resolves its own provider from the model/provider passed in the request and inherits the parent environment for credentials.

Because each Execute call spins up an independent run, multiple sub-agents can run concurrently (the batch executor already runs parallel tool calls in separate goroutines/processes).

This file implements the generic `task` tool (US-002, #454): a general-purpose sub-agent the model can dispatch with a free-form prompt to fan out work in a single assistant message. It is a thin specialization of SubAgentTool - it reuses executeGoroutine's child-loop driving - configured with a generic system prompt (the delegated task comes from the call arguments at runtime), a shared concurrency semaphore, and a child tool set from which `task` itself is excluded (the nesting guard, wired in internal/cli/run).

This file implements structured telemetry collection for a loop run (observability -- structured telemetry collection). A lightweight accumulator observes the AgentEvents the loop already emits and folds them into a compact summary — per-tool wall-clock durations, turn count, truncation count, compaction count, and the latest context-utilization ratio — that is surfaced once at run end as a TelemetryEvent (just before agent_end).

The design is deliberately additive: telemetry rides the existing AgentEvent family and the existing stream-json output path, so no new dependency (Prometheus/OTLP) is introduced and existing stream-json consumers that do not know the "telemetry" event type keep working unchanged. Collection is passive — observing an event never changes loop behavior.

This file freezes golder's telemetry export contract (issue #569), aligning the export story with pi-telemetry's goal — a vendor-neutral, typed, conformance-tested schema — scoped to golder's run-summary model:

  • TelemetrySummary is the canonical run-level export document, JSON-tagged with snake_case names and a schema_version discriminator. Consumers can decode it without knowing golder's Go types, and the golden conformance test (telemetry_schema_test.go + testdata/telemetry) fails the build if the shape or the stream-json envelope drifts.
  • The stream-json "telemetry" event envelope (eventEnvelope in headless.go) keeps its historical camelCase field names — existing consumers depend on them — and is now pinned by the same golden machinery, so it cannot change unnoticed either.

Both documents derive from the single accumulator (telemetry) and its TelemetryEvent, so there is exactly one source of truth with two frozen projections.

This file implements the prompt-template expansion engine (US-002, #332): it turns a template body plus tokenized invocation args into the final prompt text, supporting pi's positional/default/slice syntax.

Supported placeholders (mirrors https://pi.dev/docs/latest/prompt-templates):

  • $1, $2, ... $N : Nth positional arg (1-indexed; out-of-range -> "")
  • $@, $ARGUMENTS : all args joined by a single space
  • ${1:-default} : arg 1 when present and non-empty, else `default`
  • ${@:-default}, ${ARGUMENTS:-default} : all args when non-empty, else default
  • ${@:N} : args from the Nth onward (1-indexed), joined
  • ${@:N:L} : L args starting at N, joined

A single left-to-right pass expands both braced ${...} and bare $N/$@ forms. Because the pass consumes a ${...} as one unit, a bare $1 never matches inside ${1:-...}, and a default literal containing $ is not re-expanded (the substituted text is appended verbatim and the scan advances past it).

Index

Constants

View Source
const (
	CategoryGeneral     = "General"
	CategorySession     = "Session"
	CategoryModel       = "Model"
	CategoryMemory      = "Memory"
	CategoryPermissions = "Permissions"
	CategoryModes       = "Modes"
	CategoryExtensions  = "Extensions"
)

Command categories group slash commands in /help and the TUI menu. They are display-only labels; the order below is the order the groups are rendered.

View Source
const DefaultBaseInstruction = "You are golder, a helpful coding agent. " +
	"Use the available tools to inspect files and accomplish the user's request precisely and concisely.\n\n" +
	todoGuide + "\n\n" +
	taskGuide + "\n\n" +
	patchGuide + "\n\n" +
	sandboxGuide + "\n\n" +
	approvalGuide + "\n\n" +
	codeSearchGuide + "\n\n" +
	inspectGuide + "\n\n" +
	batchGuide + "\n\n" +
	searchGuide + "\n\n" +
	contextGuide

DefaultBaseInstruction is the leading system-prompt text used when PromptConfig.BaseInstruction is empty.

View Source
const DefaultMaxSubagents = 4

DefaultMaxSubagents is the concurrency cap applied when GOLDER_MAX_SUBAGENTS is unset or invalid. It bounds how many task sub-agents run at once so a fan-out cannot overwhelm the provider rate limit.

View Source
const SubAgentRPCFlag = "--subagent-rpc"

SubAgentRPCFlag is the command-line flag the parent launches the golder subprocess with so it enters the sub-agent RPC server mode: "--subagent-rpc".

View Source
const SubAgentRPCMethod = "subagent/run"

SubAgentRPCMethod is the JSON-RPC method name the parent calls on the subprocess: "subagent/run".

View Source
const TelemetrySchemaVersion = "golder.telemetry/v1"

TelemetrySchemaVersion is the discriminant stamped on every TelemetrySummary document. A breaking shape change MUST bump it (v2) and regenerate the golden fixtures.

Variables

CategoryOrder is the render order of the built-in command categories. CategoryExtensions is last: it collects user commands, skills and plugins.

Functions

func BuildSystemPrompt

func BuildSystemPrompt(cfg PromptConfig) (string, error)

BuildSystemPrompt assembles the full system prompt from cfg: base instruction, environment block, then AGENTS.md files ordered general-to-specific from Root down to WorkingDir. Missing AGENTS.md files are skipped silently; only a present-but-unreadable file (a real I/O error other than not-exist) is reported.

func CategoryOf

func CategoryOf(c SlashCommand) string

CategoryOf returns the display category of a command: its own Category for a built-in (defaulting to General), or Extensions for anything loaded from disk (prompt templates, skills, plugins).

func CheckpointPath

func CheckpointPath(sessionID, memoryRoot string) string

CheckpointPath returns the on-disk path of a session's checkpoint file: <memoryRoot>/sessions/<sessionID>/checkpoint.md.

func DrainStream

DrainStream consumes stream to completion, invoking h's callbacks, and returns the final assistant message (or nil) plus the run's result error. It always drains every event even if a callback has side effects that fail, so the loop's producer goroutine never blocks on back-pressure (the no-leak contract). The final assistant message is taken from the run result when available, falling back to the last turn_end message observed on the stream.

func ExpandTemplate

func ExpandTemplate(template string, args []string) string

ExpandTemplate expands template against the tokenized args. A template with no placeholder preserves ParseUserCommand's behavior: with no args it is returned verbatim, with args they are appended after a blank line (joined by spaces).

func FormatSkillsForPrompt

func FormatSkillsForPrompt(skills []*Skill) string

FormatSkillsForPrompt renders the visible skills as an <available_skills> XML block for injection into the system prompt (mirrors pi's formatSkillsForPrompt). It implements progressive disclosure: only each skill's name, description, and location (the absolute SKILL.md path) are listed, so the model can read the file on demand rather than carrying every skill body in context.

Skills with DisableModelInvocation == true are excluded (they remain reachable only via their explicit "/name" slash command). When no visible skill remains, it returns the empty string so callers can append unconditionally without altering a skill-free prompt.

func HasReadTool added in v1.2.16

func HasReadTool(tools []agentcore.AgentTool) bool

HasReadTool reports whether the read tool is in the set. Skills are advertised in the prompt only then, since the model loads a skill's body with that tool.

func MaxSubagents

func MaxSubagents() int

MaxSubagents resolves the concurrency cap for task sub-agents from GOLDER_MAX_SUBAGENTS: absent or unparseable yields DefaultMaxSubagents (4), and a parsed value below 1 is floored to 1 so the semaphore always admits at least one runner.

func NewSubagentSemaphore

func NewSubagentSemaphore() chan struct{}

NewSubagentSemaphore builds the shared concurrency semaphore for task sub-agents, sized by MaxSubagents. One instance per run is created and shared across every task call so the cap is enforced run-wide.

func RegisterBuiltin

func RegisterBuiltin(cmd SlashCommand)

RegisterBuiltin registers a built-in slash command at compile time. It is intended to be called from init(); a duplicate name panics, since two built-ins claiming the same name is a programming error in the fork.

func RunHeadless

func RunHeadless(ctx context.Context, agentCtx *agentcore.AgentContext, cfg HeadlessConfig) error

RunHeadless runs the agent loop for the already-assembled agentCtx and drives output per cfg.Mode. It blocks until the run ends and returns nil on success or an error describing the failure (for exit-code mapping). It never returns before the stream is fully drained, so no goroutine is leaked.

func RunSubAgentOnce

func RunSubAgentOnce(ctx context.Context, systemPrompt, prompt string, tools []agentcore.AgentTool, runCfg RunConfig) (string, error)

RunSubAgentOnce runs one sub-agent loop to completion and returns the child's final assistant text. It is the execution core shared by the process-isolated subprocess (cmd/golder --subagent-rpc): given a resolved RunConfig (provider stream, tool registry) and the prompt/system prompt, it builds a fresh child context and drains the run. A run whose final turn stopped on error/aborted is reported as an error so the subprocess surfaces failure (as an RPC error) rather than returning empty text. It does not stream partial updates: the process protocol returns only the final result.

func SplitArgs

func SplitArgs(s string) ([]string, error)

SplitArgs tokenizes a raw argument string using shell-style quoting rules. Double quotes ("a b") and single quotes ('a b') each group one argument; surrounding quotes are stripped and internal whitespace is preserved. An empty (or all-whitespace) input yields an empty non-nil slice with no error. An unterminated quote yields an error, so the caller can fall back to treating the whole string as $ARGUMENTS rather than feeding a malformed arg list to the template engine.

func StallNote added in v1.3.8

func StallNote(s TurnStall) string

StallNote is the sentence a front-end shows for a stalled turn, in one place so the line-based REPL, the TUI and the side runs cannot describe the same event three ways.

func WrapSystemReminder

func WrapSystemReminder(body string) string

WrapSystemReminder wraps a reminder body in <system-reminder> tags with the background-context preamble. The result is the text of a single injected message.

func WriteCheckpoint

func WriteCheckpoint(sessionID, memoryRoot string, cp Checkpoint) error

WriteCheckpoint persists cp as <memoryRoot>/sessions/<sessionID>/checkpoint.md, creating parent directories (0o755). It writes to a temp file and atomically renames it into place so a concurrent reader never sees a half-written file. The write is intended to be non-fatal to callers: on error the on-disk file is left untouched and the error is returned for the caller to log-and-continue.

Types

type BudgetReminderProvider

type BudgetReminderProvider struct{}

BudgetReminderProvider surfaces the remaining context budget near the end of a window. Register it with NewReminderRegistry / TodoReminders; it stays silent when no budget state is present (e.g. runs outside the loop) or while the budget is healthy.

func (*BudgetReminderProvider) Name

func (p *BudgetReminderProvider) Name() string

Name implements ReminderProvider.

func (*BudgetReminderProvider) Reminder

Reminder implements ReminderProvider: it claims the next due threshold crossing and renders it. Claiming inside the provider (rather than in the loop) keeps the "once per crossing" guarantee next to the state that defines the crossing.

type Checkpoint

type Checkpoint struct {
	// Watermark is the message index the checkpoint summarizes up to: messages
	// [0, Watermark) are collapsed into Summary. A resumed run replays only the
	// tail after Watermark, prepending Summary as the collapsed context.
	Watermark int
	// Summary is the distilled context (the Markdown body of checkpoint.md),
	// produced by the summarization LLM call (see compaction.GenerateSummary).
	Summary string
	// CreatedAt is when the checkpoint was distilled (RFC 3339, UTC).
	CreatedAt time.Time
	// CoveredMessages is how many messages the summary actually folded in. It
	// usually equals Watermark for a linear prefix but is recorded separately so
	// a caller that checkpoints a non-contiguous slice still keeps an honest count.
	CoveredMessages int
}

Checkpoint is a distilled summary of the conversation up to (and including) Watermark. It is the in-memory form written to / read from checkpoint.md.

func BuildCheckpoint

func BuildCheckpoint(ctx context.Context, msgs []agentcore.Message, watermark int, now time.Time, summarize SummarizeFunc) (Checkpoint, error)

BuildCheckpoint distills msgs into a Checkpoint by invoking summarize, tagging the result with watermark and now (coerced to UTC). It performs no I/O — the caller persists the result with WriteCheckpoint — so the (potentially slow, potentially failing) summarization call stays off the write path. A nil summarize or a summarization error is returned as an error.

func LoadCheckpoint

func LoadCheckpoint(sessionID, memoryRoot string) (*Checkpoint, bool, error)

LoadCheckpoint reads and parses the checkpoint for sessionID under memoryRoot. It returns (nil, false, nil) when the file does not exist — a missing checkpoint is a normal "no collapsed context yet" state, not an error. A present-but-malformed file yields a non-nil error.

type Config

type Config struct {
	// Model is the default model id used when a run does not specify one.
	Model string
	// Provider is the default provider name.
	Provider string
	// Credentials maps provider name → API key. Merged per-provider across
	// layers (a higher layer's key for provider X overrides a lower one, but
	// providers only present in a lower layer are retained).
	Credentials map[string]string
	// ToolExecutionMode is the default execution mode for tools that do not pin
	// their own mode.
	ToolExecutionMode agentcore.ToolExecutionMode
	// ThinkingLevel is the default reasoning-effort level.
	ThinkingLevel agentcore.ThinkingLevel
	// Hooks are the resolved, append-merged hook matchers keyed by event type.
	// Nil when no layer defined any hooks (FR-18), so the no-hooks path costs
	// nothing downstream.
	Hooks hooks.HookSet
}

Config is the fully resolved configuration a run operates under, after all layers are merged and validated.

func ResolveConfig

func ResolveConfig(layers ...*ConfigLayer) (Config, error)

ResolveConfig merges the given layers in ascending precedence order (earlier layers are overridden by later ones) and validates the result. Nil layers are skipped, so callers can pass the output of LoadConfigLayer directly. The merge is field-level: a later layer only overrides fields it sets, except Credentials, which merges per-provider.

type ConfigLayer

type ConfigLayer struct {
	Model             *string           `json:"model,omitempty"`
	Provider          *string           `json:"provider,omitempty"`
	Credentials       map[string]string `json:"credentials,omitempty"`
	ToolExecutionMode *string           `json:"toolExecutionMode,omitempty"`
	ThinkingLevel     *string           `json:"thinkingLevel,omitempty"`
	// Hooks are this layer's hook matchers keyed by event type. Unlike the
	// scalar fields, hooks are not overridden across layers: ResolveConfig
	// appends each layer's matchers per event type (FR-2), so lower-layer hooks
	// always still fire.
	Hooks hooks.HookSet `json:"hooks,omitempty"`
}

ConfigLayer is one partial layer of configuration. Pointer/optional fields distinguish "not set in this layer" (nil/empty) from an explicit value, so a higher layer only overrides the fields it actually sets.

func DefaultConfigLayer

func DefaultConfigLayer() ConfigLayer

DefaultConfigLayer is the base layer applied before all others. It gives a usable configuration out of the box.

func EnvConfigLayer

func EnvConfigLayer(getenv func(string) string) ConfigLayer

EnvConfigLayer builds a config layer from environment variables, the highest file-independent layer (below only explicit CLI flags). Recognized:

GOLDER_MODEL, GOLDER_PROVIDER, GOLDER_TOOL_EXECUTION_MODE, GOLDER_THINKING_LEVEL

Only set variables contribute; unset ones leave the field nil so lower layers show through. Credential env vars are intentionally NOT captured here — keys are resolved lazily by the CredentialStore and never merged into a struct that might be logged (US-012).

func LoadConfigLayer

func LoadConfigLayer(path string) (*ConfigLayer, error)

LoadConfigLayer reads and decodes a single JSON config layer from path. A missing file yields a nil layer and no error (an absent layer is not a failure); a present-but-malformed file is a hard error.

type ErrRunFailed

type ErrRunFailed struct {
	// Reason is the stopReason (or message) that marked the run as failed.
	Reason string
}

ErrRunFailed is the sentinel returned by RunHeadless when the agent run ended in a failure state (stopReason error/aborted). The CLI maps a non-nil error to a non-zero exit code.

func (*ErrRunFailed) Error

func (e *ErrRunFailed) Error() string

type GoalReminderProvider

type GoalReminderProvider struct {
	// State is the session goal state. When nil the provider never fires.
	State *agenttool.GoalState
}

GoalReminderProvider surfaces the active goal as background context each turn so the model keeps working toward it (mirrors pi-goal). It reads the same GoalState the /goal command drives, so the reminder always reflects the live objective. It fires only while the goal is active — a paused, blocked, or completed goal (and an idle state) injects nothing.

func (*GoalReminderProvider) Name

func (p *GoalReminderProvider) Name() string

Name implements ReminderProvider.

func (*GoalReminderProvider) Reminder

Reminder implements ReminderProvider. It injects the objective plus a persistence instruction while the goal is active, and stays silent otherwise.

type HeadlessConfig

type HeadlessConfig struct {
	// Run is the loop configuration (provider stream, tools, hooks).
	Run RunConfig
	// Mode selects print vs stream-json output. Defaults to PrintMode.
	Mode HeadlessMode
	// Out receives the run output (final text or JSON lines). Required.
	Out io.Writer
	// OnEvent, when non-nil, is invoked for every AgentEvent before output
	// handling. It is the seam plugin lifecycle-event delivery (US-017, #133)
	// hooks into, independent of the output mode. It must not block.
	OnEvent func(ev agentcore.AgentEvent)
	// Progress receives human-readable sub-agent progress lines
	// (SubAgentProgressEvent). Defaults to os.Stderr when nil. Progress is
	// stderr-only by contract: it is never serialised onto Out (stdout), so it
	// cannot pollute the final result text or the stream-json envelope stream.
	Progress io.Writer
}

HeadlessConfig configures a headless run.

type HeadlessMode

type HeadlessMode int

HeadlessMode selects how a headless run reports its progress and result.

const (
	// PrintMode runs the loop to completion and writes only the final assistant
	// text to the output writer.
	PrintMode HeadlessMode = iota
	// StreamJSONMode writes each AgentEvent as a line-delimited JSON object as it
	// is emitted.
	StreamJSONMode
)

type LoopConfig

type LoopConfig struct {
	// Model is the model id passed to StreamFn.
	Model string
	// APIKey is the static fallback key when GetAPIKey is nil or returns "".
	APIKey string
	// ThinkingLevel is the reasoning effort for requests.
	ThinkingLevel agentcore.ThinkingLevel
	// Stream produces the provider stream. Required (defaults are wired by
	// callers/tests, e.g. a fake provider).
	Stream provider.StreamFn

	// TransformContext optionally rewrites the message list before conversion
	// (context trimming/injection). Contract: must not error; on failure return
	// a safe fallback. Runs first.
	TransformContext func(ctx context.Context, msgs agentcore.MessageList) agentcore.MessageList
	// ConvertToLlm optionally filters UI-only messages. Defaults to identity.
	// Contract: must not error.
	ConvertToLlm func(msgs agentcore.MessageList) agentcore.MessageList
	// GetAPIKey optionally resolves a fresh key per request (handles short-lived
	// token expiry). Falls back to APIKey when nil or empty.
	GetAPIKey func(ctx context.Context, provider string) string
	// Provider is the provider name passed to GetAPIKey.
	Provider string

	// ContextWindow is the model's total context-token budget, used to decide
	// automatic compaction. When <= 0 the window is unknown and auto-compaction
	// is disabled (ShouldCompact returns false), so the loop behaves exactly as
	// before for callers that do not plumb it through.
	ContextWindow int
	// Compaction holds the thresholds/retention knobs for auto-compaction. Its
	// Enabled flag gates the feature independently of ContextWindow.
	Compaction compaction.CompactionSettings
	// SummaryStream produces the provider stream used to generate compaction
	// summaries. Defaults to Stream when nil.
	SummaryStream provider.StreamFn
	// SummaryModel is the model used for summarization. When zero, a model is
	// synthesized from Model/ContextWindow.
	SummaryModel provider.Model

	// Extra is forwarded to StreamConfig.Extra.
	Extra map[string]any
}

LoopConfig holds the pluggable behavior of the agent loop. Every hook is optional (nil = use the default). The pointer/func-field pattern mirrors pi's optional callbacks.

type LoopEventStream

LoopEventStream is the stream returned by the loop entry points: it carries AgentEvents and yields the messages newly produced during the run.

func StartRun

func StartRun(ctx context.Context, agentCtx *agentcore.AgentContext, cfg RunConfig) *LoopEventStream

StartRun is the exported entry point for a fresh run, used by out-of-package drivers (the interactive REPL, US-022). It is a thin wrapper over agentLoop so the loop internals stay unexported while callers outside the package can still launch a run and consume its event stream.

type MemoryReminderProvider

type MemoryReminderProvider struct {
	// Store is the persistent memory database. When nil the provider never
	// fires.
	Store *memory.Store

	// MaxChars caps the injected body length. <=0 uses
	// defaultMemoryReminderMaxChars.
	MaxChars int

	// Limit caps the number of search hits considered. <=0 uses
	// defaultMemoryReminderLimit.
	Limit int

	// Scope and ScopeID, when non-empty, focus the search on a single memory
	// scope (e.g. the current project id) via SearchOptions.
	Scope   string
	ScopeID string

	// Disabled turns the reminder off without unwiring it: the shipped default
	// (config.DefaultMemoryRecall is false), so the store and the memory_search
	// tool stay available while no turn injects anything.
	Disabled bool
	// MinUnits is the smallest query worth searching, in units. A unit is a
	// latin word or a CJK bigram — the granularity the store's unicode61
	// tokenizer cannot provide for Chinese, where it keeps a whole run as one
	// token. Default 2: "继续", "ok" and "好的" recall nothing.
	MinUnits int
	// MinOverlap is how many distinct query units a hit must contain before it
	// is injected. The store's score floor is relative and always keeps the top
	// hit, so this is the guard that answers "is that top hit actually about
	// the question", not merely "is there some match".
	MinOverlap int
	// ReconcileInterval throttles the index reconcile: the walk is linear in
	// the number of memory files (one checkpoint per compaction, so it grows),
	// and it used to run on every turn. 0 means every turn; negative means the
	// reminder never reconciles (the memory_search tool still does).
	ReconcileInterval time.Duration
	// contains filtered or unexported fields
}

MemoryReminderProvider injects relevant persistent memory as ephemeral background context on each turn (issue #478). It derives a query from the most recent user message, runs a BM25 search over the memory store, and surfaces the top-ranked snippets — budget-capped and deduped so identical context is never repeated turn after turn.

The returned body is RAW plain text; the reminder registry wraps it in <system-reminder> tags and injects it only into the per-turn LLM request, so it never enters persisted history.

func (*MemoryReminderProvider) Name

func (p *MemoryReminderProvider) Name() string

Name implements ReminderProvider.

func (*MemoryReminderProvider) Reminder

Reminder implements ReminderProvider. It fires when the latest user message yields a search query that matches stored memory, returning a concise, budget-capped body of ranked snippets. It stays silent when the store is nil, there is no user text to search on, the search errors or returns nothing, or the produced body is identical to the one injected on the previous firing turn (dedupe).

type OneShotReminderProvider

type OneShotReminderProvider struct {
	// contains filtered or unexported fields
}

OneShotReminderProvider injects a fixed body on the NEXT turn only, then stays silent forever. Unlike the always-on providers (todo/goal) it does not depend on live state — it carries a snapshot of text captured at registration time. It exists for events that produce a single ephemeral injection, such as a UserPromptSubmit hook's additionalContext (US-007, FR-9): the hook's context must reach the model on the turn the prompt is sent, but must not persist into history or re-fire on later turns. sync.Once makes the single-fire transition safe even if the loop consults providers concurrently.

func NewOneShotReminder

func NewOneShotReminder(name, body string) *OneShotReminderProvider

NewOneShotReminder builds a one-shot provider that will inject body exactly once. An empty body yields a provider that never fires.

func (*OneShotReminderProvider) Name

func (p *OneShotReminderProvider) Name() string

Name implements ReminderProvider.

func (*OneShotReminderProvider) Reminder

Reminder implements ReminderProvider. It returns its body and true on the very first consultation, then ("", false) on every subsequent turn.

type PromptConfig

type PromptConfig struct {
	// BaseInstruction is the leading text of the system prompt. When empty,
	// DefaultBaseInstruction is used.
	BaseInstruction string
	// WorkingDir is the directory the run operates in. When empty, the process
	// working directory (os.Getwd) is used. It anchors both the environment
	// block and the lower bound of the AGENTS.md walk.
	WorkingDir string
	// Root bounds the AGENTS.md walk at its top. AGENTS.md files are injected for
	// every directory from Root down to WorkingDir, inclusive. When empty, only
	// WorkingDir's own AGENTS.md (if any) is considered — no ancestor walk.
	Root string
	// AppendInstructions are appended verbatim to the end of the assembled
	// prompt, in order, each preceded by a blank line. This is the sink for
	// --append-system-prompt (mirrors pi): extra guidance layered after the base
	// instruction, environment block, and AGENTS.md. Empty entries are skipped.
	AppendInstructions []string
	// Now supplies the timestamp for the environment block. When nil, time.Now
	// is used. Injected for deterministic tests.
	Now func() time.Time
	// ReadFile reads a file's contents. When nil, os.ReadFile is used. Injected
	// for tests so AGENTS.md layout can be faked without touching disk.
	ReadFile func(path string) ([]byte, error)
	// GlobalInstructionsPath is the user-wide AGENTS.md injected before the
	// project chain. When empty, $GOLDER_HOME/AGENTS.md (typically
	// ~/.golder/AGENTS.md) is used. The read is best-effort: a missing or
	// unreadable file is skipped, so personal instructions can never block a run.
	GlobalInstructionsPath string
	// Skills are the model-invocable skills to advertise in an <available_skills>
	// block at the end of the prompt (mirrors pi's progressive disclosure). Only their
	// name/description/location are injected; the model loads a skill's body with
	// the read tool on demand. Skills flagged disable-model-invocation are
	// filtered out by FormatSkillsForPrompt. Empty means no skills block.
	Skills []*Skill
	// ReadToolAvailable signals whether the read tool is in the current tool set.
	// Skills are advertised only when it is true, since the model needs the read
	// tool to load a skill's body; otherwise the block is omitted entirely.
	ReadToolAvailable bool
	// LookPath resolves a program on PATH, for the environment block's note on
	// which search program a shell should use. When nil, exec.LookPath is used;
	// injected so the note can be asserted for both answers on any machine.
	LookPath func(string) (string, error)
}

PromptConfig configures system-prompt assembly. The zero value is usable: it produces the base instruction plus an environment block for the process working directory, with no AGENTS.md injection.

type PromptInputs added in v1.2.16

type PromptInputs struct {
	// Base replaces the default coding-assistant guide when non-empty.
	Base string
	// Appends are layered after the guide, environment block, AGENTS.md and
	// skills, in order.
	Appends []string
	// WorkingDir anchors both the environment block and the AGENTS.md walk.
	WorkingDir string
	// Skills are advertised in an <available_skills> block at the end.
	Skills []*Skill
	// Tools decides whether skills are advertised at all (see HasReadTool).
	Tools []agentcore.AgentTool
}

PromptInputs is the launch-side context a system prompt is built from, kept together so a fresh session and a RESUMED one assemble their prompt the same way. It carries the user-authored inputs (Base replaces the default guide, Appends layer after everything) plus the environment the run is in.

func (PromptInputs) Build added in v1.2.16

func (in PromptInputs) Build() (string, error)

Build assembles the system prompt for these inputs. It is the ONE assembly path: SetupEnv builds a fresh session's prompt through it, and a resumed session builds a fresh one with the session's own Base/Appends substituted (see cli.ResumeSystemPrompt), so the two can never drift apart.

type RecallStats added in v1.3.7

type RecallStats struct {
	Fires      int
	Skips      int
	LastQuery  string
	LastReason string
	LastPaths  []string
	LastFired  bool
	LastAt     time.Time
}

RecallStats is the last per-turn recall decision plus a running count, so the report can answer "why did that fire" and "has it fired at all" without the transcript carrying a line per turn.

func MemoryRecallStats added in v1.3.7

func MemoryRecallStats() RecallStats

MemoryRecallStats returns the process's recall counters and the last decision.

type ReminderFunc

type ReminderFunc struct {
	NameField string
	Fn        func(ctx context.Context, msgs agentcore.MessageList) (string, bool)
}

ReminderFunc adapts a plain function to a ReminderProvider.

func (ReminderFunc) Name

func (f ReminderFunc) Name() string

Name implements ReminderProvider.

func (ReminderFunc) Reminder

func (f ReminderFunc) Reminder(ctx context.Context, msgs agentcore.MessageList) (string, bool)

Reminder implements ReminderProvider.

type ReminderProvider

type ReminderProvider interface {
	// Name identifies the provider (for diagnostics/telemetry). It is not shown
	// to the model.
	Name() string
	// Reminder returns the reminder body and true when a reminder should be
	// injected this turn, or ("", false) to inject nothing.
	Reminder(ctx context.Context, msgs agentcore.MessageList) (body string, ok bool)
}

ReminderProvider produces an ephemeral system-reminder for the upcoming turn. Reminder is consulted every turn with the current (post-TransformContext) message list; returning ok == false means "no reminder this turn", so a provider injects only when its condition holds.

type ReminderRegistry

type ReminderRegistry struct {
	// contains filtered or unexported fields
}

ReminderRegistry holds the reminder providers consulted each turn. The zero value is usable (no providers → no injection); NewReminderRegistry is the convenience constructor.

func NewReminderRegistry

func NewReminderRegistry(providers ...ReminderProvider) *ReminderRegistry

NewReminderRegistry returns a registry pre-populated with providers.

func (*ReminderRegistry) Empty

func (r *ReminderRegistry) Empty() bool

Empty reports whether the registry has no providers (so callers can skip the injection wiring entirely).

func (*ReminderRegistry) Messages

Messages consults every provider in registration order and returns the ephemeral reminder messages to inject this turn (one UserMessage per provider that fires). Reminders are modeled as user-role messages carrying <system-reminder>-wrapped text — matching the pi / Claude Code convention where dynamic context enters through a user turn but is explicitly labeled as background context, not a user instruction.

func (*ReminderRegistry) Register

func (r *ReminderRegistry) Register(p ReminderProvider)

Register appends a provider. nil providers are ignored.

func (*ReminderRegistry) SetMemoryRecall added in v1.3.7

func (r *ReminderRegistry) SetMemoryRecall(on bool) bool

SetMemoryRecall turns the per-turn memory reminder on or off on every provider already registered, so `/memory recall on|off` takes effect in the running session instead of the next one. It reports whether a memory provider was found (a session with memory disabled has none).

type RunConfig

type RunConfig struct {
	LoopConfig
	// Batch holds the tool registry and the prepare/before/after hooks used to
	// execute each assistant message's tool calls.
	Batch agenttool.BatchConfig

	// GetFollowUpMessages is consulted after the inner loop settles (an assistant
	// message with no tool calls). Returning messages continues the outer loop
	// with them as the next input; returning none ends the run (FR-9).
	GetFollowUpMessages func(ctx context.Context, agentCtx *agentcore.AgentContext) []agentcore.AgentMessage
	// GetSteeringMessages is pulled after each turn's tool execution and injected
	// before the next turn (pi per-turn semantics, FR-8).
	GetSteeringMessages func(ctx context.Context) []agentcore.AgentMessage
	// PrepareNextTurn runs after each turn_end and may swap context / model /
	// thinkingLevel for the next turn (FR-6).
	PrepareNextTurn func(ctx context.Context, agentCtx *agentcore.AgentContext) *TurnUpdate
	// ShouldStopAfterTurn runs after each turn_end; true ends the run with an
	// agent_end event (FR-7).
	ShouldStopAfterTurn func(ctx context.Context, agentCtx *agentcore.AgentContext) bool

	// OnStop, when set, is consulted right before the run would end naturally (no
	// tool calls and no follow-up messages). Returning a decision with Block=true
	// keeps the loop running: any Guidance is appended as a user-role message to
	// steer the continued run (Stop / SubagentStop hooks, US-008/009, FR-10). The
	// seam carries no loop-protection itself — the caller's decorator owns the
	// consecutive-block counter and the FR-12 force-stop limit, so an ill-behaved
	// hook cannot loop forever. nil or a non-blocking decision lets the run end.
	OnStop func(ctx context.Context, agentCtx *agentcore.AgentContext) *StopDecision

	// Checkpoint, when set, is consulted at conversation-consistent points so a
	// driver can persist the conversation mid-run: a crash then loses at most the
	// round in flight instead of the whole session. It fires after each assistant
	// message is finalized (before any tool execution, which may run for
	// minutes), after tool results are appended, and after an in-place compaction
	// rewrote the context. compacted marks the last case: the persister must
	// re-save the rewritten context linearly instead of appending an incremental
	// tail. The hook runs on the loop goroutine, which exclusively owns
	// agentCtx.Messages, so it may read the slice directly; it sits on the turn
	// critical path, so implementations should keep it fast and never block on
	// user input. nil disables checkpointing.
	Checkpoint func(ctx context.Context, agentCtx *agentcore.AgentContext, compacted bool)

	// Reminders holds the per-turn system-reminder providers (US-002, FR-1/FR-2).
	// When non-empty, ephemeral <system-reminder> messages are injected into each
	// turn's LLM request through the existing TransformContext seam, so they never
	// enter the persisted history. nil / empty = no injection.
	Reminders *ReminderRegistry

	// Budget is the live context-window budget state shared by this run's tools
	// (get_context_remaining, new_context), its reminders, and the loop itself.
	// When nil the loop creates a run-local one, so tools and reminders work
	// without wiring; a driver that wants the low-budget reminder ladder to
	// survive across runs passes the session-scoped state it created once.
	Budget *contextbudget.State

	// EventBuffer is the buffer size of the emitted EventStream. 0 gives fully
	// synchronous back-pressure (matching pi's awaited emit).
	EventBuffer int

	// SessionID, when set, is carried in the run's agent_start event so a
	// stream-json consumer sees the backing session id in the first event and can
	// resume the run later (mirrors pi/Claude Code). It is also the session key
	// under which auto-compaction checkpoints are persisted (see MemoryRoot).
	SessionID string

	// MemoryRoot, when non-empty (together with SessionID), enables checkpoint
	// persistence for the "infinite context" feature (#480/#481): after a
	// successful auto-compaction the collapsed prefix's summary is written as a
	// checkpoint under <MemoryRoot>/sessions/<SessionID>/checkpoint.md so a later
	// run can reload it instead of replaying the whole transcript. It is left ""
	// when persistent memory is disabled (memory.enabled=false), which fully
	// disables checkpoint writing. A checkpoint write failure is non-fatal.
	MemoryRoot string
}

RunConfig is the full configuration for a loop run: the per-turn streaming config (embedded LoopConfig), the batch tool-execution config, and the four loop-level hooks. Every hook is optional (nil = default behavior).

type SearchRepeatReminderProvider

type SearchRepeatReminderProvider struct{}

TodoReminderProvider is the built-in reference reminder provider (US-002): it surfaces the current todo list as background context whenever there is incomplete work, so the model is reminded of outstanding tasks each turn without the list having to be re-sent as a durable message. It reads the same TodoStore the todo tool writes, so the reminder always reflects the latest plan. When the list is empty or every item is completed it stays silent. SearchRepeatReminderProvider is the loop guard for web research. Hosted web_search calls execute server-side inside the provider call, so there is no pre-execution hook to block a repeat; the lever left is a just-in-time reminder on the next turn's request (ephemeral: never persisted, never compacted). It covers three stop conditions in priority order:

  1. exact query repeat (hosted web_search search actions plus local websearch calls, normalized lower-case/whitespace-collapsed),
  2. exact page repeat (hosted web_search open_page URLs plus local webfetch calls, normalized), including the common misuse of passing an already-opened URL back into a search query — open it with webfetch or reuse the fetched content instead,
  3. search budget: 6+ searches without an exact repeat still get a synthesize-now nudge (stern at 10+), so open-ended "one more query" loops terminate.

Near-dupes still run; exact loops and runaway budgets do not.

func (*SearchRepeatReminderProvider) Name

Name implements ReminderProvider.

func (*SearchRepeatReminderProvider) Reminder

Reminder implements ReminderProvider.

type ShadowedEntry

type ShadowedEntry struct {
	Name   string
	Tier   Tier
	Source SlashCommandSource
}

ShadowedEntry records a command that lost a same-name conflict to a higher- tier command, for diagnostics. It carries the loser's name, tier, and source label so /help and the startup warning can say which source was shadowed.

func (ShadowedEntry) String

func (e ShadowedEntry) String() string

String renders a shadowed entry as "name (tier)" for log lines.

type Skill

type Skill struct {
	Frontmatter SkillFrontmatter
	// Body is the markdown after the frontmatter block — the skill's instructions,
	// used as the child agent's system prompt.
	Body string
	// Path is the source file, retained for diagnostics.
	Path string
}

Skill is a parsed skill file: its metadata plus the markdown body that serves as the sub-agent's system prompt.

func LoadSkillsDir

func LoadSkillsDir(dir string) ([]*Skill, error)

LoadSkillsDir loads every "*.md" skill file in dir (non-recursively) plus any "<name>/SKILL.md" nested layout (mirrors the SKILL.md convention). It returns the parsed skills sorted by name. A missing directory yields no skills and no error (skills are optional).

A malformed skill file does NOT abort the load: the file is skipped and its error accumulated, so one bad skill cannot hide every other skill in the directory (a real ~/.agents/skills holds 100+ skills authored to varying conventions). The successfully parsed skills are always returned; the error, when non-nil, joins every skip reason for the caller to surface as a non-fatal warning.

func ParseSkill

func ParseSkill(path string, content []byte) (*Skill, error)

ParseSkill parses a skill's raw file content into a Skill. The file must open with a YAML frontmatter block delimited by lines containing only "---"; the remainder is the markdown body. A missing or malformed frontmatter block is an error, since name/description drive discovery.

func (*Skill) SlashCommand

func (s *Skill) SlashCommand() SlashCommand

SlashCommand exposes the skill as a "/name" slash command (mirrors Claude Code's /skill-name invocation). Invoking it expands to the skill's instructions (its markdown body) as the prompt, with any arguments appended, so the skill runs in the current conversation. It is a prompt command (not an action): the expanded text is fed to the agent loop as the next user turn.

func (*Skill) SubAgentSpec

func (s *Skill) SubAgentSpec(tools []agentcore.AgentTool, newRunConfig func(tools []agentcore.AgentTool) RunConfig) SubAgentSpec

SubAgentSpec turns a skill into a sub-agent spec: the skill body becomes the child's system prompt, the description is surfaced to the model, and the tool set is the provided tools filtered by AllowedTools (when set). newRunConfig builds each child run's configuration; it receives the resolved tool set so the caller can wire a matching registry.

type SkillFrontmatter

type SkillFrontmatter struct {
	// Name is the skill identifier; it becomes the spawnable tool name. When
	// omitted it defaults to the file's base name (without extension).
	Name string `yaml:"name"`
	// Description tells the model what the skill does and when to use it. It is
	// injected into the capability list, so it should be action-oriented.
	Description string `yaml:"description"`
	// AllowedTools optionally restricts the tools the skill's sub-agent may use,
	// by tool name. Empty means "inherit the provided tool set as-is". Real
	// Claude Code skills write this either as a YAML list or as a single
	// scalar string (e.g. "Bash(foo:*), Read"), so it tolerates both forms.
	AllowedTools stringList `yaml:"allowed-tools"`
	// Model optionally pins the skill to a specific model; empty inherits.
	Model string `yaml:"model"`
	// DisableModelInvocation, when true, keeps the skill out of the system
	// prompt's <available_skills> list so the model cannot auto-invoke it; it
	// remains reachable only via its explicit "/name" slash command (mirrors pi's
	// disable-model-invocation frontmatter key). Defaults to false.
	DisableModelInvocation bool `yaml:"disable-model-invocation"`
}

SkillFrontmatter is the YAML metadata block at the head of a skill file.

type SlashCommand

type SlashCommand struct {
	Name        string
	Description string
	// Category groups the command in /help and the TUI menu. Empty means
	// CategoryGeneral for a built-in; non-builtin sources (skills, plugins,
	// prompt templates) are always grouped under CategoryExtensions.
	Category string
	// ArgumentHint is an optional frontmatter hint shown before the description
	// in autocomplete (e.g. "<PR-URL>"). Convention: <angle> for required args,
	// [square] for optional. Empty when not set; display-only, not enforced.
	ArgumentHint string
	Source       SlashCommandSource
	// Tier is the priority tier used to resolve same-name conflicts across
	// sources (built-in > project > global > package > settings > CLI). It is
	// set by the AddX method matching the command's source; callers should not
	// set it directly.
	Tier Tier
	// Expand maps the argument string (everything after "/name ") to the prompt
	// text the command produces. For a built-in it may be arbitrary Go; for a
	// user template it substitutes $ARGUMENTS into the markdown body. Nil for an
	// action command.
	Expand func(args string) string
	// Action performs a side effect for the invocation and returns a status
	// message to display (may be empty). Set instead of Expand for a control
	// command like "/model". Because it is an arbitrary Go closure it can capture
	// and mutate live runtime state, which Expand (a pure prompt producer)
	// cannot. Nil for a prompt command.
	Action func(args string) string
	// Run is the hybrid of Action and Expand: it performs a side effect AND may
	// produce prompt text to run as the next agent turn. It returns
	// (message, prompt): message is shown to the user immediately (like an
	// Action's status, e.g. plugin notifications), and prompt, when non-empty, is
	// run as a normal turn (like Expand's output). This is what a plugin command
	// needs — it RPCs its plugin (side effect), surfaces the returned
	// notifications (message), then injects the returned prompt (prompt). Set
	// instead of Expand/Action for such a command; nil otherwise. When Run is set
	// it takes precedence over Expand (but Action still wins over Run).
	Run func(args string) (message, prompt string)
}

SlashCommand is a resolved command: its name (without the leading "/"), a short description for the command palette, and its source. A command is one of three kinds, distinguished by which callback is set:

  • A prompt command sets Expand: it turns the invocation arguments into the prompt text fed to the agent (the original slash-command behavior).
  • An action command sets Action instead: it performs a side effect (e.g. switching the runtime model) and returns a status line to show the user, rather than producing a prompt. No agent run is started.
  • A hybrid command sets Run: it performs a side effect AND may return prompt text to run — used by plugin commands, which RPC their plugin, surface the returned notifications, then inject the returned prompt as the next turn.

Exactly one of Expand/Action/Run should be set. Precedence when more than one is set: Action wins over Run, which wins over Expand. This split is what lets a control command like "/model" change runtime state — the old design could only emit prompt text.

func LoadPromptFile

func LoadPromptFile(path string) (SlashCommand, error)

LoadPromptFile loads a single prompt-template file. The command name is the filename without its extension (e.g. /x/review.md -> "review"). It is the single-file counterpart of LoadUserCommandsDir, used for settings/CLI paths that point at one file rather than a directory.

func LoadUserCommandsDir

func LoadUserCommandsDir(dir string) ([]SlashCommand, error)

LoadUserCommandsDir loads declarative markdown command templates from dir (non-recursively). Each "*.md" file defines a command named after the file (without extension). The file may carry an optional YAML frontmatter block with a "description" (mirrors skills); the remaining body is the prompt template, expanded via ExpandTemplate at invoke time. A missing directory yields no commands and no error.

func ParseUserCommand

func ParseUserCommand(name string, content []byte) (SlashCommand, error)

ParseUserCommand parses a declarative command template. An optional YAML frontmatter block supplies a description; the body is the prompt template, expanded at invoke time via ExpandTemplate (positional $N, $@/$ARGUMENTS, ${1:-default}, ${@:N}). If arg tokenization fails (e.g. an unterminated quote) the raw arg string is used as $ARGUMENTS so the invocation still works.

type SlashCommandSource

type SlashCommandSource int

SlashCommandSource identifies where a command came from, used for the conflict/priority rule and for display.

const (
	// SourceBuiltin is a compile-time registered command (highest priority).
	SourceBuiltin SlashCommandSource = iota
	// SourceUser is a declarative markdown command template loaded from disk
	// (e.g. ~/.golder/commands/*.md).
	SourceUser
	// SourceSkill is a skill loaded from ~/.agents/skills and surfaced as a
	// /skill-name command. It behaves like SourceUser for the built-in-wins
	// conflict rule; the finer tag is for display only (e.g. /status).
	SourceSkill
	// SourcePlugin is a command declared by a loaded plugin. It behaves like
	// SourceUser for the built-in-wins conflict rule; the finer tag is for
	// display only.
	SourcePlugin
)

func (SlashCommandSource) String

func (s SlashCommandSource) String() string

type SlashKind

type SlashKind int

SlashKind classifies how a resolved invocation should be handled by the caller: run its prompt through the agent, or treat it as a completed action.

const (
	// SlashPrompt means the outcome carries prompt text to run (or, when not a
	// command at all, the verbatim input).
	SlashPrompt SlashKind = iota
	// SlashAction means an action command already ran; the outcome carries only
	// a status Message and no agent run should start.
	SlashAction
)

type SlashOutcome

type SlashOutcome struct {
	Handled bool
	Kind    SlashKind
	Prompt  string
	Message string
}

SlashOutcome is the structured result of resolving one input line. Handled is false when the input was not a slash command (Prompt holds the verbatim input to run). When Handled is true, Kind says whether Prompt should be run (SlashPrompt) or an action already ran and Message should be shown without starting a run (SlashAction).

A hybrid (Run) command resolves to Kind SlashPrompt with BOTH fields set: its side effect already ran, Message carries the text to show the user first (e.g. plugin notifications), and Prompt, when non-empty, is the turn to run after. The caller shows Message (if any) then runs Prompt (if non-empty).

type SlashRegistry

type SlashRegistry struct {
	// contains filtered or unexported fields
}

SlashRegistry resolves "/name" invocations against built-in and user commands, applying the built-in-wins priority rule.

func NewSlashRegistry

func NewSlashRegistry() *SlashRegistry

NewSlashRegistry builds a registry seeded with all registered built-ins.

func (*SlashRegistry) AddBuiltin

func (r *SlashRegistry) AddBuiltin(cmd SlashCommand)

AddBuiltin installs a built-in command directly on this registry instance, bypassing the compile-time global. It exists for action commands whose closure must capture live, per-run state (e.g. a model controller created in main) — such state cannot be reached from an init()-time RegisterBuiltin. The command is marked SourceBuiltin so it wins over a same-named user command, exactly like a globally registered built-in. A duplicate name panics, since two built-ins claiming one name is a programming error.

func (*SlashRegistry) AddCLI

func (r *SlashRegistry) AddCLI(cmd SlashCommand)

AddCLI installs a prompt template referenced by --prompt-template (TierCLI, the lowest priority).

func (*SlashRegistry) AddPlugin

func (r *SlashRegistry) AddPlugin(cmd SlashCommand)

AddPlugin installs a plugin-declared command at TierGlobal, mirroring AddUser with a SourcePlugin tag for display.

func (*SlashRegistry) AddProject

func (r *SlashRegistry) AddProject(cmd SlashCommand)

AddProject installs a project-local prompt template (TierProject), which overrides a same-named global/package/settings/CLI template but loses to a built-in.

func (*SlashRegistry) AddSettings

func (r *SlashRegistry) AddSettings(cmd SlashCommand)

AddSettings installs a prompt template referenced by config.toml (TierSettings).

func (*SlashRegistry) AddSkill

func (r *SlashRegistry) AddSkill(cmd SlashCommand)

AddSkill installs a skill command (loaded from ~/.agents/skills) at TierGlobal. It follows the same tier rule as AddUser - a built-in or project-tier command wins - only the source tag differs, so /status can report skills separately.

func (*SlashRegistry) AddUser

func (r *SlashRegistry) AddUser(cmd SlashCommand)

AddUser installs a user command (TierGlobal), e.g. a prompt template from ~/.golder/prompts or the legacy ~/.golder/commands. A same-named built-in or project-tier command wins; same-tier (global) adds override silently.

func (*SlashRegistry) List

func (r *SlashRegistry) List() []SlashCommand

List returns all commands sorted by name.

func (*SlashRegistry) Lookup

func (r *SlashRegistry) Lookup(name string) (SlashCommand, bool)

Lookup returns the command bound to name (without the leading "/").

func (*SlashRegistry) Resolve

func (r *SlashRegistry) Resolve(input string) (prompt string, handled bool, err error)

Resolve parses a raw input line and, if it is a slash-command invocation, expands it to the prompt text the agent should run. It returns (prompt, true) when input begins with "/" and names a known PROMPT command; (input, false) when the input is not a slash command (the caller runs it verbatim); and an error when input is a "/name" for an unknown command.

This is the legacy string API, kept for callers that only handle prompt commands. It reports an action command as handled with an empty prompt (the action does NOT run here) — callers that want action commands to execute must use ResolveOutcome instead.

func (*SlashRegistry) ResolveOutcome

func (r *SlashRegistry) ResolveOutcome(input string) (SlashOutcome, error)

ResolveOutcome parses a raw input line into a structured SlashOutcome. For a non-command it returns {Handled:false, Prompt:input}. For a known prompt command it returns {Handled:true, Kind:SlashPrompt, Prompt:<expanded>}. For a known action command it RUNS the action and returns {Handled:true, Kind:SlashAction, Message:<status>} — no prompt to run. For a known hybrid (Run) command it RUNS the side effect and returns {Handled:true, Kind:SlashPrompt, Message:<status>, Prompt:<text>} — the caller shows Message then runs Prompt when non-empty. An unknown "/name" yields an error.

func (*SlashRegistry) Shadowed

func (r *SlashRegistry) Shadowed() []ShadowedEntry

Shadowed returns the commands that lost a same-name conflict to a higher-tier command, with their tier and source for diagnostics. Same-tier overrides (last-write-wins) are not recorded here.

func (*SlashRegistry) UsageLine added in v1.2.20

func (r *SlashRegistry) UsageLine(name string) string

UsageLine renders the one-line usage for a command — "usage: /name <grammar>" — from the grammar the command declares in ArgumentHint. It is the single source for every surface that has to teach the syntax (an argument error, a refusal, a picker's hint): the hint is what the popup and /help advertise, so a usage line built from it cannot drift into a second spelling of the same grammar. A command that takes no arguments renders as "usage: /name".

The line is total on purpose — an unknown name (a front-end printing usage for something this registry does not carry) or a nil registry still renders "usage: /name", which is true and printable. Returning "" would make callers print empty notices, and a caller has no better fallback than the name.

type StopDecision

type StopDecision struct {
	Block    bool
	Guidance string
}

StopDecision is the result of the OnStop seam. Block=true prevents the run from ending; Guidance, when non-empty, is appended as a user-role message to steer the forced continuation (the Stop / SubagentStop hook's reason). The zero value (Block=false) lets the run end.

type StreamHandler

type StreamHandler struct {
	// OnText receives each new suffix of the streaming assistant text: the bytes
	// produced since the last OnText call for the current turn. The final suffix
	// is flushed at turn end before OnTurnEnd, so a consumer that only implements
	// OnText still sees the complete text.
	OnText func(delta string)
	// OnTurnEnd fires once per completed turn, after the turn's text is fully
	// flushed, carrying the final assistant message and the tool results produced
	// during the turn. Consumers render tool activity here, and use stall to say
	// what happened when the turn produced nothing to show (see TurnStall).
	OnTurnEnd func(msg agentcore.AssistantMessage, results []agentcore.ToolResultMessage, stall TurnStall)
	// OnEvent, when set, receives every raw event before the typed callbacks —
	// used by the stream-json protocol driver, which serialises the whole event.
	OnEvent func(ev agentcore.AgentEvent)
}

StreamHandler is the set of callbacks DrainStream invokes as it consumes a run's events. Every field is optional (nil = ignore that signal). Callbacks run on the draining goroutine, in event order.

type SubAgentIsolation

type SubAgentIsolation int

SubAgentIsolation selects how a sub-agent runs relative to its parent.

const (
	// SubAgentIsolationGoroutine runs the child agent loop in-process in a
	// goroutine. This is the default and the original behavior; it changes
	// nothing about how sub-agents previously ran.
	SubAgentIsolationGoroutine SubAgentIsolation = iota
	// SubAgentIsolationProcess runs the child in a fresh golder subprocess,
	// delegating the run over stdio JSON-RPC. A subprocess crash is surfaced to
	// the parent as a tool error and never affects the parent loop.
	SubAgentIsolationProcess
)

type SubAgentProcessConfig

type SubAgentProcessConfig struct {
	// Command is the executable to spawn. When empty, os.Executable() (the golder
	// binary itself) is used so a golder process spawns another golder.
	Command string
	// Args are appended to the command after the subagent-rpc flag. Rarely
	// needed; reserved for test doubles or non-standard layouts.
	Args []string
	// Model is the model id the subprocess runs against. Required. A
	// "provider/model" routed id (e.g. "openrouter/free") or an
	// ollama/nvidia-prefixed id resolves its own provider; a custom gateway
	// needs BaseURL/Protocol.
	Model string
	// BaseURL and Protocol override the provider endpoint and wire protocol for
	// custom gateways (Protocol "anthropic"/"openai" forces that wire format).
	// Empty falls back to the same resolution the CLI uses.
	BaseURL  string
	Protocol string
	// ToolNames restricts the subprocess's builtin tool set to the named tools
	// (e.g. a read-only researcher). Empty keeps all builtins. Non-builtin names
	// are ignored: custom/plugin tools cannot cross a process boundary, so a
	// process-isolated child runs with builtins only.
	ToolNames []string
	// Env is the child's environment (os/exec form). When nil the child inherits
	// the parent environment, which is how it picks up provider API keys.
	Env []string
	// Dir is the child's working directory; empty means the parent's.
	Dir string
	// Stderr optionally receives the child's stderr. When nil it is discarded.
	Stderr io.Writer
}

SubAgentProcessConfig configures process-isolated sub-agent execution. It carries the serializable provider config the subprocess needs to reconstruct the run: the in-process Stream/GetAPIKey functions a goroutine-mode NewRunConfig returns cannot cross a process boundary, so the parent forwards the model (and optional base URL/protocol) and the subprocess resolves the provider itself, inheriting the parent environment for API keys.

type SubAgentRunParams

type SubAgentRunParams struct {
	Prompt       string   `json:"prompt"`
	SystemPrompt string   `json:"systemPrompt,omitempty"`
	Model        string   `json:"model"`
	BaseURL      string   `json:"baseUrl,omitempty"`
	Protocol     string   `json:"protocol,omitempty"`
	Tools        []string `json:"tools,omitempty"`
	// Auth is the dispatching session's authorization snapshot (see
	// agentcore.ToolAuth): the trust decision for the working directory, the
	// session reads grant, and the read and write roots the user allowed this
	// session. A subprocess cannot share the parent's gates - it is a different
	// address space - so it is handed the decisions those gates would have
	// applied and rebuilds equivalent gates around them. Omitted when the parent
	// ran with no gate chain, in which case the child's own gates fail closed on
	// anything they cannot settle.
	Auth *agentcore.ToolAuth `json:"auth,omitempty"`
	// Origin is the label the child stamps onto the questions and notes its
	// gates produce, so a line this process prints is attributable to the agent
	// that asked. It is the parent's own origin plus this child's name, and it
	// is never empty for a dispatched run.
	Origin string `json:"origin,omitempty"`
}

SubAgentRunParams is the JSON-RPC request payload for a process-isolated sub-agent run (the "subagent/run" method). It is the wire contract between the parent (SubAgentTool in process mode) and the golder subprocess (cmd/golder --subagent-rpc).

type SubAgentRunResult

type SubAgentRunResult struct {
	Text string `json:"text"`
}

SubAgentRunResult is the JSON-RPC response payload carrying the child's final assistant text.

type SubAgentSpec

type SubAgentSpec struct {
	// Name is the tool name the parent invokes to spawn this sub-agent.
	Name string
	// Description is injected into the parent's tool list / capability list so
	// the model knows when to delegate.
	Description string
	// SystemPrompt seeds the child context's system prompt. When empty the child
	// runs with no system prompt.
	SystemPrompt string
	// Tools is the child's independent tool set. It may differ from the parent's
	// (e.g. a read-only researcher sub-agent) and may be empty. In goroutine
	// mode these exact tools run in-process; in process mode only the tools'
	// NAMES are forwarded (the subprocess rebuilds builtins by name).
	Tools []agentcore.AgentTool
	// NewRunConfig builds the loop configuration for one child run in goroutine
	// mode. It is called per spawn; the returned config's Batch registry should
	// contain Tools. Ignored in process mode (the subprocess resolves its own).
	NewRunConfig func() RunConfig
	// Isolation selects goroutine (default) vs process execution. Zero value is
	// goroutine, preserving the original behavior.
	Isolation SubAgentIsolation
	// Process configures process-isolated execution. Required when Isolation is
	// SubAgentIsolationProcess; ignored otherwise.
	Process SubAgentProcessConfig
	// Schema, when non-empty, overrides the default single-prompt argument schema
	// advertised to the model. The generic task tool uses this to also accept an
	// optional description; a nil/empty Schema keeps the original prompt-only
	// schema so existing specs are unaffected.
	Schema json.RawMessage
	// Sem, when non-nil, is a shared buffered channel used as a concurrency
	// semaphore for goroutine-mode runs: executeGoroutine acquires a slot before
	// spawning the child and releases it when the child settles. A full channel
	// blocks (queues) the acquire rather than erroring. nil disables limiting, so
	// existing sub-agent specs run unbounded exactly as before.
	Sem chan struct{}
}

SubAgentSpec declares a spawnable sub-agent: its identity (surfaced to the model as a tool), the system prompt and tools its child context runs with, and a factory for the child's run configuration (provider stream, batch registry, hooks). The factory is called once per spawn so each child gets an independent RunConfig; NewRunConfig must wire a ToolRegistry consistent with Tools. It is used by goroutine mode; process mode uses Process instead (the subprocess builds its own RunConfig from the serializable provider config).

type SubAgentTool

type SubAgentTool struct {
	// contains filtered or unexported fields
}

SubAgentTool adapts a SubAgentSpec into an AgentTool. Executing it spawns a child agent run (in a goroutine or a subprocess, per Isolation) and returns the child's final text.

func NewSubAgentTool

func NewSubAgentTool(spec SubAgentSpec) *SubAgentTool

NewSubAgentTool builds a sub-agent tool from a spec. In goroutine mode NewRunConfig is required (it supplies the provider stream that drives the child); in process mode Process.Model is required instead.

func NewTaskTool

func NewTaskTool(factory func() RunConfig, sem chan struct{}) *SubAgentTool

NewTaskTool builds the generic `task` sub-agent tool. factory produces a fresh child RunConfig per spawn (reusing the parent's provider stream/model and a child tool registry that must exclude `task` for the nesting guard); sem is a shared buffered channel bounding concurrent task runs (nil disables limiting). The child prompt comes from the call arguments at runtime, so a single generic spec serves every delegated task.

func (*SubAgentTool) Description

func (t *SubAgentTool) Description() string

func (*SubAgentTool) Execute

Execute spawns the child agent run and blocks until it settles, then returns the child's final assistant text as the tool result. The parent's ctx governs the child, so cancelling the parent run cancels in-flight sub-agents (in goroutine mode via ctx; in process mode via ctx cancelling the JSON-RPC call and Close killing the child).

func (*SubAgentTool) ExecutionMode

func (t *SubAgentTool) ExecutionMode() agentcore.ToolExecutionMode

ExecutionMode is parallel: independent sub-agents may run concurrently, since each spawns its own context and run (goroutine or process) with no shared mutable state.

func (*SubAgentTool) Name

func (t *SubAgentTool) Name() string

func (*SubAgentTool) Schema

func (t *SubAgentTool) Schema() json.RawMessage

type SummarizeFunc

type SummarizeFunc func(ctx context.Context, msgs []agentcore.Message) (string, error)

SummarizeFunc distills a slice of conversation messages into a single summary string. It is the seam that lets BuildCheckpoint reuse compaction.GenerateSummary without this package depending on the provider stack: the caller supplies a closure over GenerateSummary (binding ctx/stream/model/cfg), and BuildCheckpoint invokes it. A summarization error is propagated, never swallowed.

type TelemetrySummary

type TelemetrySummary struct {
	SchemaVersion      string                       `json:"schema_version"`
	Turns              int                          `json:"turns"`
	TruncationCount    int                          `json:"truncation_count"`
	CompactionCount    int                          `json:"compaction_count"`
	ContextTokens      int                          `json:"context_tokens"`
	ContextWindow      int                          `json:"context_window"`
	ContextUtilization float64                      `json:"context_utilization"`
	ToolDurations      map[string]ToolTimingSummary `json:"tool_durations_ms"`
}

TelemetrySummary is the stable, run-level telemetry export document.

func (TelemetrySummary) MarshalJSON

func (s TelemetrySummary) MarshalJSON() ([]byte, error)

MarshalJSON guarantees the document always carries the schema_version discriminator even when constructed directly.

type Tier

type Tier int

Tier is the priority tier of a command, used to resolve same-name conflicts across sources (mirrors pi prompt-templates discovery priority). Higher tiers win; the loser is recorded in Shadowed. Within the same tier the last-added command wins (a re-load overrides). Skills and plugins are treated as Global-tier for priority - their finer Source label is for display only.

const (
	// Tier values are ordered lowest-to-highest priority: in a same-name
	// conflict the higher Tier value wins, so TierBuiltin always wins and
	// TierCLI always loses. Declared ascending so the natural > comparison
	// matches "higher priority wins".
	TierCLI Tier = iota
	// TierSettings is a prompt template referenced by the config.toml prompts array.
	TierSettings
	// TierPackage is a prompt template discovered from an installed package
	// source (distinct from one copied into the global dir).
	TierPackage
	// TierGlobal is a global user prompt template (e.g. ~/.golder/prompts or the
	// legacy ~/.golder/commands); also the tier used for skills and plugins.
	TierGlobal
	// TierProject is a project-local prompt template (e.g. .golder/prompts).
	TierProject
	// TierBuiltin is a compile-time or instance built-in command (highest).
	TierBuiltin
)

func (Tier) String

func (t Tier) String() string

type TodoReminderProvider

type TodoReminderProvider struct {
	// Store is the session todo list. When nil the provider never fires.
	Store *agenttool.TodoStore
}

func (*TodoReminderProvider) Name

func (p *TodoReminderProvider) Name() string

Name implements ReminderProvider.

func (*TodoReminderProvider) Reminder

Reminder implements ReminderProvider. It fires only when the store holds at least one item that is not yet completed, keeping the condition deterministic and easy to test.

type ToolTimingSummary

type ToolTimingSummary struct {
	Count   int   `json:"count"`
	TotalMs int64 `json:"total_ms"`
}

ToolTimingSummary is one tool's aggregated timing in the export schema.

type TurnStall added in v1.3.8

type TurnStall struct {
	// Count is the number of such turns in a row ending with this one; 0 for an
	// ordinary turn.
	Count int
	// Limit is how many automatic continuations the loop makes. At or below it
	// the loop has asked the model to carry on; above it the loop has stopped.
	Limit int
}

TurnStall describes a turn that produced nothing the person can act on: the model reasoned and then ended the turn without an answer and without a tool call. It is not an error and not an interrupt — the run may be carrying on by itself — but it is also not an answer, and a consumer that says nothing leaves the person unable to tell "finished" from "stopped".

type TurnUpdate

type TurnUpdate struct {
	Messages      *agentcore.MessageList
	SystemPrompt  *string
	Tools         *[]agentcore.AgentTool
	Model         *string
	ThinkingLevel *agentcore.ThinkingLevel
}

TurnUpdate is the optional result of PrepareNextTurn: any non-nil field replaces the corresponding piece of loop state before the next turn. It lets a caller swap the trimmed context, system prompt, tool set, model, or thinking level between turns (FR-6).

Jump to

Keyboard shortcuts

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