repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

fix(specs): add PluginEvent and BlockReason enums to SM-009, remove stale SessionEntry/SessionStore from SM-004

c2f5e65f57365071c9c47b5dfa5d919fdacf6c35

HallucyGenie Agent <agent@hallucygenie.local> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (2)

+1690 / −0 text lines

Diff layout

docs/spec-sm-004-architecture.md

Added
new file mode 100644

+1127 / −0 text lines

1# SM-004: smith Architecture Design
2
3## Summary
4
5Design the full application architecture for smith — a Rust coding agent TUI.
6Define module boundaries, data flow, trait hierarchies, extension points, and
7security model. Output as architecture document + skeleton Rust modules with
8doc comments and TODO stubs. No implementation beyond type definitions and
9trait declarations.
11## Context
13SM-003 established the project foundation (workspace, xtask, testing, config).
14This task designs what smith actually *is*: a fast, extensible coding
15agent with a TUI interface.
17**Inspired by pi's architecture**, but with distinct design choices:
18- Modern terminal rendering via Kitty protocol
19- Plugin system: LuaJIT only
20- LLM is the only untrusted actor
21- Everything is a plugin: tools, themes, keybindings
23## Architecture Overview
25smith is split into **6 crates**:
27| Crate | Purpose |
28|-------|---------|
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 |
36**Data flow:**
38```
39User Input → smith-cli (parse) → smith-harness (orchestrate)
40 ↓
41 ┌─────────────────┼─────────────────┐
42 ↓ ↓ ↓
43 smith-core smith-ai smith-tui
44 (session/tools) (providers) (render)
45 ↓ ↓ ↓
46 └─────────────────┼─────────────────┘
47 ↓
48 smith-harness (coordination)
49 ↓
50 smith-tui (display)
51```
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 |
67SM-004 is the **architecture narrative** — for type definitions, see the canonical specs above.
69### Core Principle: Everything is a Plugin
71smith-harness defines the plugin system. All extensibility comes through plugins:
73- `read`, `write`, `edit`, `bash` — shipped as Lua plugins in smith's built-in package
74- Themes — Lua tables defining colors/styles
75- Keybindings — Lua tables mapping keys → actions
76- Default prompts — Lua strings
77- UI layout configuration — Lua tables
79This means:
801. The plugin system is battle-tested from day one (smith depends on it)
812. Users can override ANY built-in with their own implementation
823. Iteration on tools/themes/config doesn't require recompiling Rust
834. No "second class" API — built-in and user plugins use the exact same interface
85### Configuration Language: Lua
87Lua is smith's configuration language. Rust defines the types/schemas;
88Lua provides the values:
90```lua
91-- ~/.smith/config.lua
92theme = "catppuccin"
93keybindings = {
94 ["ctrl+l"] = "cycle_model",
95 ["ctrl+c"] = "abort",
96}
97tools = { "read", "write", "edit", "bash" }
98model = "anthropic/claude-sonnet-4"
99```
101### Configuration Cascade
103Settings are resolved in layers, later layers override earlier:
105```
106Rust type definitions (schema validation)
107 ↓
108Built-in Lua defaults (shipped with smith)
109 ↓
110Plugin contributions (plugins register themes, keybindings, tools)
111 ↓
112User config (~/.smith/config.lua)
113 ↓
114CLI flags (--model, --theme, etc.)
115```
117Each layer is validated against the Rust schema. Invalid values are rejected
118with a clear error message. Unknown keys are either ignored or warned.
120### Credentials
122Credentials (API keys, tokens) read from environment variables or plain text config.
123No OS keychain integration. No encryption. Plaintext in config or environment.
125Rationale: smith runs as the same user. If an attacker can read smith's data,
126they can read the user's environment. OS keychain adds complexity without security benefit.
128```lua
129-- config.lua — credentials in plain text
130return {
131 anthropic_api_key = "sk-ant-...",
132 openai_api_key = "sk-...",
133}
134```
136Or via environment variables (preferred):
137```bash
138export ANTHROPIC_API_KEY="sk-ant-..."
139smith
140```
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\` |
150```
151data_dir/smith/
152 sessions/ ← length-prefixed CBOR-seq files
153 2026-04-20T08-30-00.session
154 2026-04-20T09-15-22.session
155 plugins/ ← installed user Lua plugins
156 data/ ← plugin persistent state (per-plugin)
158cache_dir/smith/
159 bytecode/ ← compiled LuaJIT bytecode with source hash headers
161config_dir/smith/
162 config.lua ← user configuration
163 themes/ ← user theme overrides
164 keybindings/ ← user keybinding overrides
165```
167**Session format**: Length-prefixed CBOR-seq (RFC 8949 entries with u32 BE length prefix).
169File structure:
170```
171┌────────────┬──────────────────┬────────────┬──────────────────┐
172│ u32 BE len │ CBOR entry bytes │ u32 BE len │ CBOR entry bytes │
173└────────────┴──────────────────┴────────────┴──────────────────┘
174```
176Session entries use a typed envelope + CBOR payload:
177**Session entries** (CBOR-encoded, length-prefixed):
179```rust
180// Envelope — every entry has this structure
181struct SessionEntry {
182 type_: String, // "user", "assistant", "tool_call", "secret_register", "compaction"
183 id: String, // unique entry ID
184 timestamp: u64,
185 payload: Vec<u8>, // inner CBOR — decoded by type
186}
188// Payload types
189struct UserPayload { content: Vec<ContentBlock> }
190struct AssistantPayload { content: Vec<ContentBlock>, usage: ProviderUsage }
191struct ToolCallPayload { tool: String, args: String }
192struct SecretRegisterPayload { id: String, value: String, source: String }
193struct CompactionPayload { summary: String, prev_ids: Vec<String> }
194```
196**Secret proxy**: Translation table is stored as `secret_register` session entries.
197Session resume builds the table by scanning backward from the end, collecting the
198most recent registration for each `smith:sec:N` ID. History is self-describing —
199any point in the session can be fully restored.
201Compaction rolls up old entries into a `compaction` entry that preserves the
202secret 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, reader
206 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.
215```
216smith session dump # latest session as JSONL
217smith session dump <session-id> # specific session
218smith session dump --last 5 # last 5 entries
219smith session dump --output out.jsonl # write to file
220smith session list # list all sessions
221```
223**Session migration**: Session format versions. Migrate on load.
224```rust
225pub const CURRENT_SESSION_VERSION: u32 = 1;
227fn migrate_entries(entries: &mut Vec<SessionEntry>) {
228 let version = entries.first()
229 .and_then(|e| match e {
230 SessionEntry::Session { version, .. } => Some(*version),
231 _ => None,
232 })
233 .unwrap_or(1);
234
235 if version < 1 { migrate_v0_to_v1(entries); }
236 // Future: if version < 2 { migrate_v1_to_v2(entries); }
237}
238```
240## Crate: smith (Shared Library)
242Shared types and utilities. No business logic.
244### Responsibilities
245- Common types (EntryId, SessionId, Message, ContentBlock, Role, etc.)
246- Lua runtime setup (mlua, mlua-pkg)
247- Config resolution from Lua files
248- Error types (smith Error)
250### Key Types
252Types are defined in **SM-005** (`smith/` shared library). This crate re-exports
253`smith_core::SessionEntry`, `smith_core::Session`, etc. See SM-005 §types.rs,
254§config.rs, §lua.rs, and §error.rs for canonical definitions.
256```rust
257// Re-exported from smith-core
258pub use smith_core::{EntryId, SessionId, Session, SessionEntry, Message, ContentBlock, Role};
259```
261## Crate: smith-core
263Pure business logic. No I/O, no side effects. Session management, tools, hooks.
265### Responsibilities
266- Session management (tree, entries, compaction)
267- Session format (CBOR encode/decode)
268- Tool registry and execution
269- Hook types and registration
270- Secret proxy
271- System prompt building
272- Engine event types
274### Key Types
276```rust
277/// Session: conversation with an LLM
278pub struct Session {
279 pub id: SessionId,
280 pub name: Option<String>,
281 pub cwd: PathBuf,
282 pub entries: Vec<SessionEntry>,
283 pub current_leaf: EntryId,
284 pub created: u64,
285 pub updated: u64,
286}
288/// SessionEntry, SessionStore, AgentEvent, and EngineEvent are defined in
289/// **SM-006** (`smith-core/`). See SM-006 §session.rs, §session_format.rs,
290/// §agent.rs, and §events.rs for canonical definitions.
292/// Tool trait — canonical definition is `AgentTool` (async) in **SM-005** §tool.rs.
293/// The tool registry uses `Arc<dyn AgentTool>`. See SM-006 §tools.rs.
295/// Event bus — replaced by `mpsc::UnboundedSender<AgentEvent>`. See SM-006 §agent.rs.
297/// Events are split into two layers:
298/// - **AgentEvent** (source of truth, emitted by the agent loop) — defined in **SM-006** §agent.rs.
299/// - **EngineEvent** (harness-level wrapper with session/steering events) — defined in **SM-006** §events.rs.
300/// See SM-009 §event_bridge.rs for the mapping to plugin SDK events.
302/// Secret proxy
303pub trait SecretProxy: Send + Sync {
304 fn register(&mut self, secret: String) -> SecretId;
305 fn resolve(&self, id: &SecretId) -> Option<&str>;
306}
307```
309### Extension Points
310- Add new `SessionEntry` variants
311- Add new `EngineEvent` variants
312- Custom `Tool` implementations
314## Crate: smith-ai
316LLM provider layer. Preconfigured providers + config-driven models.
318### Responsibilities
319- Provider trait (streaming responses, tool calling)
320- Preconfigured providers (Anthropic, OpenAI, Google, local)
321- Model registry and resolution
322- API calls and streaming
323- Reads Lua config for provider/model settings
325### Key Types
327Provider trait, streaming types, model registry, and auth are defined in
328**SM-007** (`smith-ai/`). Shared streaming types (`ProviderEvent`, `ProviderRequest`)
329live in **SM-005** §types.rs to enable parallel builds.
331Provider implementations: AnthropicProvider, OpenAIProvider, GoogleProvider,
332OpenAICompatProvider. See also `docs/AI-CRATE-DESIGN.md`.
334```rust
335// Re-exported from smith (shared types)
336pub use smith::{ProviderEvent, ProviderRequest, ProviderUsage, StopReason};
337```
339## Crate: smith-tui
341Terminal rendering. Widgets, themes, keybindings. Receives events from harness.
343### Responsibilities
344- Render UI based on engine state
345- Send UI events (input, resize, abort) to harness
346- Widgets (message list, input area, status bar)
347- Theme system
348- Keybinding handling
350```
351Main Thread (Engine) UI Thread (Rendering)
352 │ │
353 ├─state_tx───►[TuiState]──────────────┤ (what to render)
354 │ │
355 │◄──input_rx───[user input]───────────┤ (what to do)
356 │ │
357 ├─EngineEvent: ThinkingStarted ───────►│
358 ├─EngineEvent: TokenDelta ─────────────►│
359 ├─EngineEvent: ToolCall ───────────────►│
360 ├─EngineEvent: ToolResult ─────────────►│
361 └─EngineEvent: Error ───────────────────►│
363Tool Thread (Execution)
364 │
365 ├─tool_rx──►Engine (results)
366```
368Engine event loop (never blocks on UI):
369```rust
370loop {
371 select! {
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(),
375 }
376}
377```
379### TUI State Machine
381Every state is interruptible by the user (Ctrl+C → abort flag).
383```rust
384pub enum TuiState {
385 Idle, // waiting for input, blinking cursor
386 Thinking, // LLM processing, spinner, input locked
387 ToolRunning, // tool executing, can cancel
388 ToolResult, // showing tool output, input unlocked
389 Error, // error displayed, input unlocked
390 Exiting, // terminal restore, cleanup
391}
392// Note: Security confirmations are not in core — tools are either exposed or not via config.
393```
395### Layout
397```
398┌─────────────────────────────────────────────────────────┐
399│ [ctx: 45k/200k] [$0.23] [session: foo] [claude-sonnet-4]│ ← status bar
400├─────────────────────────────────────────────────────────┤
401│ User: Read the Cargo.toml │
402│ Assistant: [tool: read("Cargo.toml")] │ ← message history
403│ Tool: [expanded inline or collapsed] │ (virtual scroll)
404│ │
405├─────────────────────────────────────────────────────────┤
406│ > cargo run -- --help │ ← input area
407│ [Enter: send] [Ctrl+C: abort] [Ctrl+L: model] │ ← hint bar
408└─────────────────────────────────────────────────────────┘
409```
411**Status bar**: No smith name/version. Shows:
412- `ctx: X/Y` — current context usage / max
413- `$N.NN` — running cost estimate (updated in real time)
414- `session: name` — current session
415- `model: name` — active model
417**Message history**: Virtual scrolling. `sticky_bottom` flag:
418- `true` (default): new messages auto-scroll to bottom
419- `false` (user scrolled up): stay in place until user scrolls back or submits
421**Input area**: Custom `InputArea` widget on ratatui. Not reedline — reedline
422owns inline rendering which conflicts with ratatui managing the whole screen.
423Built with ratatui primitives + crossterm cursor. Single-line by default,
424multiline when content wraps. Arrow keys navigate. Ctrl+C cancels.
426**Hint bar**: Keyboard shortcuts for current state. Updates dynamically.
428### Rendering: ratatui + crossterm
430ratatui handles widgets, layout, TestBackend for snapshots.
431crossterm handles terminal I/O, cursor, Kitty keyboard protocol flags.
433```rust
434// Kitty keyboard flags via crossterm
435use crossterm::event::{KeyboardEnhancementFlags, DisableBracketedPaste};
437terminal.push_event_filter(KeyboardEnhancementFlags::DisambiguateEscapeCodes);
438terminal.push_event_filter(KeyboardEnhancementFlags::ReportEventTypes);
439```
441Custom `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 v1
446ratatui `TestBackend` enables snapshot testing:
447```rust
448#[test]
449fn 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());
454}
455```
457### Theme System
459Themes defined in config.lua, not separate files:
461```lua
462return {
463 theme = {
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" },
471 },
472}
473```
475Rust defines the theme schema (validates keys and color formats). Lua provides values.
476No `themes/` directory — themes live in config.lua.
478### Deferred (v1 scope)
480- Vim-style normal mode editing
481- Multiline input with explicit newline insertion
482- Inline image rendering (Kitty graphics)
483- Fuzzy history search
484- Split panes / tabs
485- Multiple simultaneous sessions
487## Crate: smith-harness
489Orchestrator + plugin system. Owns the event loop, coordinates all crates.
491### Responsibilities
492- Plugin loading (LuaJIT via mlua)
493- Plugin SDK (sandboxing, credential access)
494- Event loop (engine owns it)
495- Coordinates core + ai + tui
496- Receives UI events, dispatches to engine
498### Key Types
500```rust
501pub struct Harness {
502 pub core: CoreEngine,
503 pub ai: AiLayer,
504 pub tui: TuiBridge,
505 pub plugins: PluginManager,
506}
508pub struct PluginManager {
509 lua: LuaRuntime,
510 plugins: Vec<LoadedPlugin>,
511}
513pub struct PluginSdk {
514 // smith.fs.*, smith.env.*, smith.credentials.*
515}
516```
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:
524```lua
525smith.fs.read("path") -- read file (enforced: scoped to project dirs)
526smith.fs.write("path", data) -- write file (enforced: scoped to project dirs)
527smith.env.get("HOME") -- read-only env access
528smith.time.now() -- safe timestamp
529```
531Path restrictions are enforced by the SDK (Rust), not by plugins. Plugins only have
532access through `smith.fs.*`. They cannot bypass restrictions because they have no
533raw filesystem API. The SDK enforces: reads/writes are scoped to smith's working
534directory or explicitly allowed paths. Plugins are Lua (untrusted), SDK is Rust
535(trusted).
537**Custom require** via `mlua-pkg` crate — composable resolver chain:
538- `NativeResolver` — smith's Rust API surface to plugins
539- `FsResolver` — scoped to plugin's own directory only
540- `MemoryResolver` — embedded modules smith provides
541- Plugins can be multi-file with nested directories
543**Bytecode caching**: Smith compiles `.lua` → bytecode on first load, caches
544by source hash. Smith never loads bytecode it didn't compile itself. No signing
545needed — trust is in the source, cache is just a performance optimization.
549### OCaml-Style Interface Modules
551In OCaml, a library exposes a module signature (.mli) that others implement.
552In smith, a plugin can declare it implements one or more **interfaces**:
554```rust
555/// Interface that plugins can optionally implement.
556/// Each interface corresponds to an extension point in smith.
557pub trait PluginInterface: Send + Sync {
558 /// Unique interface name (e.g., "tool", "widget")
559 fn interface_name(&self) -> &str;
560}
562/// A plugin can implement multiple interfaces
563pub trait Plugin: Send + Sync {
564 /// Plugin metadata
565 fn metadata(&self) -> PluginMetadata;
566 /// Return interfaces this plugin implements
567 fn interfaces(&self) -> Vec<Box<dyn PluginInterface>>;
568}
570/// Tool interface — plugin provides a tool for the LLM
571pub trait ToolInterface: PluginInterface {
572 /// Returns the tool implementation. Canonical trait: `AgentTool` (SM-005 §tool.rs).
573 fn tool(&self) -> Box<dyn AgentTool>;
574}
576/// Widget interface — plugin provides a TUI widget
577pub trait WidgetInterface: PluginInterface {
578 fn widget(&self) -> Box<dyn Widget>;
579}
581/// Hook interface — plugin subscribes to engine events
582pub trait HookInterface: PluginInterface {
583 fn hooks(&self) -> Vec<HookRegistration>;
584}
585```
587### Plugin Loading
589```rust
590/// Plugin loader — discovers and instantiates plugins
591pub trait PluginLoader {
592 /// Load a plugin from the given path
593 fn load(&self, path: &Path) -> Result<Box<dyn Plugin>>;
594 /// List available plugin interfaces
595 fn available_interfaces(&self) -> &[InterfaceDescriptor];
596}
598/// Lua plugin loader (uses mlua with LuaJIT + mlua-pkg for custom require)
599pub struct LuaPluginLoader { /* TODO */ }
601// SandboxConfig and Capability are defined canonically in SM-005 (smith/src/config.rs).
602```
604### Extension Points
605- New interface types (add to `PluginInterface` hierarchy)
606- New plugin loaders (e.g., native Rust `.so` plugins)
607- Sandbox policies
608- Plugin-to-plugin communication
610## Crate: smith-cli
612Binary entry point. Parses args, creates harness, runs it.
614```rust
615pub struct CliArgs { /* clap derive */ }
617pub struct AppConfig {
618 pub mode: AppMode,
619 pub provider: ProviderConfig,
620 pub model: ModelSelection,
621 pub session: SessionSelection,
622 pub tools: ToolSelection,
623 pub ui: UiConfig,
624}
626pub enum AppMode {
627 Interactive,
628 Print { prompt: String },
629 Json,
630 Rpc,
631}
633pub fn main() -> Result<()> {
634 let args = CliArgs::parse();
635 let config = resolve_config(args)?;
636 let mut harness = Harness::new(config)?;
637 harness.run()
638}
639```
641## Security Model
643The LLM is the **only untrusted actor**. Everything else is trusted.
645**Trusted** (inside boundary):
646- User's machine, OS, filesystem
647- User running smith
648- Plugins (user verified source before installing)
649- Smith itself
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 provider
656**What this means in practice:**
657- Session files: plaintext CBOR-seq, no encryption
658- Secret proxy translation table: merged into session entries, plaintext
659- API keys: read from environment variables or plain text config, smith passes them to tools
660- No OS keychain integration — credentials stay in env/config
661- Smith focuses security effort on **bounding LLM capabilities**, not encrypting local data
663**LLM bounding mechanisms:**
6641. Tool registry: smith controls which tools the LLM sees — not all tools are exposed
6652. Secret proxy: LLM sees `smith:sec:N` identifiers, never real secrets
6663. SDK path restrictions: plugins access filesystem only through `smith.fs.*` (Rust),
667 which enforces scoping. Plugins have no raw filesystem API and cannot bypass.
669Security is **configuration**, not confirmation dialogs. Users configure which tools
670are 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 LLM
675- When LLM makes a tool call, arguments scanned for identifiers and rehydrated
676- Translation table: stored as session entries, restored on session resume
678Secret registration entries:
679```rust
680// Stored as session entries, not separate file
681struct SecretRegisterEntry {
682 id: String, // "smith:sec:1"
683 value: String, // actual secret (plaintext in session)
684 source: String, // "env:SMITH_API_KEY", "manual"
685 timestamp: u64,
686}
687```
689Session resume builds translation table by scanning backward for most recent
690`secret_register` entry per ID. History is always restorable.
692## Concurrency Model
694Three threads. The engine (main thread) drives the event loop. The UI thread is
695purely reactive and must never stall user input.
697```
698Main Thread (Engine) UI Thread Tool Thread
699(owns the event loop) (rendering) (execution)
700 │ │ │
701 ├─state_tx──────────────►│ (TuiState updates) │
702 │◄──input_rx─────────────┤ (user input) │
703 │ │ │
704 │ LLM streaming ─────────┼── EngineEvent ────────►│
705 │ │ ├─tool_rx──►Engine
706 │ config resolution ├─snapshot capture │ tool execution
707 │ session management │ │ subprocess
708 │ state machine │ │ file I/O
709```
711- **Engine (main thread)**: Owns the event loop. Receives user input via
712 `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 input
715 to engine via `input_tx`. Never calls the engine directly. Never blocks
716 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.
721The engine loop uses non-blocking channel receives. If no input is available,
722the loop proceeds without waiting. The UI thread is always responsive.
724**Every state is interruptible**: Ctrl+C sets an abort flag. The current
725operation checks the flag and bails cleanly. No state is a dead end.
727**Async boundary**: `tokio` is scoped to the **provider layer** (smith-ai)
728and **agent loop** (smith-core). Tool execution and TUI rendering remain
729sync/single-threaded on their respective threads. The engine main thread uses
730`tokio::select!` for non-blocking channel receives. See SM-005 (tokio sync),
731SM-006 (tokio rt+sync), and SM-007 (tokio full) for crate-specific async usage.
733## Error Handling Strategy
735Two-tier error model:
737```rust
738/// Recoverable errors — canonical definition in SM-005 §8 (`smith/src/error.rs`).
739pub enum SmithError {
740 Provider(ProviderError),
741 Auth(AuthError),
742 Tool(ToolError),
743 Plugin { plugin: String, message: String },
744 Session(std::io::Error),
745 Config(String),
746 Lua(mlua::Error),
747 Io(std::io::Error),
748 Cbor(minicbor::decode::Error),
749}
750```
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 failure
755/// Used for: invariant violations, impossible states, programmer errors
756/// These are NOT caught — they indicate bugs.
757///
758/// assert!(entries.len() <= MAX_ENTRIES);
759/// assert_eq!(state.current_turn, expected_turn);
760```
762Rule of thumb:
763- External failures (network, disk, LLM, plugins) → `Result<_, SmithError>`
764- Internal invariants (state machine consistency, bounds) → `assert!`
765- Never use `unwrap()`/`expect()` — clippy denies them
767## Example Plugin
769A concrete example of what a real smith plugin looks like. This informs the
770architecture — every trait and type must support this use case:
772```lua
773-- built-in/tools/read.lua
774-- One of smith's built-in tools — implements the "read" tool for the LLM
775-- Uses the same plugin API as any user plugin
777local smith = require("smith")
779return {
780 name = "read",
781 version = smith.version,
782 description = "Read file contents",
784 interfaces = {
785 tool = true,
786 },
788 tool = {
789 name = "read",
790 description = "Read file contents. Supports offset/limit for large files.",
791 parameters = {
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 },
795 },
796 execute = function(params)
797 -- smith.fs.* is the safe, sandboxed file API
798 local content = smith.fs.read(params.path)
799 if params.offset then
800 content = smith.string.lines(content, params.offset, params.limit)
801 end
802 return { content = content }
803 end,
804 },
805}
806```
808And a user plugin for comparison:
810```lua
811-- ~/.smith/plugins/my_search/init.lua
812-- User plugin — semantic code search
814local smith = require("smith")
816return {
817 name = "my_search",
818 version = "0.1.0",
820 interfaces = {
821 tool = true,
822 hook = true,
823 },
825 tool = {
826 name = "search",
827 description = "Search the codebase",
828 parameters = {
829 query = { type = "string", description = "Search query" },
830 },
831 execute = function(params)
832 local files = smith.fs.list_dir("src")
833 -- ... search logic ...
834 return { results = results }
835 end,
836 },
838 hooks = {
839 on_session_start = function(event)
840 smith.log("info", "Search plugin loaded")
841 end,
842 },
843}
844```
846Both use the same API. Built-in tools have no special privileges.
848## Novel Tool Research
850Traditional coding agents expose: `read`, `write`, `edit`, `bash`.
851Smith wants to explore richer tool primitives. Architecturally, the `AgentTool`
852trait (SM-005 §tool.rs) and `PluginInterface` system support this — any research
853into novel tools just implements the `AgentTool` trait.
855Ideas to explore (not implement now, just design space):
856- Structured editing (AST-aware, not text-based)
857- Semantic search over codebase
858- Execution tracing / debugging tools
859- Multi-file refactoring primitives
860- Test generation and mutation tools
862## Dependency Decisions
864### Workspace Crates
866```
867smith/ — shared library (types, Lua runtime, config)
868smith-core/ — pure business logic (session, tools, hooks)
869smith-ai/ — LLM providers (preconfigured + config-driven)
870smith-tui/ — terminal rendering (widgets, themes)
871smith-harness/ — orchestrator + plugins (event loop, SDK)
872smith-cli/ — binary entry point
873xtask/ — build subcrate (check, test, lint)
874```
876### Production Dependencies
878| Crate | Purpose |
879|-------|---------|
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 |
897### Dev Dependencies
899| Crate | Purpose |
900|-------|---------|
901| `insta` | Snapshot testing |
902| `assert_cmd` | CLI integration tests |
904### Deferred
906| Item | Decision |
907|------|----------|
908| Kitty graphics (sixel/kitty-ki) | v1: text only. v2: evaluate crate |
911## Deliverables
913### 1. Architecture Document
915Create `docs/ARCHITECTURE.md` — the authoritative architecture reference:
916- Module overview with responsibilities
917- Data flow diagram (text-based)
918- Trait hierarchy for each module
919- Extension point catalog
920- Security model layers
921- Plugin system design (interfaces, loading, sandboxing)
922- Dependency decisions with rationale
923- Open research questions
925### 2. Skeleton Modules
927Create Rust files with doc comments, type definitions, trait declarations, and
928`todo!()` stubs. **No implementation** — just the shape:
930```
931src/
932 lib.rs
933 engine/
934 mod.rs — module root, re-exports
935 provider.rs — Provider trait, ProviderStream, ProviderEvent, Message, ContentBlock
936 session.rs — Session, SessionEntry (typed envelope + CBOR payload), SessionStore trait
937 session_format.rs — Length-prefixed CBOR-seq read/write, fault-tolerant parser
938 tools.rs — Tool trait, ToolDefinition, ToolInput/Output
939 events.rs — EngineEvent enum, EventBus trait
940 error.rs — SmithError enum (two-tier: recoverable vs asserted)
941 config.rs — ConfigResolver, ConfigCascade, ConfigSource
942 credentials.rs — CredentialReader trait (env vars + config)
943 secret_proxy.rs — Secret detection, identifier substitution, translation table
944 engine.rs — Engine struct, agent loop, 3-thread concurrency
945 compaction.rs — Token estimation, cut points, summarization, compaction
946 tool_exec.rs — Tool execution modes, retry policy, sequential/parallel
947 system_prompt.rs — System prompt construction from components
948 commands.rs — Slash commands, CommandHandler trait
949 hooks.rs — Extension hooks, HookRegistration, ExtensionRunner
950 /// ============================================================================
951 /// AGENT LOOP
952 /// ============================================================================
953 /// Based on pi's agent-loop design. Simple event-driven loop with two nested loops:
954 /// - Outer loop: handles tool calls + pending messages
955 /// - Inner loop: streams LLM response
956 ///
957 /// 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)
961 ///
962 /// The loop NEVER blocks on UI. Input is delivered via channel.
963 ///
964 /// Start a new turn:
965 /// agent_loop_add_prompt(prompts, context, config, signal, emit)
966 ///
967 /// Continue without adding prompt (for retry):
968 /// agent_loop_continue(context, config, signal, emit)
969 ///
970 /// Main loop structure:
971 /// loop {
972 /// // Inner: process tool calls and steering
973 /// while has_tool_calls || has_pending {
974 /// // Emit turn start
975 /// // Process pending steering messages
976 /// // Stream assistant response
977 /// // Execute tool calls (sequential or parallel)
978 /// // Collect results
979 /// // Check for more steering
980 /// }
981 /// // Check if agent would stop
982 /// if has_followup_messages {
983 /// // Continue with follow-ups (sets pending, goes back to inner loop)
984 /// continue;
985 /// }
986 /// // No more messages, exit
987 /// break;
988 /// }
989 ///
990 /// Tool execution:
991 /// - Sequential: execute one at a time, feed results back
992 /// - Parallel: execute independent tools simultaneously
993 /// - Before/after hooks via ExtensionRunner
994 ///
995 /// Error handling:
996 /// - Tool errors: retry with backoff, or return error to LLM
997 /// - LLM errors: abort, emit error event
998 /// - User abort (Ctrl+C): set abort flag, current operation checks flag and bails
999 interface/
1000 mod.rs — module root, re-exports
1001 cli.rs — CliArgs, clap derive
1002 config.rs — AppConfig, resolve_config()
1003 tui/
1004 mod.rs — module root, re-exports
1005 backend.rs — TerminalBackend trait, TerminalCapabilities
1006 app.rs — TuiState, TuiEvent, run_tui()
1007 widget.rs — Widget trait
1008 theme.rs — Theme types (schema — values come from Lua)
1009 keybinding.rs — Keybinding types (schema — values come from Lua)
1010 plugins/
1011 mod.rs — module root, re-exports
1012 interface.rs — PluginInterface, Plugin, ToolInterface, WidgetInterface, etc.
1013 loader.rs — PluginLoader trait, LuaPluginLoader
1014 sandbox.rs — SandboxConfig, Capability, bytecode caching
1015 sdk.rs — smith.* Lua module definition (what plugins can call)
1016built-in/ — Lua plugins shipped with smith (NOT in src/)
1017 tools/
1018 read.lua — read tool implementation
1019 write.lua — write tool implementation
1020 edit.lua — edit tool implementation
1021 bash.lua — bash tool implementation
1022 keybindings/
1023 default.lua — default keybindings
1024 config.lua — default configuration (includes theme values)
1025```
1027### 3. Tests
1029Every skeleton file must compile. Write **test stubs** that document the
1030intended test behavior with `todo!()`:
1032```rust
1033#[cfg(test)]
1034mod tests {
1035 use super::*;
1037 #[test]
1038 fn provider_completes_with_streaming_response() {
1039 todo!("mock provider, send request, verify streaming events");
1040 }
1042```
1044These stubs serve as the test plan. Future tasks fill them in via TDD.
1046### 4. Update CONTEXT.md
1048Add architecture section to `docs/CONTEXT.md`:
1049- Module overview
1050- Key traits and their relationships
1051- Where to add new functionality (extension points)
1053## Steps
1055- [ ] Step 1: Create `docs/ARCHITECTURE.md` — full architecture document
1056- [ ] Step 2: Create `src/engine/` — trait definitions and type stubs
1057- [ ] Step 3: Create `src/interface/` — config types and CLI skeleton
1058- [ ] Step 4: Create `src/tui/` — backend trait, app state, widget trait
1059- [ ] Step 5: Create `src/plugins/` — interface module hierarchy, loader traits
1060- [ ] Step 6: Create `src/lib.rs` — re-export all modules
1061- [ ] 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 warnings
1064- [ ] Step 10: Update `docs/CONTEXT.md` with architecture section
1065- [ ] Step 11: Commit with `jj describe -m "arch(SM-004): smith architecture design — engine, interface, tui, plugins"
1067### Edge Cases and Design Decisions
10691. **Tool failure**: Return error to LLM, LLM decides next action.
1070 - `execute_with_retry` retries transients
1071 - Final error → tool_result content → LLM handles it
10732. **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 operation
10783. **Streaming vs non-streaming**: Both supported.
1079 - `ProviderStream` trait: `async fn next() -> Option<ProviderEvent>`
1080 - Streaming: yields tokens as they arrive
1081 - Non-streaming: waits for complete response, yields all at once
1082 - Same trait, different implementations
10834. **Thinking/reasoning**: Part of model configuration, not auto-detected.
1084 - `Model` struct has `thinking_levels: Vec<ThinkingLevel>` field
1085 - User configures which thinking levels the model supports
1086 - No runtime detection — user knows their model
10875. **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 compaction
1090 - If compaction fails: trim more, repeat
1091 - Only fail after N iterations (prevent infinite loop)
1092 - Never error to user — keep trying until context fits
10936. **Steering/follow-up/feedback loop**: Works exactly like pi.
1094 - Steering (queue during streaming): processed immediately after current tool result
1095 - Follow-up (queue when agent would stop): processed when agent would exit
1096 - Max iterations: `max_tool_calls_per_turn: usize` (default: 100), `max_turns_per_user_message: usize` (default: 50)
1098### Implementation Notes
11001. **Model capabilities**: Handled via model configuration.
1101 - Each `Model` declares its supported features (thinking, vision, streaming, etc.)
1102 - No auto-detection — user configures their models
1103 - Provider decides which features to enable per-request
11052. **Branching UX**: Like pi.
1106 - `/tree` shows session tree
1107 - Jump to any point, continue from there
1108 - Branches are immutable once created
11103. **Graceful shutdown**: Like pi.
1111 - Signal handling for SIGTERM, SIGINT
1112 - Save session on signal, cleanup protocol
11144. **Cost calculation**: Like pi.
1115 - Track input/output/cache tokens per response
1116 - Multiply by provider pricing (hardcoded per provider)
11185. **Plugin secret access**: Like pi.
1119 - Plugins declare required secrets in manifest
1120 - User sets credentials in config.lua or env vars
1121 - Plugins request secrets via SDK API
11236. **Tool argument validation**: Use existing crate (jsonschema).
1125## Out of Scope

docs/spec-sm-009-harness.md

Added
new file mode 100644

+563 / −0 text lines

1# SM-009: smith-harness/ — Orchestrator + Plugin SDK
2
3Create the `smith-harness/` crate that wires all components together and implements
4the Lua plugin system.
5
6## Context
7
8Integration crate. Depends on smith/ (SM-005), smith-core/ (SM-006),
9smith-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:
121. Wire concrete providers → StreamFn → Agent
132. Load and manage Lua plugins
143. Expose SDK to Lua
154. Build system prompt
17**Design docs:** `docs/PLUGIN-SDK-DESIGN.md`, `docs/PLUGIN-DOC-PLAN.md`
19## Key Design Decisions
211. **Agent loop is in smith-core** — this crate just wires it
222. **provider_to_stream_fn** — from smith-ai, creates the StreamFn for the agent
233. **Lua plugins** — SDK exposed via mlua globals
244. **Unified provider API** — `smith.provider.register()` adds/overrides
255. **30+ events** — AgentEvent (from smith-core) mapped to plugin SDK events
266. **Sandbox** — capability-based
277. **Documentation as code** — `---@` annotations are source of truth
29## Deliverables
31### 1. `smith-harness/Cargo.toml`
33```toml
34[package]
35name = "smith-harness"
36version = "0.1.0"
37edition = "2024"
39[dependencies]
40smith = { path = "../smith" }
41smith-core = { path = "../smith-core" }
42smith-ai = { path = "../smith-ai" }
43smith-tui = { path = "../smith-tui" }
44mlua = { workspace = true }
45mlua-pkg = { workspace = true }
46tokio = { workspace = true, features = ["full"] }
47serde = { workspace = true }
48serde_json = { workspace = true }
49tracing = { workspace = true }
50thiserror = { workspace = true }
51```
53### 2. Core Structure
55```
56smith-harness/src/
57├── lib.rs
58├── harness.rs — Harness struct: wires provider → stream_fn → agent
59├── plugins/
60│ ├── mod.rs
61│ ├── manager.rs — PluginManager
62│ ├── loader.rs — LuaPluginLoader
63│ ├── sandbox.rs — SandboxConfig
64│ └── sdk.rs — SDK registration into Lua globals
65├── event_bridge.rs — Maps AgentEvent → plugin SDK events
66├── commands.rs — Slash command registry
67└── help.rs — smith help command (reads embedded docs)
68```
70### 3. Harness — The Wiring Layer
72```rust
73use smith_core::agent::{Agent, AgentLoopConfig, AgentEvent};
74use smith_ai::{Provider, provider_to_stream_fn, ModelRegistry, FileAuthResolver};
75use smith_tui::TuiApp;
76use std::sync::Arc;
78pub struct Harness {
79 agent: Agent,
80 providers: HashMap<String, Arc<dyn Provider>>,
81 model_registry: ModelRegistry,
82 auth_resolver: FileAuthResolver,
83 plugin_manager: PluginManager,
84 tui: Option<TuiApp>,
85 active_provider: Arc<dyn Provider>, // Provider: Send + Sync (see SM-007 §2)
86 active_model_id: String,
87}
89impl Harness {
90 pub fn new(config: Config) -> Result<Self> {
91 // 1. Load model registry from embedded JSON
92 // 2. Load auth resolver
93 // 3. Create providers from registry
94 // 4. Select active provider + model
95 // 5. Create StreamFn from active provider
96 // 6. Create Agent with StreamFn
97 // 7. Load plugins
98 // 8. Register SDK into Lua
99 }
101 /// Wire the active provider into a StreamFn for the agent
102 fn wire_provider(&self) -> Box<smith::StreamFn> {
103 provider_to_stream_fn(self.active_provider.clone())
104 }
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<()>;
109}
110```
112### 4. Event Bridge
114Maps smith-core's `AgentEvent` to plugin SDK events:
116```rust
117/// Events emitted to Lua plugins via the EventBridge.
118pub enum PluginEvent {
119 AgentStart,
120 AgentEnd,
121 TurnStart,
122 TurnEnd,
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 },
132}
134/// Reason a tool call was blocked by an event handler.
135pub enum BlockReason {
136 BlockedByPlugin(String),
137 UserDenied,
138 PolicyViolation { capability: String, reason: String },
139}
141impl EventBridge {
142 fn agent_event_to_plugin_event(event: &AgentEvent) -> Vec<PluginEvent> {
143 match event {
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 } => {
148 vec![
149 PluginEvent::ToolExecutionStart { tool_call_id, tool_name, args },
150 PluginEvent::ToolCall { tool_call_id, tool_name, input: args },
151 ]
152 }
153 // ... etc
154 }
155 }
157 /// Dispatches events to registered handlers. For ToolCall events, checks
158 /// whether any handler returns Err(BlockReason) and aborts the tool if so.
159 fn dispatch_event(
160 &self,
161 event: &PluginEvent,
162 handlers: &HashMap<String, Vec<mlua::RegistryKey>>,
163 lua: &Lua,
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()));
170 }
171 }
172 }
173 Ok(())
174 }
175}
176```
178### 5. SDK API (exposed to Lua)
180From `docs/PLUGIN-SDK-DESIGN.md`:
182- `smith.tool.register(definition)` — registers AgentTool in tool registry
183- `smith.on(event, handler)` — subscribes to events via event bridge
184- `smith.command.register(name, options)` — slash commands
185- `smith.shortcut.register(key, options)` — keyboard shortcuts
186- `smith.provider.register(name, config)` — updates model registry
187- `smith.provider.unregister(name)` — removes provider
188- `smith.provider.unregister_model(provider, model_id)` — removes model
189- `smith.tui.*` — layout + widget control
190- `smith.fs.*` — sandboxed filesystem
191- `smith.env.*` — read-only env access
192- `smith.credentials.*` — credential management
193- `smith.send_message(text, opts)` — inject messages
194- `smith.active_tools.*` — manage tool availability
195- `smith.request_capability(capability, options)` — request sandbox capability (Tier 1+)
197### 6. Built-in Plugins (Lua)
199- `default-layout` — center: StatusBar + VirtualScroll + Editor + HintBar
200- `read` — file read tool
201- `write` — file write tool
202- `edit` — file edit tool (find-and-replace)
203- `bash` — shell command execution
204- `compact` — context compaction
206### 7. Built-in Tool Specifications
208All built-in tools are implemented as Lua plugins (Tier 0) using the same SDK as user plugins.
210#### 7.1 `read`
212```lua
213-- parameters
214{
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 },
219}
221-- execute
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 lines
225-- 4. Format as numbered lines for LLM context
226-- 5. Return { content = lines }
228-- errors
229-- ENOPATH : File not found
230-- EISDIR : Path is a directory
231-- EPERM : Path outside sandbox allowlist
232-- E2BIG : File exceeds read_limit (default 500 lines); use offset/limit
233```
235#### 7.2 `write`
237```lua
238-- parameters
239{
240 path = { type = "string", required = true },
241 content = { type = "string", required = true },
242 create_dirs = { type = "boolean", required = false, default = true },
243}
245-- execute
246-- 1. sandbox_path_check(path, 'fs_write')
247-- 2. If create_dirs, mkdir -p parent
248-- 3. Write atomically (temp file + rename)
249-- 4. Return { path = path, bytes = #content }
251-- errors
252-- EPERM : Path outside sandbox write boundaries
253-- EIO : Failed to write
254```
256#### 7.3 `edit`
258```lua
259-- parameters
260{
261 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 },
265}
267-- execute
268-- 1. sandbox_path_check(path, 'fs_write')
269-- 2. Read file
270-- 3. Find old_text occurrences
271-- 4. If !allow_multiple and count > 1 → fail
272-- 5. Replace all occurrences
273-- 6. Write back atomically
274-- 7. Return { changes = count }
276-- errors
277-- ENOTFOUND : old_text not found
278-- EMULTIPLE : old_text found multiple times (without allow_multiple)
279-- EPERM : Path outside sandbox
280```
282#### 7.4 `bash`
284```lua
285-- parameters
286{
287 command = { type = "string", required = true },
288 timeout = { type = "number", required = false, default = 120 },
289 signal = { type = "string", required = false, default = "SIGTERM" },
290}
292-- execute
293-- 1. sandbox_check('subprocess')
294-- 2. Spawn via tokio::process::Command
295-- 3. Pipe stdout/stderr
296-- 4. Apply timeout
297-- 5. On timeout, send signal
298-- 6. Return { stdout = ..., stderr = ..., exit_code = ..., timed_out = ... }
300-- errors
301-- ETIMEDOUT : Command timed out
302-- EPERM : Subprocess not allowed by sandbox
303-- EIO : Failed to spawn
305-- security
306-- 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.lua
310-- 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.
313```
315#### 7.5 `compact`
317```lua
318-- parameters
319{
320 threshold = { type = "number", required = false }, -- null = context_window * 0.8
321 strategy = { type = "string", required = false, default = "summarize", enum = {"summarize","truncate","drop_old"} },
322}
324-- execute
325-- 1. Estimate current tokens
326-- 2. If below threshold → return { compacted = false }
327-- 3. Delegate to smith-core CompactionExecutor
328-- 4. Return { compacted = true, entries_before, entries_after, tokens_saved }
329```
331### 8. Lua → Rust Plugin Bridge
333Four-phase loading model that converts Lua factory functions into Rust trait implementations.
335#### Phase 1: Load
337```rust
338// LuaPluginLoader loads .lua file and calls it as a function
339let factory: mlua::Function = lua.load(&source).eval()?;
340let sdk_collector = SdkCollector::new(); // empty registrations
341lua.globals().set("smith", sdk_collector.to_table())?;
342factory.call(sdk_collector.to_table())?;
343```
345#### Phase 2: Collect
347```rust
348struct 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>,
356}
358// After factory returns, extract each sub-table and validate schemas
359```
361#### Phase 3: Materialize
363```rust
364// For each LuaToolDef: create LuaAgentTool struct
365pub struct LuaAgentTool {
366 definition: ToolDefinition,
367 execute_fn: mlua::RegistryKey,
368 lua: Arc<Lua>,
369 timeout: Duration,
370}
372impl 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<...>>> {
375 // spawn_blocking: lua.call_function(execute_fn, convert_params(params))
376 // with timeout
377 //
378 // NOTE: spawn_blocking threads are NOT interruptible by tokio.
379 // If the Lua function hangs (infinite loop, blocking I/O), the timeout
380 // future resolves with ToolError::Timeout but the underlying thread
381 // continues executing. This is an accepted v1 limitation.
382 // Mitigation: limit max_blocking_threads in tokio runtime config.
383 // Future: run Lua tools in a separate process or WASM sandbox.
384 }
385}
387// For each event subscription: EventHandler holding RegistryKey
388// For each command: LuaCommand implementing Command trait
389```
391#### Phase 4: Register
393```rust
394// tools → ToolRegistry (smith-core)
395// events → EventBridge handler map
396// commands → CommandRegistry
397// providers → ModelRegistry (smith-ai)
398// layout → TUI layout (applied after all plugins loaded)
399```
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
405All enforcement is in Rust (`sdk.rs`), not Lua. Plugins have no `io`/`os`/`debug` globals.
407#### Path Validation Algorithm
409```
4101. Canonicalize requested path (resolve symlinks, .., .)
4112. Check: canonical_path.starts_with(allowed_prefix) for each prefix in capability's paths list
4123. If any prefix matches → ALLOW
4134. If no prefix matches → DENY (return EPERM)
4145. Reject if canonicalization itself fails (broken symlink) → DENY
415```
417Edge cases:
418- 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 |
426|---|---|---|
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
4381. Plugin calls `smith.request_capability('fs_read', { paths = {'./src'} })`
4392. SDK collects request into `PluginRegistrations.capabilities`
4403. `PluginManager` resolves against `SandboxPolicy` (from `~/.smith/sandbox.lua`)
4414. Granted capabilities stored per plugin instance in `GrantedCapabilities`
4425. Denied capabilities cause plugin load failure (with warning + user notification)
444#### Sandbox Policy and Granted Capabilities
446```rust
447/// Loaded from ~/.smith/sandbox.lua.
448/// Parsed in a RESTRICTED Lua context: no `io`, `os`, `debug`, `package`, `require`.
449/// Alternatively, a JSON/TOML file at ~/.smith/sandbox.json is also accepted.
450/// If neither exists, use the default policy below.
451pub struct SandboxPolicy {
452 pub fs_read: Vec<PathBuf>,
453 pub fs_write: Vec<PathBuf>,
454 pub env: Vec<String>,
455 pub network: bool,
456 pub credentials: bool,
457 pub subprocess: bool,
458}
460/// Resolved per-plugin at load time.
461pub struct GrantedCapabilities {
462 pub fs_read: Vec<PathBuf>,
463 pub fs_write: Vec<PathBuf>,
464 pub env: HashSet<String>,
465 pub network: bool,
466 pub credentials: bool,
467 pub subprocess: bool,
468}
469```
471Default policy: `fs_read: ["./"], fs_write: ["./"], env: [], network: false, credentials: false, subprocess: false`.
473Tier overrides:
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
480Load order:
4811. `read` (tool registration)
4822. `write` (tool registration)
4833. `edit` (tool registration)
4844. `bash` (tool registration + tool_call hook for optional confirmation)
4855. `compact` (tool registration)
4866. `default-layout` (TUI layout setup)
488Override rules:
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).
494Disable 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
498```
499smith-harness/src/lua/sdk/
500├── smith_tool.lua — annotations + @usage
501├── smith_provider.lua
502├── smith_command.lua
503├── smith_shortcut.lua
504├── smith_tui.lua
505├── smith_fs.lua
506├── smith_env.lua
507├── smith_credentials.lua
508├── smith_events.lua
509├── guides/
510│ ├── getting-started.lua
511│ ├── tools.lua
512│ ├── events.lua
513│ ├── providers.lua
514│ ├── tui.lua
515│ └── sandbox.lua
516└── examples/
517 ├── 01-hello-world.lua through 12-streaming-updates.lua
518```
520## Tests
522- Harness wires provider → StreamFn → Agent correctly
523- Agent loop runs with real provider types (mock HTTP)
524- Plugin loader: load Lua file, execute factory function
525- Plugin manager: load order (built-in → global → project)
526- SDK: register_tool creates AgentTool in registry
527- SDK: provider.register updates model registry with merge
528- Event bridge: AgentEvent maps to correct plugin events
529- Sandbox: fs_read restricted to allowed paths
530- Sandbox: path validation rejects symlink escape
531- Sandbox: capability denied → plugin load failure
532- LuaAgentTool: executes Lua function via RegistryKey
533- Built-in read: returns file content with line numbers
534- Built-in write: atomic write via temp+rename
535- Built-in edit: exact find-and-replace, rejects ambiguous match
536- Built-in bash: timeout, signal, output truncation
537- Built-in compact: delegates to CompactionExecutor
538- `smith help` reads embedded docs
540## Steps
542- [ ] 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 bindings
554- [ ] Implement Lua → Rust plugin bridge (4-phase pipeline)
555- [ ] Implement LuaAgentTool struct
556- [ ] Implement built-in plugins
557- [ ] Implement sandbox enforcement (path validation, capabilities, resource limits)
558- [ ] Implement `smith help`
559- [ ] Implement system prompt bootstrap
560- [ ] Write tests
561- [ ] 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"`