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)
docs/spec-sm-006-core.md
Addednew file mode 100644+537 / −0 text lines
1+# SM-006: smith-core/ — Agent Loop + Session + Business Logic 3+Create the `smith-core/` crate with the agent loop, session management, and core business logic. 7+Depends on smith/ (SM-005) only. Does NOT depend on smith-ai. 8+The agent loop takes a `StreamFn` (from smith/) — it never imports provider types. 9+This enables parallel builds: smith-core and smith-ai build simultaneously. 11+**Architecture:** Follows pi's `pi-agent-core` pattern, but uses dependency inversion 12+via `StreamFn` instead of importing provider types directly. 14+## Key Design Decision 16+The agent loop is here, not in smith-harness. It is fully testable with mock stream functions. 17+smith-harness wires concrete providers into the stream function. 21+### 1. `smith-core/Cargo.toml` 28+rust-version.workspace = true 31+smith = { path = "../smith" } 32+serde = { workspace = true } 33+serde_json = { workspace = true } 34+minicbor = { workspace = true } 35+tokio = { workspace = true, features = ["sync", "rt"] } 36+futures = { workspace = true } 37+tracing = { workspace = true } 38+thiserror = { workspace = true } 39+uuid = { workspace = true, features = ["v7"] } 42+tokio = { workspace = true, features = ["full"] } 43+insta = { workspace = true } 46+### 2. `smith-core/src/lib.rs` 51+pub mod session_format; 56+pub mod system_prompt; 60+pub use agent::{Agent, AgentContext, AgentEvent, AgentState, AgentLoopConfig}; 61+pub use session::{Session, SessionEntry, SessionStore, SessionInfo}; 62+pub use session_format::SessionCodec; 63+pub use tools::ToolRegistry; 64+pub use hooks::{HookRegistration, HookContext, HookResult}; 65+pub use events::EngineEvent; 66+pub use secret_proxy::{SecretProxy, SecretId, InMemorySecretProxy}; 67+pub use system_prompt::SystemPromptBuilder; 68+pub use compaction::{CompactionSettings, CompactionExecutor, TokenEstimator, HeuristicEstimator}; 69+pub use cost::CostTracker; 72+### 3. `smith-core/src/agent.rs` — The Agent Loop 74+This is the core LLM interaction loop. It takes a StreamFn and tools, 75+sends requests, processes responses, executes tools, and repeats. 79+ StreamFn, AgentTool, AgentToolResult, ToolError, 80+ ProviderEvent, ProviderRequest, ProviderUsage, 81+ Message, ContentBlock, Role, StopReason, ThinkingLevel, ToolDefinition, 83+use std::collections::HashMap; 85+use tokio::sync::mpsc; 89+pub struct AgentContext { 90+ pub system_prompt: String, 91+ pub messages: Vec<Message>, 92+ pub tools: Vec<ToolDefinition>, 96+#[derive(Clone, Debug)] 100+ AgentEnd { messages: Vec<Message> }, 103+ TurnStart { turn_index: usize }, 104+ TurnEnd { turn_index: usize, message: Message, tool_results: Vec<ContentBlock> }, 107+ MessageStart { message: Message }, 108+ MessageUpdate { message: Message, delta: ContentBlock }, 109+ MessageEnd { message: Message, usage: ProviderUsage, stop_reason: StopReason }, 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 }, 117+ ThinkingDelta { delta: String }, 118+ TextDelta { delta: String }, 121+ Error { message: String }, 125+pub 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>>, 140+ tools: HashMap<String, Arc<dyn AgentTool>>, 141+ stream_fn: Box<StreamFn>, 142+ event_tx: mpsc::UnboundedSender<AgentEvent>, 143+ event_rx: mpsc::UnboundedReceiver<AgentEvent>, 147+pub 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>, 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; 171+1. Convert messages to LLM format (convert_to_llm) 172+2. Optionally transform context (transform_context) 173+3. Build ProviderRequest 174+4. Call stream_fn(request) → get event stream 175+5. 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 180+6. 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 185+7. If stop_reason == ToolUse, goto 1 (next turn) 186+8. If stop_reason == EndTurn, emit AgentEnd 189+### 4. `smith-core/src/events.rs` — Engine Event Bus 191+`EngineEvent` wraps `AgentEvent` and adds harness-level session/steering events. 192+This is the event type consumed by smith-harness and smith-tui. 195+use smith::{Message, ContentBlock, ProviderUsage, StopReason}; 197+#[derive(Clone, Debug)] 198+pub enum EngineEvent { 203+ SessionSaved { session_id: SessionId }, 205+ CompactionEnd { tokens_before: u64, tokens_after: u64 }, 208+ BranchCreated { from_id: EntryId, to_id: EntryId }, 211+ SteeringQueued { text: String }, 212+ FollowUpQueued { text: String }, 215+ Retry { attempt: u8, tool_name: String }, 218+ CostUpdate { cumulative_cost: f64, last_response_cost: f64 }, 225+**Design note:** `EngineEvent::Agent(AgentEvent)` wraps ALL agent events. 226+Downstream consumers match with: 228+if let EngineEvent::Agent(AgentEvent::TextDelta { delta }) = event { ... } 230+This avoids duplicating 15 agent event variants at the harness level. 232+### 5. `smith-core/src/session.rs` — Session Management 234+Session management (tree, entries, compaction point). 239+ pub name: Option<String>, 241+ pub entries: Vec<SessionEntry>, 242+ pub current_leaf: EntryId, 248+#[derive(Clone, Debug, Serialize, Deserialize, minicbor::Encode, minicbor::Decode)] 249+pub 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 }, 264+pub 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<()>; 271+pub struct SessionInfo { 273+ pub name: Option<String>, 277+ pub entry_count: usize, 281+### 6. `smith-core/src/session_format.rs` — CBOR Codec 283+Length-prefixed CBOR-seq codec for session persistence. 288+pub struct SessionCodec; 291+pub struct DecodeError { 292+ pub entry_index: usize, 293+ pub error_offset: usize, 299+ pub fn encode(entries: &[SessionEntry]) -> Result<Vec<u8>>; 304+ pub fn decode(data: &[u8]) -> (Vec<SessionEntry>, Vec<DecodeError>); 307+ pub fn append_entry(writer: &mut impl Write, entry: &SessionEntry) -> Result<()>; 311+ pub fn read_file(path: &Path) -> (Vec<SessionEntry>, Vec<DecodeError>); 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` 325+Tool registry (maps names to AgentTool instances). 328+pub struct ToolRegistry { 329+ tools: HashMap<String, Arc<dyn AgentTool>>, 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>; 341+### 8. `smith-core/src/hooks.rs` 343+Hook system for intercepting events. Maps to plugin SDK events. 346+pub struct HookRegistration { 348+ pub handler: Box<dyn Fn(&HookContext) -> HookResult + Send + Sync>, 351+pub struct HookContext { 353+ pub data: serde_json::Value, 356+pub enum HookResult { 358+ Block { reason: String }, 359+ Modify { data: serde_json::Value }, 363+### 9. `smith-core/src/system_prompt.rs` 365+Builds the system prompt from components. 370+pub struct SystemPromptBuilder { 371+ base_template: String, 372+ tool_registry: ToolRegistry, 373+ session_context: SessionContext, 374+ plugin_sections: Vec<(String, String)>, 377+pub struct SessionContext { 379+ pub git_branch: Option<String>, 380+ pub file_tree_summary: Option<String>, 383+impl 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); 394+ pub fn build(&self) -> String; 398+### 10. `smith-core/src/compaction.rs` 400+Context compaction and token estimation. 403+pub struct CompactionSettings { 404+ pub max_tokens: u64, 405+ pub threshold_ratio: f64, 408+pub struct CompactionExecutor; 410+impl CompactionExecutor { 411+ pub fn compact(session: &mut Session, settings: &CompactionSettings) -> Result<CompactionSummary>; 414+pub 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>, 423+pub trait TokenEstimator: Send + Sync { 424+ fn estimate(&self, messages: &[Message]) -> u64; 428+pub struct HeuristicEstimator; 430+impl TokenEstimator for HeuristicEstimator { 431+ fn estimate(&self, messages: &[Message]) -> u64 { 432+ let total_chars: usize = messages.iter() 433+ .flat_map(|m| &m.content) 435+ ContentBlock::Text(t) => t.len(), 436+ ContentBlock::Thinking { content } => content.len(), 437+ ContentBlock::ToolCall { arguments, .. } => arguments.len(), 438+ ContentBlock::ToolResult { result, .. } => result.len(), 442+ (total_chars / 4) as u64 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` 456+Cost tracking across a session. 461+pub struct CostTracker { 462+ cumulative_input_tokens: u64, 463+ cumulative_output_tokens: u64, 464+ cumulative_cache_read_tokens: u64, 465+ cumulative_cache_write_tokens: u64, 467+ cost_per_response: Vec<f64>, 471+ pub fn new() -> Self; 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); 482+### 12. `smith-core/src/secret_proxy.rs` 484+Secret proxy for hiding sensitive data from the LLM. 487+pub trait SecretProxy: Send + Sync { 488+ fn register(&mut self, secret: String) -> SecretId; 489+ fn resolve(&self, id: &SecretId) -> Option<&str>; 492+pub struct InMemorySecretProxy { 493+ table: HashMap<SecretId, String>, 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** 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"`