repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

fix(spec-sm-005): add #[from] to SmithError::Provider and Auth variants

966d28a1eb82d5f67f2953616ba976d8baf0217e

HallucyGenie Agent <agent@hallucygenie.local> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (1)

+411 / −0 text lines

Diff layout

docs/spec-sm-005-shared-types.md

Added
new file mode 100644

+411 / −0 text lines

1# SM-005: smith/ Shared Library
2
3Create the `smith/` shared library crate with types, streaming primitives, tool trait, and config resolution.
4
5## Context
6
7This is the foundation crate. ALL other crates depend on it.
8It contains shared types, the StreamFn abstraction, and the AgentTool trait.
9
10**Architecture note:** In pi, `pi-agent-core` depends on `pi-ai` for streaming types.
11In Rust, we avoid this dependency by putting shared streaming types here. This lets
12`smith-core` and `smith-ai` build in parallel with no coupling.
14## Deliverables
16### 1. `smith/Cargo.toml`
18```toml
19[package]
20name = "smith"
21version = "0.1.0"
22edition = "2024"
23rust-version.workspace = true
25[dependencies]
26mlua = { workspace = true }
27mlua-pkg = { workspace = true }
28minicbor = { workspace = true }
29serde = { workspace = true }
30serde_json = { workspace = true }
31thiserror = { workspace = true }
32tracing = { workspace = true }
33tokio = { workspace = true, features = ["sync"] }
34futures = { workspace = true }
35dirs = { workspace = true }
36jsonschema = { workspace = true }
38[dev-dependencies]
39tokio = { workspace = true, features = ["full"] }
40```
42### 2. `smith/src/lib.rs`
44```rust
45pub mod types;
46pub mod stream;
47pub mod tool;
48pub mod lua;
49pub mod config;
50pub mod error;
52pub use types::*;
53pub use stream::StreamFn;
54pub use tool::{AgentTool, AgentToolResult, AgentToolUpdate};
55pub use lua::LuaRuntime;
56pub use config::{Config, SandboxConfig, Capability};
57pub use error::SmithError;
58```
60### 3. `smith/src/types.rs`
62All shared types used across crates.
64```rust
65use serde::{Deserialize, Serialize};
67/// Unique entry identifier (UUID v7 for time-ordering)
68#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
69pub struct EntryId(pub String);
71impl EntryId {
72 pub fn new() -> Self;
73 pub fn from_string(s: String) -> Self;
74 pub fn as_str(&self) -> &str;
75}
77/// Unique session identifier
78#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
79pub struct SessionId(pub String);
81/// Message role
82#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
83pub enum Role {
84 System,
85 User,
86 Assistant,
87 Tool,
88 ToolResult,
89 Custom,
90 BashExecution,
91}
93/// Content block in a message
94#[derive(Clone, Debug, Serialize, Deserialize)]
95pub enum ContentBlock {
96 Text(String),
97 Image { data: Vec<u8>, media_type: String },
98 ToolCall { id: String, name: String, arguments: String },
99 ToolResult { id: String, result: String, is_error: bool },
100 Thinking { content: String },
101}
103/// Message in the conversation
104#[derive(Clone, Debug, Serialize, Deserialize)]
105pub struct Message {
106 pub role: Role,
107 pub content: Vec<ContentBlock>,
108}
110/// Token usage from a completed response
111#[derive(Clone, Debug, Default, Serialize, Deserialize)]
112pub struct ProviderUsage {
113 pub input_tokens: u64,
114 pub output_tokens: u64,
115 pub cache_read_tokens: Option<u64>,
116 pub cache_write_tokens: Option<u64>,
117 pub total_tokens: Option<u64>,
118}
120/// Why the LLM stopped generating
121#[derive(Clone, Debug, Copy, PartialEq, Eq, Serialize, Deserialize)]
122pub enum StopReason {
123 EndTurn,
124 ToolUse,
125 OverMaxTokens,
126 Aborted,
127 StopSequence,
128 Error,
129}
131/// Thinking level
132#[derive(Clone, Debug, Copy, PartialEq, Eq, Serialize, Deserialize)]
133pub enum ThinkingLevel {
134 Off,
135 Minimal,
136 Low,
137 Medium,
138 High,
139 XHigh,
140}
142/// Secret identifier for secret proxy
143#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
144pub struct SecretId(pub String);
146// --- Streaming types (shared between smith-core and smith-ai) ---
148/// Streaming event from an LLM provider.
149/// Used by both the agent loop (smith-core) and provider implementations (smith-ai).
150#[derive(Clone, Debug)]
151pub enum ProviderEvent {
152 TextDelta { text: String },
153 ToolCall { id: String, name: String, arguments: String },
154 ThinkingDelta { text: String },
155 Done { usage: ProviderUsage, stop_reason: StopReason },
156 Error { message: String },
157}
159/// Request sent to an LLM provider.
160/// Constructed by the agent loop, consumed by provider implementations.
161#[derive(Clone, Debug)]
162pub struct ProviderRequest {
163 pub messages: Vec<Message>,
164 pub system_prompt: String,
165 pub model_id: String,
166 pub provider_id: String,
167 pub tools: Vec<ToolDefinition>,
168 pub thinking_level: ThinkingLevel,
169 pub max_tokens: Option<u32>,
170 pub stop_sequences: Vec<String>,
171}
173/// Tool definition for LLM function calling
174#[derive(Clone, Debug, Serialize, Deserialize)]
175pub struct ToolDefinition {
176 pub name: String,
177 pub description: String,
178 pub parameters: serde_json::Value,
179}
181/// Cost information for a model
182#[derive(Clone, Debug, Copy, Default, Serialize, Deserialize)]
183pub struct ModelCost {
184 pub input: f64,
185 pub output: f64,
186 pub cache_read: f64,
187 pub cache_write: f64,
188}
189```
191### 4. `smith/src/stream.rs`
193Streaming abstraction. Enables smith-core to call LLM without knowing about providers.
195```rust
196use crate::types::{ProviderEvent, ProviderRequest};
197use futures::Stream;
198use std::pin::Pin;
200/// Type alias for the streaming function.
201/// The agent loop calls this to get LLM responses.
202/// Provider implementations (smith-ai) create concrete instances.
203pub type StreamFn = Box<
204 dyn Fn(ProviderRequest) -> Pin<Box<dyn Stream<Item = ProviderEvent> + Send>>
205 + Send
206 + Sync,
207>;
208```
210### 5. `smith/src/tool.rs`
212Tool trait used by the agent loop.
214```rust
215use crate::types::{ContentBlock, ToolDefinition};
216use serde_json::Value as JsonValue;
217use std::future::Future;
218use std::pin::Pin;
220/// Result returned from a tool execution
221#[derive(Clone, Debug)]
222pub struct AgentToolResult {
223 pub content: Vec<ContentBlock>,
224 pub details: JsonValue,
225 pub terminate: bool,
226}
228/// Callback for streaming partial tool results
229pub type AgentToolUpdate = Box<dyn Fn(AgentToolResult) + Send + Sync>;
231/// Tool trait. Implementations are provided by smith-harness (built-in tools + Lua plugins).
232pub trait AgentTool: Send + Sync {
233 fn definition(&self) -> ToolDefinition;
234 fn execute(
235 &self,
236 tool_call_id: &str,
237 params: JsonValue,
238 signal: Option<tokio::sync::watch::Receiver<bool>>,
239 on_update: Option<&AgentToolUpdate>,
240 ) -> Pin<Box<dyn Future<Output = Result<AgentToolResult, ToolError>> + Send + '_>>;
241}
243#[derive(thiserror::Error, Debug)]
244pub enum ToolError {
245 #[error("Invalid arguments: {0}")]
246 InvalidArguments(String),
247 #[error("Execution failed: {0}")]
248 ExecutionFailed(String),
249 #[error("Timeout")]
250 Timeout,
251 #[error("Blocked: {0}")]
252 Blocked(String),
253}
254```
256### 6. `smith/src/lua.rs`
258Lua runtime setup with mlua-pkg.
260```rust
261use mlua::Lua;
262use std::path::PathBuf;
264pub struct LuaRuntime {
265 lua: Lua,
266 config_path: PathBuf,
267}
269impl LuaRuntime {
270 pub fn new(config_path: PathBuf) -> Result<Self, SmithError>;
271 pub fn load_config(&self) -> Result<Config, SmithError>;
272 pub fn load_module(&self, path: &std::path::Path) -> Result<mlua::Value, SmithError>;
273 pub fn execute(&self, code: &str) -> Result<mlua::Value, SmithError>;
274 pub fn globals(&self) -> mlua::Table;
275}
276```
278### 7. `smith/src/config.rs`
280Config loaded from Lua.
282```rust
283#[derive(Clone, Debug)]
284pub struct Config {
285 pub theme: String,
286 pub model: String,
287 pub provider: String,
288 pub tools: Vec<String>,
289 pub keybindings: std::collections::HashMap<String, String>,
290 pub extensions: Vec<String>,
291 pub thinking_level: ThinkingLevel,
292 pub max_tokens: Option<u32>,
293 pub system_prompt: Option<String>,
294 pub sandbox: SandboxConfig,
295}
297impl Config {
298 pub fn from_lua_table(table: mlua::Table) -> Result<Self, SmithError>;
299}
301/// Plugin sandbox configuration — enforced through SDK layer, not OS-level.
302/// Moved here from the architecture doc (SM-004) to live in the foundation crate.
303#[derive(Clone, Debug, Default, Serialize, Deserialize)]
304pub struct SandboxConfig {
305 pub capabilities: Vec<Capability>,
306}
308/// Capability declarations — enforced by SDK (Rust), not OS-level sandboxing.
309#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
310pub enum Capability {
311 FileSystemRead,
312 FileSystemWrite,
313 Network,
314 Subprocess,
315 Environment,
316}
317```
319### 8. `smith/src/error.rs`
321Error types.
323```rust
324use thiserror::Error;
326#[derive(Error, Debug)]
327pub enum SmithError {
328 #[error("Lua error: {0}")]
329 Lua(#[from] mlua::Error),
330 #[error("IO error: {0}")]
331 Io(#[from] std::io::Error),
332 #[error("Config error: {0}")]
333 Config(String),
334 #[error("CBOR error: {0}")]
335 Cbor(#[from] minicbor::decode::Error),
336 #[error("Provider error: {0}")]
337 Provider(#[from] ProviderError),
338 #[error("Auth error: {0}")]
339 Auth(#[from] AuthError),
340 #[error("Tool error: {0}")]
341 Tool(#[from] ToolError),
342}
344/// Provider-specific errors. Lives in smith/ (not smith-ai) to avoid circular deps.
345/// smith-ai adds conversion impls from reqwest::Error etc.
346#[derive(Error, Clone, Debug)]
347pub enum ProviderError {
348 #[error("Rate limit exceeded. Retry after {retry_after:?}s")]
349 RateLimit { retry_after: Option<u64> },
350 #[error("Auth failed for {provider}: {reason}")]
351 AuthFailed { provider: String, reason: String },
352 #[error("Network error: {message}")]
353 Network { message: String },
354 #[error("Invalid request: {0}")]
355 InvalidRequest(String),
356 #[error("Server error {status}: {message}")]
357 ServerError { status: u16, message: String },
358 #[error("Timeout after {elapsed:?}")]
359 Timeout { elapsed: std::time::Duration },
360 #[error("Model not found: {provider}/{model}")]
361 ModelNotFound { provider: String, model: String },
362 #[error("Response parse error: {0}")]
363 ResponseParse(String),
364 #[error("Stream aborted")]
365 StreamAborted,
366}
368/// Authentication errors.
369#[derive(Error, Clone, Debug)]
370pub enum AuthError {
371 #[error("Credentials not found for {provider} ({auth_type})")]
372 NotFound { provider: String, auth_type: String },
373 #[error("Token expired for {provider}")]
374 Expired { provider: String },
375 #[error("Token refresh failed for {provider}: {reason}")]
376 RefreshFailed { provider: String, reason: String },
377 #[error("Invalid token for {provider}")]
378 InvalidToken { provider: String },
379 #[error("Storage error at {path}: {source}")]
380 StorageError { path: String, source: String },
381 #[error("OAuth callback failed: {0}")]
382 OAuthCallbackFailed(String),
383}
384```
386## Tests
388- `EntryId::new()` generates valid UUID v7
389- `ContentBlock` serialization roundtrip
390- `ProviderEvent` can be created and matched
391- `ProviderRequest` construction
392- `Config::from_lua_table` with valid/invalid tables
393- Lua runtime executes simple code
394- `StreamFn` can be boxed and called (mock test)
395- `ProviderError::Network` roundtrips through `SmithError::Provider`
396- `AuthError::NotFound` display formatting
398## Steps
400- [ ] Create `smith/Cargo.toml`
401- [ ] Create `smith/src/lib.rs`
402- [ ] Create `smith/src/types.rs` (all shared types + streaming types)
403- [ ] Create `smith/src/stream.rs` (StreamFn type alias)
404- [ ] Create `smith/src/tool.rs` (AgentTool trait)
405- [ ] Create `smith/src/lua.rs`
406- [ ] Create `smith/src/config.rs` (Config + SandboxConfig + Capability)
407- [ ] Create `smith/src/error.rs` (SmithError + ProviderError + AuthError)
408- [ ] Write tests
409- [ ] Verify: `cargo check -p smith`
410- [ ] Test: `cargo test -p smith`
411- [ ] Commit: `jj describe -m "feat(SM-005): smith shared library — types, StreamFn, AgentTool, lua, config, errors"`