repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

fix(SM-006): fault-tolerant decode, thinking tokens, serde derives

41819f729e5772c9f78c3a2a649da3a5428d5325

HallucyGenie Agent <agent@hallucygenie.local> ·

SSH signature · not checked

Browse filesCompare with HEAD

- SessionCodec::decode/read_file return (Vec<SessionEntry>, Vec<DecodeError>)
  for partial decoding without losing entries on corruption
- HeuristicEstimator counts ContentBlock::Thinking tokens
- SessionEntry derives Serialize, Deserialize, minicbor::Encode, minicbor::Decode
  enabling JSONL dump (SM-010) and CBOR codec

Changed files (1)

+537 / −0 text lines

Diff layout

docs/spec-sm-006-core.md

Added
new file mode 100644

+537 / −0 text lines

1# SM-006: smith-core/ — Agent Loop + Session + Business Logic
2
3Create the `smith-core/` crate with the agent loop, session management, and core business logic.
4
5## Context
6
7Depends on smith/ (SM-005) only. Does NOT depend on smith-ai.
8The agent loop takes a `StreamFn` (from smith/) — it never imports provider types.
9This enables parallel builds: smith-core and smith-ai build simultaneously.
11**Architecture:** Follows pi's `pi-agent-core` pattern, but uses dependency inversion
12via `StreamFn` instead of importing provider types directly.
14## Key Design Decision
16The agent loop is here, not in smith-harness. It is fully testable with mock stream functions.
17smith-harness wires concrete providers into the stream function.
19## Deliverables
21### 1. `smith-core/Cargo.toml`
23```toml
24[package]
25name = "smith-core"
26version = "0.1.0"
27edition = "2024"
28rust-version.workspace = true
30[dependencies]
31smith = { path = "../smith" }
32serde = { workspace = true }
33serde_json = { workspace = true }
34minicbor = { workspace = true }
35tokio = { workspace = true, features = ["sync", "rt"] }
36futures = { workspace = true }
37tracing = { workspace = true }
38thiserror = { workspace = true }
39uuid = { workspace = true, features = ["v7"] }
41[dev-dependencies]
42tokio = { workspace = true, features = ["full"] }
43insta = { workspace = true }
44```
46### 2. `smith-core/src/lib.rs`
48```rust
49pub mod agent;
50pub mod session;
51pub mod session_format;
52pub mod tools;
53pub mod hooks;
54pub mod events;
55pub mod secret_proxy;
56pub mod system_prompt;
57pub mod compaction;
58pub mod cost;
60pub use agent::{Agent, AgentContext, AgentEvent, AgentState, AgentLoopConfig};
61pub use session::{Session, SessionEntry, SessionStore, SessionInfo};
62pub use session_format::SessionCodec;
63pub use tools::ToolRegistry;
64pub use hooks::{HookRegistration, HookContext, HookResult};
65pub use events::EngineEvent;
66pub use secret_proxy::{SecretProxy, SecretId, InMemorySecretProxy};
67pub use system_prompt::SystemPromptBuilder;
68pub use compaction::{CompactionSettings, CompactionExecutor, TokenEstimator, HeuristicEstimator};
69pub use cost::CostTracker;
70```
72### 3. `smith-core/src/agent.rs` — The Agent Loop
74This is the core LLM interaction loop. It takes a StreamFn and tools,
75sends requests, processes responses, executes tools, and repeats.
77```rust
78use smith::{
79 StreamFn, AgentTool, AgentToolResult, ToolError,
80 ProviderEvent, ProviderRequest, ProviderUsage,
81 Message, ContentBlock, Role, StopReason, ThinkingLevel, ToolDefinition,
82};
83use std::collections::HashMap;
84use std::sync::Arc;
85use tokio::sync::mpsc;
87/// Agent context snapshot passed into the loop
88#[derive(Clone)]
89pub struct AgentContext {
90 pub system_prompt: String,
91 pub messages: Vec<Message>,
92 pub tools: Vec<ToolDefinition>,
93}
95/// Events emitted by the agent during a run. This is the canonical source of truth.
96#[derive(Clone, Debug)]
97pub enum AgentEvent {
98 // Lifecycle
99 AgentStart,
100 AgentEnd { messages: Vec<Message> },
102 // Turn tracking
103 TurnStart { turn_index: usize },
104 TurnEnd { turn_index: usize, message: Message, tool_results: Vec<ContentBlock> },
106 // Message streaming
107 MessageStart { message: Message },
108 MessageUpdate { message: Message, delta: ContentBlock },
109 MessageEnd { message: Message, usage: ProviderUsage, stop_reason: StopReason },
111 // Tool execution
112 ToolExecutionStart { tool_call_id: String, tool_name: String, args: serde_json::Value },
113 ToolExecutionEnd { tool_call_id: String, tool_name: String, result: Vec<ContentBlock>, is_error: bool },
114 ToolExecutionUpdate { tool_call_id: String, tool_name: String, partial: String },
116 // Streaming deltas
117 ThinkingDelta { delta: String },
118 TextDelta { delta: String },
120 // Error
121 Error { message: String },
122}
124/// Configuration for the agent loop
125pub struct AgentLoopConfig {
126 pub model_id: String,
127 pub provider_id: String,
128 pub thinking_level: ThinkingLevel,
129 pub max_tokens: Option<u32>,
130 pub convert_to_llm: Box<dyn Fn(Vec<Message>) -> Vec<Message> + Send + Sync>,
131 pub transform_context: Option<Box<dyn Fn(Vec<Message>) -> Vec<Message> + Send + Sync>>,
132 pub get_api_key: Option<Box<dyn Fn(&str) -> Option<String> + Send + Sync>>,
133 pub before_tool_call: Option<Box<dyn Fn(&str, &serde_json::Value) -> Option<HookResult> + Send + Sync>>,
134 pub after_tool_call: Option<Box<dyn Fn(&str, &AgentToolResult) -> Option<AgentToolResult> + Send + Sync>>,
135}
137/// Stateful agent wrapper (like pi's Agent class)
138pub struct Agent {
139 state: AgentState,
140 tools: HashMap<String, Arc<dyn AgentTool>>,
141 stream_fn: Box<StreamFn>,
142 event_tx: mpsc::UnboundedSender<AgentEvent>,
143 event_rx: mpsc::UnboundedReceiver<AgentEvent>,
144}
146/// Current agent state
147pub struct AgentState {
148 pub system_prompt: String,
149 pub messages: Vec<Message>,
150 pub model_id: String,
151 pub provider_id: String,
152 pub thinking_level: ThinkingLevel,
153 pub is_streaming: bool,
154 pub abort_signal: tokio::sync::watch::Sender<bool>,
155}
157impl Agent {
158 pub fn new(stream_fn: Box<StreamFn>) -> Self;
159 pub fn set_tools(&mut self, tools: HashMap<String, Arc<dyn AgentTool>>);
160 pub fn subscribe(&self) -> mpsc::UnboundedReceiver<AgentEvent>;
161 pub fn state(&self) -> &AgentState;
162 pub async fn prompt(&mut self, text: &str, config: AgentLoopConfig) -> Result<(), SmithError>;
163 pub async fn continue_loop(&mut self, config: AgentLoopConfig) -> Result<(), SmithError>;
164 pub fn abort(&self);
165 pub fn is_streaming(&self) -> bool;
166}
167```
169The core loop:
170```
1711. Convert messages to LLM format (convert_to_llm)
1722. Optionally transform context (transform_context)
1733. Build ProviderRequest
1744. Call stream_fn(request) → get event stream
1755. Process ProviderEvents:
176 - TextDelta → emit AgentEvent::TextDelta, accumulate
177 - ToolCall → queue tool call
178 - ThinkingDelta → emit AgentEvent::ThinkingDelta
179 - Done → finalize assistant message, execute queued tools
1806. For each tool call:
181 a. before_tool_call hook (can block)
182 b. Execute tool (AgentTool::execute)
183 c. after_tool_call hook (can modify result)
184 d. Add tool result to messages
1857. If stop_reason == ToolUse, goto 1 (next turn)
1868. If stop_reason == EndTurn, emit AgentEnd
187```
189### 4. `smith-core/src/events.rs` — Engine Event Bus
191`EngineEvent` wraps `AgentEvent` and adds harness-level session/steering events.
192This is the event type consumed by smith-harness and smith-tui.
194```rust
195use smith::{Message, ContentBlock, ProviderUsage, StopReason};
197#[derive(Clone, Debug)]
198pub enum EngineEvent {
199 // All agent events are wrapped in a single variant
200 Agent(AgentEvent),
202 // Session events (not from agent loop)
203 SessionSaved { session_id: SessionId },
204 CompactionStart,
205 CompactionEnd { tokens_before: u64, tokens_after: u64 },
207 // Session tree events
208 BranchCreated { from_id: EntryId, to_id: EntryId },
210 // User interaction events
211 SteeringQueued { text: String },
212 FollowUpQueued { text: String },
214 // Retry policy
215 Retry { attempt: u8, tool_name: String },
217 // Cost tracking
218 CostUpdate { cumulative_cost: f64, last_response_cost: f64 },
220 // Shutdown
221 Shutdown,
222}
223```
225**Design note:** `EngineEvent::Agent(AgentEvent)` wraps ALL agent events.
226Downstream consumers match with:
227```rust
228if let EngineEvent::Agent(AgentEvent::TextDelta { delta }) = event { ... }
229```
230This avoids duplicating 15 agent event variants at the harness level.
232### 5. `smith-core/src/session.rs` — Session Management
234Session management (tree, entries, compaction point).
236```rust
237pub struct Session {
238 pub id: SessionId,
239 pub name: Option<String>,
240 pub cwd: PathBuf,
241 pub entries: Vec<SessionEntry>,
242 pub current_leaf: EntryId,
243 pub created: u64,
244 pub updated: u64,
245}
247/// Session entry — immutable record. Canonical definition lives here.
248#[derive(Clone, Debug, Serialize, Deserialize, minicbor::Encode, minicbor::Decode)]
249pub enum SessionEntry {
250 Session { version: u32, created: u64 },
251 User { id: EntryId, parent_id: Option<EntryId>, content: Vec<ContentBlock>, timestamp: u64 },
252 Assistant { id: EntryId, parent_id: Option<EntryId>, content: Vec<ContentBlock>, usage: ProviderUsage, provider: String, model: String, stop_reason: StopReason, timestamp: u64 },
253 ToolResult { id: EntryId, parent_id: Option<EntryId>, tool_call_id: String, tool_name: String, content: Vec<ContentBlock>, is_error: bool, timestamp: u64 },
254 Compaction { id: EntryId, parent_id: Option<EntryId>, summary: String, first_kept_id: EntryId, tokens_before: u64, read_files: Vec<String>, modified_files: Vec<String>, timestamp: u64 },
255 BranchSummary { id: EntryId, parent_id: Option<EntryId>, summary: String, from_id: EntryId, timestamp: u64 },
256 ThinkingLevelChange { id: EntryId, parent_id: Option<EntryId>, level: ThinkingLevel, timestamp: u64 },
257 ModelChange { id: EntryId, parent_id: Option<EntryId>, provider: String, model_id: String, timestamp: u64 },
258 BashExecution { id: EntryId, parent_id: Option<EntryId>, command: String, output: String, timestamp: u64 },
259 Label { id: EntryId, parent_id: Option<EntryId>, label: String, timestamp: u64 },
260 SecretRegister { id: EntryId, parent_id: Option<EntryId>, secret_id: String, value: String, source: String, timestamp: u64 },
261 Unknown { id: EntryId, data: Vec<u8>, timestamp: u64 },
262}
264pub trait SessionStore: Send + Sync {
265 fn load(&self, id: &SessionId) -> Result<Session>;
266 fn save(&self, session: &Session) -> Result<()>;
267 fn list(&self) -> Result<Vec<SessionInfo>>;
268 fn delete(&self, id: &SessionId) -> Result<()>;
269}
271pub struct SessionInfo {
272 pub id: SessionId,
273 pub name: Option<String>,
274 pub cwd: PathBuf,
275 pub created: u64,
276 pub updated: u64,
277 pub entry_count: usize,
278}
279```
281### 6. `smith-core/src/session_format.rs` — CBOR Codec
283Length-prefixed CBOR-seq codec for session persistence.
285```rust
286/// Wire format:
287/// [u32 BE len][CBOR entry bytes][u32 BE len][CBOR entry bytes]...
288pub struct SessionCodec;
290/// Decode error for a single entry.
291pub struct DecodeError {
292 pub entry_index: usize,
293 pub error_offset: usize,
294 pub source: String,
295}
297impl SessionCodec {
298 /// Encode entries to CBOR-seq bytes.
299 pub fn encode(entries: &[SessionEntry]) -> Result<Vec<u8>>;
301 /// Decode CBOR-seq bytes to entries (fault-tolerant).
302 /// Returns all successfully decoded entries plus a list of per-entry errors.
303 /// Never returns Err for partial corruption — skips corrupt entries and continues.
304 pub fn decode(data: &[u8]) -> (Vec<SessionEntry>, Vec<DecodeError>);
306 /// Append a single entry (for incremental writes during a session).
307 pub fn append_entry(writer: &mut impl Write, entry: &SessionEntry) -> Result<()>;
309 /// Read entries from a file path (fault-tolerant).
310 /// Returns entries and errors separately so callers can decide whether to proceed.
311 pub fn read_file(path: &Path) -> (Vec<SessionEntry>, Vec<DecodeError>);
312}
313```
315**Fault tolerance rules:**
316- Truncated entry (crash mid-write) → stop reading, all prior entries intact.
317- Corrupt CBOR bytes → log warning, skip entry (advance by len), continue.
318- Unknown entry type → keep as `SessionEntry::Unknown { data }`.
319- Unknown CBOR fields in known entry → ignored (forward compatible).
320- Missing optional fields → `None` (backward compatible).
321- Empty or missing file → return empty vec, create on first write.
323### 7. `smith-core/src/tools.rs`
325Tool registry (maps names to AgentTool instances).
327```rust
328pub struct ToolRegistry {
329 tools: HashMap<String, Arc<dyn AgentTool>>,
330}
332impl ToolRegistry {
333 pub fn new() -> Self;
334 pub fn register(&mut self, tool: Arc<dyn AgentTool>);
335 pub fn get(&self, name: &str) -> Option<&Arc<dyn AgentTool>>;
336 pub fn list(&self) -> Vec<&Arc<dyn AgentTool>>;
337 pub fn definitions(&self) -> Vec<ToolDefinition>;
338}
339```
341### 8. `smith-core/src/hooks.rs`
343Hook system for intercepting events. Maps to plugin SDK events.
345```rust
346pub struct HookRegistration {
347 pub event: String,
348 pub handler: Box<dyn Fn(&HookContext) -> HookResult + Send + Sync>,
349}
351pub struct HookContext {
352 pub event: String,
353 pub data: serde_json::Value,
354}
356pub enum HookResult {
357 Pass,
358 Block { reason: String },
359 Modify { data: serde_json::Value },
360}
361```
363### 9. `smith-core/src/system_prompt.rs`
365Builds the system prompt from components.
367```rust
368/// Builds the system prompt from components.
369/// Called once per agent loop invocation.
370pub struct SystemPromptBuilder {
371 base_template: String,
372 tool_registry: ToolRegistry,
373 session_context: SessionContext,
374 plugin_sections: Vec<(String, String)>,
375}
377pub struct SessionContext {
378 pub cwd: PathBuf,
379 pub git_branch: Option<String>,
380 pub file_tree_summary: Option<String>,
381}
383impl SystemPromptBuilder {
384 pub fn new(base_template: String, tools: ToolRegistry) -> Self;
385 pub fn set_context(&mut self, context: SessionContext);
386 pub fn add_plugin_section(&mut self, name: String, content: String);
387 /// Build the complete system prompt string.
388 /// Components (in order):
389 /// 1. Base instructions ("You are smith, a coding agent...")
390 /// 2. Tool descriptions (from ToolRegistry::definitions())
391 /// 3. Session context (cwd, file tree, git branch)
392 /// 4. Plugin-provided prompt additions
393 /// 5. Self-extension instructions (how to use smith's plugin system)
394 pub fn build(&self) -> String;
395}
396```
398### 10. `smith-core/src/compaction.rs`
400Context compaction and token estimation.
402```rust
403pub struct CompactionSettings {
404 pub max_tokens: u64,
405 pub threshold_ratio: f64, // default 0.8
406}
408pub struct CompactionExecutor;
410impl CompactionExecutor {
411 pub fn compact(session: &mut Session, settings: &CompactionSettings) -> Result<CompactionSummary>;
412}
414pub struct CompactionSummary {
415 pub tokens_before: u64,
416 pub tokens_after: u64,
417 pub summary: String,
418 pub read_files: Vec<String>,
419 pub modified_files: Vec<String>,
420}
422/// Token estimator for compaction decisions.
423pub trait TokenEstimator: Send + Sync {
424 fn estimate(&self, messages: &[Message]) -> u64;
425}
427/// Default estimator: chars / 4 (rough but safe for context window checks).
428pub struct HeuristicEstimator;
430impl TokenEstimator for HeuristicEstimator {
431 fn estimate(&self, messages: &[Message]) -> u64 {
432 let total_chars: usize = messages.iter()
433 .flat_map(|m| &m.content)
434 .map(|c| match c {
435 ContentBlock::Text(t) => t.len(),
436 ContentBlock::Thinking { content } => content.len(),
437 ContentBlock::ToolCall { arguments, .. } => arguments.len(),
438 ContentBlock::ToolResult { result, .. } => result.len(),
439 _ => 0,
440 })
441 .sum();
442 (total_chars / 4) as u64
443 }
444}
445```
447**Token counting strategy:**
448- v1 uses `HeuristicEstimator` (chars/4) for compaction decisions.
449- Exact per-model tokenization (tiktoken, cl100k) is a smith-ai concern.
450- The agent loop checks `estimate(messages) > model.context_window * threshold_ratio`
451 to trigger compaction.
452- Cost calculation uses `ModelCost` × tokens from `ProviderUsage` (exact where available).
454### 11. `smith-core/src/cost.rs`
456Cost tracking across a session.
458```rust
459/// Tracks cumulative cost across a session.
460/// Emits CostUpdate events via the agent loop for TUI display.
461pub struct CostTracker {
462 cumulative_input_tokens: u64,
463 cumulative_output_tokens: u64,
464 cumulative_cache_read_tokens: u64,
465 cumulative_cache_write_tokens: u64,
466 total_cost: f64,
467 cost_per_response: Vec<f64>,
468}
470impl CostTracker {
471 pub fn new() -> Self;
473 /// Record usage from a completed LLM response. Returns the cost of this response.
474 pub fn record(&mut self, usage: &ProviderUsage, cost: &ModelCost) -> f64;
476 pub fn total_cost(&self) -> f64;
477 pub fn total_input_tokens(&self) -> u64;
478 pub fn reset(&mut self);
479}
480```
482### 12. `smith-core/src/secret_proxy.rs`
484Secret proxy for hiding sensitive data from the LLM.
486```rust
487pub trait SecretProxy: Send + Sync {
488 fn register(&mut self, secret: String) -> SecretId;
489 fn resolve(&self, id: &SecretId) -> Option<&str>;
490}
492pub struct InMemorySecretProxy {
493 table: HashMap<SecretId, String>,
494}
495```
497## Tests
499- **Agent loop with mock stream** — most important test
500 - Mock StreamFn returns TextDelta + Done
501 - Agent emits AgentStart, MessageStart, TextDelta, MessageEnd, AgentEnd
502 - Messages appended to state
503- **Agent loop with tool calls**
504 - Mock StreamFn returns ToolCall + Done
505 - Agent executes tool, adds result, loops again
506 - Second loop returns EndTurn
507- **Agent loop with blocked tool**
508 - before_tool_call returns Block
509 - Tool not executed, error result added
510- **Session creation and entry addition**
511- **Session fork creates correct tree**
512- **SecretProxy hides and restores secrets**
513- **Token estimation** (HeuristicEstimator)
514- **Compaction cut point**
515- **CostTracker accumulation**
516- **SystemPromptBuilder includes all components**
517- **SessionCodec roundtrip and fault tolerance**
519## Steps
521- [ ] Create `smith-core/Cargo.toml`
522- [ ] Create `smith-core/src/lib.rs`
523- [ ] Create `smith-core/src/agent.rs` (agent loop — most important)
524- [ ] Create `smith-core/src/session.rs` (SessionEntry canonical definition)
525- [ ] Create `smith-core/src/session_format.rs` (CBOR codec)
526- [ ] Create `smith-core/src/tools.rs` (ToolRegistry)
527- [ ] Create `smith-core/src/hooks.rs`
528- [ ] Create `smith-core/src/events.rs` (EngineEvent wrapping AgentEvent)
529- [ ] Create `smith-core/src/secret_proxy.rs`
530- [ ] Create `smith-core/src/system_prompt.rs` (expanded)
531- [ ] Create `smith-core/src/compaction.rs` (TokenEstimator)
532- [ ] Create `smith-core/src/cost.rs` (CostTracker)
533- [ ] Write agent loop tests (mock stream function)
534- [ ] Write session/tool/hook/cost tests
535- [ ] Verify: `cargo check -p smith-core`
536- [ ] Test: `cargo test -p smith-core`
537- [ ] Commit: `jj describe -m "feat(SM-006): smith-core — agent loop, session, events, cost, compaction"`