Documentation
¶
Overview ¶
Package agent contains SelfTUI's bounded coding-agent loop and its jailed filesystem tools.
Index ¶
- Constants
- Variables
- func AgentTools() []ollama.ToolDefinition
- func ApproxTokens(messages []ollama.ChatMessage) int
- func BudgetMessages(messages []ollama.ChatMessage, numCtx int) []ollama.ChatMessage
- func EditFile(root, requested, old, new string) error
- func EscapeFileRef(path string) string
- func ExpandFileRefs(ctx context.Context, root, text string) string
- func FileRefTokens(text string) []string
- func Grep(ctx context.Context, root, pattern, path string, authorize func(string) error) (string, error)
- func ListDir(ctx context.Context, root, path string) (string, error)
- func ReadFile(ctx context.Context, root, path string) (string, error)
- func ReadOnlyTools() []ollama.ToolDefinition
- func RunCommand(ctx context.Context, root string, argv []string, timeoutSeconds int, ...) (string, error)
- func WorkspaceContext(ctx context.Context, root string) string
- func WorkspaceFiles(ctx context.Context, root string) []string
- func WriteFile(root, requested, content string, overwrite bool) error
- type AgentDoneMsg
- type BatchFileReview
- type BatchReviewMsg
- type FallbackMsg
- type FileRecord
- type Msg
- type Request
- type Runner
- type StaleEntry
- type ThinkingMsg
- type TokenMsg
- type ToolConfirmMsg
- type ToolOutputMsg
- type ToolPolicy
- type ToolResultMsg
- type ToolStartMsg
- type UndoJournal
- func (j *UndoJournal) CanRedo() bool
- func (j *UndoJournal) CanUndo() bool
- func (j *UndoJournal) Close() error
- func (j *UndoJournal) Commit(e *undoEntry)
- func (j *UndoJournal) Counts() (undo, redo int)
- func (j *UndoJournal) Dir() string
- func (j *UndoJournal) Discard(e *undoEntry)
- func (j *UndoJournal) KeepPartial(e *undoEntry)
- func (j *UndoJournal) Prepare(files []FileRecord) (*undoEntry, error)
- func (j *UndoJournal) Redo() (UndoResult, error)
- func (j *UndoJournal) Stale() []StaleEntry
- func (j *UndoJournal) Undo() (UndoResult, error)
- type UndoResult
Constants ¶
const DefaultMaxIterations = 12
const TruncationNotice = "Earlier conversation omitted to fit the context window."
TruncationNotice is the deterministic marker BudgetMessages inserts when it drops earlier conversation (PLAN.md §10 M7-C: the UI shows the same marker in the transcript once its context meter passes the budget, so a silent wire-only truncation becomes visible).
Variables ¶
var ( // ErrNothingToUndo / ErrNothingToRedo are the empty-stack results. /undo // and /redo surface them as notices ("nothing to undo"). ErrNothingToUndo = errors.New("nothing to undo") ErrNothingToRedo = errors.New("nothing to redo") )
Functions ¶
func AgentTools ¶
func AgentTools() []ollama.ToolDefinition
AgentTools is the explicit schema exposed to models. Keep this list closed: an unknown model-generated name can never become an execution primitive.
func ApproxTokens ¶
func ApproxTokens(messages []ollama.ChatMessage) int
ApproxTokens is the exported approximate-token estimator (4 chars per token, tool-call arguments counted) that drives both BudgetMessages and the UI context meter (M7-C). The meter reuses exactly this math so its percentage is the number the runner will actually budget against.
func BudgetMessages ¶
func BudgetMessages(messages []ollama.ChatMessage, numCtx int) []ollama.ChatMessage
BudgetMessages keeps the pinned system prompt and the newest atomic exchanges while dropping the oldest conversation when the approximate input budget is full. Three quarters of numCtx are reserved for input so the model has room to reply.
Eviction is atomic per user-led exchange (M-02): a tool turn is stored as an assistant tool_calls message plus all of its correlated role=tool results, and that group is never split — dropping a single message could otherwise send the model an orphan tool result, misassociate a result, or begin retained history with a role=tool message. The newest complete user-led exchange is always retained.
Two shapes cannot be shrunk by eviction or content truncation and are bounded deterministically instead of being sent raw past the budget: an oversized latest tool call (its arguments become the placeholder above) and an oversized pinned system prompt (its content is shortened with the same "[truncated] " convention as a last resort). ApproxTokens(out) <= 3/4 of numCtx whenever such a bounded representation is possible.
func EditFile ¶
EditFile replaces exactly one occurrence of old in an existing regular file under root. Requiring one match makes the model's mutation deterministic.
func EscapeFileRef ¶
EscapeFileRef makes one workspace path safe inside an @-reference: literal spaces become "\ " so the tokenizer keeps the whole path as one token. The picker inserts escaped paths; hand-typed drafts may use the same form.
func ExpandFileRefs ¶
ExpandFileRefs turns one draft into the wire content for an agent turn: every '@token' that resolves to a readable workspace file gets an inline `[file: token]` block appended (in first-mention order, deduplicated); references that name an existing but unreadable file (directory, over the size cap, a workspace escape attempt, or a path the workspace tool policy refuses — .env, credentials, .ssh/… trees) carry a visible "unavailable" note instead of content. Tokens that name no file at all are left as ordinary prose. The returned value is the full message content to send.
func FileRefTokens ¶
FileRefTokens extracts the workspace-file candidates from a draft: every '@' begins a token that runs to the next unescaped whitespace (or end of text), with trailing prose punctuation ("@README.md.", "@src/app.go,") stripped so a sentence-final reference still resolves. A whitespace character preceded by a backslash ("\ ") stays inside the token, so paths containing spaces — which the @-picker offers in the escaped form — survive tokenization. The tokens are candidates only — ExpandFileRefs decides which ones name real, readable workspace files; anything else stays ordinary prose.
func Grep ¶
func Grep(ctx context.Context, root, pattern, path string, authorize func(string) error) (string, error)
Grep searches files under root matching pattern, bounded to maxResultBytes and sorted deterministically. path is workspace-relative or absolute; a directory is searched recursively and a regular file directly.
authorize, when non-nil, is the sensitive-path policy applied to every canonical workspace-relative descendant (C-01): a denied directory is pruned before descent and a denied file is skipped before it is ever opened, so a denied path can neither leak content nor its own name. A nil authorize allows every descendant, preserving the pre-policy direct-call behavior for callers that intend no policy. Denials are skips, never whole-operation failures; real traversal/I/O errors still fail the grep.
ctx is checked before the walk and before each file is scanned so a canceled run returns promptly instead of grinding through the tree (Task 13/M-06 boundary).
func ReadFile ¶
ReadFile reads one workspace file, bounded to maxReadBytes. ctx is checked before and after the operation (M-06): a canceled run neither starts a doomed read nor reports a result that only finished after the context died — cancellation wins and the caller stops promptly.
func ReadOnlyTools ¶
func ReadOnlyTools() []ollama.ToolDefinition
ReadOnlyTools remains available for focused M3a compatibility tests and callers. It deliberately excludes every mutation primitive.
func RunCommand ¶
func RunCommand(ctx context.Context, root string, argv []string, timeoutSeconds int, emit func(stream, text string)) (string, error)
RunCommand executes the deliberately small argv allowlist inside the bubblewrap sandbox. It accepts argv, never a shell string. The sandbox is the primary V2c containment boundary; timeout, bounded output, process-group cancellation, and serialization remain enforced by this executor too.
func WorkspaceContext ¶
WorkspaceContext builds the bounded, deterministic context block injected into an armed agent turn: git branch/status/log when root is inside a git work tree (fixed read-only argv on the host process, never in the V2c sandbox — the sandbox is for model-requested commands) plus a bounded project tree. Sections that do not apply are omitted; a workspace that cannot be read at all yields "" so nothing is injected.
func WorkspaceFiles ¶
WorkspaceFiles lists the workspace's regular files as workspace-relative paths for the composer's @-file picker (PLAN.md §12 N6). It shares the workspaceTree walk discipline: symlinks are never followed (WalkDir), .git is pruned, depth is capped at maxTreeDepth, and entries are capped so a huge checkout degrades to a truncated list. The paths are exactly what securePath will re-verify when the reference is expanded, so nothing here is an authority — it is a convenience listing inside the same jail.
Types ¶
type AgentDoneMsg ¶
type AgentDoneMsg struct {
Err string
Reason string
Metrics ollama.ChatMetrics
}
AgentDoneMsg is emitted exactly once, after the loop or any error. Reason is the terminal Ollama done_reason of the final stream ("stop", "length", "tool_calls") so the UI can show why the turn ended (M7-B); it stays empty on errors where no terminal event arrived. Metrics carries the final chunk's generation stats of the turn's last stream (N3); it stays zero when no terminal event arrived (error/stop paths keep today's shape).
type BatchFileReview ¶ added in v0.4.0
type BatchFileReview struct {
Path string
Kind string // create | overwrite | edit (verb for the summary row)
Summary string // e.g. "M internal/agent/runner.go +18 −6"
Rows []string
}
BatchFileReview is the UI-facing summary of one file in a proposed batch: one summary row plus the rendered one-column diff rows (review overlay).
type BatchReviewMsg ¶ added in v0.4.0
type BatchReviewMsg struct {
Name string
Workspace string
Timeout time.Duration
Files []BatchFileReview
Note string
// contains filtered or unexported fields
}
BatchReviewMsg replaces the generic raw-args confirm for the write_files tool (design §4.2 step 1): the UI receives summary rows + rendered per-file unified diffs instead of a raw-args modal. Reply is one boolean for the whole batch — all-or-nothing; there is no per-file accept/reject in this cut. Decline or expiry apply nothing.
func (BatchReviewMsg) Respond ¶ added in v0.4.0
func (m BatchReviewMsg) Respond(approved bool)
Respond releases the batch review with one whole-batch decision.
type FallbackMsg ¶
type FallbackMsg struct{ Reason string }
type FileRecord ¶ added in v0.4.0
type FileRecord struct {
Requested string // workspace-relative path as the model wrote it
Path string // canonical absolute path the mutation will write
Mode os.FileMode // pre-existing mode (or 0600 for a new file)
Existed bool // the file existed before this mutation
Pre []byte // nil when !Existed
Post []byte // the content that will be written (never nil)
}
FileRecord is one file's mutation, handed to the journal by the apply engine with the pre-image already captured and the post (applied) content already computed but not yet written. The journal fsyncs the pre-image blob before the engine performs its first atomicWrite (capture-before- mutate ordering, design §4.2 step 5).
type Msg ¶
type Msg interface{}
Msg is an event consumed by the UI. Concrete messages intentionally contain presentation-neutral data so the agent loop can be tested without Bubble Tea.
type Request ¶
type Request struct {
Model string
Messages []ollama.ChatMessage
SystemPrompt string
Temperature float64
TopP float64
NumCtx int
}
Request is one agent turn. Messages should contain the current conversation but not the system prompt; Runner adds that exactly once.
type Runner ¶
type Runner struct {
// contains filtered or unexported fields
}
func NewRunner ¶
func NewRunner(client *ollama.Client, workspaceRoot, systemPrompt string, maxIterations int) *Runner
NewRunner builds a runner with workspace tools DISABLED. It remains the compatibility constructor for callers that predate the tool-trust policy; the disabled default is deliberate — tools only exist when the user explicitly enables them (config tools_enabled) and the code passes a real policy through NewRunnerWithPolicy.
func NewRunnerWithPolicy ¶
func NewRunnerWithPolicy(client *ollama.Client, workspaceRoot, systemPrompt string, maxIterations int, policy *ToolPolicy) *Runner
NewRunnerWithPolicy builds the runner used when workspace tools are enabled. policy must be non-nil: it decides which tools the model may request (Tools) and which paths those tools may touch (AuthorizePath). A nil policy here is equivalent to NewRunner (plain chat).
func (*Runner) Root ¶
Root returns the canonical workspace root the runner was built with (the same root its jailed tools resolve against). The composer's @-file picker and attachment expansion use it so user-initiated references land inside exactly the jail the tools use (PLAN.md §12 N6).
func (*Runner) Run ¶
Run executes one agent turn. With tools disabled (NewRunner, no policy) it streams plain chat — no tools field reaches the wire. With tools armed (NewRunnerWithPolicy) it runs the tool loop (read-only first, then the confirmed mutation set) with the plain-chat fallback. The first tools request doubles as a capability probe: models that reject tools with HTTP 400 are explicitly downgraded to plain chat instead of silently pretending to be an agent. AgentDoneMsg is emitted exactly once, after the loop or any error, carrying the terminal done_reason of the final stream when one arrived (M7-B).
func (*Runner) WithJournal ¶ added in v0.4.0
func (r *Runner) WithJournal(j *UndoJournal) *Runner
WithJournal attaches the session undo journal (V2e). Mutations that are confirmed and applied then record a change-set entry for /undo; write_files batches record as one entry. The UI re-attaches the same journal after every runner rebuild (ApplyConfig), so undo survives settings changes.
func (*Runner) WithLogger ¶
WithLogger attaches the shared debug logger (PLAN.md §12 N5). The Agent view re-attaches it after every ApplyConfig runner rebuild, so the drawer keeps following the loop across settings saves. Nil (the default) logs nothing.
type StaleEntry ¶ added in v0.4.0
type StaleEntry struct {
Dir string // artifact directory under the journal root
Files []string // requested paths the interrupted entry touched (meta read)
}
StaleEntry is one crash-left journal artifact found at open: a previous process died mid-apply, leaving fsynced pre-images. It is reported, never auto-reverted (design §4.3).
type ThinkingMsg ¶
type ThinkingMsg struct{ Text string }
ThinkingMsg relays one reasoning delta from a thinking model (qwen3). The runner never interprets it and never feeds it to a tool parser or the model context; it exists so the UI can store reasoning per turn and render it behind the /thinking toggle (PLAN.md §12 N6). Delivery is unconditional: the gating is display-only in the AgentView, so toggling reveals past turns' reasoning without a replay.
type ToolConfirmMsg ¶
type ToolConfirmMsg struct {
Name string
Input string
Workspace string
Timeout time.Duration
// contains filtered or unexported fields
}
ToolConfirmMsg pauses a gated tool operation until the user explicitly responds. The reply channel is deliberately private so only Respond can release it.
func (ToolConfirmMsg) Respond ¶
func (m ToolConfirmMsg) Respond(approved bool)
type ToolOutputMsg ¶
ToolOutputMsg streams bounded command output while the sandboxed command is running. The final ToolResultMsg carries the complete bounded result.
type ToolPolicy ¶
type ToolPolicy struct{}
ToolPolicy is the opt-in workspace tool trust policy (v0.1 hardening).
A Runner built through NewRunnerWithPolicy carries a policy: it advertises the seven jailed V2e tools (Tools) and refuses to execute any path-based tool on a path AuthorizePath rejects. A Runner built through the compatibility constructor NewRunner carries no policy and is plain chat — no tool definition ever reaches the model, so nothing the model says can turn into a filesystem operation. The zero value is a fully armed policy; arming is expressed by which constructor the caller uses.
func (ToolPolicy) AuthorizePath ¶
func (ToolPolicy) AuthorizePath(requested string) error
AuthorizePath applies the sensitive-path policy to a requested path (relative to the workspace or absolute) before any tool touches it. It is lexical and independent of the canonical workspace containment in securePath/canonicalRoot — containment answers "can this path resolve inside the workspace?", this answers "is this path ever worth touching?". A path containing a sensitive component (.ssh, .gnupg, .aws, .azure, .kube, .git or the .config/gcloud composite), or whose basename is a credential file (.env*, credentials, credentials.json), is refused; .env.example is the one dotenv file that stays allowed.
func (ToolPolicy) Tools ¶
func (ToolPolicy) Tools() []ollama.ToolDefinition
Tools returns the seven V2e tools: read-only read_file/list_dir/grep, the confirmed write_file/edit_file, the write_files batch tool, and the confirmed sandboxed run_command. The set is closed — no shell or interpreter is directly exposed.
type ToolResultMsg ¶
type ToolStartMsg ¶
type UndoJournal ¶ added in v0.4.0
type UndoJournal struct {
// contains filtered or unexported fields
}
UndoJournal is the session-scoped undo/redo store for confirmed agent mutations (V2e, docs/v2e-multifile-undo-design.md §4.3). Every confirmed single-file mutation and every applied batch is recorded here as one change-set entry (single-file calls are 1-op change-sets), so /undo pops the newest entry and /redo restores it.
The journal is deliberately "in-process, never sandboxed": undo/redo shell nothing out; they are plain Go over the journal, host-side, because the sandboxed git is read-only by design. Entry stacks are session-scoped (they die with the process); the optional disk dir holds fsynced pre-image blobs as crash-recovery artifacts that are GC'd at clean exit (Close). A process crash mid-apply therefore leaves a detectable stale entry (Stale) that the next start reports without auto-reverting.
Concurrency: the runner goroutine records entries while the UI goroutine runs /undo and /redo; every method takes the internal mutex, and the UI additionally refuses undo while a turn is streaming so a mutation can never race an undo of the same entry.
func NewUndoJournal ¶ added in v0.4.0
func NewUndoJournal(dir string) (*UndoJournal, error)
NewUndoJournal opens the journal. dir is the crash-artifact root ($XDG_STATE_HOME/selftui/undo in production; empty keeps the journal memory-only). Any leftover entry directories are reported as Stale — a clean exit removes them all (Close), so anything found at open is a crash artifact and is never auto-reverted.
func (*UndoJournal) CanRedo ¶ added in v0.4.0
func (j *UndoJournal) CanRedo() bool
CanRedo reports whether /redo has an entry.
func (*UndoJournal) CanUndo ¶ added in v0.4.0
func (j *UndoJournal) CanUndo() bool
CanUndo reports whether /undo has an entry.
func (*UndoJournal) Close ¶ added in v0.4.0
func (j *UndoJournal) Close() error
Close is the clean-exit lifecycle boundary: it GCs every crash artifact under dir (entries die with the process; the disk blobs were only for crash recovery). Idempotent and nil-safe.
func (*UndoJournal) Commit ¶ added in v0.4.0
func (j *UndoJournal) Commit(e *undoEntry)
Commit pushes a prepared entry onto the undo stack once the engine applied every op successfully. It clears the redo stack (a new mutation makes earlier redos non-sequential) and enforces the bounds with LRU eviction of the oldest entries.
func (*UndoJournal) Counts ¶ added in v0.4.0
func (j *UndoJournal) Counts() (undo, redo int)
Counts exposes the live stack sizes for the UI ("2 changes").
func (*UndoJournal) Dir ¶ added in v0.4.0
func (j *UndoJournal) Dir() string
Dir is the artifact root ("" for a memory-only journal); used by tests.
func (*UndoJournal) Discard ¶ added in v0.4.0
func (j *UndoJournal) Discard(e *undoEntry)
Discard drops a prepared entry whose apply failed and rolled back cleanly (nothing half-applied; no entry survives). Disk artifacts are removed.
func (*UndoJournal) KeepPartial ¶ added in v0.4.0
func (j *UndoJournal) KeepPartial(e *undoEntry)
KeepPartial retains a prepared entry whose apply failed AND whose compensating rollback failed (owner decision #8): the tree is partially applied and the journal entry stays so a later /undo can retry the restore.
func (*UndoJournal) Prepare ¶ added in v0.4.0
func (j *UndoJournal) Prepare(files []FileRecord) (*undoEntry, error)
Prepare writes one entry's pre-image blobs and meta to disk and fsyncs them, BEFORE the engine performs its first atomicWrite (design §4.2 step 5). It returns the entry handle. Memory-only journals skip the disk work.
func (*UndoJournal) Redo ¶ added in v0.4.0
func (j *UndoJournal) Redo() (UndoResult, error)
Redo is the symmetric operation: the newest undone entry's current state must equal the state undo left (the pre-images); then the post-images are restored and the entry moves back onto the undo stack.
func (*UndoJournal) Stale ¶ added in v0.4.0
func (j *UndoJournal) Stale() []StaleEntry
Stale returns the crash-left entries found at open (nil when clean).
func (*UndoJournal) Undo ¶ added in v0.4.0
func (j *UndoJournal) Undo() (UndoResult, error)
Undo pops the newest entry and reverts it: each file's current content must hash-equal the entry's post content (refuse-guard); any mismatch refuses the whole undo naming the file (an external edit since the mutation is a visible refusal, never a silent clobber). Revert restores the pre-image via atomicWrite (or deletes a created file). The entry moves to the redo stack with its post-images captured (the symmetric operation).
type UndoResult ¶ added in v0.4.0
type UndoResult struct {
Action string // "undo" | "redo" | "undo retry"
Files []string // requested paths restored (sorted)
}
UndoResult describes one completed undo/redo: the notice line for the status bar plus the per-file restore summary.