chore: sync current workspace changes
Desktop CI Build / Build macOS ARM64 DMG (push) Has been cancelled
Desktop CI Build / Build Windows x64 (push) Has been cancelled
Desktop CI Build / Build macOS ARM64 DMG (push) Has been cancelled
Desktop CI Build / Build Windows x64 (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,75 @@
|
||||
// Example 1: Simple Query with Streaming
|
||||
//
|
||||
// Demonstrates the basic Agent::new() + query() flow with
|
||||
// real-time event streaming.
|
||||
//
|
||||
// Run: cargo run --example 01-simple-query
|
||||
|
||||
use open_agent_sdk::types;
|
||||
use open_agent_sdk::{Agent, AgentOptions, SDKMessage};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
println!("--- Example 1: Simple Query ---");
|
||||
|
||||
let mut agent = Agent::new(AgentOptions {
|
||||
max_turns: Some(10),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let (mut rx, handle) = agent
|
||||
.query("Read Cargo.toml and tell me the project name and version in one sentence.")
|
||||
.await;
|
||||
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
SDKMessage::Assistant { message, .. } => {
|
||||
for block in &message.content {
|
||||
match block {
|
||||
types::ContentBlock::ToolUse { id, name, input } => {
|
||||
let input_str = serde_json::to_string(input).unwrap_or_default();
|
||||
let truncated = if input_str.len() > 80 {
|
||||
format!("{}...", &input_str[..80])
|
||||
} else {
|
||||
input_str
|
||||
};
|
||||
println!("[Tool] {}({})", name, truncated);
|
||||
}
|
||||
types::ContentBlock::Text { text } => {
|
||||
if !text.trim().is_empty() {
|
||||
println!("\nAssistant: {}", text);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
SDKMessage::ToolResult {
|
||||
tool_name, content, ..
|
||||
} => {
|
||||
let truncated = if content.len() > 200 {
|
||||
format!("{}...", &content[..200])
|
||||
} else {
|
||||
content
|
||||
};
|
||||
println!("[Result: {}] {}", tool_name, truncated);
|
||||
}
|
||||
SDKMessage::Result { usage, .. } => {
|
||||
println!("\n--- Result ---");
|
||||
println!(
|
||||
"Tokens: {} in / {} out",
|
||||
usage.input_tokens, usage.output_tokens
|
||||
);
|
||||
}
|
||||
SDKMessage::Error { message } => {
|
||||
eprintln!("Error: {}", message);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
handle.await.unwrap();
|
||||
agent.close().await;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// Example 2: Multi-Tool Orchestration
|
||||
//
|
||||
// The agent autonomously uses Glob, Bash, and Read to find files,
|
||||
// count lines, and provide a summary.
|
||||
//
|
||||
// Run: cargo run --example 02-multi-tool
|
||||
|
||||
use open_agent_sdk::types;
|
||||
use open_agent_sdk::{Agent, AgentOptions, SDKMessage};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
println!("--- Example 2: Multi-Tool ---");
|
||||
|
||||
let mut agent = Agent::new(AgentOptions {
|
||||
max_turns: Some(15),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let (mut rx, handle) = agent
|
||||
.query(
|
||||
"Find all .rs files in the src/ directory, count the total lines of code \
|
||||
with wc, and give me a brief summary.",
|
||||
)
|
||||
.await;
|
||||
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
SDKMessage::Assistant { message, .. } => {
|
||||
for block in &message.content {
|
||||
match block {
|
||||
types::ContentBlock::ToolUse { name, input, .. } => {
|
||||
let input_str = serde_json::to_string(input).unwrap_or_default();
|
||||
let truncated = if input_str.len() > 80 {
|
||||
format!("{}...", &input_str[..80])
|
||||
} else {
|
||||
input_str
|
||||
};
|
||||
println!("[{}] {}", name, truncated);
|
||||
}
|
||||
types::ContentBlock::Text { text } => {
|
||||
if !text.trim().is_empty() {
|
||||
println!("\n{}", text);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
SDKMessage::Result { usage, .. } => {
|
||||
println!("\n--- Done ---");
|
||||
println!(
|
||||
"Tokens: {} in / {} out",
|
||||
usage.input_tokens, usage.output_tokens
|
||||
);
|
||||
}
|
||||
SDKMessage::Error { message } => {
|
||||
eprintln!("Error: {}", message);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
handle.await.unwrap();
|
||||
agent.close().await;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Example 3: Multi-Turn Conversation
|
||||
//
|
||||
// Three turns with context retention: create a file, read it back,
|
||||
// then delete it.
|
||||
//
|
||||
// Run: cargo run --example 03-multi-turn
|
||||
|
||||
use open_agent_sdk::{Agent, AgentOptions};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
println!("--- Example 3: Multi-Turn ---");
|
||||
|
||||
let mut agent = Agent::new(AgentOptions {
|
||||
max_turns: Some(10),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Turn 1: Create a file
|
||||
println!("\n[Turn 1] Creating file...");
|
||||
match agent
|
||||
.prompt(
|
||||
"Use Bash to create a file /tmp/sdk-test-rust.txt with the text 'Hello from Rust SDK!'",
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(result) => println!("Response: {}", result.text),
|
||||
Err(e) => eprintln!("Error: {}", e),
|
||||
}
|
||||
|
||||
// Turn 2: Read it back
|
||||
println!("\n[Turn 2] Reading file...");
|
||||
match agent
|
||||
.prompt("Now read /tmp/sdk-test-rust.txt and tell me what it says")
|
||||
.await
|
||||
{
|
||||
Ok(result) => println!("Response: {}", result.text),
|
||||
Err(e) => eprintln!("Error: {}", e),
|
||||
}
|
||||
|
||||
// Turn 3: Delete it
|
||||
println!("\n[Turn 3] Cleaning up...");
|
||||
match agent
|
||||
.prompt("Delete /tmp/sdk-test-rust.txt using Bash")
|
||||
.await
|
||||
{
|
||||
Ok(result) => {
|
||||
println!("Response: {}", result.text);
|
||||
println!("\nTotal messages: {}", agent.get_messages().len());
|
||||
}
|
||||
Err(e) => eprintln!("Error: {}", e),
|
||||
}
|
||||
|
||||
agent.close().await;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// Example 4: Blocking Prompt API
|
||||
//
|
||||
// Uses agent.prompt() for a quick one-shot query without streaming.
|
||||
//
|
||||
// Run: cargo run --example 04-prompt-api
|
||||
|
||||
use open_agent_sdk::{Agent, AgentOptions};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
println!("--- Example 4: Prompt API ---");
|
||||
|
||||
let mut agent = Agent::new(AgentOptions {
|
||||
max_turns: Some(5),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
match agent
|
||||
.prompt("Run 'rustc --version' and 'cargo --version' using Bash, and tell me the versions.")
|
||||
.await
|
||||
{
|
||||
Ok(result) => {
|
||||
println!("\nResponse: {}", result.text);
|
||||
println!("\nTurns: {}", result.num_turns);
|
||||
println!(
|
||||
"Tokens: {} in / {} out",
|
||||
result.usage.input_tokens, result.usage.output_tokens
|
||||
);
|
||||
println!("Duration: {}ms", result.duration_ms);
|
||||
}
|
||||
Err(e) => eprintln!("Error: {}", e),
|
||||
}
|
||||
|
||||
agent.close().await;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Example 5: Custom System Prompt
|
||||
//
|
||||
// Creates a specialized code reviewer agent with a custom system prompt.
|
||||
//
|
||||
// Run: cargo run --example 05-custom-system-prompt
|
||||
|
||||
use open_agent_sdk::types;
|
||||
use open_agent_sdk::{Agent, AgentOptions, SDKMessage};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
println!("--- Example 5: Custom System Prompt ---");
|
||||
|
||||
let mut agent = Agent::new(AgentOptions {
|
||||
system_prompt: Some(
|
||||
"You are a senior code reviewer. When analyzing code, focus on:\n\
|
||||
1. Security vulnerabilities\n\
|
||||
2. Performance issues\n\
|
||||
3. Maintainability concerns\n\
|
||||
Be concise and use bullet points."
|
||||
.to_string(),
|
||||
),
|
||||
max_turns: Some(10),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let (mut rx, handle) = agent
|
||||
.query("Read src/lib.rs and give a brief code review.")
|
||||
.await;
|
||||
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
SDKMessage::Assistant { message, .. } => {
|
||||
let text = types::extract_text(&message);
|
||||
if !text.is_empty() {
|
||||
print!("{}", text);
|
||||
}
|
||||
}
|
||||
SDKMessage::Result { .. } => {
|
||||
println!("\n\n--- Done ---");
|
||||
}
|
||||
SDKMessage::Error { message } => {
|
||||
eprintln!("Error: {}", message);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
handle.await.unwrap();
|
||||
agent.close().await;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// Example 6: MCP Server Integration
|
||||
//
|
||||
// Connects to the filesystem MCP server via stdio transport.
|
||||
// Requires: npm install -g @modelcontextprotocol/server-filesystem
|
||||
//
|
||||
// Run: cargo run --example 06-mcp-server
|
||||
|
||||
use open_agent_sdk::types::{self, McpServerConfig};
|
||||
use open_agent_sdk::{Agent, AgentOptions, SDKMessage};
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
println!("--- Example 6: MCP Server ---");
|
||||
|
||||
let mut mcp_servers = HashMap::new();
|
||||
mcp_servers.insert(
|
||||
"filesystem".to_string(),
|
||||
McpServerConfig::Stdio {
|
||||
command: "npx".to_string(),
|
||||
args: vec![
|
||||
"-y".to_string(),
|
||||
"@modelcontextprotocol/server-filesystem".to_string(),
|
||||
"/tmp".to_string(),
|
||||
],
|
||||
env: HashMap::new(),
|
||||
},
|
||||
);
|
||||
|
||||
let agent = Agent::new(AgentOptions {
|
||||
mcp_servers,
|
||||
max_turns: Some(10),
|
||||
..Default::default()
|
||||
})
|
||||
.await;
|
||||
|
||||
match agent {
|
||||
Ok(mut agent) => {
|
||||
let (mut rx, handle) = agent
|
||||
.query("List files in /tmp using the filesystem MCP tools. Be brief.")
|
||||
.await;
|
||||
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
SDKMessage::Assistant { message, .. } => {
|
||||
let text = types::extract_text(&message);
|
||||
if !text.is_empty() {
|
||||
print!("{}", text);
|
||||
}
|
||||
}
|
||||
SDKMessage::Result { .. } => {
|
||||
println!("\n--- Done ---");
|
||||
}
|
||||
SDKMessage::Error { message } => {
|
||||
eprintln!("Error: {}", message);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
handle.await.unwrap();
|
||||
agent.close().await;
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"Failed to create agent: {}\n\
|
||||
Make sure the MCP server is installed:\n\
|
||||
npm install -g @modelcontextprotocol/server-filesystem",
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
// Example 7: Custom Tools
|
||||
//
|
||||
// Shows how to define and use custom tools alongside built-in tools.
|
||||
//
|
||||
// Run: cargo run --example 07-custom-tools
|
||||
|
||||
use async_trait::async_trait;
|
||||
use open_agent_sdk::types::{self, Tool, ToolError, ToolInputSchema, ToolResult, ToolUseContext};
|
||||
use open_agent_sdk::{Agent, AgentOptions, SDKMessage};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
// --- GetWeather tool ---
|
||||
|
||||
struct WeatherTool;
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for WeatherTool {
|
||||
fn name(&self) -> &str {
|
||||
"GetWeather"
|
||||
}
|
||||
fn description(&self) -> &str {
|
||||
"Get current weather for a city. Returns temperature and conditions."
|
||||
}
|
||||
fn input_schema(&self) -> ToolInputSchema {
|
||||
ToolInputSchema {
|
||||
schema_type: "object".to_string(),
|
||||
properties: HashMap::from([(
|
||||
"city".to_string(),
|
||||
json!({"type": "string", "description": "City name (e.g., \"Tokyo\", \"London\")"}),
|
||||
)]),
|
||||
required: vec!["city".to_string()],
|
||||
additional_properties: Some(false),
|
||||
}
|
||||
}
|
||||
fn is_read_only(&self, _: &Value) -> bool {
|
||||
true
|
||||
}
|
||||
async fn call(&self, input: Value, _ctx: &ToolUseContext) -> Result<ToolResult, ToolError> {
|
||||
let city = input
|
||||
.get("city")
|
||||
.and_then(|c| c.as_str())
|
||||
.unwrap_or("Unknown");
|
||||
let temps: HashMap<&str, i32> = HashMap::from([
|
||||
("tokyo", 22),
|
||||
("london", 14),
|
||||
("beijing", 25),
|
||||
("new york", 18),
|
||||
("paris", 16),
|
||||
]);
|
||||
let temp = temps
|
||||
.get(city.to_lowercase().as_str())
|
||||
.copied()
|
||||
.unwrap_or(20);
|
||||
Ok(ToolResult::text(format!(
|
||||
"Weather in {}: {}°C, partly cloudy",
|
||||
city, temp
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
// --- Calculator tool ---
|
||||
|
||||
struct CalculatorTool;
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for CalculatorTool {
|
||||
fn name(&self) -> &str {
|
||||
"Calculator"
|
||||
}
|
||||
fn description(&self) -> &str {
|
||||
"Evaluate a simple mathematical expression with two numbers and an operator (+, -, *, /, **)."
|
||||
}
|
||||
fn input_schema(&self) -> ToolInputSchema {
|
||||
ToolInputSchema {
|
||||
schema_type: "object".to_string(),
|
||||
properties: HashMap::from([(
|
||||
"expression".to_string(),
|
||||
json!({"type": "string", "description": "Math expression (e.g., \"2 ** 10\", \"42 * 17\")"}),
|
||||
)]),
|
||||
required: vec!["expression".to_string()],
|
||||
additional_properties: Some(false),
|
||||
}
|
||||
}
|
||||
fn is_read_only(&self, _: &Value) -> bool {
|
||||
true
|
||||
}
|
||||
async fn call(&self, input: Value, _ctx: &ToolUseContext) -> Result<ToolResult, ToolError> {
|
||||
let expr = input
|
||||
.get("expression")
|
||||
.and_then(|e| e.as_str())
|
||||
.unwrap_or("0");
|
||||
let result = eval_simple(expr);
|
||||
Ok(ToolResult::text(match result {
|
||||
Ok(val) => format!("{} = {}", expr, val),
|
||||
Err(e) => format!("Error: {}", e),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fn eval_simple(expr: &str) -> Result<String, String> {
|
||||
for op in &["**", "*", "/", "+", "-"] {
|
||||
if let Some(idx) = expr.find(op) {
|
||||
if idx == 0 {
|
||||
continue;
|
||||
}
|
||||
let left: f64 = expr[..idx]
|
||||
.trim()
|
||||
.parse()
|
||||
.map_err(|_| "invalid number".to_string())?;
|
||||
let right: f64 = expr[idx + op.len()..]
|
||||
.trim()
|
||||
.parse()
|
||||
.map_err(|_| "invalid number".to_string())?;
|
||||
let result = match *op {
|
||||
"**" => left.powf(right),
|
||||
"*" => left * right,
|
||||
"/" => {
|
||||
if right == 0.0 {
|
||||
return Err("division by zero".to_string());
|
||||
}
|
||||
left / right
|
||||
}
|
||||
"+" => left + right,
|
||||
"-" => left - right,
|
||||
_ => return Err(format!("unknown operator: {}", op)),
|
||||
};
|
||||
return if result == (result as i64) as f64 {
|
||||
Ok(format!("{}", result as i64))
|
||||
} else {
|
||||
Ok(format!("{:.4}", result))
|
||||
};
|
||||
}
|
||||
}
|
||||
Err(format!("cannot evaluate: {}", expr))
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
println!("--- Example 7: Custom Tools ---");
|
||||
|
||||
let mut agent = Agent::new(AgentOptions {
|
||||
max_turns: Some(10),
|
||||
custom_tools: vec![Arc::new(WeatherTool), Arc::new(CalculatorTool)],
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
println!("Loaded tools with 2 custom tools (GetWeather, Calculator)\n");
|
||||
|
||||
let (mut rx, handle) = agent
|
||||
.query("What is the weather in Tokyo and London? Also calculate 2 ** 10 * 3. Be brief.")
|
||||
.await;
|
||||
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
SDKMessage::Assistant { message, .. } => {
|
||||
for block in &message.content {
|
||||
match block {
|
||||
types::ContentBlock::ToolUse { name, input, .. } => {
|
||||
println!(
|
||||
"[{}] {}",
|
||||
name,
|
||||
serde_json::to_string(input).unwrap_or_default()
|
||||
);
|
||||
}
|
||||
types::ContentBlock::Text { text } => {
|
||||
if !text.trim().is_empty() {
|
||||
println!("\n{}", text);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
SDKMessage::Result { .. } => {
|
||||
println!("\n--- Done ---");
|
||||
}
|
||||
SDKMessage::Error { message } => {
|
||||
eprintln!("Error: {}", message);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
handle.await.unwrap();
|
||||
agent.close().await;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// Example 8: One-shot Query
|
||||
//
|
||||
// Quick one-shot agent query with restricted tools.
|
||||
//
|
||||
// Run: cargo run --example 08-oneshot-query
|
||||
|
||||
use open_agent_sdk::{Agent, AgentOptions};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
println!("--- Example 8: One-shot Query ---");
|
||||
|
||||
let mut agent = Agent::new(AgentOptions {
|
||||
max_turns: Some(5),
|
||||
allowed_tools: Some(vec!["Bash".to_string(), "Glob".to_string()]),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
match agent
|
||||
.prompt("List the files in the current directory. Be brief.")
|
||||
.await
|
||||
{
|
||||
Ok(result) => {
|
||||
println!("\n{}", result.text);
|
||||
println!(
|
||||
"\n({} turns, {} tokens)",
|
||||
result.num_turns,
|
||||
result.usage.input_tokens + result.usage.output_tokens
|
||||
);
|
||||
}
|
||||
Err(e) => eprintln!("Error: {}", e),
|
||||
}
|
||||
|
||||
agent.close().await;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// Example 9: Subagents
|
||||
//
|
||||
// Creates a specialized code-reviewer subagent with restricted tools.
|
||||
//
|
||||
// Run: cargo run --example 09-subagents
|
||||
|
||||
use open_agent_sdk::agent::SubagentDefinition;
|
||||
use open_agent_sdk::types;
|
||||
use open_agent_sdk::{Agent, AgentOptions, SDKMessage};
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
println!("--- Example 9: Subagents ---");
|
||||
|
||||
let mut agents = HashMap::new();
|
||||
agents.insert(
|
||||
"code-reviewer".to_string(),
|
||||
SubagentDefinition {
|
||||
description: "Expert code reviewer that analyzes code quality".to_string(),
|
||||
instructions: Some(
|
||||
"You are an expert code reviewer. Analyze code for:\n\
|
||||
- Code quality and readability\n\
|
||||
- Potential bugs or edge cases\n\
|
||||
- Suggested improvements\n\
|
||||
Be concise and constructive."
|
||||
.to_string(),
|
||||
),
|
||||
tools: Some(vec![
|
||||
"Read".to_string(),
|
||||
"Glob".to_string(),
|
||||
"Grep".to_string(),
|
||||
]),
|
||||
model: None,
|
||||
},
|
||||
);
|
||||
|
||||
let mut agent = Agent::new(AgentOptions {
|
||||
max_turns: Some(15),
|
||||
agents,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let (mut rx, handle) = agent
|
||||
.query("Use the code-reviewer agent to review src/lib.rs")
|
||||
.await;
|
||||
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
SDKMessage::Assistant { message, .. } => {
|
||||
let text = types::extract_text(&message);
|
||||
if !text.is_empty() {
|
||||
print!("{}", text);
|
||||
}
|
||||
}
|
||||
SDKMessage::Result { cost_usd, .. } => {
|
||||
println!("\n\n--- Done (${:.4}) ---", cost_usd);
|
||||
}
|
||||
SDKMessage::Error { message } => {
|
||||
eprintln!("Error: {}", message);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
handle.await.unwrap();
|
||||
agent.close().await;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// Example 10: Permissions
|
||||
//
|
||||
// Read-only agent with AllowedTools restriction.
|
||||
// Can only use Read, Glob, Grep — no write or execute.
|
||||
//
|
||||
// Run: cargo run --example 10-permissions
|
||||
|
||||
use open_agent_sdk::types;
|
||||
use open_agent_sdk::{Agent, AgentOptions, SDKMessage};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
println!("--- Example 10: Permissions ---");
|
||||
|
||||
let mut agent = Agent::new(AgentOptions {
|
||||
max_turns: Some(10),
|
||||
allowed_tools: Some(vec![
|
||||
"Read".to_string(),
|
||||
"Glob".to_string(),
|
||||
"Grep".to_string(),
|
||||
]),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let (mut rx, handle) = agent
|
||||
.query("Review the code in src/lib.rs for best practices and potential improvements.")
|
||||
.await;
|
||||
|
||||
while let Some(event) = rx.recv().await {
|
||||
match event {
|
||||
SDKMessage::Assistant { message, .. } => {
|
||||
let text = types::extract_text(&message);
|
||||
if !text.is_empty() {
|
||||
print!("{}", text);
|
||||
}
|
||||
}
|
||||
SDKMessage::Result { cost_usd, .. } => {
|
||||
println!("\n\n--- Done (${:.4}) ---", cost_usd);
|
||||
}
|
||||
SDKMessage::Error { message } => {
|
||||
eprintln!("Error: {}", message);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
handle.await.unwrap();
|
||||
agent.close().await;
|
||||
}
|
||||
@@ -0,0 +1,590 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Open Agent SDK - Chat</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background: #f9fafb;
|
||||
color: #1a1a1a;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
/* Header */
|
||||
.header {
|
||||
padding: 16px 24px;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
background: #fff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.header h1 {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: #111;
|
||||
}
|
||||
.header .actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
.btn-icon {
|
||||
width: 36px; height: 36px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #e5e7eb;
|
||||
background: #fff;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 16px;
|
||||
color: #666;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
.btn-icon:hover { background: #f3f4f6; border-color: #d1d5db; }
|
||||
|
||||
/* Chat area */
|
||||
.chat-container {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 24px;
|
||||
max-width: 800px;
|
||||
width: 100%;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
/* Welcome screen */
|
||||
.welcome {
|
||||
text-align: center;
|
||||
padding: 80px 20px 40px;
|
||||
}
|
||||
.welcome h2 {
|
||||
font-size: 28px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 32px;
|
||||
color: #111;
|
||||
}
|
||||
.suggestions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.suggestion {
|
||||
padding: 8px 16px;
|
||||
border-radius: 20px;
|
||||
border: 1px solid #e5e7eb;
|
||||
background: #fff;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
color: #555;
|
||||
transition: all 0.15s;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.suggestion:hover { border-color: #c4c4c4; background: #f9fafb; }
|
||||
|
||||
/* Messages */
|
||||
.message { margin-bottom: 20px; animation: fadeIn 0.2s ease; }
|
||||
@keyframes fadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
|
||||
|
||||
.message-user {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.message-user .bubble {
|
||||
background: #111;
|
||||
color: #fff;
|
||||
padding: 10px 16px;
|
||||
border-radius: 18px 18px 4px 18px;
|
||||
max-width: 70%;
|
||||
font-size: 15px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.message-assistant {
|
||||
padding-left: 4px;
|
||||
}
|
||||
.message-assistant .text-content {
|
||||
font-size: 15px;
|
||||
line-height: 1.7;
|
||||
color: #1a1a1a;
|
||||
max-width: 100%;
|
||||
}
|
||||
.message-assistant .text-content p { margin-bottom: 8px; }
|
||||
.message-assistant .text-content strong { font-weight: 600; }
|
||||
.message-assistant .text-content code {
|
||||
background: #f3f4f6;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
font-family: 'SF Mono', Monaco, monospace;
|
||||
font-size: 13px;
|
||||
}
|
||||
.message-assistant .text-content pre {
|
||||
background: #1e1e1e;
|
||||
color: #d4d4d4;
|
||||
padding: 12px 16px;
|
||||
border-radius: 8px;
|
||||
overflow-x: auto;
|
||||
margin: 8px 0;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.message-assistant .text-content pre code {
|
||||
background: none;
|
||||
padding: 0;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
/* Tool calls */
|
||||
.tool-call {
|
||||
background: #f9fafb;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 12px;
|
||||
padding: 10px 14px;
|
||||
margin: 8px 0;
|
||||
font-size: 13px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.tool-call .tool-icon {
|
||||
width: 28px; height: 28px;
|
||||
border-radius: 6px;
|
||||
background: #f3f4f6;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 14px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.tool-call .tool-name {
|
||||
font-weight: 600;
|
||||
color: #374151;
|
||||
margin-right: 6px;
|
||||
}
|
||||
.tool-call .tool-input {
|
||||
color: #9ca3af;
|
||||
font-family: 'SF Mono', Monaco, monospace;
|
||||
font-size: 12px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.tool-call.tool-error { border-color: #fecaca; background: #fef2f2; }
|
||||
.tool-call.tool-error .tool-icon { background: #fee2e2; }
|
||||
|
||||
.tool-result-output {
|
||||
background: #f9fafb;
|
||||
border-left: 3px solid #e5e7eb;
|
||||
margin: 0 0 8px 36px;
|
||||
padding: 8px 12px;
|
||||
border-radius: 0 8px 8px 0;
|
||||
font-size: 12px;
|
||||
max-height: 200px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.tool-result-output pre {
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
font-family: 'SF Mono', Monaco, monospace;
|
||||
font-size: 12px;
|
||||
color: #374151;
|
||||
background: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* Thinking */
|
||||
.thinking-block {
|
||||
background: #fffbeb;
|
||||
border: 1px solid #fde68a;
|
||||
border-radius: 12px;
|
||||
padding: 10px 14px;
|
||||
margin: 8px 0;
|
||||
font-size: 13px;
|
||||
color: #92400e;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
/* Result banner */
|
||||
.result-banner {
|
||||
background: #ecfdf5;
|
||||
border: 1px solid #a7f3d0;
|
||||
border-radius: 12px;
|
||||
padding: 10px 16px;
|
||||
margin: 12px 0;
|
||||
font-size: 14px;
|
||||
color: #065f46;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.result-banner .check { font-size: 16px; }
|
||||
.result-banner .stats {
|
||||
color: #047857;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* Error */
|
||||
.error-banner {
|
||||
background: #fef2f2;
|
||||
border: 1px solid #fecaca;
|
||||
border-radius: 12px;
|
||||
padding: 10px 16px;
|
||||
margin: 12px 0;
|
||||
font-size: 14px;
|
||||
color: #991b1b;
|
||||
}
|
||||
|
||||
/* Typing indicator */
|
||||
.typing {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
padding: 8px 0;
|
||||
}
|
||||
.typing span {
|
||||
width: 6px; height: 6px;
|
||||
background: #9ca3af;
|
||||
border-radius: 50%;
|
||||
animation: bounce 1.2s infinite;
|
||||
}
|
||||
.typing span:nth-child(2) { animation-delay: 0.2s; }
|
||||
.typing span:nth-child(3) { animation-delay: 0.4s; }
|
||||
@keyframes bounce {
|
||||
0%, 80%, 100% { transform: translateY(0); }
|
||||
40% { transform: translateY(-6px); }
|
||||
}
|
||||
|
||||
/* Input area */
|
||||
.input-area {
|
||||
padding: 16px 24px 24px;
|
||||
background: #fff;
|
||||
border-top: 1px solid #e5e7eb;
|
||||
}
|
||||
.input-wrapper {
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
position: relative;
|
||||
}
|
||||
.input-box {
|
||||
width: 100%;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 16px;
|
||||
padding: 14px 52px 14px 16px;
|
||||
font-size: 15px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
resize: none;
|
||||
min-height: 52px;
|
||||
max-height: 200px;
|
||||
line-height: 1.5;
|
||||
transition: border-color 0.15s;
|
||||
background: #fff;
|
||||
}
|
||||
.input-box:focus { border-color: #a3a3a3; }
|
||||
.input-box::placeholder { color: #9ca3af; }
|
||||
.input-box:disabled { background: #f9fafb; color: #9ca3af; }
|
||||
|
||||
.send-btn {
|
||||
position: absolute;
|
||||
right: 8px;
|
||||
bottom: 8px;
|
||||
width: 36px; height: 36px;
|
||||
border-radius: 10px;
|
||||
border: none;
|
||||
background: #111;
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 18px;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
.send-btn:hover { background: #333; }
|
||||
.send-btn:disabled { background: #d1d5db; cursor: not-allowed; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="header">
|
||||
<h1>Open Agent SDK</h1>
|
||||
<div class="actions">
|
||||
<button class="btn-icon" onclick="newSession()" title="New session">+</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="chat-container" id="chat">
|
||||
<div class="welcome" id="welcome">
|
||||
<h2>What can I do for you?</h2>
|
||||
<div class="suggestions">
|
||||
<div class="suggestion" onclick="sendSuggestion('List all Rust files in this project')">📁 List Rust files</div>
|
||||
<div class="suggestion" onclick="sendSuggestion('Read Cargo.toml and explain the dependencies')">📄 Read Cargo.toml</div>
|
||||
<div class="suggestion" onclick="sendSuggestion('Count lines of code in the src directory')">📊 Count lines</div>
|
||||
<div class="suggestion" onclick="sendSuggestion('What is my Rust version and OS?')">💻 System info</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="input-area">
|
||||
<div class="input-wrapper">
|
||||
<textarea
|
||||
class="input-box"
|
||||
id="input"
|
||||
placeholder="Assign a task or ask anything"
|
||||
rows="1"
|
||||
onkeydown="handleKey(event)"
|
||||
oninput="autoResize(this)"
|
||||
></textarea>
|
||||
<button class="send-btn" id="sendBtn" onclick="sendMessage()">↑</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const chat = document.getElementById('chat');
|
||||
const input = document.getElementById('input');
|
||||
const sendBtn = document.getElementById('sendBtn');
|
||||
const welcome = document.getElementById('welcome');
|
||||
let isStreaming = false;
|
||||
|
||||
const toolIcons = {
|
||||
'Bash': '>_',
|
||||
'Read': '📄',
|
||||
'Write': '📝',
|
||||
'Edit': '✏️',
|
||||
'Glob': '🔍',
|
||||
'Grep': '🔎',
|
||||
'WebFetch': '🌐',
|
||||
'WebSearch': '🔎',
|
||||
'Agent': '🤖',
|
||||
'TaskCreate': '📋',
|
||||
};
|
||||
|
||||
function getToolIcon(name) {
|
||||
if (toolIcons[name]) return toolIcons[name];
|
||||
if (name.startsWith('mcp__')) return '🔌';
|
||||
return '🔧';
|
||||
}
|
||||
|
||||
function autoResize(el) {
|
||||
el.style.height = 'auto';
|
||||
el.style.height = Math.min(el.scrollHeight, 200) + 'px';
|
||||
}
|
||||
|
||||
function handleKey(e) {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
sendMessage();
|
||||
}
|
||||
}
|
||||
|
||||
function sendSuggestion(text) {
|
||||
input.value = text;
|
||||
sendMessage();
|
||||
}
|
||||
|
||||
function scrollToBottom() {
|
||||
chat.scrollTop = chat.scrollHeight;
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function renderMarkdown(text) {
|
||||
let html = escapeHtml(text);
|
||||
html = html.replace(/```(\w*)\n([\s\S]*?)```/g, '<pre><code>$2</code></pre>');
|
||||
html = html.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>');
|
||||
html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
|
||||
html = html.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
|
||||
html = html.replace(/^- (.+)$/gm, '• $1');
|
||||
html = html.replace(/\n\n/g, '</p><p>');
|
||||
html = '<p>' + html + '</p>';
|
||||
html = html.replace(/\n/g, '<br>');
|
||||
return html;
|
||||
}
|
||||
|
||||
async function newSession() {
|
||||
await fetch('/api/new', { method: 'POST' });
|
||||
chat.innerHTML = `
|
||||
<div class="welcome" id="welcome">
|
||||
<h2>What can I do for you?</h2>
|
||||
<div class="suggestions">
|
||||
<div class="suggestion" onclick="sendSuggestion('List all Rust files in this project')">📁 List Rust files</div>
|
||||
<div class="suggestion" onclick="sendSuggestion('Read Cargo.toml and explain the dependencies')">📄 Read Cargo.toml</div>
|
||||
<div class="suggestion" onclick="sendSuggestion('Count lines of code in the src directory')">📊 Count lines</div>
|
||||
<div class="suggestion" onclick="sendSuggestion('What is my Rust version and OS?')">💻 System info</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
async function sendMessage() {
|
||||
const text = input.value.trim();
|
||||
if (!text || isStreaming) return;
|
||||
|
||||
const w = document.getElementById('welcome');
|
||||
if (w) w.remove();
|
||||
|
||||
chat.innerHTML += `<div class="message message-user"><div class="bubble">${escapeHtml(text)}</div></div>`;
|
||||
|
||||
input.value = '';
|
||||
input.style.height = 'auto';
|
||||
isStreaming = true;
|
||||
sendBtn.disabled = true;
|
||||
input.disabled = true;
|
||||
|
||||
const typingId = 'typing-' + Date.now();
|
||||
chat.innerHTML += `<div class="message message-assistant" id="${typingId}"><div class="typing"><span></span><span></span><span></span></div></div>`;
|
||||
scrollToBottom();
|
||||
|
||||
let accumulatedText = '';
|
||||
let assistantDiv = null;
|
||||
let textContentDiv = null;
|
||||
|
||||
try {
|
||||
const resp = await fetch('/api/chat', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ message: text }),
|
||||
});
|
||||
|
||||
const reader = resp.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() || '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith('data: ')) continue;
|
||||
const jsonStr = line.slice(6);
|
||||
if (!jsonStr) continue;
|
||||
|
||||
let event;
|
||||
try { event = JSON.parse(jsonStr); } catch { continue; }
|
||||
|
||||
const typingEl = document.getElementById(typingId);
|
||||
if (typingEl) typingEl.remove();
|
||||
|
||||
if (!assistantDiv) {
|
||||
assistantDiv = document.createElement('div');
|
||||
assistantDiv.className = 'message message-assistant';
|
||||
chat.appendChild(assistantDiv);
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case 'text':
|
||||
accumulatedText += event.data.text;
|
||||
if (!textContentDiv) {
|
||||
textContentDiv = document.createElement('div');
|
||||
textContentDiv.className = 'text-content';
|
||||
assistantDiv.appendChild(textContentDiv);
|
||||
}
|
||||
textContentDiv.innerHTML = renderMarkdown(accumulatedText);
|
||||
scrollToBottom();
|
||||
break;
|
||||
|
||||
case 'tool_use': {
|
||||
textContentDiv = null;
|
||||
accumulatedText = '';
|
||||
const inputStr = JSON.stringify(event.data.input || {});
|
||||
const tc = document.createElement('div');
|
||||
tc.className = 'tool-call';
|
||||
tc.id = 'tool-' + event.data.id;
|
||||
tc.innerHTML = `
|
||||
<div class="tool-icon">${getToolIcon(event.data.name)}</div>
|
||||
<span class="tool-name">${escapeHtml(event.data.name)}</span>
|
||||
<span class="tool-input">${escapeHtml(inputStr)}</span>
|
||||
`;
|
||||
assistantDiv.appendChild(tc);
|
||||
scrollToBottom();
|
||||
break;
|
||||
}
|
||||
|
||||
case 'tool_result': {
|
||||
const toolCallEl = document.getElementById('tool-' + event.data.tool_use_id);
|
||||
if (toolCallEl) {
|
||||
const resultDiv = document.createElement('div');
|
||||
resultDiv.className = 'tool-result-output';
|
||||
const content = event.data.content || '';
|
||||
const truncated = content.length > 500 ? content.substring(0, 500) + '...' : content;
|
||||
resultDiv.innerHTML = `<pre>${escapeHtml(truncated)}</pre>`;
|
||||
toolCallEl.insertAdjacentElement('afterend', resultDiv);
|
||||
scrollToBottom();
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'thinking': {
|
||||
const th = document.createElement('div');
|
||||
th.className = 'thinking-block';
|
||||
th.textContent = event.data.thinking;
|
||||
assistantDiv.appendChild(th);
|
||||
scrollToBottom();
|
||||
break;
|
||||
}
|
||||
|
||||
case 'result': {
|
||||
const d = event.data;
|
||||
const costStr = d.cost < 0.01 ? `$${d.cost.toFixed(4)}` : `$${d.cost.toFixed(2)}`;
|
||||
const durStr = (d.duration_ms / 1000).toFixed(1) + 's';
|
||||
const banner = document.createElement('div');
|
||||
banner.className = 'result-banner';
|
||||
banner.innerHTML = `
|
||||
<span class="check">✅</span>
|
||||
<span>Done</span>
|
||||
<span class="stats">· ${costStr} · ${durStr} · ${d.input_tokens + d.output_tokens} tokens</span>
|
||||
`;
|
||||
assistantDiv.appendChild(banner);
|
||||
scrollToBottom();
|
||||
break;
|
||||
}
|
||||
|
||||
case 'error': {
|
||||
const errDiv = document.createElement('div');
|
||||
errDiv.className = 'error-banner';
|
||||
errDiv.textContent = '❌ ' + (event.data?.message || 'Unknown error');
|
||||
assistantDiv.appendChild(errDiv);
|
||||
scrollToBottom();
|
||||
break;
|
||||
}
|
||||
|
||||
case 'done':
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
const typingEl = document.getElementById(typingId);
|
||||
if (typingEl) typingEl.remove();
|
||||
chat.innerHTML += `<div class="error-banner">❌ ${escapeHtml(err.message)}</div>`;
|
||||
}
|
||||
|
||||
isStreaming = false;
|
||||
sendBtn.disabled = false;
|
||||
input.disabled = false;
|
||||
input.focus();
|
||||
scrollToBottom();
|
||||
}
|
||||
|
||||
input.focus();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,243 @@
|
||||
// Example 11: Web Chat UI
|
||||
//
|
||||
// A web-based chat interface for interacting with the agent.
|
||||
// Shows streaming text, tool calls with input/output, and cost tracking.
|
||||
//
|
||||
// Run: cargo run --example web-chat
|
||||
// Then open http://localhost:8082
|
||||
|
||||
use open_agent_sdk::types;
|
||||
use open_agent_sdk::{Agent, AgentOptions, SDKMessage};
|
||||
use serde::Serialize;
|
||||
use std::sync::Arc;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
const INDEX_HTML: &str = include_str!("index.html");
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct SseEvent {
|
||||
#[serde(rename = "type")]
|
||||
event_type: String,
|
||||
data: serde_json::Value,
|
||||
}
|
||||
|
||||
struct AppState {
|
||||
agent: Option<Agent>,
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let port = std::env::var("PORT").unwrap_or_else(|_| "8082".to_string());
|
||||
let state = Arc::new(Mutex::new(AppState { agent: None }));
|
||||
|
||||
let listener = TcpListener::bind(format!("0.0.0.0:{}", port))
|
||||
.await
|
||||
.expect("Failed to bind");
|
||||
|
||||
println!("🚀 Web Chat running at http://localhost:{}", port);
|
||||
|
||||
loop {
|
||||
let (stream, _) = listener.accept().await.expect("Failed to accept");
|
||||
let state = state.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
handle_connection(stream, state).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_connection(mut stream: tokio::net::TcpStream, state: Arc<Mutex<AppState>>) {
|
||||
let mut buf = vec![0u8; 8192];
|
||||
let n = match stream.read(&mut buf).await {
|
||||
Ok(n) => n,
|
||||
Err(_) => return,
|
||||
};
|
||||
let request = String::from_utf8_lossy(&buf[..n]).to_string();
|
||||
|
||||
let first_line = request.lines().next().unwrap_or("");
|
||||
|
||||
if first_line.starts_with("GET / ") || first_line.starts_with("GET /index.html") {
|
||||
// Serve index.html
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\n\r\n{}",
|
||||
INDEX_HTML.len(),
|
||||
INDEX_HTML
|
||||
);
|
||||
let _ = stream.write_all(response.as_bytes()).await;
|
||||
} else if first_line.starts_with("POST /api/new") {
|
||||
// New session
|
||||
{
|
||||
let mut state = state.lock().await;
|
||||
if let Some(agent) = state.agent.take() {
|
||||
agent.close().await;
|
||||
}
|
||||
}
|
||||
let response =
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"status\":\"ok\"}";
|
||||
let _ = stream.write_all(response.as_bytes()).await;
|
||||
} else if first_line.starts_with("POST /api/chat") {
|
||||
// Extract body from request
|
||||
let body = extract_body(&request);
|
||||
let message = extract_json_field(&body, "message");
|
||||
|
||||
if message.is_empty() {
|
||||
let response =
|
||||
"HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\n\r\ninvalid request";
|
||||
let _ = stream.write_all(response.as_bytes()).await;
|
||||
return;
|
||||
}
|
||||
|
||||
// SSE headers
|
||||
let headers = "HTTP/1.1 200 OK\r\n\
|
||||
Content-Type: text/event-stream\r\n\
|
||||
Cache-Control: no-cache\r\n\
|
||||
Connection: keep-alive\r\n\
|
||||
X-Accel-Buffering: no\r\n\r\n";
|
||||
let _ = stream.write_all(headers.as_bytes()).await;
|
||||
|
||||
let start = std::time::Instant::now();
|
||||
|
||||
// Get or create agent
|
||||
let agent = {
|
||||
let mut state = state.lock().await;
|
||||
if state.agent.is_none() {
|
||||
let model =
|
||||
std::env::var("CODEANY_MODEL").unwrap_or_else(|_| "sonnet-4-6".to_string());
|
||||
match Agent::new(AgentOptions {
|
||||
model: Some(model),
|
||||
max_turns: Some(20),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(a) => state.agent = Some(a),
|
||||
Err(e) => {
|
||||
let event = format_sse("error", &serde_json::json!({"message": e}));
|
||||
let _ = stream.write_all(event.as_bytes()).await;
|
||||
let done = format_sse("done", &serde_json::json!(null));
|
||||
let _ = stream.write_all(done.as_bytes()).await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// We need a mutable reference; use a different approach
|
||||
state.agent.take()
|
||||
};
|
||||
|
||||
let mut agent = agent.unwrap();
|
||||
|
||||
let (mut rx, handle) = agent.query(&message).await;
|
||||
|
||||
while let Some(event) = rx.recv().await {
|
||||
let sse = match &event {
|
||||
SDKMessage::Assistant { message, .. } => {
|
||||
let mut parts = Vec::new();
|
||||
for block in &message.content {
|
||||
match block {
|
||||
types::ContentBlock::Text { text } if !text.is_empty() => {
|
||||
parts.push(format_sse("text", &serde_json::json!({"text": text})));
|
||||
}
|
||||
types::ContentBlock::ToolUse { id, name, input } => {
|
||||
parts.push(format_sse(
|
||||
"tool_use",
|
||||
&serde_json::json!({"id": id, "name": name, "input": input}),
|
||||
));
|
||||
}
|
||||
types::ContentBlock::Thinking { thinking, .. }
|
||||
if !thinking.is_empty() =>
|
||||
{
|
||||
parts.push(format_sse(
|
||||
"thinking",
|
||||
&serde_json::json!({"thinking": thinking}),
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
parts.join("")
|
||||
}
|
||||
SDKMessage::ToolResult {
|
||||
tool_use_id,
|
||||
content,
|
||||
is_error,
|
||||
..
|
||||
} => format_sse(
|
||||
"tool_result",
|
||||
&serde_json::json!({
|
||||
"tool_use_id": tool_use_id,
|
||||
"content": content,
|
||||
"is_error": is_error,
|
||||
}),
|
||||
),
|
||||
SDKMessage::Result {
|
||||
usage,
|
||||
num_turns,
|
||||
cost_usd,
|
||||
..
|
||||
} => format_sse(
|
||||
"result",
|
||||
&serde_json::json!({
|
||||
"num_turns": num_turns,
|
||||
"input_tokens": usage.input_tokens,
|
||||
"output_tokens": usage.output_tokens,
|
||||
"cost": cost_usd,
|
||||
"duration_ms": start.elapsed().as_millis() as u64,
|
||||
}),
|
||||
),
|
||||
SDKMessage::Error { message } => {
|
||||
format_sse("error", &serde_json::json!({"message": message}))
|
||||
}
|
||||
_ => String::new(),
|
||||
};
|
||||
|
||||
if !sse.is_empty() {
|
||||
if stream.write_all(sse.as_bytes()).await.is_err() {
|
||||
break;
|
||||
}
|
||||
let _ = stream.flush().await;
|
||||
}
|
||||
}
|
||||
|
||||
let _ = handle.await;
|
||||
|
||||
let done = format_sse("done", &serde_json::json!(null));
|
||||
let _ = stream.write_all(done.as_bytes()).await;
|
||||
|
||||
// Put agent back
|
||||
let mut state = state.lock().await;
|
||||
state.agent = Some(agent);
|
||||
} else {
|
||||
let response = "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\n\r\nNot Found";
|
||||
let _ = stream.write_all(response.as_bytes()).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn format_sse(event_type: &str, data: &serde_json::Value) -> String {
|
||||
let payload = serde_json::json!({"type": event_type, "data": data});
|
||||
format!("data: {}\n\n", serde_json::to_string(&payload).unwrap())
|
||||
}
|
||||
|
||||
fn extract_body(request: &str) -> String {
|
||||
if let Some(idx) = request.find("\r\n\r\n") {
|
||||
request[idx + 4..].to_string()
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_json_field(body: &str, field: &str) -> String {
|
||||
// Simple JSON field extraction without a full parser dependency
|
||||
if let Ok(value) = serde_json::from_str::<serde_json::Value>(body) {
|
||||
value
|
||||
.get(field)
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
}
|
||||
|
||||
use tokio::io::AsyncReadExt;
|
||||
Reference in New Issue
Block a user