Agent Spec: A Claude Code–Equivalent on My LLM Interpreter
Status: specification; implementation to do (roadmap M10).
Instructions for Claude Code: This file is the full specification. Read all of it before starting.
Rule #1: audit before you build. This program already contains functionality. For every section of this spec, you must first search the existing code for what's already implemented. Then build only what's missing, and extend what's partial. Never rewrite or duplicate a working feature. Reuse existing modules, naming and conventions.
- Phase 0 — Audit (§0A). Search the whole repo and produce
docs/gap-analysis.md. It classifies every feature in this spec as ✅ Present / 🟡 Partial / ❌ Missing / ⚠️ Conflicting, with file:line evidence.- Write
docs/agent-design.md. It should cover:
- how the interpreter is invoked, streaming, chat templates, the tokenizer, context length, and native tool calling
- for each section below, which existing module it maps to, or where new code will go
- Stop and show me both docs. Ask only questions you can't answer from the code.
- Implement milestone by milestone (§26), only the ❌ and 🟡 items. Start each milestone with a fresh targeted search, since earlier work may have changed things. Keep a todo list. At the end of each milestone, run the acceptance checks, show me the evidence, and wait for my go-ahead.
- Never skip tests. Never mark a milestone done while checks fail. If an existing feature already satisfies an acceptance check, add a test that proves it and move on.
Fill in before starting:
- Interpreter / runtime:
[...] - Model(s) + context window:
[...] - Native tool calling:
[yes/no/partial] - Vision (image input):
[yes/no] - Implementation language:
[...] - Platforms:
[Linux / macOS / Windows] - Binary name:
[agent]; config dir:[.agent]; memory file:[AGENT.md]
0. Guiding principles
- The model backend is swappable. Everything above the adapter is model-agnostic.
- Tools never crash the loop. Every failure becomes a tool result the model can read and recover from.
- The user stays in control. Permissions, interrupts, rewind, and visible diffs are all required.
- Context is a scarce resource. Every component has to answer: how many tokens does this cost?
- Everything is testable without a real model. A scripted mock model is a first-class backend.
- Prefer few dependencies and readable code over clever abstractions.
0A. Phase 0: Audit of the existing program (mandatory, applies to every section)
How to search
- Map the repo first:
- entrypoints, CLI parsing, the main loop, model calls
- anything named
tool*,agent*,skill*,mcp*,memory*,prompt*,session*,hook*,command*,permission*,config*/settings* - config/dot-directories,
*.mdfiles read at runtime - JSON-RPC or stdio subprocess code (which may be MCP)
- frontmatter/YAML parsing (which may be skills, agents or commands)
- Search by behavior, not just name. For example: "where does the program read a markdown file into the prompt?" (memory), "where are subprocesses spawned with stdin/stdout pipes?" (MCP stdio), "where is a JSON schema attached to a function?" (tools).
- Read tests, docs, README and changelogs for features that exist but are hard to spot in the code.
- Use parallel read-only search subagents (Explore) for broad sweeps, one per spec area.
Output:
docs/gap-analysis.md
One table per spec section:
| Spec item | Status | Evidence (file:line) | What's missing / differs | Plan (reuse / extend / new) |
|---|
Status values:
- ✅ Present: matches the spec. Leave it alone, apart from adding a test if none exists.
- 🟡 Partial: extend it in place.
- ❌ Missing: implement it, inside the existing architecture.
- ⚠️ Conflicting: the existing behavior differs from the spec in a way that matters, e.g. a different memory file name or config format. Ask me before changing it, and propose a backward-compatible path such as aliases or a migration.
Rules during implementation
- Existing names, file formats and directories win over this spec's suggested names, unless I say otherwise. Add compatibility aliases where useful.
- Don't introduce a second implementation of anything, e.g. two tool registries or two config loaders.
- Every 🟡/❌ item closed gets a test. Every ✅ item with no test gets one.
- Update the gap-analysis table as items are closed. It doubles as the progress tracker.
1. Proposed directory layout (adjust to the language; prefer the existing layout if one exists)
src/
cli/ # arg parsing, entrypoints (interactive, -p headless)
tui/ # rendering, input editor, keybindings, status line
core/
loop.* # agent loop
messages.* # message/content-block types
session.* # transcript persistence, resume, fork
context.* # token accounting, compaction
prompt.* # system prompt assembly
checkpoints.* # file snapshots + rewind
model/
adapter.* # interface
local.* # my interpreter
toolproto.* # text tool-call protocol + parser (if no native)
mock.* # scripted model for tests
tools/ # one file per tool + registry
permissions/ # modes, rules, matcher, prompts, sandbox
config/ # settings hierarchy, env vars
memory/ # AGENT.md discovery, imports
extensions/
commands/ # slash commands (builtin + custom)
agents/ # subagent definitions
skills/
hooks/
mcp/
plugins/
sdk/ # programmatic API + stream-json I/O
tests/
unit/ integration/ e2e/ evals/
docs/
2. Model adapter layer
2.1 Interface
interface ModelAdapter {
name: string
contextWindow: int
maxOutputTokens: int
supportsNativeTools: bool
supportsVision: bool
supportsThinking: bool
countTokens(messages, tools, system) -> int
stream(request) -> async iterator of StreamEvent
}
request = { system, messages, tools, maxTokens, temperature, stop, thinkingBudget?, cacheHints? }
StreamEvent = TextDelta | ThinkingDelta | ToolCallStart | ToolCallArgsDelta | ToolCallEnd
| Usage{input, output, cachedInput} | Stop{reason: end_turn|tool_use|max_tokens|stop_seq|error}
2.2 Local interpreter adapter
- Build the chat template correctly for the model, including role tokens, tool definitions, and tool results.
- Stream tokens and turn them into
StreamEvents. - KV/prefix cache reuse: keep the system prompt and tool definitions byte-stable, and only append to the conversation. Mark cache breakpoints after the system prompt, after tools, and after the last turn. Report cached-token counts.
- Support cancellation mid-generation, and free resources when that happens.
- Retry with backoff on transient errors. Fail cleanly on fatal ones.
2.3 Text tool-call protocol (used when native tool calling isn't available)
- Format:
<tool_call>{"name": "...", "input": {...}}</tool_call>, with several calls allowed per message. - The protocol and examples go in the system prompt.
- Use the closing tag as a stop sequence, or parse while streaming.
- Robust parser: tolerate code fences, trailing commas, single quotes, unescaped newlines in strings, and missing closing tags at EOS.
- Validate the input against the tool's JSON schema. On failure, send a tool_result error that includes the schema and an example. Retry at most N times, then surface the failure to the user.
- Detect a model that "pretends" to have run a tool, i.e. writes fake results itself, and strip it.
2.4 Thinking / reasoning
- If the model emits reasoning blocks (e.g.
<think>), parse them intoThinkingDelta. - Show them dimmed or collapsed, and keep them out of later context unless the model requires them.
think/think hardkeywords in the user prompt, or a setting, raise the reasoning budget.
2.5 Multiple models
- The main model handles the loop.
- An optional "small/fast" model handles cheap tasks: titles, compaction summaries, bash-command safety classification, web page summarization.
/modelswitches models at runtime. Subagents can choose their model.
2.6 Mock adapter
- Replays scripted responses (text and tool calls) from a fixture file.
- Records the requests it received, so tests can assert on them.
3. Messages and content blocks
- Roles:
system,user,assistant. - Content blocks:
text,image,thinking,tool_use{id, name, input},tool_result{tool_use_id, content, is_error}. - Every
tool_usemust get exactly onetool_resultbefore the next model call. That includes interrupted calls, which get the result "Interrupted by user". - Messages carry metadata: uuid, parentUuid (for forks and rewind),
timestamp, token usage, model, and an
isMetaflag for injected reminders.
4. Agent loop
loop:
run UserPromptSubmit hooks (may block or add context)
inject system reminders (todo state, changed files, mode notices)
if context > threshold: auto-compact
stream model response; render text/thinking live
if no tool calls: run Stop hook (may force continuation); end turn
for each tool call (read-only ones in parallel, others sequential, in order):
validate input → PreToolUse hooks → permission check → execute → PostToolUse hooks
append tool_result (truncated if large)
if maxTurns reached: stop with notice
Requirements:
- Interrupts: Esc or Ctrl+C cancels generation or the running tool. Partial assistant text is kept, and pending tool calls get "Interrupted" results. A second Ctrl+C on an empty prompt exits.
- Steering: the user can type while the agent works. Queued messages are injected at the next safe point, between tool calls.
- Loop detection: if the same failing tool call repeats 3 or more times, inject a reminder to change approach.
- System reminders: short
isMetamessages, e.g. "The todo list is now: …", "file X was modified externally since you read it", "You are in plan mode". - Token budget per turn, plus a hard ceiling on total turns in headless mode.
5. Tools
Common contract: name, description (written
for the model, with usage guidance), inputSchema,
isReadOnly, isConcurrencySafe,
needsPermission(input),
execute(input, ctx) -> result, renderCall,
renderResult.
ctxholds cwd, the abort signal, a session file-read registry, the permission engine, and settings.- Results over the size limit (configurable, e.g. 30k chars) are truncated with an explicit marker. The full output is saved to a temp file whose path is given to the model.
5.1 Read
- Inputs:
file_path(absolute),offset?,limit?(default 2000 lines). - Output is
cat -nstyle with line numbers. Lines over 2000 chars are truncated. - Images are returned as image blocks if the model has vision, otherwise as a description or an error.
- PDFs are read by page range, with text extracted. Jupyter notebooks return cells with their outputs.
- Detect binaries and refuse with a useful message. Empty files return an explicit notice.
- Record
(path, mtime, hash)in the session read registry.
5.2 Write
- Creates or overwrites a file and creates parent directories.
- Overwriting requires that the file was Read in this session and hasn't changed since. Otherwise, return an error.
- Preserve the original line endings and encoding.
5.3 Edit
- Inputs:
file_path,old_string,new_string,replace_all?. - Exact match is required. Errors are distinct and descriptive: not found, multiple matches (with a count and a suggestion to add context), identical strings, file not read, file changed since read.
- Tolerate the model pasting line-number prefixes from Read output: strip them and retry.
- Return a short snippet of the edited region. The UI shows a colored diff.
5.4 MultiEdit
- Applies several edits to one file atomically: either all succeed or none are applied.
5.5 Glob
- Fast pattern matching that respects
.gitignore. Results are sorted by mtime, newest first, with a cap.
5.6 Grep
- Wraps ripgrep, with a fallback when it isn't installed.
- Options:
pattern,path,glob,type,-i,-n,-A/-B/-C,multiline,output_mode(content | files_with_matches | count),head_limit,offset.
5.7 LS (optional)
- Lists a directory, with ignore patterns.
5.8 Bash
- A persistent shell session: cwd and env survive between calls. Optionally reset cwd to the project root when a command leaves allowed directories.
timeoutdefaults to 2 minutes, with a maximum of 10. Captures stdout and stderr and reports the exit code.run_in_background: true: background processes (ids, logs, reading new output, backgrounding on timeout, Ctrl+B) are process_spec.md §2–§3. The persistent shell itself is spawned through the same job manager.- Output is truncated (keep head and tail). ANSI codes are stripped for the model and kept for display.
- Interactive commands are refused or neutralized: the environment every command gets (editor, pager and prompt variables) is defined once in process_spec.md §2.2; git's interactive commands are refused per git_spec.md §2.4.
- The description tells the model to prefer the dedicated tools over
cat,grep,findandsed.
5.9 BashOutput / KillShell
Owned by process_spec.md: its §3
tools (ProcessOutput, ProcessStop,
ProcessList, with BashOutput /
KillShell and OKLM's JobOutput /
JobKill as aliases) and its §13 /tasks panel
(alias /bashes).
5.10 WebFetch
- Fetches a URL and converts HTML to markdown. A small model answers a
promptagainst the page. - Has a 15-minute cache. Redirects are reported rather than followed across hosts.
5.11 WebSearch (optional)
- Uses a pluggable search provider and returns titles and URLs, with allowed and blocked domain lists.
5.12 TodoWrite
- Replaces the whole list. Items have
{content, activeForm, status: pending|in_progress|completed}. - Only one item can be
in_progressat a time. The list is rendered live in the UI and in system reminders.
5.13 Task (subagents) — see §12.
5.14 NotebookEdit
- Replace, insert, or delete a cell by id.
5.15 AskUserQuestion
- Up to 4 multiple-choice questions, with "Other" always available. Unavailable in headless mode, where the model must decide on its own.
5.16 ExitPlanMode / EnterPlanMode — see §7.4.
5.17 Skill — see §13.
5.18 ToolSearch (deferred tools)
- When there are many tools (e.g. from MCP), only their names go in
the prompt.
ToolSearchloads full schemas on demand. This saves context.
5.19 Tool registry
- Each tool can be enabled or disabled through settings, the
--allowedToolsand--disallowedToolsflags, and per-agent tool lists.
6. Permissions and sandboxing
6.1 Modes (cycled with Shift+Tab)
default: prompt for writes, bash and network.acceptEdits: file edits are auto-approved, bash still prompts.plan: only read-only tools are allowed, and the model must call ExitPlanMode with a plan before doing anything else.bypassPermissions(--dangerously-skip-permissions): no prompts. Show a warning banner. It can be disabled by managed policy.
6.2 Rules
- Syntax:
ToolorTool(specifier). Examples:Bash(npm run test:*),Bash(git status),Edit(src/**),Read(~/.ssh/**),WebFetch(domain:github.com),mcp__server__tool. - Three lists:
allow,ask,deny. Precedence: deny > ask > allow > mode default. - Bash matching parses compound commands
(
&&,||,;,|, subshells). Every sub-command must be allowed. Prefix rules must not matchcmd; rm -rf ~. - Path rules are resolved against the project root. Symlinks are followed, and escaping the allowed directories is blocked.
additionalDirectoriesand/add-dirextend the working set.
6.3 Prompt UX
- Shows the tool, its input, and a diff preview for edits.
- Choices: Yes, Yes, and don't ask again for
<generated rule>(saved to local settings), No, and tell the model what to do instead (feedback becomes the tool result).
6.4 Safety checks
- A built-in dangerous-pattern list (
rm -rf /,mkfs, fork bombs,curl … | sh, writes to/etcor~/.ssh) always prompts, even when allowed. This section owns the mechanism (a pass after the rules turns allow back into ask); git's patterns are git_spec.md §2.3 and the integrations' process_spec.md §11, both entries of this one list. - Optionally, the small model classifies bash commands for injection risk.
- Detect and flag secrets (keys, tokens) in tool output. Redact them in logs.
- Treat tool results, web pages and file contents as untrusted data, not instructions. The system prompt says so explicitly.
6.5 OS sandbox (later milestone)
- Linux uses bubblewrap. macOS uses
sandbox-exec. - Bash runs with filesystem write access only to the project and tmp, and network only through an allowlisted proxy.
- With the sandbox on, auto-allowing bash is acceptable.
7. Configuration and settings
7.1 Hierarchy (highest priority first)
- Managed/enterprise policy file (e.g.
/etc/agent/managed-settings.json), which can't be overridden - CLI flags
.agent/settings.local.json(git-ignored, personal).agent/settings.json(committed, shared with the team)~/.agent/settings.json(user)
Arrays (such as permission rules) are merged. Scalars take the highest-priority value.
7.2 Keys (non-exhaustive)
model, smallModel,
permissions{allow,ask,deny,defaultMode,additionalDirectories},
hooks, env, mcpServers (or
.mcp.json), statusLine,
outputStyle, theme, autoCompact,
compactThreshold, maxToolOutputChars,
bashTimeout, includeCoAuthoredBy,
cleanupPeriodDays, enabledPlugins,
sandbox.
7.3 Environment variables
Model endpoint, API keys if relevant, debug flags,
MAX_THINKING_TOKENS, disabling telemetry, and timeouts.
7.4 /config and
/permissions
Interactive editors for these settings.
8. AGENT.md (project memory) — full support plan
8.1 Audit first
Search for:
- any existing "project instructions" or "context file" loading: reads
of
*.mdat startup,README-into-prompt,.cursorrules/CLAUDE.md/AGENTS.md-style files, custom prompt-file flags - the code that assembles the system prompt
- any
#-prefix or "remember this" feature
Record what exists in the gap analysis.
8.2 File locations and load order
Earlier entries are lower priority. Later, more specific files take precedence when instructions conflict.
| Scope | Path | Shared? |
|---|---|---|
| Managed policy | /etc/agent/AGENT.md (macOS:
/Library/Application Support/Agent/AGENT.md; Windows:
C:\ProgramData\Agent\AGENT.md) |
org-wide, read-only |
| User | ~/.agent/AGENT.md |
just me, all projects |
| Project ancestors | every AGENT.md and .agent/AGENT.md from
the repo root (or filesystem root) down to cwd |
team (committed) |
| Project local | AGENT.local.md in the same dirs |
just me (auto-added to .gitignore) |
| Subdirectories | AGENT.md in dirs below cwd |
loaded lazily (8.4) |
Compatibility: optionally also read
CLAUDE.md and AGENTS.md as aliases, controlled
by the memoryFileNames setting. If the program already uses
another name, keep it as the primary name (⚠️ ask me).
8.3 Imports
- The syntax
@relative/or/absolute/path.md(or@~/path) on its own or inline is replaced by that file's content. The model sees it wrapped as<file path="...">…</file>. - Resolution is relative to the importing file.
- Recursive, with a max depth of 5, cycle detection, and a size cap per file and in total. Over-cap files are truncated with a notice.
- Not evaluated inside code spans or code blocks.
- A missing import produces a visible warning in
/memoryand/doctor, never a crash. - Imports of files outside the project or home directory require the trust prompt.
8.4 Lazy subdirectory loading
- When any file tool touches a path under a directory with an unloaded
AGENT.md, inject it as a system reminder: "Instructions forsrc/api/: …". - Load each file once per session, and track this in the session so it survives compaction (re-inject after compaction if the directory is still relevant).
8.5 Prompt injection format
Memory is placed in the system prompt after the environment section:
# Project instructions
Contents of /home/me/.agent/AGENT.md (user instructions, applies to all projects):
…
Contents of /repo/AGENT.md (project instructions, checked into the codebase):
…
Tell the model that these instructions override default behavior, and that they must be followed exactly.
8.6 Commands and UX
/init: the agent analyzes the repo (build, test and lint commands, architecture, conventions, gotchas) and writes or improvesAGENT.md. If one exists, it proposes a diff instead of overwriting.#quick memory: an input starting with#asks which file (user / project / local) to append to. The model rewrites the note into a concise bullet, and the user confirms it./memory: lists every loaded memory file with its path, scope, size, tokens and import tree, and opens one in$EDITOR./context: shows memory's share of tokens.- File watching: if a memory file changes on disk mid-session, reload it before the next turn and add a system reminder.
- Settings:
memory.enabled,memory.fileNames,memory.maxTokens,memory.lazySubdirs.--no-memorydisables it.
8.7 Tests
- Discovery order with nested directories
- Local files gitignored
- Import recursion, cycles, missing files and caps
- Lazy load triggers once
- Survives compaction
/initproduces a valid file in a fixture repo#appends to the right file- Snapshot of the rendered prompt section
8.8 Done when
In a fixture monorepo with user, root, local and subdirectory files plus imports, the rendered prompt and lazy reminders match the expected snapshots, and an E2E run follows a project rule such as "always use pnpm, never npm".
9. System prompt assembly
Sections, in a stable order to maximize cache hits:
- Identity and role, plus the core behavior rules: be concise, read before editing, follow existing code conventions, don't add comments unless asked, verify with tests or lint, don't commit unless asked, refuse malicious code.
- Tool-use policy: prefer dedicated tools, batch independent calls in parallel, use TodoWrite for multi-step tasks, and use Task for broad searches.
- Tool definitions, or the text protocol plus definitions.
- Output style (see §18).
- Environment: cwd, whether it's a git repo, platform, OS version, today's date, model name.
- Git snapshot: git_spec.md §1.2.
- Memory files (§8).
- Append text from
--append-system-promptor a full replacement from--system-prompt.
Keep the prompt text in template files, not hardcoded strings. Add a test that renders the full prompt to a snapshot.
10. Context management
- Accounting: maintain a running token count per
message, using the adapter's counter.
/contextshows a breakdown: system, tools, memory, messages and free space, as a grid or bar. - Auto-compact at a configurable threshold, e.g. 85%
of the window minus the output reserve:
- Run the
PreCompacthook. - Ask the model (or the small model) for a structured summary covering: the user's goals and requests verbatim, key decisions, files read and modified with their relevance, errors and fixes, current state, open todos, and the next step.
- Replace the history with: the summary, the latest user message, the current todo list, and re-reads of the most recently edited files (up to a budget).
- Run the
/compact [instructions]runs compaction manually, with optional focus instructions.- Micro-compaction: before full compaction, replace
old large tool results with
[output cleared — re-run if needed]. - Warnings: show a status-bar indicator when context is above 70%.
/clearstarts a fresh conversation in the same process.
11. Sessions, checkpoints and rewind
- Transcripts are stored as JSONL under
~/.agent/projects/<escaped-cwd>/<session-id>.jsonl, with append-only writes that are crash-safe. --continue/-cresumes the most recent session in this directory.--resume/-ropens a picker showing title, date and message count. The small model generates titles.- Fork: resuming from an earlier message creates a
new branch via
parentUuid. - Checkpoints: before every file-mutating tool call, snapshot the affected files' prior contents, keyed to the message uuid.
- Rewind (Esc Esc or
/rewind): pick an earlier user message, then choose restore conversation, restore code, or both. Bash side effects aren't tracked; say so in the UI. - Clean up transcripts and snapshots older than
cleanupPeriodDays. /exportsaves the conversation as markdown to a file or the clipboard.
12. Subagents
- Task tool inputs:
description,prompt,subagent_type, and optionalmodel,run_in_background,isolation: worktree. - A subagent runs its own agent loop with a fresh context, its own system prompt and a restricted tool set. It returns only its final message to the parent, and tracks its own token usage.
- Definitions are markdown files with YAML
frontmatter in
.agent/agents/(project) and~/.agent/agents/(user):--- name: code-reviewer description: When to use this agent (the parent model reads this to choose) tools: Read, Grep, Glob # omit = inherit all model: small | main | <name> --- System prompt body... - Built-in agents:
general-purposewith all tools,Explore(read-only, fast, for searching), andPlan(read-only, for designing). - Parallelism: multiple Task calls in one turn run
concurrently. Background agents notify the parent when done, and
SendMessagecontinues a finished agent. Their place in/tasksand the processes they start: process_spec.md §7. - Worktree isolation
(
isolation: worktree): owned by git_spec.md §9. - No recursive Task calls by default (depth limit 1, configurable).
/agentslists, creates, and edits agent definitions. Creation is assisted by the model.- The
SubagentStophook fires when a subagent finishes.
13. Skills — full support plan
13.1 Audit first
Search for:
- existing "skills", "recipes", "playbooks", "prompt templates" or plugin-like instruction folders
- YAML frontmatter parsing
- any mechanism that loads instructions on demand
If a similar concept exists, extend it to this format instead of adding a parallel system (⚠️ ask me if the formats clash).
13.2 What a skill is
A folder of instructions, scripts and resources that the agent loads only when relevant:
my-skill/
SKILL.md # required
reference.md # optional extra docs, read on demand
scripts/fill.py # optional executables the agent runs via Bash
templates/… # optional assets
SKILL.md:
---
name: pdf-forms # kebab-case, ≤64 chars, unique
description: Fill PDF forms. Use when the user mentions filling, completing or extracting fields from a PDF. # ≤1024 chars; says WHAT and WHEN
allowed-tools: Read, Bash(python:*) # optional: tools pre-approved while skill is active
model: main # optional
disable-model-invocation: false # optional: true = only user can invoke via /name
---
# Instructions body (markdown)…
13.3 Discovery and precedence
- Locations:
- Project:
.agent/skills/*/SKILL.md, committed - User:
~/.agent/skills/*/SKILL.md - Plugin-provided: namespaced
plugin:skill - Built-in: shipped with the program
- Project:
- Name clashes: project > user > plugin >
built-in. Warn about the shadowed one in
/skills. - Validate frontmatter on load. Invalid skills are skipped with a
warning listed in
/doctor, never a crash. - Hot reload when skill folders change.
13.4 Progressive disclosure (the core mechanism)
- Level 1, always loaded: an
<available_skills>block in the system prompt with onlynameanddescriptionper skill, about 100 tokens each. If there are too many skills, cap the list and expose the rest viaSearchSkills/ToolSearch. - Level 2, on invoke: the
Skilltool ({skill: name, args?}) returns the fullSKILL.mdbody plus the skill's directory path, so relative paths resolve. - Level 3, as needed: the agent reads referenced files with Read or runs scripts with Bash. Script output enters context, and script source doesn't need to.
13.5 Invocation
- Model-invoked: the system prompt tells the model to
check the skill list before tasks and call
Skillwhen a description matches. - User-invoked:
/skill-name args, through the command framework (commands_spec.md §1.7: skills and custom commands are one format). - While a skill is active: its
allowed-toolsare auto-approved, still subject to deny rules. This lasts until the turn ends. - The loaded skill content is tracked in the session. After compaction, keep a note "skill X was loaded", and allow re-invocation.
- Subagents can declare
skills:in their frontmatter to have them preloaded.
13.6 Management
/skills: commands_spec.md §3.3.skill-creatorbuilt-in skill: helps the user write a new skill (interview, draft, validate frontmatter, test triggering).agent skills validate <dir>is a CLI check.
13.7 Security
- Project skills from an untrusted repo are not loaded until the folder is trusted.
- Scripts run through Bash with the normal permission checks.
13.8 Tests
- Discovery and precedence
- Frontmatter validation errors
- Only name and description appear in the prompt
Skillreturns the body and base path/nameinvocation with argsallowed-toolsscoping ends with the turndisable-model-invocationrespected- Hot reload
- E2E: a fixture skill with a unique trigger word ("use the zorblax format") gets auto-invoked by the real model, and its script runs.
13.9 Done when
The E2E above passes, and the idle token cost of 20 installed skills stays under the configured budget.
14. Slash commands
Superseded by commands_spec.md: its
§1 framework (registry, parsing, menu and autocomplete, custom commands
as skills with $ARGUMENTS, @path and
!`cmd` expansion) and its §3 catalog, which lists every
built-in this section named (/todos included;
/vim became an editor setting under /config).
The behavior of each command stays in the section that owns it here (§8
memory, §10 context, §11 sessions, §12 agents, §15 hooks, §16 MCP, §18
output styles, §19 terminal, §23 diagnostics data).
15. Hooks
- Events:
SessionStart,SessionEnd,UserPromptSubmit,PreToolUse,PostToolUse,Notification(fires when the agent needs input or is idle),Stop,SubagentStop,PreCompact. - Config:
"hooks": { "PreToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "./scripts/lint.sh", "timeout": 60 } ] } ] } - Input: JSON on stdin with
session_id,transcript_path,cwd,hook_event_name, plus event-specific fields such astool_name,tool_input,tool_responseandprompt. - Output protocol:
- Exit 0: success. Stdout is shown in verbose mode. For
UserPromptSubmitandSessionStart, stdout is added as context. - Exit 2: blocking error. Stderr is fed back to the model (Pre/PostToolUse, Stop) or shown to the user.
- Other exit codes: a non-blocking error, which is shown to the user.
- Alternatively, a JSON stdout object:
{decision: "block"|"approve", reason, continue: false, stopReason, suppressOutput, additionalContext, updatedInput}.
- Exit 0: success. Stdout is shown in verbose mode. For
- Matching hooks for an event run in parallel and are deduplicated. Each has a timeout.
/hooksUI shows them. Show a warning when hook config changed since the session started, since it's a security concern.
16. MCP (Model Context Protocol) — full support plan
16.1 Audit first
Search for:
- any JSON-RPC code, plugin/extension tool loading, subprocess tool servers, or an existing MCP SDK dependency
- the existing tool registry, which MCP tools must plug into rather than duplicate
If the official MCP SDK exists for the implementation language, prefer it over hand-rolling the protocol. Note the spec version supported, and target the latest stable one.
16.2 Configuration
- Scopes:
- local: this project, just me, stored in user config keyed by project path
- project:
.mcp.jsonat the repo root, committed - user:
~/.agent/settings.json→mcpServers, all projects - managed: policy file, with allow and deny lists of servers
- Format:
{ "mcpServers": { "github": { "type": "http", "url": "https://api.example.com/mcp", "headers": {"Authorization": "Bearer ${GITHUB_TOKEN}"} }, "fs": { "type": "stdio", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."], "env": {"FOO": "${FOO:-default}"} }, "legacy": { "type": "sse", "url": "https://…/sse" } } } - Variable expansion:
${VAR}and${VAR:-default}in command, args, env, url and headers. - CLI:
agent mcp add <name> [--scope] [--transport stdio|http|sse] [--env K=V] [--header] -- <cmd…>agent mcp add-json,remove,list,get,reset-project-choices--mcp-config <file>and--strict-mcp-configfor headless runs
- Trust: project
.mcp.jsonservers need one-time approval per server, which is remembered.
16.3 Transports and lifecycle
- stdio: newline-delimited JSON-RPC over the server's
stdin/stdout. The process itself (spawning, stderr log, kill-tree,
restart with backoff, crash events) is a job of kind
mcp: process_spec.md §6. - Streamable HTTP: POST plus optional SSE stream, session id header, resumability.
- SSE (legacy): for backward compatibility.
- Lifecycle:
initialize→ capability negotiation →notifications/initialized. - Servers connect in parallel at startup, with a connect timeout, so a slow server doesn't block the REPL.
- Reconnect with backoff on failure. One failed server never affects the others or the agent.
- Notifications: handle
tools/list_changed,resources/list_changedandprompts/list_changedby refreshing the registry. Handle progress notifications and logging messages. - Graceful shutdown on exit.
16.4 Tools
- Each MCP tool is registered in the existing tool
registry as
mcp__<server>__<tool>(names sanitized, length-capped), using the server's JSON schema. - Calls go through the full pipeline: validation → PreToolUse hooks → permissions → execute → PostToolUse hooks.
- Results:
- text, image and embedded-resource content blocks map to tool_result blocks
isErrormaps to an error result- structured content becomes JSON text
- Output cap: default about 25k tokens, configurable. Warn when over 10k.
- Tool annotations such as
readOnlyHintinform permissions and parallelism. They are hints, not trusted guarantees. - Timeouts: a per-call timeout, with cancellation via
notifications/cancelledon interrupt. - Context economy: if the total MCP tool schemas exceed a token threshold (e.g. 10% of context), switch to deferred loading: put names in the prompt and load schemas through ToolSearch.
16.5 Resources
@server:protocol://pathmentions in user input fetch and attach the resource.@autocomplete lists them.- Generic tools
ListMcpResourcesandReadMcpResource. - Subscriptions are optional.
16.6 Prompts
- Server prompts appear as slash commands
/mcp__server__prompt arg1 arg2, with arguments mapped in order and autocomplete hints.
16.7 Authentication
- OAuth 2.1 for remote servers: discovery via protected-resource metadata, dynamic client registration, PKCE, a browser redirect to a localhost callback, and token refresh.
- Tokens are stored in the OS keychain, or an encrypted file as a fallback.
/mcpshows "needs auth" and starts the flow. A clear-auth option exists.- Static headers or bearer tokens are supported via config.
16.8 Other client features
- Roots: expose the project directories to servers.
- Elicitation: when a server asks the user for input mid-call, render a form prompt. In headless mode, decline.
- Sampling: off by default. If enabled, server-requested completions go through the local model, with user approval.
16.9 UX
/mcplists servers with status (connected / failed / needs auth / disabled), transport, tool, resource and prompt counts, and token cost. From there the user can reconnect, enable, disable, authenticate, or view tools and logs.- The startup notice tells the user when a server failed, with a hint
to run
/mcp. - The permission prompt shows the server and tool names clearly.
16.10 Agent as an MCP server (optional, later)
agent mcp serveexposes the built-in tools (Read, Edit, Bash, …) over stdio, so other clients can use them.
16.11 Security
- Untrusted servers: tool descriptions and results are untrusted data. Watch for prompt injection in descriptions, and flag descriptions containing instruction-like text.
- Never pass secrets to servers beyond those configured.
- Managed allow and deny lists apply.
16.12 Tests
- A fake MCP server fixture (stdio and HTTP) supporting tools, resources, prompts, list_changed, slow responses, crashes, oversized output, OAuth (mock authorization server) and elicitation
- Config scope merge and variable expansion
- Trust prompt behavior
- Permission rules for
mcp__* - Deferred loading threshold
- Reconnect after a crash
- Cancellation on interrupt
- E2E: connect the official filesystem reference server and have the agent use it to list and read a file.
16.13 Done when
- The E2E passes.
- A crashing server leaves the agent fully usable.
/mcpaccurately reflects the state of every server.
17. Plugins (later milestone)
- A plugin is a directory with
plugin.jsonthat bundles commands, agents, skills, hooks and MCP servers. - Marketplaces: a git repo or URL with a
marketplace.jsonindex./pluginlets users browse, install, enable, disable and update. - Plugin components are namespaced so they don't collide.
18. Output styles
- Built-in styles:
default,explanatory(adds educational insights), andlearning(leavesTODO(human)parts for the user to do). - Custom styles are markdown files in
.agent/output-styles/, which modify or replace the behavior section of the system prompt. - Switched with
/output-style.
19. Terminal UI
- Rendering: streaming markdown (code blocks with
syntax highlighting, lists, tables), with tool calls shown compactly:
Ctrl+R toggles verbose or full output.● Read(src/main.rs) ⎿ Read 120 lines ● Update(src/lib.rs) ⎿ Updated with 3 additions and 1 removal [colored diff] - Spinner with a whimsical verb, elapsed time, token count, and "esc to interrupt".
- Todo list panel, live-updated.
- Input editor:
- multiline (Shift+Enter,
\+Enter, or Option+Enter), history (↑/↓, Ctrl+R search), paste handling with a large-paste placeholder, and image paste/drag (as file paths or clipboard images) - prefix modes:
/opens the command menu (commands_spec.md §1.6),@file path fuzzy autocomplete,!bash mode (runs directly and adds the output to context),#memory add (§8.6) - vim mode, as an editor setting under
/config
- multiline (Shift+Enter,
- Keybindings:
- Esc interrupts. Esc Esc opens rewind.
- Shift+Tab cycles the permission mode.
- Ctrl+C clears input, or exits on a double press. Ctrl+D exits.
- Ctrl+L redraws. Ctrl+B moves a running bash command to the background (process_spec.md §3).
- Status line: a user-configurable shell command that
receives session JSON on stdin and prints one line, e.g. model, branch,
context %, cost. This section owns it; the git state (git_spec.md §1.3) and the process counts (process_spec.md §13) are fields of the
session JSON, and
/statuslineconfigures it (commands_spec.md §3.3). - Notifications: a terminal bell or OS notification when the agent needs input or finishes a long task. This section owns the mechanism; process crashes, readiness failures and finished background agents are more triggers (process_spec.md §13).
- Themes: dark, light and colorblind-friendly.
Respect
NO_COLOR. Handle terminal resize and narrow widths. - Welcome screen: shows cwd, model, tips, and a warning if the folder isn't trusted. On first run in a folder, ask whether the user trusts it.
20. Headless mode and SDK
agent -p "prompt"runs non-interactively and prints the result to stdout.- Flags:
--output-format text|json|stream-json--input-format text|stream-json(multi-turn over stdin)--max-turns,--model,--allowedTools,--disallowedTools,--permission-mode--system-prompt,--append-system-prompt,--mcp-config,--continue,--resume <id>,--verbose,--add-dir
- JSON result:
{type: "result", subtype: success|error_max_turns|error, result, session_id, num_turns, duration_ms, usage}. - stream-json emits one JSON event per line:
system/init,assistant,user(tool results), andresult. - Exit codes: 0 for success, non-zero for errors.
- Stdin piping works:
cat log.txt | agent -p "explain the error". - SDK: the same core exposed as a library,
query({prompt, options}) -> async iterator of messages, with options for custom tools (in-process), hooks as callbacks, acanUseToolpermission callback, and abort.
21. Git and GitHub workflows
Owned by git_spec.md: commit guidance and
workflow (its §3), pull requests through the host's CLI or API (§5),
/code-review / /review (§8.2), CI use (§13),
EnterWorktree / ExitWorktree (§9).
22. Background work and monitoring
Owned by process_spec.md: background
processes (§2, §3), the Monitor tool and the event bus (§4.1, §4.2),
scheduled wakeups (§4.3). Background sub-agents are §12 here, their
processes the process specification's §7. /loop and
/schedule are commands_spec.md §3.5.
23. Cost, usage and diagnostics
- Track tokens per model: input, output and cached. Track wall time and API time. If the user configures a price table, compute a cost.
/usage(alias/cost) and/statusdisplay these numbers: commands_spec.md §3.7. This section owns the tracking.--debugandAGENT_DEBUGwrite logs to~/.agent/logs/. Optional OpenTelemetry export of metrics and events./doctor,/bugand/feedback: commands_spec.md §3.7 (each specification contributes its checks: orphan processes, orphan worktrees, memory files).
24. Security checklist
25. Testing strategy
- Unit tests:
- every tool's edge cases
- the tool-call parser, including a fuzz corpus of malformed outputs
- permission rule matching, including compound and injection cases
- settings merge, memory discovery and imports, slash command expansion
- hook I/O protocol, compaction summary assembly, token accounting
- Integration tests with the mock model: scripted multi-turn sessions that assert on file system state, transcripts, permission prompts (with simulated answers), interrupts, rewind, resume, subagents, and hooks blocking and modifying.
- Snapshot tests: the rendered system prompt and TUI frames for key states.
- E2E with the real model: 10–20 small tasks in temp
repos, each with a checker script. Examples:
- fix a failing test
- add a CLI flag
- rename a function across files
- find and explain a bug
- write a README from code
- Eval harness:
agent-eval runreports pass rate, turns, tokens and time per task. Run it after prompt or tool changes to catch regressions. - CI: lint, unit, integration, and e2e behind a flag.
26. Milestones and acceptance criteria
Every milestone follows the same steps:
- Re-search the code for that milestone's features.
- Update
docs/gap-analysis.md. - Implement only the ❌/🟡 items.
- Add tests for ✅ items that don't have any.
- Run the acceptance checks.
- Report what was reused, extended and new.
| # | Milestone | Done when |
|---|---|---|
| M0 | Audit: full gap analysis + design doc | docs/gap-analysis.md covers every spec section with
evidence; ⚠️ items reviewed with me |
| M1 | Model adapter, streaming, mock adapter | Streams a reply in the REPL; mock replays a fixture; cancel works |
| M2 | Messages, agent loop, text tool protocol/parser, Read/Glob/Grep | Agent answers "where is X defined?" correctly using tools; parser passes fuzz corpus |
| M3 | Write/Edit/MultiEdit/Bash (persistent, timeout, truncation) | E2E "create fizzbuzz + make test pass" succeeds |
| M4 | Permissions (modes, rules, compound bash parsing, prompts, dangerous list) | Rule-matching test suite green; Shift+Tab cycles modes; plan mode blocks writes |
| M5 | System prompt assembly, TodoWrite, system reminders | Snapshot test of prompt |
| M5b | AGENT.md full support (§8): all scopes, imports,
lazy subdir loading, /init, #,
/memory, file watching |
§8.8 criteria |
| M6 | Settings hierarchy, env vars, /config,
/permissions |
Merge-precedence tests green |
| M7 | Context accounting, /context, auto/manual compaction,
micro-compaction |
2-hour synthetic session stays within window without losing task state |
| M8 | Sessions JSONL, --continue/--resume,
checkpoints, rewind, /export |
Kill -9 mid-session, then resume works; rewind restores files |
| M9 | TUI polish: markdown, diffs, spinner, input modes
(@ ! #; / is commands C2), history,
keybindings, status line, notifications, themes |
Manual checklist + frame snapshots |
| M10 | Slash commands: commands_spec.md C1–C3 (framework, menu, custom commands as skills); the catalog follows in its C4–C10 | Its C1–C3 criteria |
| M11 | Hooks (all events, exit codes, JSON decisions) | Hook that blocks Edit on *.lock works;
formatter PostToolUse hook works |
| M12 | Subagents (Task, definitions, built-ins, parallel, background); worktree isolation is git_spec.md G9 | Parallel Explore agents return summaries; parent context stays small |
| M13 | Skills full support (§13) + ToolSearch deferred tools | §13.9 criteria; deferred tool loads on demand |
| M14 | Headless -p, json/stream-json, SDK API |
Scripted CI usage example works; exit codes correct |
| M15 | MCP full support (§16): config scopes,
stdio/HTTP/SSE, tools, resources, prompts, OAuth, elicitation,
/mcp, agent mcp CLI |
§16.13 criteria |
| M16 | WebFetch/WebSearch, NotebookEdit, AskUserQuestion (Monitor and BashOutput/KillShell are process_spec.md P3 and P5) | Tool tests green |
| M17 | Output styles, usage tracking, logging, telemetry
(/doctor, /usage, /status are commands_spec.md C9) |
Manual checks |
| M18 | OS sandbox for bash | Sandboxed bash cannot write outside project or reach blocked hosts |
| M19 | Plugins + marketplace | Install a sample plugin bundling a command, an agent and a hook |
| M20 | Eval harness + docs (docs/user-guide.md,
docs/extending.md) |
Eval report generated; docs cover every feature |
Priority if time is short: M1–M8 give a usable agent. M9–M14 give feature parity for daily use. M15–M20 give full parity.
The order across this specification and the process, git and commands ones, and which specification owns each shared part, is agent-specs.md.
27. Notes for weaker or local models
- Keep the always-loaded tool set small (Read, Edit, Write, Bash, Grep, Glob, TodoWrite). Defer everything else.
- Put 1–2 worked tool-call examples in the system prompt.
- Make the error messages instructional, e.g. "old_string matched 3 times; include the surrounding function signature to make it unique".
- Lower the temperature for tool-calling turns.
- Prefer the full-file
Writefallback ifEditaccuracy is poor, and measure that with the eval harness. - Lower the compaction threshold if quality drops as context fills.