README Source History Refs Reviews Compare Notes Search Review guide fix(specs): add PluginEvent and BlockReason enums to SM-009, remove stale SessionEntry/SessionStore from SM-004
c2f5e65f57365071c9c47b5dfa5d919fdacf6c35
HallucyGenie Agent <agent@hallucygenie.local > · 21 May 2026
SSH signature · not checked
Browse files Compare with HEAD
Changed files (2) Diff layout Auto Unified Split
docs/spec-sm-004-architecture.md Added new file mode 100644+1127 / −0 text lines
1 + # SM-004: smith Architecture Design 5 + Design the full application architecture for smith — a Rust coding agent TUI.6 + Define module boundaries, data flow, trait hierarchies, extension points, and7 + security model. Output as architecture document + skeleton Rust modules with8 + doc comments and TODO stubs. No implementation beyond type definitions and13 + SM-003 established the project foundation (workspace, xtask, testing, config).14 + This task designs what smith actually *is*: a fast, extensible coding15 + agent with a TUI interface.17 + **Inspired by pi's architecture**, but with distinct design choices:18 + - Modern terminal rendering via Kitty protocol19 + - Plugin system: LuaJIT only20 + - LLM is the only untrusted actor21 + - Everything is a plugin: tools, themes, keybindings23 + ## Architecture Overview 25 + smith is split into **6 crates**:29 + | `smith/` | Shared library — types, Lua runtime, config |30 + | `smith-core/` | Pure business logic — session, tools, hooks |31 + | `smith-ai/` | LLM providers — preconfigured + config-driven |32 + | `smith-tui/` | Terminal rendering — widgets, themes |33 + | `smith-harness/` | Orchestrator + plugins — event loop, SDK |34 + | `smith-cli/` | Binary entry point |39 + User Input → smith-cli (parse) → smith-harness (orchestrate)41 + ┌─────────────────┼─────────────────┐43 + smith-core smith-ai smith-tui44 + (session/tools) (providers) (render)46 + └─────────────────┼─────────────────┘48 + smith-harness (coordination)53 + ### Canonical Spec Map 55 + | Type / Trait | Canonical Spec | Notes |56 + |-------------|----------------|-------|57 + | `Config`, `LuaRuntime`, `SmithError` | **SM-005** (`smith/`) | Shared types, error types |58 + | `AgentTool`, `ToolDefinition`, `ProviderRequest`, `ProviderEvent`, `ProviderUsage`, `StopReason` | **SM-005** (`smith/`) | Tool and streaming types |59 + | `Session`, `SessionEntry`, `SessionStore`, `AgentEvent`, `EngineEvent`, `AgentLoopConfig` | **SM-006** (`smith-core/`) | Business logic, events, sessions |60 + | `Provider` trait, model registry, auth | **SM-007** (`smith-ai/`) | LLM providers |61 + | TUI widgets, `TuiApp`, render loop, themes | **SM-008** (`smith-tui/`) | Terminal rendering |62 + | Plugin system, SDK, built-in tools, sandbox | **SM-009** (`smith-harness/`) | Orchestration + plugins |63 + | CLI args, session commands | **SM-010** (`smith-cli/`) | Binary entry point |64 + | Workspace deps, crate graph | **SM-011** | Workspace manifest |65 + | Testing strategy | **SM-012** | Test plan |67 + SM-004 is the **architecture narrative** — for type definitions, see the canonical specs above.69 + ### Core Principle: Everything is a Plugin 71 + smith-harness defines the plugin system. All extensibility comes through plugins:73 + - `read`, `write`, `edit`, `bash` — shipped as Lua plugins in smith's built-in package74 + - Themes — Lua tables defining colors/styles75 + - Keybindings — Lua tables mapping keys → actions76 + - Default prompts — Lua strings77 + - UI layout configuration — Lua tables80 + 1. The plugin system is battle-tested from day one (smith depends on it)81 + 2. Users can override ANY built-in with their own implementation82 + 3. Iteration on tools/themes/config doesn't require recompiling Rust83 + 4. No "second class" API — built-in and user plugins use the exact same interface85 + ### Configuration Language: Lua 87 + Lua is smith's configuration language. Rust defines the types/schemas;88 + Lua provides the values:91 + -- ~/.smith/config.lua94 + ["ctrl+l"] = "cycle_model",95 + ["ctrl+c"] = "abort",97 + tools = { "read", "write", "edit", "bash" }98 + model = "anthropic/claude-sonnet-4"101 + ### Configuration Cascade 103 + Settings are resolved in layers, later layers override earlier:106 + Rust type definitions (schema validation)108 + Built-in Lua defaults (shipped with smith)110 + Plugin contributions (plugins register themes, keybindings, tools)112 + User config (~/.smith/config.lua)114 + CLI flags (--model, --theme, etc.)117 + Each layer is validated against the Rust schema. Invalid values are rejected118 + with a clear error message. Unknown keys are either ignored or warned.122 + Credentials (API keys, tokens) read from environment variables or plain text config.123 + No OS keychain integration. No encryption. Plaintext in config or environment.125 + Rationale: smith runs as the same user. If an attacker can read smith's data,126 + they can read the user's environment. OS keychain adds complexity without security benefit.129 + -- config.lua — credentials in plain text131 + anthropic_api_key = "sk-ant-...",132 + openai_api_key = "sk-...",136 + Or via environment variables (preferred):138 + export ANTHROPIC_API_KEY= "sk-ant-..." 142 + **Runtime data** (sessions, cache, state): XDG-compliant directory structure via `dirs` crate:144 + | Platform | Config | Data | Cache |145 + |----------|--------|------|-------|146 + | Linux | `~/.config/smith/` | `~/.local/share/smith/` | `~/.cache/smith/` |147 + | macOS | `~/Library/Application Support/smith/` | same | `~/Library/Caches/smith/` |148 + | Windows | `%APPDATA%\smith\` | `%LOCALAPPDATA%\smith\` | `%LOCALAPPDATA%\smith\cache\` |152 + sessions/ ← length-prefixed CBOR-seq files153 + 2026-04-20T08-30-00.session154 + 2026-04-20T09-15-22.session155 + plugins/ ← installed user Lua plugins156 + data/ ← plugin persistent state (per-plugin)159 + bytecode/ ← compiled LuaJIT bytecode with source hash headers162 + config.lua ← user configuration163 + themes/ ← user theme overrides164 + keybindings/ ← user keybinding overrides167 + **Session format**: Length-prefixed CBOR-seq (RFC 8949 entries with u32 BE length prefix).171 + ┌────────────┬──────────────────┬────────────┬──────────────────┐172 + │ u32 BE len │ CBOR entry bytes │ u32 BE len │ CBOR entry bytes │173 + └────────────┴──────────────────┴────────────┴──────────────────┘176 + Session entries use a typed envelope + CBOR payload:177 + **Session entries** (CBOR-encoded, length-prefixed):181 + struct SessionEntry {189 + struct UserPayload { content: Vec <ContentBlock> }190 + struct AssistantPayload { content: Vec <ContentBlock>, usage: ProviderUsage }191 + struct ToolCallPayload { tool: String, args: String }192 + struct SecretRegisterPayload { id: String, value: String, source: String }193 + struct CompactionPayload { summary: String, prev_ids: Vec <String > }196 + **Secret proxy**: Translation table is stored as `secret_register` session entries.197 + Session resume builds the table by scanning backward from the end, collecting the198 + most recent registration for each `smith:sec:N` ID. History is self-describing —199 + any point in the session can be fully restored.201 + Compaction rolls up old entries into a `compaction` entry that preserves the202 + secret registrations from the rolled-up range, so no data is lost.204 + **Fault tolerance** — session parsing MUST NOT crash smith:205 + - Length prefix is the recovery mechanism: even with corrupt CBOR, reader206 + always knows where next entry starts (`pos + len`).207 + - Truncated entry (crash mid-write) → stop, all prior entries intact.208 + - Corrupt CBOR bytes → log warning, skip entry, continue.209 + - Unknown entry type → keep entry with `Payload::Unknown`.210 + - Unknown CBOR fields in known entry → ignored (forward compatible).211 + - Missing optional fields → `None` (backward compatible).212 + - File missing or empty → return empty vec, create on first write.214 + **Human-readable output**: `smith session dump` converts CBOR-seq → JSONL to stdout.216 + smith session dump # latest session as JSONL217 + smith session dump <session-id> # specific session218 + smith session dump --last 5 # last 5 entries219 + smith session dump --output out.jsonl # write to file220 + smith session list # list all sessions223 + **Session migration**: Session format versions. Migrate on load.225 + pub const CURRENT_SESSION_VERSION : u32 = 1 ;227 + fn migrate_entries (entries: &mut Vec <SessionEntry>) {228 + let version = entries.first ()229 + .and_then (|e| match e {230 + SessionEntry::Session { version, .. } => Some (* version),235 + if version < 1 { migrate_v0_to_v1 (entries); }240 + ## Crate: smith (Shared Library) 242 + Shared types and utilities. No business logic.245 + - Common types (EntryId, SessionId, Message, ContentBlock, Role, etc.)246 + - Lua runtime setup (mlua, mlua-pkg)247 + - Config resolution from Lua files248 + - Error types (smith Error)252 + Types are defined in **SM-005** (`smith/` shared library). This crate re-exports253 + `smith_core::SessionEntry`, `smith_core::Session`, etc. See SM-005 §types.rs,254 + §config.rs, §lua.rs, and §error.rs for canonical definitions.258 + pub use smith_core::{EntryId, SessionId, Session, SessionEntry, Message, ContentBlock, Role};263 + Pure business logic. No I/O, no side effects. Session management, tools, hooks.266 + - Session management (tree, entries, compaction)267 + - Session format (CBOR encode/decode)268 + - Tool registry and execution269 + - Hook types and registration271 + - System prompt building280 + pub name: Option <String >,282 + pub entries: Vec <SessionEntry>,283 + pub current_leaf: EntryId,303 + pub trait SecretProxy : Send + Sync {304 + fn register (&mut self, secret: String) -> SecretId;305 + fn resolve (& self, id: & SecretId) -> Option <&str >;310 + - Add new `SessionEntry` variants311 + - Add new `EngineEvent` variants312 + - Custom `Tool` implementations316 + LLM provider layer. Preconfigured providers + config-driven models.319 + - Provider trait (streaming responses, tool calling)320 + - Preconfigured providers (Anthropic, OpenAI, Google, local)321 + - Model registry and resolution322 + - API calls and streaming323 + - Reads Lua config for provider/model settings327 + Provider trait, streaming types, model registry, and auth are defined in328 + **SM-007** (`smith-ai/`). Shared streaming types (`ProviderEvent`, `ProviderRequest`)329 + live in **SM-005** §types.rs to enable parallel builds.331 + Provider implementations: AnthropicProvider, OpenAIProvider, GoogleProvider,332 + OpenAICompatProvider. See also `docs/AI-CRATE-DESIGN.md`.336 + pub use smith::{ProviderEvent, ProviderRequest, ProviderUsage, StopReason};341 + Terminal rendering. Widgets, themes, keybindings. Receives events from harness.344 + - Render UI based on engine state345 + - Send UI events (input, resize, abort) to harness346 + - Widgets (message list, input area, status bar)348 + - Keybinding handling351 + Main Thread (Engine) UI Thread (Rendering)353 + ├─state_tx───►[TuiState]──────────────┤ (what to render)355 + │◄──input_rx───[user input]───────────┤ (what to do)357 + ├─EngineEvent: ThinkingStarted ───────►│358 + ├─EngineEvent: TokenDelta ─────────────►│359 + ├─EngineEvent: ToolCall ───────────────►│360 + ├─EngineEvent: ToolResult ─────────────►│361 + └─EngineEvent: Error ───────────────────►│363 + Tool Thread (Execution)365 + ├─tool_rx──►Engine (results)368 + Engine event loop (never blocks on UI):372 + input = input_rx.recv () => self.handle_input (input? ),373 + result = tool_rx.recv () => self.handle_tool_result (result? ),374 + _ = tick (Duration::from_millis(16 )) => self.ui_state.render (),379 + ### TUI State Machine 381 + Every state is interruptible by the user (Ctrl+C → abort flag).398 + ┌─────────────────────────────────────────────────────────┐399 + │ [ctx: 45k/200k] [$0.23] [session: foo] [claude-sonnet-4]│ ← status bar400 + ├─────────────────────────────────────────────────────────┤401 + │ User: Read the Cargo.toml │402 + │ Assistant: [tool: read("Cargo.toml")] │ ← message history403 + │ Tool: [expanded inline or collapsed] │ (virtual scroll)405 + ├─────────────────────────────────────────────────────────┤406 + │ > cargo run -- --help │ ← input area407 + │ [Enter: send] [Ctrl+C: abort] [Ctrl+L: model] │ ← hint bar408 + └─────────────────────────────────────────────────────────┘411 + **Status bar**: No smith name/version. Shows:412 + - `ctx: X/Y` — current context usage / max413 + - `$N.NN` — running cost estimate (updated in real time)414 + - `session: name` — current session415 + - `model: name` — active model417 + **Message history**: Virtual scrolling. `sticky_bottom` flag:418 + - `true` (default): new messages auto-scroll to bottom419 + - `false` (user scrolled up): stay in place until user scrolls back or submits421 + **Input area**: Custom `InputArea` widget on ratatui. Not reedline — reedline422 + owns inline rendering which conflicts with ratatui managing the whole screen.423 + Built with ratatui primitives + crossterm cursor. Single-line by default,424 + multiline when content wraps. Arrow keys navigate. Ctrl+C cancels.426 + **Hint bar**: Keyboard shortcuts for current state. Updates dynamically.428 + ### Rendering: ratatui + crossterm 430 + ratatui handles widgets, layout, TestBackend for snapshots.431 + crossterm handles terminal I/O, cursor, Kitty keyboard protocol flags.435 + use crossterm::event::{KeyboardEnhancementFlags, DisableBracketedPaste};437 + terminal.push_event_filter (KeyboardEnhancementFlags::DisambiguateEscapeCodes);438 + terminal.push_event_filter (KeyboardEnhancementFlags::ReportEventTypes);441 + Custom `Backend` wraps crossterm, emits Kitty escape sequences for:442 + - Extended colors (24-bit, beyond 256)443 + - Undercurl (spelled out for cross-compatibility)444 + - Image support (sixel/kitty-ki) — deferred v1446 + ratatui `TestBackend` enables snapshot testing:449 + fn renders_status_bar_with_context () {450 + let backend = TestBackend::new(80 , 24 );451 + let mut terminal = Terminal::new(backend).unwrap ();452 + terminal.draw (|f| render_status_bar (f, "45k" , "$0.23" ));453 + insta::assert_snapshot! (terminal.backend ());459 + Themes defined in config.lua, not separate files:464 + status_bar = { bg = "#1a1a2e", fg = "#eeeaea" },465 + user_message = { bg = "#16213e", fg = "#e8e8e8" },466 + assistant = { bg = "#0f0f23", fg = "#c4c4c4" },467 + tool_call = { bg = "#2d2d44", fg = "#7f7fff" },468 + tool_result = { bg = "#1a1a1a", fg = "#00ff00" },469 + error = { bg = "#2a0a0a", fg = "#ff4444" },470 + input = { bg = "#1e1e2e", fg = "#cdd6f4" },475 + Rust defines the theme schema (validates keys and color formats). Lua provides values.476 + No `themes/` directory — themes live in config.lua.478 + ### Deferred (v1 scope) 480 + - Vim-style normal mode editing481 + - Multiline input with explicit newline insertion482 + - Inline image rendering (Kitty graphics)483 + - Fuzzy history search485 + - Multiple simultaneous sessions487 + ## Crate: smith-harness 489 + Orchestrator + plugin system. Owns the event loop, coordinates all crates.492 + - Plugin loading (LuaJIT via mlua)493 + - Plugin SDK (sandboxing, credential access)494 + - Event loop (engine owns it)495 + - Coordinates core + ai + tui496 + - Receives UI events, dispatches to engine502 + pub core: CoreEngine,505 + pub plugins: PluginManager,508 + pub struct PluginManager {510 + plugins: Vec <LoadedPlugin>,513 + pub struct PluginSdk {518 + ### LuaJIT Sandbox Configuration 520 + **Standard libraries**: Keep `string`, `table`, `math`, `coroutine`, `utf8`, `package`521 + (with custom searchers). Strip `io`, `os`, `debug`, `getfenv`, `setfenv`.523 + **Safe host functions** exposed through a `smith.*` Lua module:525 + smith.fs.read("path") -- read file (enforced: scoped to project dirs)526 + smith.fs.write("path", data) -- write file (enforced: scoped to project dirs)527 + smith.env.get("HOME") -- read-only env access528 + smith.time.now() -- safe timestamp531 + Path restrictions are enforced by the SDK (Rust), not by plugins. Plugins only have532 + access through `smith.fs.*`. They cannot bypass restrictions because they have no533 + raw filesystem API. The SDK enforces: reads/writes are scoped to smith's working534 + directory or explicitly allowed paths. Plugins are Lua (untrusted), SDK is Rust537 + **Custom require** via `mlua-pkg` crate — composable resolver chain:538 + - `NativeResolver` — smith's Rust API surface to plugins539 + - `FsResolver` — scoped to plugin's own directory only540 + - `MemoryResolver` — embedded modules smith provides541 + - Plugins can be multi-file with nested directories543 + **Bytecode caching**: Smith compiles `.lua` → bytecode on first load, caches544 + by source hash. Smith never loads bytecode it didn't compile itself. No signing545 + needed — trust is in the source, cache is just a performance optimization.549 + ### OCaml-Style Interface Modules 551 + In OCaml, a library exposes a module signature (.mli) that others implement.552 + In smith, a plugin can declare it implements one or more **interfaces**:557 + pub trait PluginInterface : Send + Sync {559 + fn interface_name (& self) -> &str ;563 + pub trait Plugin : Send + Sync {565 + fn metadata (& self) -> PluginMetadata;567 + fn interfaces (& self) -> Vec <Box <dyn PluginInterface>>;571 + pub trait ToolInterface : PluginInterface {573 + fn tool (& self) -> Box <dyn AgentTool>;577 + pub trait WidgetInterface : PluginInterface {578 + fn widget (& self) -> Box <dyn Widget>;582 + pub trait HookInterface : PluginInterface {583 + fn hooks (& self) -> Vec <HookRegistration>;591 + pub trait PluginLoader {593 + fn load (& self, path: & Path) -> Result <Box <dyn Plugin>>;595 + fn available_interfaces (& self) -> & [InterfaceDescriptor];599 + pub struct LuaPluginLoader { }605 + - New interface types (add to `PluginInterface` hierarchy)606 + - New plugin loaders (e.g., native Rust `.so` plugins)608 + - Plugin-to-plugin communication612 + Binary entry point. Parses args, creates harness, runs it.615 + pub struct CliArgs { }617 + pub struct AppConfig {619 + pub provider: ProviderConfig,620 + pub model: ModelSelection,621 + pub session: SessionSelection,622 + pub tools: ToolSelection,628 + Print { prompt: String },633 + pub fn main () -> Result <()> {634 + let args = CliArgs::parse();635 + let config = resolve_config (args)? ;636 + let mut harness = Harness::new(config)? ;643 + The LLM is the **only untrusted actor**. Everything else is trusted.645 + **Trusted** (inside boundary):646 + - User's machine, OS, filesystem648 + - Plugins (user verified source before installing)650 + - All local data (sessions, secrets, config)652 + **Untrusted** (outside boundary):653 + - The LLM (remote server — could be compromised, prompt-injected, or adversarial)654 + - Network calls to LLM provider656 + **What this means in practice:**657 + - Session files: plaintext CBOR-seq, no encryption658 + - Secret proxy translation table: merged into session entries, plaintext659 + - API keys: read from environment variables or plain text config, smith passes them to tools660 + - No OS keychain integration — credentials stay in env/config661 + - Smith focuses security effort on **bounding LLM capabilities**, not encrypting local data663 + **LLM bounding mechanisms:**664 + 1. Tool registry: smith controls which tools the LLM sees — not all tools are exposed665 + 2. Secret proxy: LLM sees `smith:sec:N` identifiers, never real secrets666 + 3. SDK path restrictions: plugins access filesystem only through `smith.fs.*` (Rust),667 + which enforces scoping. Plugins have no raw filesystem API and cannot bypass.669 + Security is **configuration**, not confirmation dialogs. Users configure which tools670 + are available. Popups that users learn to auto-accept are theater, not security.672 + **The secret proxy system** prevents LLM data exfiltration:673 + - Every user message and tool output scanned for secret patterns (env vars, tokens, keys)674 + - Detected secrets replaced with `smith:sec:N` identifiers before reaching LLM675 + - When LLM makes a tool call, arguments scanned for identifiers and rehydrated676 + - Translation table: stored as session entries, restored on session resume678 + Secret registration entries:681 + struct SecretRegisterEntry {689 + Session resume builds translation table by scanning backward for most recent690 + `secret_register` entry per ID. History is always restorable.694 + Three threads. The engine (main thread) drives the event loop. The UI thread is695 + purely reactive and must never stall user input.698 + Main Thread (Engine) UI Thread Tool Thread699 + (owns the event loop) (rendering) (execution)701 + ├─state_tx──────────────►│ (TuiState updates) │702 + │◄──input_rx─────────────┤ (user input) │704 + │ LLM streaming ─────────┼── EngineEvent ────────►│705 + │ │ ├─tool_rx──►Engine706 + │ config resolution ├─snapshot capture │ tool execution707 + │ session management │ │ subprocess708 + │ state machine │ │ file I/O711 + - **Engine (main thread)**: Owns the event loop. Receives user input via712 + `input_rx` channel. Never blocks on UI operations. Drives state machine.713 + Receives tool results via `tool_rx`. Sends state updates via `state_tx`.714 + - **UI thread**: Renders continuously. Reads from `state_rx`. Sends input715 + to engine via `input_tx`. Never calls the engine directly. Never blocks716 + on engine operations.717 + - **Tool thread**: Executes tools, runs subprocesses, performs file I/O.718 + Returns results to engine via `tool_rx`. Plugins run here.720 + **Never block the UI**: Every user keypress must be acknowledged within 16ms.721 + The engine loop uses non-blocking channel receives. If no input is available,722 + the loop proceeds without waiting. The UI thread is always responsive.724 + **Every state is interruptible**: Ctrl+C sets an abort flag. The current725 + operation checks the flag and bails cleanly. No state is a dead end.727 + **Async boundary**: `tokio` is scoped to the **provider layer** (smith-ai)728 + and **agent loop** (smith-core). Tool execution and TUI rendering remain729 + sync/single-threaded on their respective threads. The engine main thread uses730 + `tokio::select!` for non-blocking channel receives. See SM-005 (tokio sync),731 + SM-006 (tokio rt+sync), and SM-007 (tokio full) for crate-specific async usage.733 + ## Error Handling Strategy 735 + Two-tier error model:739 + pub enum SmithError {740 + Provider(ProviderError),743 + Plugin { plugin: String , message: String },744 + Session(std::io::Error),748 + Cbor(minicbor::decode::Error),752 + `ProviderError` and `AuthError` are defined in **SM-005** §error.rs. `SmithError` is defined in **SM-005** §error.rs.754 + /// Unreachable states — asserted, panic on failure755 + /// Used for: invariant violations, impossible states, programmer errors756 + /// These are NOT caught — they indicate bugs.758 + /// assert!(entries.len() <= MAX_ENTRIES);759 + /// assert_eq!(state.current_turn, expected_turn);763 + - External failures (network, disk, LLM, plugins) → `Result<_, SmithError>`764 + - Internal invariants (state machine consistency, bounds) → `assert!`765 + - Never use `unwrap()`/`expect()` — clippy denies them769 + A concrete example of what a real smith plugin looks like. This informs the770 + architecture — every trait and type must support this use case:773 + -- built-in/tools/read.lua774 + -- One of smith's built-in tools — implements the "read" tool for the LLM775 + -- Uses the same plugin API as any user plugin777 + local smith = require("smith")781 + version = smith.version,782 + description = "Read file contents",790 + description = "Read file contents. Supports offset/limit for large files.",792 + path = { type = "string", description = "File path to read" },793 + offset = { type = "number", description = "Line offset", optional = true },794 + limit = { type = "number", description = "Max lines", optional = true },796 + execute = function(params)797 + -- smith.fs.* is the safe, sandboxed file API798 + local content = smith.fs.read(params.path)799 + if params.offset then800 + content = smith.string.lines(content, params.offset, params.limit)802 + return { content = content }808 + And a user plugin for comparison:811 + -- ~/.smith/plugins/my_search/init.lua812 + -- User plugin — semantic code search814 + local smith = require("smith")827 + description = "Search the codebase",829 + query = { type = "string", description = "Search query" },831 + execute = function(params)832 + local files = smith.fs.list_dir("src")833 + -- ... search logic ...834 + return { results = results }839 + on_session_start = function(event)840 + smith.log("info", "Search plugin loaded")846 + Both use the same API. Built-in tools have no special privileges.848 + ## Novel Tool Research 850 + Traditional coding agents expose: `read`, `write`, `edit`, `bash`.851 + Smith wants to explore richer tool primitives. Architecturally, the `AgentTool`852 + trait (SM-005 §tool.rs) and `PluginInterface` system support this — any research853 + into novel tools just implements the `AgentTool` trait.855 + Ideas to explore (not implement now, just design space):856 + - Structured editing (AST-aware, not text-based)857 + - Semantic search over codebase858 + - Execution tracing / debugging tools859 + - Multi-file refactoring primitives860 + - Test generation and mutation tools862 + ## Dependency Decisions 867 + smith/ — shared library (types, Lua runtime, config)868 + smith-core/ — pure business logic (session, tools, hooks)869 + smith-ai/ — LLM providers (preconfigured + config-driven)870 + smith-tui/ — terminal rendering (widgets, themes)871 + smith-harness/ — orchestrator + plugins (event loop, SDK)872 + smith-cli/ — binary entry point873 + xtask/ — build subcrate (check, test, lint)876 + ### Production Dependencies 880 + | `ratatui` | Widget system, TestBackend for snapshots |881 + | `crossterm` | Terminal I/O, cursor, Kitty keyboard flags |882 + | `clap` | CLI argument parsing (derive macros) |883 + | `minicbor` | CBOR-seq encode/decode for sessions |884 + | `dirs` | XDG directory paths |885 + | `mlua` | LuaJIT bindings |886 + | `mlua-pkg` | Lua module loader (custom require) |887 + | `tokio` | Async runtime (provider layer) |888 + | `reqwest` | HTTP client (provider API calls) |889 + | `uuid` | Entry IDs (v7 for time-ordering) |890 + | `serde_json` | Tool definitions, JSON handling |891 + | `jsonschema` | Tool argument validation |892 + | `tracing` | Structured logging |893 + | `tracing-subscriber` | Log formatting (JSON, pretty) |894 + | `color-eyre` | **Deferred** — not used in v1 |895 + | `indicatif` | **Deferred** — not used in v1 |901 + | `insta` | Snapshot testing |902 + | `assert_cmd` | CLI integration tests |908 + | Kitty graphics (sixel/kitty-ki) | v1: text only. v2: evaluate crate |913 + ### 1. Architecture Document 915 + Create `docs/ARCHITECTURE.md` — the authoritative architecture reference:916 + - Module overview with responsibilities917 + - Data flow diagram (text-based)918 + - Trait hierarchy for each module919 + - Extension point catalog920 + - Security model layers921 + - Plugin system design (interfaces, loading, sandboxing)922 + - Dependency decisions with rationale923 + - Open research questions925 + ### 2. Skeleton Modules 927 + Create Rust files with doc comments, type definitions, trait declarations, and928 + `todo!()` stubs. **No implementation** — just the shape:934 + mod.rs — module root, re-exports935 + provider.rs — Provider trait, ProviderStream, ProviderEvent, Message, ContentBlock936 + session.rs — Session, SessionEntry (typed envelope + CBOR payload), SessionStore trait937 + session_format.rs — Length-prefixed CBOR-seq read/write, fault-tolerant parser938 + tools.rs — Tool trait, ToolDefinition, ToolInput/Output939 + events.rs — EngineEvent enum, EventBus trait940 + error.rs — SmithError enum (two-tier: recoverable vs asserted)941 + config.rs — ConfigResolver, ConfigCascade, ConfigSource942 + credentials.rs — CredentialReader trait (env vars + config)943 + secret_proxy.rs — Secret detection, identifier substitution, translation table944 + engine.rs — Engine struct, agent loop, 3-thread concurrency945 + compaction.rs — Token estimation, cut points, summarization, compaction946 + tool_exec.rs — Tool execution modes, retry policy, sequential/parallel947 + system_prompt.rs — System prompt construction from components948 + commands.rs — Slash commands, CommandHandler trait949 + hooks.rs — Extension hooks, HookRegistration, ExtensionRunner950 + /// ============================================================================952 + /// ============================================================================953 + /// Based on pi's agent-loop design. Simple event-driven loop with two nested loops:954 + /// - Outer loop: handles tool calls + pending messages955 + /// - Inner loop: streams LLM response957 + /// Key insight: The loop is reactive. It responds to:958 + /// - User input via channel (non-blocking)959 + /// - Steering messages (queue during streaming)960 + /// - Follow-up messages (queue when agent would stop)962 + /// The loop NEVER blocks on UI. Input is delivered via channel.964 + /// Start a new turn:965 + /// agent_loop_add_prompt(prompts, context, config, signal, emit)967 + /// Continue without adding prompt (for retry):968 + /// agent_loop_continue(context, config, signal, emit)970 + /// Main loop structure:972 + /// // Inner: process tool calls and steering973 + /// while has_tool_calls || has_pending {974 + /// // Emit turn start975 + /// // Process pending steering messages976 + /// // Stream assistant response977 + /// // Execute tool calls (sequential or parallel)978 + /// // Collect results979 + /// // Check for more steering981 + /// // Check if agent would stop982 + /// if has_followup_messages {983 + /// // Continue with follow-ups (sets pending, goes back to inner loop)986 + /// // No more messages, exit991 + /// - Sequential: execute one at a time, feed results back992 + /// - Parallel: execute independent tools simultaneously993 + /// - Before/after hooks via ExtensionRunner996 + /// - Tool errors: retry with backoff, or return error to LLM997 + /// - LLM errors: abort, emit error event998 + /// - User abort (Ctrl+C): set abort flag, current operation checks flag and bails1000 + mod.rs — module root, re-exports1001 + cli.rs — CliArgs, clap derive1002 + config.rs — AppConfig, resolve_config()1004 + mod.rs — module root, re-exports1005 + backend.rs — TerminalBackend trait, TerminalCapabilities1006 + app.rs — TuiState, TuiEvent, run_tui()1007 + widget.rs — Widget trait1008 + theme.rs — Theme types (schema — values come from Lua)1009 + keybinding.rs — Keybinding types (schema — values come from Lua)1011 + mod.rs — module root, re-exports1012 + interface.rs — PluginInterface, Plugin, ToolInterface, WidgetInterface, etc.1013 + loader.rs — PluginLoader trait, LuaPluginLoader1014 + sandbox.rs — SandboxConfig, Capability, bytecode caching1015 + sdk.rs — smith.* Lua module definition (what plugins can call)1016 + built-in/ — Lua plugins shipped with smith (NOT in src/)1018 + read.lua — read tool implementation1019 + write.lua — write tool implementation1020 + edit.lua — edit tool implementation1021 + bash.lua — bash tool implementation1023 + default.lua — default keybindings1024 + config.lua — default configuration (includes theme values)1029 + Every skeleton file must compile. Write **test stubs** that document the1030 + intended test behavior with `todo!()`:1038 + fn provider_completes_with_streaming_response () {1039 + todo! ("mock provider, send request, verify streaming events" );1044 + These stubs serve as the test plan. Future tasks fill them in via TDD.1046 + ### 4. Update CONTEXT.md 1048 + Add architecture section to `docs/CONTEXT.md`:1050 + - Key traits and their relationships1051 + - Where to add new functionality (extension points)1055 + - [ ] Step 1: Create `docs/ARCHITECTURE.md` — full architecture document1056 + - [ ] Step 2: Create `src/engine/` — trait definitions and type stubs1057 + - [ ] Step 3: Create `src/interface/` — config types and CLI skeleton1058 + - [ ] Step 4: Create `src/tui/` — backend trait, app state, widget trait1059 + - [ ] Step 5: Create `src/plugins/` — interface module hierarchy, loader traits1060 + - [ ] Step 6: Create `src/lib.rs` — re-export all modules1061 + - [ ] Step 7: Write test stubs for every module (document intended test behavior)1062 + - [ ] Step 8: Verify everything compiles: `cargo xtask check`1063 + - [ ] Step 9: Run `cargo xtask lint` — zero warnings1064 + - [ ] Step 10: Update `docs/CONTEXT.md` with architecture section1065 + - [ ] Step 11: Commit with `jj describe -m "arch(SM-004): smith architecture design — engine, interface, tui, plugins"1067 + ### Edge Cases and Design Decisions 1069 + 1. **Tool failure**: Return error to LLM, LLM decides next action.1070 + - `execute_with_retry` retries transients1071 + - Final error → tool_result content → LLM handles it1073 + 2. **UI-to-Engine communication**: All UI events go through an event queue.1074 + - UI emits events: abort, user_input, resize, etc.1075 + - Engine processes events from queue (non-blocking)1076 + - Example: Ctrl+C → emit Abort event → engine checks abort flag → stops current operation1078 + 3. **Streaming vs non-streaming**: Both supported.1079 + - `ProviderStream` trait: `async fn next() -> Option<ProviderEvent>`1080 + - Streaming: yields tokens as they arrive1081 + - Non-streaming: waits for complete response, yields all at once1082 + - Same trait, different implementations1083 + 4. **Thinking/reasoning**: Part of model configuration, not auto-detected.1084 + - `Model` struct has `thinking_levels: Vec<ThinkingLevel>` field1085 + - User configures which thinking levels the model supports1086 + - No runtime detection — user knows their model1087 + 5. **Context overflow**: Trim oldest entries, retry compaction until it fits.1088 + - Start with oldest non-essential entries (redundant tool outputs)1089 + - If still overflow: run compaction1090 + - If compaction fails: trim more, repeat1091 + - Only fail after N iterations (prevent infinite loop)1092 + - Never error to user — keep trying until context fits1093 + 6. **Steering/follow-up/feedback loop**: Works exactly like pi.1094 + - Steering (queue during streaming): processed immediately after current tool result1095 + - Follow-up (queue when agent would stop): processed when agent would exit1096 + - Max iterations: `max_tool_calls_per_turn: usize` (default: 100), `max_turns_per_user_message: usize` (default: 50)1098 + ### Implementation Notes 1100 + 1. **Model capabilities**: Handled via model configuration.1101 + - Each `Model` declares its supported features (thinking, vision, streaming, etc.)1102 + - No auto-detection — user configures their models1103 + - Provider decides which features to enable per-request1105 + 2. **Branching UX**: Like pi.1106 + - `/tree` shows session tree1107 + - Jump to any point, continue from there1108 + - Branches are immutable once created1110 + 3. **Graceful shutdown**: Like pi.1111 + - Signal handling for SIGTERM, SIGINT1112 + - Save session on signal, cleanup protocol1114 + 4. **Cost calculation**: Like pi.1115 + - Track input/output/cache tokens per response1116 + - Multiply by provider pricing (hardcoded per provider)1118 + 5. **Plugin secret access**: Like pi.1119 + - Plugins declare required secrets in manifest1120 + - User sets credentials in config.lua or env vars1121 + - Plugins request secrets via SDK API1123 + 6. **Tool argument validation**: Use existing crate (jsonschema).docs/spec-sm-009-harness.md Added new file mode 100644+563 / −0 text lines
1 + # SM-009: smith-harness/ — Orchestrator + Plugin SDK 3 + Create the `smith-harness/` crate that wires all components together and implements8 + Integration crate. Depends on smith/ (SM-005), smith-core/ (SM-006),9 + smith-ai/ (SM-007), and smith-tui/ (SM-008).11 + **Key insight:** The agent loop lives in smith-core (SM-006). This crate's job is:12 + 1. Wire concrete providers → StreamFn → Agent13 + 2. Load and manage Lua plugins15 + 4. Build system prompt17 + **Design docs:** `docs/PLUGIN-SDK-DESIGN.md`, `docs/PLUGIN-DOC-PLAN.md`19 + ## Key Design Decisions 21 + 1. **Agent loop is in smith-core** — this crate just wires it22 + 2. **provider_to_stream_fn** — from smith-ai, creates the StreamFn for the agent23 + 3. **Lua plugins** — SDK exposed via mlua globals24 + 4. **Unified provider API** — `smith.provider.register()` adds/overrides25 + 5. **30+ events** — AgentEvent (from smith-core) mapped to plugin SDK events26 + 6. **Sandbox** — capability-based27 + 7. **Documentation as code** — `---@` annotations are source of truth31 + ### 1. `smith-harness/Cargo.toml` 35 + name = "smith-harness"40 + smith = { path = "../smith" }41 + smith-core = { path = "../smith-core" }42 + smith-ai = { path = "../smith-ai" }43 + smith-tui = { path = "../smith-tui" }44 + mlua = { workspace = true }45 + mlua-pkg = { workspace = true }46 + tokio = { workspace = true, features = ["full"] }47 + serde = { workspace = true }48 + serde_json = { workspace = true }49 + tracing = { workspace = true }50 + thiserror = { workspace = true }58 + ├── harness.rs — Harness struct: wires provider → stream_fn → agent61 + │ ├── manager.rs — PluginManager62 + │ ├── loader.rs — LuaPluginLoader63 + │ ├── sandbox.rs — SandboxConfig64 + │ └── sdk.rs — SDK registration into Lua globals65 + ├── event_bridge.rs — Maps AgentEvent → plugin SDK events66 + ├── commands.rs — Slash command registry67 + └── help.rs — smith help command (reads embedded docs)70 + ### 3. Harness — The Wiring Layer 73 + use smith_core::agent::{Agent, AgentLoopConfig, AgentEvent};74 + use smith_ai::{Provider, provider_to_stream_fn, ModelRegistry, FileAuthResolver};75 + use smith_tui::TuiApp;80 + providers: HashMap<String , Arc<dyn Provider>>,81 + model_registry: ModelRegistry,82 + auth_resolver: FileAuthResolver,83 + plugin_manager: PluginManager,85 + active_provider: Arc<dyn Provider>, 86 + active_model_id: String,90 + pub fn new (config: Config) -> Result <Self > {102 + fn wire_provider (& self) -> Box <smith::StreamFn> {103 + provider_to_stream_fn (self.active_provider.clone ())106 + pub async fn run_interactive (&mut self) -> Result <()>;107 + pub async fn run_eval (&mut self, prompt: &str , json: bool ) -> Result <String >;108 + pub async fn run_rpc (&mut self) -> Result <()>;114 + Maps smith-core's `AgentEvent` to plugin SDK events:118 + pub enum PluginEvent {123 + MessageStart { message: Message },124 + MessageUpdate { message: Message, delta: ContentBlock },125 + MessageEnd { message: Message, usage: ProviderUsage, stop_reason: StopReason },126 + ToolExecutionStart { tool_call_id: String , tool_name: String , args: serde_json::Value },127 + ToolExecutionEnd { tool_call_id: String , tool_name: String , result: Vec <ContentBlock>, is_error: bool },128 + ToolCall { tool_call_id: String , tool_name: String , input: serde_json::Value },129 + TextDelta { delta: String },130 + ThinkingDelta { delta: String },131 + Error { message: String },135 + pub enum BlockReason {136 + BlockedByPlugin(String ),138 + PolicyViolation { capability: String , reason: String },142 + fn agent_event_to_plugin_event (event: & AgentEvent) -> Vec <PluginEvent> {144 + AgentEvent::AgentStart => vec! [PluginEvent::AgentStart],145 + AgentEvent::TurnStart { .. } => vec! [PluginEvent::TurnStart],146 + AgentEvent::MessageStart { message } => vec! [PluginEvent::MessageStart { message }],147 + AgentEvent::ToolExecutionStart { tool_call_id, tool_name, args } => {149 + PluginEvent::ToolExecutionStart { tool_call_id, tool_name, args },150 + PluginEvent::ToolCall { tool_call_id, tool_name, input: args },161 + event: & PluginEvent,162 + handlers: & HashMap<String , Vec <mlua::RegistryKey>>,164 + ) -> Result <(), BlockReason> {165 + if let PluginEvent::ToolCall { tool_call_id, tool_name, .. } = event {166 + for handler in handlers.get ("tool_call" ).unwrap_or (& vec! []) {167 + let result: Result <String , mlua::Error> = lua.call_function (handler.clone (), (tool_call_id, tool_name));168 + if let Err (e) = result {169 + return Err (BlockReason::BlockedByPlugin(e.to_string ()));178 + ### 5. SDK API (exposed to Lua) 180 + From `docs/PLUGIN-SDK-DESIGN.md`:182 + - `smith.tool.register(definition)` — registers AgentTool in tool registry183 + - `smith.on(event, handler)` — subscribes to events via event bridge184 + - `smith.command.register(name, options)` — slash commands185 + - `smith.shortcut.register(key, options)` — keyboard shortcuts186 + - `smith.provider.register(name, config)` — updates model registry187 + - `smith.provider.unregister(name)` — removes provider188 + - `smith.provider.unregister_model(provider, model_id)` — removes model189 + - `smith.tui.*` — layout + widget control190 + - `smith.fs.*` — sandboxed filesystem191 + - `smith.env.*` — read-only env access192 + - `smith.credentials.*` — credential management193 + - `smith.send_message(text, opts)` — inject messages194 + - `smith.active_tools.*` — manage tool availability195 + - `smith.request_capability(capability, options)` — request sandbox capability (Tier 1+)197 + ### 6. Built-in Plugins (Lua) 199 + - `default-layout` — center: StatusBar + VirtualScroll + Editor + HintBar200 + - `read` — file read tool201 + - `write` — file write tool202 + - `edit` — file edit tool (find-and-replace)203 + - `bash` — shell command execution204 + - `compact` — context compaction206 + ### 7. Built-in Tool Specifications 208 + All built-in tools are implemented as Lua plugins (Tier 0) using the same SDK as user plugins.215 + path = { type = "string", required = true },216 + offset = { type = "number", required = false, default = 1 },217 + limit = { type = "number", required = false },218 + read_limit = { type = "number", required = false, default = 500 },222 + -- 1. Canonicalize path → sandbox_path_check(path, 'fs_read')223 + -- 2. Read file via smith.fs.read(path)224 + -- 3. If offset/limit provided, slice lines225 + -- 4. Format as numbered lines for LLM context226 + -- 5. Return { content = lines }229 + -- ENOPATH : File not found230 + -- EISDIR : Path is a directory231 + -- EPERM : Path outside sandbox allowlist232 + -- E2BIG : File exceeds read_limit (default 500 lines); use offset/limit240 + path = { type = "string", required = true },241 + content = { type = "string", required = true },242 + create_dirs = { type = "boolean", required = false, default = true },246 + -- 1. sandbox_path_check(path, 'fs_write')247 + -- 2. If create_dirs, mkdir -p parent248 + -- 3. Write atomically (temp file + rename)249 + -- 4. Return { path = path, bytes = #content }252 + -- EPERM : Path outside sandbox write boundaries253 + -- EIO : Failed to write261 + path = { type = "string", required = true },262 + old_text = { type = "string", required = true },263 + new_text = { type = "string", required = true },264 + allow_multiple = { type = "boolean", required = false, default = false },268 + -- 1. sandbox_path_check(path, 'fs_write')270 + -- 3. Find old_text occurrences271 + -- 4. If !allow_multiple and count > 1 → fail272 + -- 5. Replace all occurrences273 + -- 6. Write back atomically274 + -- 7. Return { changes = count }277 + -- ENOTFOUND : old_text not found278 + -- EMULTIPLE : old_text found multiple times (without allow_multiple)279 + -- EPERM : Path outside sandbox287 + command = { type = "string", required = true },288 + timeout = { type = "number", required = false, default = 120 },289 + signal = { type = "string", required = false, default = "SIGTERM" },293 + -- 1. sandbox_check('subprocess')294 + -- 2. Spawn via tokio::process::Command295 + -- 3. Pipe stdout/stderr297 + -- 5. On timeout, send signal298 + -- 6. Return { stdout = ..., stderr = ..., exit_code = ..., timed_out = ... }301 + -- ETIMEDOUT : Command timed out302 + -- EPERM : Subprocess not allowed by sandbox303 + -- EIO : Failed to spawn306 + -- DEFAULT: bash requires user confirmation before execution.307 + -- smith-harness emits PluginEvent::ToolCall before bash execution.308 + -- If any event handler returns Block, the command is aborted.309 + -- User can add provider IDs to `auto_approve_bash` in ~/.smith/config.lua310 + -- to skip confirmation for trusted providers.311 + -- Default timeout: 120s. Max output: 50KB per stream (truncated with notice).312 + -- Runs in smith's CWD, inherits smith's environment.320 + threshold = { type = "number", required = false }, -- null = context_window * 0.8321 + strategy = { type = "string", required = false, default = "summarize", enum = {"summarize","truncate","drop_old"} },325 + -- 1. Estimate current tokens326 + -- 2. If below threshold → return { compacted = false }327 + -- 3. Delegate to smith-core CompactionExecutor328 + -- 4. Return { compacted = true, entries_before, entries_after, tokens_saved }331 + ### 8. Lua → Rust Plugin Bridge 333 + Four-phase loading model that converts Lua factory functions into Rust trait implementations.339 + let factory: mlua::Function = lua.load (& source).eval ()? ;340 + let sdk_collector = SdkCollector::new(); 341 + lua.globals ().set ("smith" , sdk_collector.to_table ())? ;342 + factory.call (sdk_collector.to_table ())? ;345 + #### Phase 2: Collect 348 + struct PluginRegistrations {349 + tools: Vec <LuaToolDef>,350 + events: Vec <(String, mlua::RegistryKey)>,351 + commands: Vec <LuaCommandDef>,352 + shortcuts: Vec <LuaShortcutDef>,353 + providers: Vec <LuaProviderDef>,354 + capabilities: Vec <CapabilityRequest>,355 + layout: Option <LayoutDef>,361 + #### Phase 3: Materialize 365 + pub struct LuaAgentTool {366 + definition: ToolDefinition,367 + execute_fn: mlua::RegistryKey,372 + impl AgentTool for LuaAgentTool {373 + fn definition (& self) -> ToolDefinition { self.definition.clone () }374 + fn execute (& self, tool_call_id, params, signal, on_update) -> Pin<Box <dyn Future<...>>> {391 + #### Phase 4: Register 401 + **Error handling:** If any phase fails, the entire plugin fails to load. Error is logged with plugin path + phase + detail. Other plugins continue loading.403 + ### 9. Sandbox Enforcement — Runtime Rules 405 + All enforcement is in Rust (`sdk.rs`), not Lua. Plugins have no `io`/`os`/`debug` globals.407 + #### Path Validation Algorithm 410 + 1. Canonicalize requested path (resolve symlinks, .., .)411 + 2. Check: canonical_path.starts_with(allowed_prefix) for each prefix in capability's paths list412 + 3. If any prefix matches → ALLOW413 + 4. If no prefix matches → DENY (return EPERM)414 + 5. Reject if canonicalization itself fails (broken symlink) → DENY418 + - Symlinks: resolved before check. Symlink inside sandbox pointing outside → DENY.419 + - Path traversal (`../`): canonicalized away before check.420 + - Absolute paths: checked against allowlist normally.421 + - CWD-relative: resolved against smith's working directory, then checked.423 + #### Capability Enforcement Table 425 + | Capability | Lua API | Enforcement |427 + | `fs_read` | `smith.fs.read(path)` | `path_validation(path, granted.fs_read.paths)` |428 + | `fs_write` | `smith.fs.write(path, data)` | `path_validation(path, granted.fs_write.paths)` |429 + | `fs_list` | `smith.fs.list(path)` | `path_validation(path, granted.fs_read.paths)` |430 + | `fs_glob` | `smith.fs.glob(pattern)` | All resolved matches within `fs_read` paths |431 + | `env` | `smith.env.get(name)` | Check `name` in `granted.env.vars` |432 + | `subprocess` | `bash` tool | Check `granted.subprocess == true` |433 + | `network` | *(reserved for v2)* | Check `granted.network == true` |434 + | `credentials` | `smith.credentials.get(provider)` | Check `granted.credentials == true` |436 + #### Capability Grant Flow 438 + 1. Plugin calls `smith.request_capability('fs_read', { paths = {'./src'} })`439 + 2. SDK collects request into `PluginRegistrations.capabilities`440 + 3. `PluginManager` resolves against `SandboxPolicy` (from `~/.smith/sandbox.lua`)441 + 4. Granted capabilities stored per plugin instance in `GrantedCapabilities`442 + 5. Denied capabilities cause plugin load failure (with warning + user notification)444 + #### Sandbox Policy and Granted Capabilities 451 + pub struct SandboxPolicy {452 + pub fs_read: Vec <PathBuf>,453 + pub fs_write: Vec <PathBuf>,454 + pub env: Vec <String >,456 + pub credentials: bool ,457 + pub subprocess: bool ,461 + pub struct GrantedCapabilities {462 + pub fs_read: Vec <PathBuf>,463 + pub fs_write: Vec <PathBuf>,464 + pub env: HashSet<String >,466 + pub credentials: bool ,467 + pub subprocess: bool ,471 + Default policy: `fs_read: ["./"], fs_write: ["./"], env: [], network: false, credentials: false, subprocess: false`.474 + - **Tier 0 (built-in)**: All capabilities granted automatically.475 + - **Tier 1 (trusted Lua)**: Capabilities requested, resolved against user `sandbox.lua` policy.476 + - **Tier 2 (WASM)**: Capability-gated via wasmtime. Not in v1.478 + ### 10. Built-in Plugin Load Order and Interactions 481 + 1. `read` (tool registration)482 + 2. `write` (tool registration)483 + 3. `edit` (tool registration)484 + 4. `bash` (tool registration + tool_call hook for optional confirmation)485 + 5. `compact` (tool registration)486 + 6. `default-layout` (TUI layout setup)489 + - User plugins load after built-ins.490 + - Last `smith.tool.register()` for a given name wins.491 + - Last `smith.tui.set_center_layout()` wins.492 + - Events are additive (all handlers fire).494 + Disable built-in: A user plugin can call `smith.active_tools.set({...})` excluding a built-in tool name. The tool definition won't be sent to the LLM.496 + ### 11. Documentation Files 499 + smith-harness/src/lua/sdk/500 + ├── smith_tool.lua — annotations + @usage501 + ├── smith_provider.lua502 + ├── smith_command.lua503 + ├── smith_shortcut.lua507 + ├── smith_credentials.lua510 + │ ├── getting-started.lua517 + ├── 01-hello-world.lua through 12-streaming-updates.lua522 + - Harness wires provider → StreamFn → Agent correctly523 + - Agent loop runs with real provider types (mock HTTP)524 + - Plugin loader: load Lua file, execute factory function525 + - Plugin manager: load order (built-in → global → project)526 + - SDK: register_tool creates AgentTool in registry527 + - SDK: provider.register updates model registry with merge528 + - Event bridge: AgentEvent maps to correct plugin events529 + - Sandbox: fs_read restricted to allowed paths530 + - Sandbox: path validation rejects symlink escape531 + - Sandbox: capability denied → plugin load failure532 + - LuaAgentTool: executes Lua function via RegistryKey533 + - Built-in read: returns file content with line numbers534 + - Built-in write: atomic write via temp+rename535 + - Built-in edit: exact find-and-replace, rejects ambiguous match536 + - Built-in bash: timeout, signal, output truncation537 + - Built-in compact: delegates to CompactionExecutor538 + - `smith help` reads embedded docs542 + - [ ] Create `smith-harness/Cargo.toml`543 + - [ ] Create `smith-harness/src/lib.rs`544 + - [ ] Create `smith-harness/src/harness.rs` (wiring layer)545 + - [ ] Create `smith-harness/src/event_bridge.rs`546 + - [ ] Create `smith-harness/src/plugins/` (manager, loader, sandbox, sdk)547 + - [ ] Create `smith-harness/src/plugins/builtin/` (read, write, edit, bash, compact, default-layout)548 + - [ ] Create `smith-harness/src/lua/sdk/` (all SDK annotation files)549 + - [ ] Create `smith-harness/src/lua/sdk/guides/`550 + - [ ] Create `smith-harness/src/lua/sdk/examples/` (12 examples)551 + - [ ] Create `smith-harness/src/commands.rs`552 + - [ ] Create `smith-harness/src/help.rs`553 + - [ ] Implement SDK bindings554 + - [ ] Implement Lua → Rust plugin bridge (4-phase pipeline)555 + - [ ] Implement LuaAgentTool struct556 + - [ ] Implement built-in plugins557 + - [ ] Implement sandbox enforcement (path validation, capabilities, resource limits)558 + - [ ] Implement `smith help`559 + - [ ] Implement system prompt bootstrap561 + - [ ] Verify: `cargo check -p smith-harness`562 + - [ ] Test: `cargo test -p smith-harness`563 + - [ ] Commit: `jj describe -m "feat(SM-009): smith-harness — orchestrator, plugin SDK, wiring"`