ai-agent-sdk 0.4.0

Idiomatic agent sdk inspired by the claude code source leak
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use crate::types::*;
use crate::engine::{QueryEngine, QueryEngineConfig};
use crate::error::AgentError;
use crate::env::EnvConfig;
use crate::tools::bash::BashTool;
use crate::tools::read::FileReadTool as ReadTool;
use crate::tools::write::FileWriteTool as WriteTool;
use crate::tools::glob::GlobTool;
use crate::tools::grep::GrepTool;
use crate::tools::edit::FileEditTool;

/// Register all built-in tool executors
fn register_all_tool_executors(engine: &mut QueryEngine) {
    type BoxFuture<T> = std::pin::Pin<Box<dyn std::future::Future<Output = T> + Send>>;

    // Bash tool - clone tool and ctx into async block
    let bash_executor = move |input: serde_json::Value, ctx: &ToolContext| -> BoxFuture<Result<ToolResult, AgentError>> {
        let tool_clone = BashTool::new();
        let cwd = ctx.cwd.clone();
        Box::pin(async move {
            let ctx2 = ToolContext { cwd, abort_signal: None };
            tool_clone.execute(input, &ctx2).await
        })
    };
    engine.register_tool("Bash".to_string(), bash_executor);

    // FileRead tool
    let read_executor = move |input: serde_json::Value, ctx: &ToolContext| -> BoxFuture<Result<ToolResult, AgentError>> {
        let tool_clone = ReadTool::new();
        let cwd = ctx.cwd.clone();
        Box::pin(async move {
            let ctx2 = ToolContext { cwd, abort_signal: None };
            tool_clone.execute(input, &ctx2).await
        })
    };
    engine.register_tool("FileRead".to_string(), read_executor);

    // FileWrite tool
    let write_executor = move |input: serde_json::Value, ctx: &ToolContext| -> BoxFuture<Result<ToolResult, AgentError>> {
        let tool_clone = WriteTool::new();
        let cwd = ctx.cwd.clone();
        Box::pin(async move {
            let ctx2 = ToolContext { cwd, abort_signal: None };
            tool_clone.execute(input, &ctx2).await
        })
    };
    engine.register_tool("FileWrite".to_string(), write_executor);

    // Glob tool
    let glob_executor = move |input: serde_json::Value, ctx: &ToolContext| -> BoxFuture<Result<ToolResult, AgentError>> {
        let tool_clone = GlobTool::new();
        let cwd = ctx.cwd.clone();
        Box::pin(async move {
            let ctx2 = ToolContext { cwd, abort_signal: None };
            tool_clone.execute(input, &ctx2).await
        })
    };
    engine.register_tool("Glob".to_string(), glob_executor);

    // Grep tool
    let grep_executor = move |input: serde_json::Value, ctx: &ToolContext| -> BoxFuture<Result<ToolResult, AgentError>> {
        let tool_clone = GrepTool::new();
        let cwd = ctx.cwd.clone();
        Box::pin(async move {
            let ctx2 = ToolContext { cwd, abort_signal: None };
            tool_clone.execute(input, &ctx2).await
        })
    };
    engine.register_tool("Grep".to_string(), grep_executor);

    // FileEdit tool
    let edit_executor = move |input: serde_json::Value, ctx: &ToolContext| -> BoxFuture<Result<ToolResult, AgentError>> {
        let tool_clone = FileEditTool::new();
        let cwd = ctx.cwd.clone();
        Box::pin(async move {
            let ctx2 = ToolContext { cwd, abort_signal: None };
            tool_clone.execute(input, &ctx2).await
        })
    };
    engine.register_tool("FileEdit".to_string(), edit_executor);

    // Skill tool
    use crate::tools::skill::SkillTool;
    use crate::tools::skill::register_skills_from_dir;
    use std::path::Path;

    // Register skills from examples/skills directory
    register_skills_from_dir(Path::new("examples/skills"));

    let skill_executor = move |input: serde_json::Value, ctx: &ToolContext| -> BoxFuture<Result<ToolResult, AgentError>> {
        let tool_clone = SkillTool::new();
        let cwd = ctx.cwd.clone();
        Box::pin(async move {
            let ctx2 = ToolContext { cwd, abort_signal: None };
            tool_clone.execute(input, &ctx2).await
        })
    };
    engine.register_tool("Skill".to_string(), skill_executor);

    // Add stub executors for other tools (they have definitions but no full implementation)
    let stub_executor = |input: serde_json::Value, _ctx: &ToolContext| -> BoxFuture<Result<ToolResult, AgentError>> {
        let tool_name = input.get("name")
            .and_then(|n| n.as_str())
            .unwrap_or("unknown")
            .to_string();
        Box::pin(async move {
            Ok(ToolResult {
                result_type: "text".to_string(),
                tool_use_id: tool_name.clone(),
                content: format!("Tool '{}' is not fully implemented yet", tool_name),
                is_error: Some(false),
            })
        })
    };

    // Register stub executors for tools without full implementations
    for tool_name in &["TaskCreate", "TaskList", "TaskUpdate", "TaskGet", "TeamCreate", "TeamDelete", "SendMessage", "EnterWorktree", "ExitWorktree", "EnterPlanMode", "ExitPlanMode", "AskUserQuestion", "ToolSearch", "CronCreate", "CronDelete", "CronList", "Config", "TodoWrite", "NotebookEdit", "WebFetch", "WebSearch", "Agent"] {
        engine.register_tool(tool_name.to_string(), stub_executor);
    }
}

pub struct Agent {
    config: AgentOptions,
    model: String,
    api_key: Option<String>,
    base_url: Option<String>,
    tool_pool: Vec<ToolDefinition>,
    messages: Vec<Message>,
    session_id: String,
}

impl From<AgentOptions> for Agent {
    fn from(options: AgentOptions) -> Self {
        Agent::create(options)
    }
}

impl Agent {
    /// Create a new agent with model name and max turns
    pub fn new(model: &str, max_turns: u32) -> Self {
        Self::create(AgentOptions {
            model: Some(model.to_string()),
            max_turns: Some(max_turns),
            ..Default::default()
        })
    }

    /// Create agent from AgentOptions
    pub fn create(options: AgentOptions) -> Self {
        // Load env config for defaults
        let env_config = EnvConfig::load();

        // Use env value, then options value, then default
        let model = env_config.model.clone()
            .or_else(|| options.model.clone())
            .unwrap_or_else(|| "claude-sonnet-4-6".to_string());

        let api_key = env_config.auth_token.clone()
            .or_else(|| options.api_key.clone());

        let base_url = env_config.base_url.clone()
            .or_else(|| options.base_url.clone());

        let session_id = uuid::Uuid::new_v4().to_string();

        Self {
            config: options.clone(),
            model,
            api_key,
            base_url,
            tool_pool: options.tools.clone(),
            messages: vec![],
            session_id,
        }
    }

    pub fn get_model(&self) -> &str {
        &self.model
    }

    pub fn get_session_id(&self) -> &str {
        &self.session_id
    }

    /// Get all messages in the conversation history
    pub fn get_messages(&self) -> &[Message] {
        &self.messages
    }

    /// Get all tools available to the agent
    pub fn get_tools(&self) -> &[ToolDefinition] {
        &self.tool_pool
    }

    /// Set system prompt for the agent
    pub fn set_system_prompt(&mut self, prompt: &str) {
        self.config.system_prompt = Some(prompt.to_string());
    }

    /// Set the working directory for the agent
    pub fn set_cwd(&mut self, cwd: &str) {
        self.config.cwd = Some(cwd.to_string());
    }

    /// Execute a tool directly (for testing/demo purposes)
    pub async fn execute_tool(&mut self, name: &str, input: serde_json::Value) -> Result<ToolResult, AgentError> {
        // Create a temporary engine to execute the tool
        let cwd = self.config.cwd.clone().unwrap_or_else(|| std::env::current_dir().map(|p| p.to_string_lossy().to_string()).unwrap_or_else(|_| ".".to_string()));
        let model = self.model.clone();
        let api_key = self.api_key.clone();
        let base_url = self.base_url.clone();

        let mut engine = QueryEngine::new(QueryEngineConfig {
            cwd: cwd.clone(),
            model: model.clone(),
            api_key: api_key.clone(),
            base_url: base_url.clone(),
            tools: vec![],
            system_prompt: None,
            max_turns: 10,
            max_budget_usd: None,
            max_tokens: 16384,
            can_use_tool: None,
        });

        // Register all tool executors (including Bash, Read, Write, etc.)
        register_all_tool_executors(&mut engine);

        // Register Agent tool executor
        let agent_tool_executor = move |input: serde_json::Value, _ctx: &ToolContext| -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<ToolResult, AgentError>> + Send>> {
            let cwd = cwd.clone();
            let api_key = api_key.clone();
            let base_url = base_url.clone();
            let model = model.clone();

            Box::pin(async move {
                let description = input["description"].as_str().unwrap_or("subagent");
                let subagent_prompt = input["prompt"].as_str().unwrap_or("");
                let subagent_model = input["model"].as_str().map(|s| s.to_string()).unwrap_or_else(|| model.clone());
                let max_turns = input["max_turns"].as_u64().unwrap_or(10) as u32;

                // Create sub-agent engine
                let mut sub_engine = QueryEngine::new(QueryEngineConfig {
                    cwd,
                    model: subagent_model.to_string(),
                    api_key,
                    base_url,
                    tools: vec![],
                    system_prompt: None,
                    max_turns,
                    max_budget_usd: None,
                    max_tokens: 16384,
                    can_use_tool: None,
                });

                match sub_engine.submit_message(subagent_prompt).await {
                    Ok(result_text) => {
                        Ok(ToolResult {
                            result_type: "text".to_string(),
                            tool_use_id: "agent_tool".to_string(),
                            content: format!("[Subagent: {}]\n\n{}", description, result_text),
                            is_error: Some(false),
                        })
                    }
                    Err(e) => {
                        Ok(ToolResult {
                            result_type: "text".to_string(),
                            tool_use_id: "agent_tool".to_string(),
                            content: format!("[Subagent: {}] Error: {}", description, e),
                            is_error: Some(true),
                        })
                    }
                }
            })
        };

        engine.register_tool("Agent".to_string(), agent_tool_executor);
        engine.execute_tool(name, input).await
    }

    /// Simple blocking prompt method - sends a prompt and returns the result.
    /// This matches the TypeScript SDK's agent.prompt() API.
    pub async fn prompt(&mut self, prompt: &str) -> Result<QueryResult, AgentError> {
        self.query(prompt).await
    }

    pub async fn query(&mut self, prompt: &str) -> Result<QueryResult, AgentError> {
        use crate::memory::load_memory_prompt;
        use crate::ai_md::load_ai_md;
        use crate::tools::get_all_base_tools;

        let cwd = self.config.cwd.clone().unwrap_or_else(|| std::env::current_dir().map(|p| p.to_string_lossy().to_string()).unwrap_or_else(|_| ".".to_string()));
        let cwd_path = std::path::Path::new(&cwd);
        let model = self.model.clone();
        let api_key = self.api_key.clone();
        let base_url = self.base_url.clone();

        // Build system prompt: AI.md + memory prompt + custom system prompt
        let ai_md_prompt = load_ai_md(cwd_path).ok().flatten();
        let memory_prompt = load_memory_prompt();

        // Combine: AI.md (highest priority) -> memory -> custom
        let system_prompt = match (&ai_md_prompt, &memory_prompt, &self.config.system_prompt) {
            (Some(ai_md), Some(mem), Some(custom)) => Some(format!("{}\n\n{}\n\n{}", ai_md, mem, custom)),
            (Some(ai_md), Some(mem), None) => Some(format!("{}\n\n{}", ai_md, mem)),
            (Some(ai_md), None, Some(custom)) => Some(format!("{}\n\n{}", ai_md, custom)),
            (Some(ai_md), None, None) => Some(ai_md.clone()),
            (None, Some(mem), Some(custom)) => Some(format!("{}\n\n{}", mem, custom)),
            (None, Some(mem), None) => Some(mem.clone()),
            (None, None, Some(custom)) => Some(custom.clone()),
            (None, None, None) => None,
        };

        // Use base tools if tool_pool is empty
        let tools = if self.tool_pool.is_empty() {
            get_all_base_tools()
        } else {
            self.tool_pool.clone()
        };

        let mut engine = QueryEngine::new(QueryEngineConfig {
            cwd: cwd.clone(),
            model: model.clone(),
            api_key: api_key.clone(),
            base_url: base_url.clone(),
            tools,
            system_prompt,
            max_turns: self.config.max_turns.unwrap_or(10),
            max_budget_usd: self.config.max_budget_usd,
            max_tokens: self.config.max_tokens.unwrap_or(16384),
            can_use_tool: None,
        });
        // Register the Agent tool executor to spawn sub-agents
        let agent_tool_executor = move |input: serde_json::Value, _ctx: &ToolContext| -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<ToolResult, AgentError>> + Send>> {
            let cwd = cwd.clone();
            let api_key = api_key.clone();
            let base_url = base_url.clone();
            let model = model.clone();

            Box::pin(async move {
                // Extract parameters from input
                let description = input["description"].as_str().unwrap_or("subagent");
                let subagent_prompt = input["prompt"].as_str().unwrap_or("");
                let subagent_model = input["model"].as_str().map(|s| s.to_string()).unwrap_or_else(|| model.clone());
                let max_turns = input["max_turns"].as_u64().unwrap_or(10) as u32;

                // Create a new engine for the subagent
                let mut sub_engine = QueryEngine::new(QueryEngineConfig {
                    cwd,
                    model: subagent_model.to_string(),
                    api_key,
                    base_url,
                    tools: vec![],
                    system_prompt: None,
                    max_turns,
                    max_budget_usd: None,
                    max_tokens: 16384,
                    can_use_tool: None,
                });

                // Run the subagent
                match sub_engine.submit_message(subagent_prompt).await {
                    Ok(result_text) => {
                        Ok(ToolResult {
                            result_type: "text".to_string(),
                            tool_use_id: "agent_tool".to_string(),
                            content: format!("[Subagent: {}]\n\n{}", description, result_text),
                            is_error: Some(false),
                        })
                    }
                    Err(e) => {
                        Ok(ToolResult {
                            result_type: "text".to_string(),
                            tool_use_id: "agent_tool".to_string(),
                            content: format!("[Subagent: {}] Error: {}", description, e),
                            is_error: Some(true),
                        })
                    }
                }
            })
        };

        // Register all tool executors
        register_all_tool_executors(&mut engine);
        engine.register_tool("Agent".to_string(), agent_tool_executor);

        // Pass existing messages to engine for continuing conversation
        engine.set_messages(self.messages.clone());

        let start = std::time::Instant::now();
        let response_text = engine.submit_message(prompt).await?;
        let messages = engine.get_messages();

        // Get usage from last assistant message if available
        let usage = TokenUsage {
            input_tokens: 100, // Would need to extract from engine
            output_tokens: 50,
            cache_creation_input_tokens: None,
            cache_read_input_tokens: None,
        };

        // Store messages in agent
        self.messages = messages;

        Ok(QueryResult {
            text: response_text,
            usage,
            num_turns: engine.get_turn_count(),
            duration_ms: start.elapsed().as_millis() as u64,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_create_agent() {
        // Test that Agent can be created with options
        let agent = Agent::create(AgentOptions {
            model: Some("claude-sonnet-4-6".to_string()),
            ..Default::default()
        });
        // Model will be from .env if set, otherwise from options, otherwise default
        assert!(!agent.get_model().is_empty());
    }
}