From f4f2887fb30782a8025ce3728c09afe8e1f973c6 Mon Sep 17 00:00:00 2001 From: Hefeng Zhou Date: Tue, 24 Mar 2026 18:14:46 +0800 Subject: [PATCH 1/2] Update user guidence --- manual/ADVANCED_DEVELOPER_MANUAL.md | 315 +++++++ manual/ADVANCED_DEVELOPER_MANUAL_CN.md | 1179 ++++++++++++++++++++++++ manual/USER_DEVELOPER_MANUAL.md | 970 +++++++++++++++++++ 3 files changed, 2464 insertions(+) create mode 100644 manual/ADVANCED_DEVELOPER_MANUAL.md create mode 100644 manual/ADVANCED_DEVELOPER_MANUAL_CN.md create mode 100644 manual/USER_DEVELOPER_MANUAL.md diff --git a/manual/ADVANCED_DEVELOPER_MANUAL.md b/manual/ADVANCED_DEVELOPER_MANUAL.md new file mode 100644 index 0000000..ca7e319 --- /dev/null +++ b/manual/ADVANCED_DEVELOPER_MANUAL.md @@ -0,0 +1,315 @@ +# A3S Code Advanced Developer Manual + +For core developers, architects, and advanced users + +## Table of Contents + +1. Internal Architecture +2. Advanced Configuration +3. Advanced Tool Development +4. Advanced Skill Programming +5. Advanced Hook System +6. Security Hardening +7. Performance Optimization +8. Production Deployment +9. Integration +10. Troubleshooting + +# Chapter 1: Internal Architecture + +## 1.1 Runtime Architecture + +A3S Code uses multi-threaded architecture: +- Main Thread: HTTP API / WebSocket / Scheduled Tasks +- Worker Thread Pool: Multiple Sessions +- I/O Thread Pool: LLM Client / Tool Execution / File I/O + +## 1.2 AgentLoop State Machine + +```rust +pub enum LoopState { + Idle, + Planning, + Executing, + WaitingForLLM, + Compacting, + Error, + Completed, +} +``` + +## 1.3 Circuit Breaker + +```rust +pub struct CircuitBreaker { + failure_threshold: u32, // Default: 3 + reset_timeout: Duration, // Default: 30s +} +``` + +# Chapter 2: Advanced Configuration + +## 2.1 Queue System Configuration + +```hcl +queue { + control_max_concurrency = 2 + query_max_concurrency = 10 + execute_max_concurrency = 5 + generate_max_concurrency = 1 + enable_metrics = true + enable_dlq = true +} +``` + +## 2.2 LLM Client Configuration + +```rust +pub struct LlmClientConfig { + pool_size: usize, // Default: 10 + connection_timeout: Duration, // Default: 30s + request_timeout: Duration, // Default: 120s +} +``` + +## 2.3 Memory Limits + +```rust +pub struct MemoryLimits { + max_session_memory_mb: usize, // Default: 100 + max_message_history: usize, // Default: 100 + max_context_tokens: usize, // Default: 8000 +} +``` + +# Chapter 3: Advanced Tool Development + +## 3.1 Tool Lifecycle + +Register -> Initialize -> Validate Input -> Pre-execute Hook -> Execute -> Post-execute Hook -> Cleanup + +## 3.2 Advanced Tool Trait + +```rust +#[async_trait] +pub trait AdvancedTool: Tool { + async fn initialize(&mut self, config: &ToolConfig) -> Result<()>; + fn validate_input(&self, input: &Value) -> Result<()>; + fn pre_execute(&self, ctx: &Context) -> Result; + async fn execute_async(&self, input: ToolInput) -> Result; + fn post_execute(&self, output: &ToolOutput) -> Result<()>; + async fn cleanup(&mut self) -> Result<()>; +} +``` + +## 3.3 Async Tool Example + +```rust +use async_trait::async_trait; + +pub struct AsyncWebTool { + client: reqwest::Client, + rate_limiter: RateLimiter, +} + +#[async_trait] +impl Tool for AsyncWebTool { + fn name(&self) -> &str { "async_web_fetch" } + + async fn execute(&self, input: ToolInput) -> Result { + self.rate_limiter.acquire().await?; + let response = self.client + .get(input.get("url")?) + .timeout(Duration::from_secs(30)) + .send().await?; + Ok(ToolOutput::new(response.text().await?)) + } +} +``` + +# Chapter 4: Advanced Skill Programming + +## 4.1 Skill Parsing Flow + +1. Frontmatter parsing (YAML) +2. Content extraction (Markdown) +3. Template compilation +4. Permission validation +5. Injection into system prompt + +## 4.2 Programmatic Skill Generation + +```rust +pub struct SkillBuilder { + name: String, + description: String, + allowed_tools: Vec, + content: String, +} + +impl SkillBuilder { + pub fn new(name: &str) -> Self; + pub fn with_description(mut self, desc: &str) -> Self; + pub fn with_tool(mut self, tool: &str) -> Self; + pub fn build(self) -> Skill; +} +``` + +# Chapter 5: Advanced Hook System + +## 5.1 Hook Chains + +```rust +pub struct HookChain { + hooks: Vec<(u32, Box)>, +} + +impl HookChain { + pub fn register(&mut self, priority: u32, hook: Box); + pub async fn execute(&self, event: Event) -> HookResult; +} +``` + +## 5.2 Conditional Hooks + +```rust +pub struct ConditionalHook { + condition: Box bool>, + hook: Box, +} +``` + +# Chapter 6: Security Hardening + +## 6.1 AHP Integration + +```rust +pub struct AHPConfig { + enabled: bool, + harness_endpoint: String, + timeout: Duration, + retry_policy: RetryPolicy, +} +``` + +## 6.2 Sandboxing + +```rust +pub struct SandboxConfig { + enabled: bool, + chroot_path: Option, + network_access: bool, + allowed_paths: Vec, + forbidden_commands: Vec, +} +``` + +# Chapter 7: Performance Optimization + +## 7.1 Token Usage Optimization + +- Use compact context strategies +- Enable message summarization +- Set appropriate token limits + +## 7.2 Caching Strategies + +```rust +pub struct CacheConfig { + enabled: bool, + backend: CacheBackend, + ttl: Duration, + max_size: usize, +} + +pub enum CacheBackend { + InMemory, + Redis(String), + Disk(PathBuf), +} +``` + +# Chapter 8: Production Deployment + +## 8.1 Docker Deployment + +```dockerfile +FROM rust:1.75-slim as builder +WORKDIR /app +COPY . . +RUN cargo build --release + +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y libssl3 +COPY --from=builder /app/target/release/a3s-code /usr/local/bin/ +ENTRYPOINT ["a3s-code"] +``` + +## 8.2 Kubernetes Deployment + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: a3s-code +spec: + replicas: 3 + selector: + matchLabels: + app: a3s-code + template: + metadata: + labels: + app: a3s-code + spec: + containers: + - name: a3s-code + image: a3s-lab/code:latest + resources: + limits: + memory: "2Gi" + cpu: "1000m" +``` + +# Chapter 9: Integration + +## 9.1 MCP Protocol + +```rust +pub struct MCPConfig { + enabled: bool, + server_url: String, + capabilities: Vec, +} +``` + +## 9.2 Custom Storage Backend + +```rust +pub trait CustomStorage: Send + Sync { + async fn save(&self, key: &str, value: &[u8]) -> Result<()>; + async fn load(&self, key: &str) -> Result>>; + async fn delete(&self, key: &str) -> Result<()>; +} +``` + +# Chapter 10: Troubleshooting + +## 10.1 Debug Mode + +```bash +export RUST_LOG=debug +export A3S_DEBUG=1 +``` + +## 10.2 Common Issues + +| Issue | Solution | +|-------|----------| +| High memory usage | Reduce max_context_tokens | +| Slow LLM responses | Check connection pool size | +| Tool timeout | Increase timeout in config | + +--- + +End of Advanced Developer Manual diff --git a/manual/ADVANCED_DEVELOPER_MANUAL_CN.md b/manual/ADVANCED_DEVELOPER_MANUAL_CN.md new file mode 100644 index 0000000..3721224 --- /dev/null +++ b/manual/ADVANCED_DEVELOPER_MANUAL_CN.md @@ -0,0 +1,1179 @@ +# A3S Code 高级开发者手册 + +> **面向核心开发者、架构师和高级用户** +> 深入理解 A3S Code 内部机制、高级扩展与生产环境部署 + +--- + +## 目录 + +1. [第一章:内部架构深度解析](#第一章内部架构深度解析) +2. [第二章:高级配置与调优](#第二章高级配置与调优) +3. [第三章:高级工具开发](#第三章高级工具开发) +4. [第四章:Skill 高级编程](#第四章skill-高级编程) +5. [第五章:Hook 系统高级应用](#第五章hook-系统高级应用) +6. [第六章:安全加固](#第六章安全加固) +7. [第七章:性能优化](#第七章性能优化) +8. [第八章:生产环境部署](#第八章生产环境部署) +9. [第九章:系统集成](#第九章系统集成) +10. [第十章:故障排查与调试](#第十章故障排查与调试) + + +--- + +# 第一章:内部架构深度解析 + +## 1.1 运行时架构 + +### 1.1.1 线程模型 + +A3S Code 使用多线程架构设计: + +- **主线程**:处理 HTTP API / WebSocket / 计划任务 +- **工作线程池**:多个 Session,每个拥有独立的 AgentLoop +- **I/O 线程池**:LLM Client / 工具执行 / 文件 I/O + +``` +主线程: HTTP API / WebSocket / 计划任务 + | + v +工作线程池: 多个 Session (AgentLoop) + | + v +I/O 线程池: LLM / 工具 / 文件 +``` + +### 1.1.2 异步运行时配置 + +```rust +pub struct RuntimeConfig { + worker_threads: usize, // 默认: CPU核心数 + max_blocking_threads: usize, // 默认: 512 + thread_stack_size: usize, // 默认: 2MB + queue_depth: usize, // 默认: 1024 +} +``` + +### 1.1.3 内存布局 + +| 组件 | 生命周期 | 线程安全 | 说明 | +|------|----------|----------|------| +| Agent | 全局单例 | Arc+Mutex | 顶层配置管理 | +| Session | 会话级别 | Send+Sync | 独立工作空间 | +| ToolExecutor | 会话级别 | Send | 工具执行器 | +| LlmClient | 会话级别 | Send+Clone | LLM 客户端 | + +## 1.2 执行循环详解 + +### 1.2.1 AgentLoop 状态机 + +```rust +pub enum LoopState { + Idle, // 等待输入 + Planning, // 规划阶段 + Executing, // 执行工具 + WaitingForLLM, // 等待 LLM 响应 + Compacting, // 上下文压缩 + Error, // 错误状态 + Completed, // 完成 +} +``` + +### 1.2.2 熔断器机制 + +```rust +pub struct CircuitBreaker { + failure_threshold: u32, // 默认: 3 + reset_timeout: Duration, // 默认: 30s + state: CircuitState, +} + +enum CircuitState { + Closed, // 正常状态 + Open, // 熔断状态 + HalfOpen, // 半开状态 +} +``` + +**工作原理**: +1. 连续失败达到阈值(3次)-> 进入 Open 状态 +2. Open 状态下所有请求立即失败 +3. 经过 reset_timeout -> 进入 HalfOpen 状态 +4. 测试请求成功 -> 恢复 Closed 状态 + +## 1.3 上下文管理 + +### 1.3.1 上下文结构 + +```rust +pub struct Context { + session_id: String, + workspace: PathBuf, + current_skill: Option, + tool_history: Vec, + message_history: Vec, + token_usage: TokenUsage, + custom_data: HashMap, +} +``` + +### 1.3.2 上下文压缩策略 + +| 策略 | 说明 | 适用场景 | 压缩比 | +|------|------|----------|--------| +| Summarize | LLM 总结历史消息 | 长对话 | 80-90% | +| Truncate | 截断早期消息 | 简单场景 | 50-70% | +| ExtractKey | 提取关键信息 | 信息密集型 | 60-80% | +| Archive | 归档到存储 | 历史保留 | 100% | + + +--- + +# 第二章:高级配置与调优 + +## 2.1 队列系统配置 (a3s-lane) + +### 2.1.1 完整队列配置 + +```hcl +queue { + control_max_concurrency = 2 + query_max_concurrency = 10 + execute_max_concurrency = 5 + generate_max_concurrency = 1 + + enable_metrics = true + enable_dlq = true + enable_alerts = true + + storage_path = "./queue_data" + default_timeout_ms = 60000 + + retry_policy { + strategy = "exponential" + max_retries = 3 + initial_delay_ms = 100 + } + + rate_limit { + limit_type = "per_second" + max_operations = 100 + } +} +``` + +### 2.1.2 通道说明 + +| 通道 | 用途 | 建议并发 | +|------|------|----------| +| control | 控制命令 | 2 | +| query | 查询操作 | 10 | +| execute | 执行操作 | 5 | +| generate | LLM 生成 | 1 | + +## 2.2 LLM 客户端调优 + +### 2.2.1 连接池配置 + +```rust +pub struct LlmClientConfig { + pool_size: usize, // 默认: 10 + connection_timeout: Duration, // 默认: 30s + request_timeout: Duration, // 默认: 120s + max_retries: u32, // 默认: 3 +} +``` + +### 2.2.2 多提供商负载均衡 + +```hcl +providers { + name = "anthropic" + api_key = env("ANTHROPIC_API_KEY") + weight = 1.5 # 权重 + priority = 1 # 优先级 +} + +providers { + name = "openai" + api_key = env("OPENAI_API_KEY") + weight = 1.0 + priority = 2 +} +``` + +## 2.3 内存与存储优化 + +### 2.3.1 内存限制配置 + +```rust +pub struct MemoryLimits { + max_session_memory_mb: usize, // 默认: 100 + max_message_history: usize, // 默认: 100 + max_tool_history: usize, // 默认: 50 + max_context_tokens: usize, // 默认: 8000 +} +``` + +### 2.3.2 存储后端对比 + +| 后端 | 持久化 | 性能 | 适用场景 | +|------|--------|------|----------| +| memory | 否 | 最高 | 临时会话 | +| file | 是 | 高 | 单机部署 | +| redis | 是 | 中高 | 分布式部署 | + + +--- + +# 第三章:高级工具开发 + +## 3.1 工具生命周期 + +工具执行完整流程: + +``` +注册 -> 初始化 -> 验证输入 -> 执行前Hook -> 执行 -> 执行后Hook -> 验证输出 -> 清理 +``` + +### 3.1.1 高级工具 trait + +```rust +#[async_trait] +pub trait AdvancedTool: Tool { + async fn initialize(&mut self, config: &ToolConfig) -> Result<()>; + fn validate_input(&self, input: &Value) -> Result<()>; + fn pre_execute(&self, ctx: &Context) -> Result; + async fn execute_async(&self, input: ToolInput) -> Result; + fn post_execute(&self, output: &ToolOutput) -> Result<()>; + async fn cleanup(&mut self) -> Result<()>; +} +``` + +### 3.1.2 工具元数据 + +```rust +pub struct ToolMetadata { + name: String, + description: String, + version: String, + author: String, + category: ToolCategory, + required_permissions: Vec, + input_schema: JSONSchema, + output_schema: JSONSchema, +} +``` + +## 3.2 异步工具实现 + +### 3.2.1 异步工具示例 + +```rust +use async_trait::async_trait; + +pub struct AsyncWebTool { + client: reqwest::Client, + rate_limiter: RateLimiter, +} + +#[async_trait] +impl Tool for AsyncWebTool { + fn name(&self) -> &str { "async_web_fetch" } + + async fn execute(&self, input: ToolInput) -> Result { + // 检查速率限制 + self.rate_limiter.acquire().await?; + + // 异步请求 + let response = self.client + .get(input.get("url")?) + .timeout(Duration::from_secs(30)) + .send().await?; + + Ok(ToolOutput::new(response.text().await?)) + } +} +``` + +## 3.3 工具组合模式 + +### 3.3.1 管道模式 + +```rust +pub struct PipelineTool { + steps: Vec>, +} + +impl Tool for PipelineTool { + async fn execute(&self, input: ToolInput) -> Result { + let mut current = input; + for step in &self.steps { + current = step.execute(current).await?; + } + Ok(current) + } +} +``` + +### 3.3.2 条件分支模式 + +```rust +pub struct ConditionalTool { + condition: Box bool>, + true_branch: Box, + false_branch: Box, +} + +impl Tool for ConditionalTool { + async fn execute(&self, input: ToolInput) -> Result { + if (self.condition)(&input) { + self.true_branch.execute(input).await + } else { + self.false_branch.execute(input).await + } + } +} +``` + + +--- + +# 第四章:Skill 高级编程 + +## 4.1 Skill 解析引擎 + +### 4.1.1 Skill 解析流程 + +1. **Frontmatter 解析** (YAML):提取元数据 +2. **内容提取** (Markdown):获取主体内容 +3. **模板编译**:处理变量和表达式 +4. **权限验证**:检查 allowed-tools +5. **注入系统提示**:合并到 LLM 上下文 + +### 4.1.2 Skill 结构 + +```rust +pub struct Skill { + metadata: SkillMetadata, + content: String, + compiled_template: Template, + permissions: PermissionSet, +} + +pub struct SkillMetadata { + name: String, + description: String, + version: String, + author: String, + tags: Vec, + allowed_tools: Vec, +} +``` + +## 4.2 程序化 Skill 生成 + +### 4.2.1 SkillBuilder 模式 + +```rust +pub struct SkillBuilder { + name: String, + description: String, + allowed_tools: Vec, + content: String, + parameters: Vec, +} + +impl SkillBuilder { + pub fn new(name: &str) -> Self { + Self { + name: name.to_string(), + description: String::new(), + allowed_tools: Vec::new(), + content: String::new(), + parameters: Vec::new(), + } + } + + pub fn with_description(mut self, desc: &str) -> Self { + self.description = desc.to_string(); + self + } + + pub fn with_tool(mut self, tool: &str) -> Self { + self.allowed_tools.push(tool.to_string()); + self + } + + pub fn with_content(mut self, content: &str) -> Self { + self.content = content.to_string(); + self + } + + pub fn build(self) -> Result { + // 验证并构建 Skill + } +} +``` + +### 4.2.2 使用示例 + +```rust +let skill = SkillBuilder::new("code-reviewer") + .with_description("Code review assistant") + .with_tool("read(*)") + .with_tool("grep(*)") + .with_content("Review code for...") + .build()?; +``` + +## 4.3 Skill 组合与继承 + +### 4.3.1 Skill 组合 + +```rust +pub struct CompositeSkill { + base_skills: Vec, + override_content: Option, +} + +impl CompositeSkill { + pub fn combine(skills: Vec) -> Self { + // 合并多个 Skill 的能力 + } +} +``` + + +--- + +# 第五章:Hook 系统高级应用 + +## 5.1 Hook 链与优先级 + +### 5.1.1 Hook 优先级机制 + +```rust +pub struct HookChain { + // (优先级, Hook),数字越小优先级越高 + hooks: Vec<(u32, Box)>, +} + +impl HookChain { + pub fn register(&mut self, priority: u32, hook: Box) { + self.hooks.push((priority, hook)); + // 按优先级排序 + self.hooks.sort_by_key(|(p, _)| *p); + } + + pub async fn execute(&self, event: Event) -> HookResult { + for (priority, hook) in &self.hooks { + match hook.handle(event.clone()).await { + HookResult::Continue => continue, + HookResult::Block(reason) => return HookResult::Block(reason), + HookResult::Modify(new_event) => { + // 修改事件并继续 + } + } + } + HookResult::Continue + } +} +``` + +### 5.1.2 优先级建议 + +| 优先级 | 用途 | +|--------|------| +| 0-10 | 安全检查和权限验证 | +| 11-50 | 日志记录和监控 | +| 51-100 | 业务逻辑处理 | +| 101+ | 后处理和清理 | + +## 5.2 条件 Hook + +```rust +pub struct ConditionalHook { + condition: Box bool + Send + Sync>, + hook: Box, +} + +impl HookHandler for ConditionalHook { + async fn handle(&self, event: Event) -> HookResult { + if (self.condition)(&event) { + self.hook.handle(event).await + } else { + HookResult::Continue + } + } +} + +// 使用示例 +let security_hook = ConditionalHook::new( + |event| matches!(event, Event::ToolUse { name, .. } if name == "bash"), + SecurityCheckHook::new(), +); +``` + +## 5.3 性能监控 Hook + +```rust +pub struct PerformanceMonitorHook { + metrics: Arc, +} + +impl HookHandler for PerformanceMonitorHook { + async fn pre_tool_use(&self, tool_name: &str, input: &Value, ctx: &Context) -> HookResult { + self.metrics.record_tool_start(tool_name); + HookResult::Continue + } + + async fn post_tool_use(&self, tool_name: &str, output: &ToolOutput, ctx: &Context) { + self.metrics.record_tool_end(tool_name); + } +} +``` + + +--- + +# 第六章:安全加固 + +## 6.1 AHP 集成深度配置 + +### 6.1.1 AHP 配置 + +```rust +pub struct AHPConfig { + enabled: bool, + harness_endpoint: String, + timeout: Duration, + retry_policy: RetryPolicy, + cache_ttl: Duration, +} + +pub struct RetryPolicy { + max_retries: u32, + backoff_strategy: BackoffStrategy, + retryable_errors: Vec, +} +``` + +### 6.1.2 AHP 工作流 + +``` +工具调用请求 + | + v +AHP 前置检查 <- 缓存检查 + | + v +风险评估 + | + +---> 通过 -> 执行工具 + | + +---> 拒绝 -> 返回错误 + | + +---> 需确认 -> 人机交互 +``` + +## 6.2 沙盒机制 + +### 6.2.1 沙盒配置 + +```rust +pub struct SandboxConfig { + enabled: bool, + chroot_path: Option, + network_access: bool, + allowed_paths: Vec, + forbidden_commands: Vec, + max_processes: usize, + max_memory_mb: usize, + timeout_seconds: u64, +} +``` + +### 6.2.2 沙盒实现 + +```rust +pub struct Sandbox { + config: SandboxConfig, + namespace: LinuxNamespace, + seccomp_filter: SeccompFilter, +} + +impl Sandbox { + pub fn execute(&self, command: &str) -> Result { + // 1. 创建隔离命名空间 + // 2. 设置资源限制 + // 3. 加载 seccomp 规则 + // 4. 执行命令 + // 5. 监控资源使用 + } +} +``` + +## 6.3 审计与日志 + +### 6.3.1 审计配置 + +```rust +pub struct AuditConfig { + enabled: bool, + log_level: LogLevel, + output: AuditOutput, + sensitive_fields: Vec, + retention_days: u32, +} + +pub enum AuditOutput { + File(PathBuf), + Syslog, + Custom(Box), +} +``` + +### 6.3.2 审计事件 + +| 事件类型 | 说明 | +|----------|------| +| SessionStart | 会话开始 | +| ToolInvocation | 工具调用 | +| PermissionDenied | 权限拒绝 | +| ConfigurationChange | 配置变更 | +| Error | 错误发生 | + + +--- + +# 第七章:性能优化 + +## 7.1 令牌使用优化 + +### 7.1.1 优化策略 + +| 策略 | 描述 | 效果 | +|------|------|------| +| 消息截断 | 限制历史消息长度 | 减少 20-40% | +| 智能摘要 | 对旧消息进行摘要 | 减少 50-70% | +| 去重 | 移除重复上下文 | 减少 10-20% | +| 压缩 | 使用紧凑表示 | 减少 30-50% | + +### 7.1.2 配置示例 + +```rust +pub struct TokenOptimizationConfig { + // 启用智能压缩 + enable_smart_compression: bool, + + // 消息保留策略 + message_retention: RetentionPolicy, + + // 摘要触发阈值 + summarize_threshold: usize, + + // 压缩目标比例 + target_compression_ratio: f32, +} + +pub enum RetentionPolicy { + KeepAll, + KeepLast(usize), + SummarizeOld(Duration), +} +``` + +## 7.2 上下文压缩策略 + +### 7.2.1 分层压缩 + +```rust +pub struct HierarchicalCompression { + layers: Vec, +} + +impl HierarchicalCompression { + pub fn compress(&self, context: &Context) -> CompressedContext { + // Layer 1: 移除系统消息 + // Layer 2: 摘要早期对话 + // Layer 3: 压缩工具输出 + // Layer 4: 归档到内存存储 + } +} +``` + +## 7.3 缓存机制 + +### 7.3.1 多级缓存 + +```rust +pub struct CacheManager { + l1_cache: Arc>>, // 内存 + l2_cache: Option>, // Redis + l3_cache: Option>, // 磁盘 +} + +pub struct CacheEntry { + key: String, + value: Vec, + created_at: Instant, + ttl: Duration, + hits: AtomicU64, +} +``` + +### 7.3.2 缓存策略 + +| 策略 | 适用场景 | +|------|----------| +| LRU | 常规缓存 | +| LFU | 热点数据 | +| TTL | 时效性数据 | +| Write-through | 一致性要求高 | +| Write-back | 性能优先 | + + +--- + +# 第八章:生产环境部署 + +## 8.1 容器化部署 + +### 8.1.1 Dockerfile + +```dockerfile +# 构建阶段 +FROM rust:1.75-slim as builder + +WORKDIR /app +COPY Cargo.toml Cargo.lock ./ +COPY core/ ./core/ +COPY sdk/ ./sdk/ + +RUN cargo build --release + +# 运行阶段 +FROM debian:bookworm-slim + +RUN apt-get update && apt-get install -y \ + libssl3 \ + ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +COPY --from=builder /app/target/release/a3s-code /usr/local/bin/ +COPY --from=builder /app/target/release/*.so /usr/local/lib/ + +ENV LD_LIBRARY_PATH=/usr/local/lib +ENV RUST_LOG=info + +EXPOSE 8080 + +ENTRYPOINT ["a3s-code"] +CMD ["--config", "/etc/a3s-code/agent.hcl"] +``` + +### 8.1.2 Docker Compose + +```yaml +version: '3.8' + +services: + a3s-code: + image: a3s-lab/code:latest + ports: + - "8080:8080" + volumes: + - ./config:/etc/a3s-code + - ./data:/data + environment: + - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY} + - RUST_LOG=info + deploy: + resources: + limits: + memory: 2G + cpus: '1.0' + restart: unless-stopped + + redis: + image: redis:7-alpine + volumes: + - redis_data:/data + restart: unless-stopped + +volumes: + redis_data: +``` + +## 8.2 Kubernetes 部署 + +### 8.2.1 Deployment + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: a3s-code + labels: + app: a3s-code +spec: + replicas: 3 + selector: + matchLabels: + app: a3s-code + template: + metadata: + labels: + app: a3s-code + spec: + containers: + - name: a3s-code + image: a3s-lab/code:latest + ports: + - containerPort: 8080 + env: + - name: ANTHROPIC_API_KEY + valueFrom: + secretKeyRef: + name: api-keys + key: anthropic + resources: + limits: + memory: "2Gi" + cpu: "1000m" + requests: + memory: "1Gi" + cpu: "500m" + livenessProbe: + httpGet: + path: /health + port: 8080 + initialDelaySeconds: 30 + periodSeconds: 10 + readinessProbe: + httpGet: + path: /ready + port: 8080 + initialDelaySeconds: 5 + periodSeconds: 5 +``` + +### 8.2.2 Service + +```yaml +apiVersion: v1 +kind: Service +metadata: + name: a3s-code +spec: + selector: + app: a3s-code + ports: + - port: 80 + targetPort: 8080 + type: ClusterIP +``` + + +--- + +# 第九章:系统集成 + +## 9.1 MCP 协议集成 + +### 9.1.1 MCP 配置 + +```rust +pub struct MCPConfig { + enabled: bool, + server_url: String, + api_key: String, + capabilities: Vec, + timeout: Duration, +} + +pub enum MCPCapability { + ToolExecution, + ResourceAccess, + PromptRendering, +} +``` + +### 9.1.2 MCP 客户端 + +```rust +pub struct MCPClient { + config: MCPConfig, + client: reqwest::Client, + connection: Option, +} + +impl MCPClient { + pub async fn connect(&mut self) -> Result<()> { + // 建立 WebSocket 连接 + // 协商能力 + // 初始化会话 + } + + pub async fn execute_tool(&self, request: ToolRequest) -> Result { + // 发送 MCP 请求 + // 等待响应 + // 解析结果 + } +} +``` + +## 9.2 自定义存储后端 + +### 9.2.1 存储 trait + +```rust +#[async_trait] +pub trait CustomStorage: Send + Sync { + async fn save(&self, key: &str, value: &[u8]) -> Result<()>; + async fn load(&self, key: &str) -> Result>>; + async fn delete(&self, key: &str) -> Result<()>; + async fn list(&self, prefix: &str) -> Result>; + async fn exists(&self, key: &str) -> Result; +} +``` + +### 9.2.2 S3 存储实现 + +```rust +pub struct S3Storage { + client: S3Client, + bucket: String, + prefix: String, +} + +#[async_trait] +impl CustomStorage for S3Storage { + async fn save(&self, key: &str, value: &[u8]) -> Result<()> { + self.client + .put_object() + .bucket(&self.bucket) + .key(format!("{}/{}", self.prefix, key)) + .body(value.to_vec().into()) + .send().await?; + Ok(()) + } + + async fn load(&self, key: &str) -> Result>> { + match self.client + .get_object() + .bucket(&self.bucket) + .key(format!("{}/{}", self.prefix, key)) + .send().await { + Ok(resp) => { + let data = resp.body.collect().await?.to_vec(); + Ok(Some(data)) + } + Err(SdkError::ServiceError { err, .. }) if err.is_no_such_key() => Ok(None), + Err(e) => Err(e.into()), + } + } +} +``` + +## 9.3 自定义 LLM 提供商 + +```rust +pub trait CustomProvider: Send + Sync { + fn name(&self) -> &str; + async fn generate(&self, request: GenerationRequest) -> Result; + async fn stream(&self, request: GenerationRequest) -> Result>; + fn supports_function_calling(&self) -> bool; + fn max_context_length(&self) -> usize; +} +``` + + +--- + +# 第十章:故障排查与调试 + +## 10.1 深度调试模式 + +### 10.1.1 启用调试日志 + +```bash +# 基础调试 +export RUST_LOG=debug + +# 详细调试 +export RUST_LOG=trace + +# 模块级调试 +export RUST_LOG=a3s_code_core=debug,a3s_code_core::agent=trace + +# 启用内部调试 +export A3S_DEBUG=1 +export A3S_TRACE_TOOLS=1 +``` + +### 10.1.2 性能分析 + +```bash +# 使用 cargo flamegraph +cargo flamegraph --bin a3s-code + +# 使用 perf +perf record -g -- cargo run --release +perf report + +# 使用 tokio-console +cargo run --features tokio-console +tokio-console +``` + +## 10.2 常见问题诊断 + +### 10.2.1 高内存使用 + +| 现象 | 原因 | 解决方案 | +|------|------|----------| +| 内存持续增长 | 上下文未压缩 | 降低 max_context_tokens | +| 突然内存飙升 | 大文件加载 | 限制文件读取大小 | +| 内存泄漏 | 未清理资源 | 检查 cleanup 实现 | + +```rust +// 内存监控代码 +pub fn log_memory_usage() { + let usage = memory_stats().unwrap(); + log::info!( + "Memory: physical={}, virtual={}", + usage.physical_mem, + usage.virtual_mem + ); +} +``` + +### 10.2.2 LLM 响应缓慢 + +| 检查项 | 命令/方法 | +|--------|-----------| +| 网络连接 | ping api.anthropic.com | +| DNS 解析 | dig api.anthropic.com | +| 连接池状态 | 查看 metrics | +| 请求超时 | 检查 timeout 配置 | + +### 10.2.3 工具执行失败 + +```rust +// 工具调试模式 +pub struct DebugToolExecutor { + inner: Box, +} + +impl ToolExecutor for DebugToolExecutor { + async fn execute(&self, tool: &str, input: Value) -> Result { + log::debug!("Executing tool: {}", tool); + log::debug!("Input: {}", input); + + let start = Instant::now(); + let result = self.inner.execute(tool, input).await; + let elapsed = start.elapsed(); + + match &result { + Ok(output) => log::debug!("Success in {:?}: {:?}", elapsed, output), + Err(e) => log::error!("Failed in {:?}: {}", elapsed, e), + } + + result + } +} +``` + +## 10.3 性能瓶颈分析 + +### 10.3.1 识别瓶颈 + +```bash +# 使用 just 运行性能测试 +just bench + +# 分析工具调用频率 +cargo run --example tool_metrics + +# 分析令牌使用 +cargo run --example token_analysis +``` + +### 10.3.2 优化检查清单 + +- [ ] 队列配置是否合理 +- [ ] 连接池大小是否合适 +- [ ] 缓存是否启用 +- [ ] 上下文压缩策略是否有效 +- [ ] 不必要的 Hook 是否禁用 +- [ ] 存储后端是否最优 + +## 10.4 灾难恢复 + +### 10.4.1 会话恢复 + +```rust +// 自动恢复配置 +pub struct RecoveryConfig { + auto_resume: bool, + max_recovery_attempts: u32, + recovery_backoff: Duration, + session_backup_interval: Duration, +} +``` + +### 10.4.2 数据备份 + +```bash +# 备份会话数据 +tar -czf sessions-backup-$(date +%Y%m%d).tar.gz ./sessions/ + +# 备份内存数据 +tar -czf memory-backup-$(date +%Y%m%d).tar.gz ./memory/ + +# 完整备份 +a3s-code admin backup --output ./backup-$(date +%Y%m%d).zip +``` + +### 10.4.3 紧急处理 + +```bash +# 强制清理所有会话 +a3s-code admin sessions kill-all + +# 重置队列 +a3s-code admin queue reset + +# 清除缓存 +a3s-code admin cache clear + +# 重启服务 +systemctl restart a3s-code +``` + +--- + +## 附录 + +### A. 配置文件完整示例 + +参见 `agent.example.hcl` + +### B. API 文档 + +- Rust: https://docs.rs/a3s-code-core +- Python: https://pypi.org/project/a3s-code +- Node.js: https://www.npmjs.com/package/@a3s-lab/code + +### C. 社区资源 + +- GitHub: https://github.com/a3s-lab/a3s-code +- 文档: https://a3s.dev/docs/code +- Discord: https://discord.gg/a3s-lab + +--- + +**最后更新**: 2026-03-24 +**版本**: 与 A3S Code 主版本同步 diff --git a/manual/USER_DEVELOPER_MANUAL.md b/manual/USER_DEVELOPER_MANUAL.md new file mode 100644 index 0000000..c80e6f2 --- /dev/null +++ b/manual/USER_DEVELOPER_MANUAL.md @@ -0,0 +1,970 @@ +# A3S Code 用户与开发者手册 + +> **A3S Code** - Agentic Agent Framework +> 一个基于 Rust 的智能代理框架,提供 Python 和 Node.js 原生绑定 + +--- + +## 📚 目录 + +- [第一部分:用户指南](#第一部分用户指南) + - [1. 简介](#1-简介) + - [2. 安装与配置](#2-安装与配置) + - [3. 快速开始](#3-快速开始) + - [4. 核心概念](#4-核心概念) + - [5. 工具系统](#5-工具系统) + - [6. Skills 系统](#6-skills-系统) + - [7. 多 Agent 协作](#7-多-agent-协作) + - [8. 安全与权限](#8-安全与权限) + - [9. 斜杠命令](#9-斜杠命令) + - [10. 计划任务](#10-计划任务) + - [11. 会话管理](#11-会话管理) +- [第二部分:开发者指南](#第二部分开发者指南) + - [12. 架构概览](#12-架构概览) + - [13. 开发环境搭建](#13-开发环境搭建) + - [14. 核心模块解析](#14-核心模块解析) + - [15. 扩展开发](#15-扩展开发) + - [16. Hook 系统](#16-hook-系统) + - [17. 插件开发](#17-插件开发) + - [18. 测试与调试](#18-测试与调试) + - [19. 贡献指南](#19-贡献指南) + +--- + +# 第一部分:用户指南 + +## 1. 简介 + +A3S Code 是一个功能强大的 **Agentic Agent 框架**,允许你赋予大型语言模型(LLM)以下能力: + +- 📁 **文件操作** - 读取、写入、编辑、补丁文件 +- 🔍 **代码搜索** - 使用 Grep、Glob 等工具搜索代码库 +- 🖥️ **命令执行** - 在沙盒环境中运行 Shell 命令 +- 🌐 **网络访问** - 网页抓取和搜索 +- 🤝 **任务委派** - 将任务分派给子代理或多代理团队 + +### 支持的语言与平台 + +| 平台 | 安装方式 | +|------|----------| +| Python | `pip install a3s-code` | +| Node.js | `npm install @a3s-lab/code` | +| Rust | `cargo add a3s-code-core` | + +### 支持的 LLM 提供商 + +- **Anthropic** (Claude 系列) +- **OpenAI** (GPT 系列) +- **DeepSeek** +- **Kimi** (Moonshot) +- **Together** +- **Groq** + +--- + +## 2. 安装与配置 + +### 2.1 Python 安装 + +```bash +pip install a3s-code +``` + +### 2.2 Node.js 安装 + +```bash +npm install @a3s-lab/code +``` + +### 2.3 配置代理 (agent.hcl) + +创建 `agent.hcl` 配置文件: + +```hcl +# 默认模型 +default_model = "anthropic/claude-sonnet-4-20250514" + +# LLM 提供商配置 +providers { + name = "anthropic" + api_key = env("ANTHROPIC_API_KEY") +} + +providers { + name = "openai" + api_key = env("OPENAI_API_KEY") +} + +# 存储后端: "memory", "file", 或 "custom" +storage_backend = "file" + +# 会话目录 +sessions_dir = "./sessions" + +# Skill 目录 +skill_dirs = ["./skills"] + +# 最大工具执行轮数 +max_tool_rounds = 50 +``` + +### 2.4 环境变量 + +```bash +export ANTHROPIC_API_KEY="your-key-here" +export OPENAI_API_KEY="your-key-here" +``` + +--- + +## 3. 快速开始 + +### 3.1 Python 示例 + +```python +from a3s_code import Agent + +# 创建代理 +agent = Agent.create("agent.hcl") + +# 创建会话 +session = agent.session("/my-project") + +# 发送请求 +result = session.send("分析这个项目的架构") +print(result.text) +``` + +### 3.2 Node.js 示例 + +```typescript +import { Agent } from '@a3s-lab/code'; + +const agent = await Agent.create('agent.hcl'); +const session = agent.session('/my-project'); + +const result = await session.send('分析这个项目的架构'); +console.log(result.text); +``` + +### 3.3 第一个任务 + +```python +# 查找所有处理认证错误的代码位置 +result = session.send("查找所有处理认证错误的代码位置") + +# 分析代码质量 +result = session.send("审查 main.py 的代码质量并给出改进建议") + +# 执行测试 +result = session.send("运行测试套件并报告结果") +``` + +--- + +## 4. 核心概念 + +### 4.1 架构层级 + +``` +Agent (配置 + 提供商注册表) + └── Session (工作空间 + 工具 + LLM) + └── AgentLoop (基于轮次的执行) + ├── LlmClient → 发送消息,接收工具调用 + ├── ToolExecutor → 运行工具,强制执行权限 + ├── SkillRegistry → 将 Skills 注入系统提示 + └── PluginManager → 加载可选的工具+Skill 包 +``` + +### 4.2 核心组件 + +| 组件 | 说明 | +|------|------| +| **Agent** | 顶层配置和工厂,管理提供商注册表 | +| **Session** | 工作空间容器,包含工具、LLM 客户端和状态 | +| **AgentLoop** | 执行循环,管理 LLM 和工具之间的交互 | +| **Skill** | Markdown 文件,定义行为和能力 | +| **Tool** | 代理可调用的功能 | + +### 4.3 SessionOptions 配置 + +```python +from a3s_code import Agent, SessionOptions + +opts = SessionOptions() + +# 指定模型 +opts.model = "openai/gpt-4o" + +# 启用内置 Skills +opts.builtin_skills = True + +# 加载自定义 Skills +opts.skill_dirs = ["./skills"] + +# 添加插件 +from a3s_code import AgenticSearch, AgenticParse +opts.plugins = [AgenticSearch(), AgenticParse()] + +session = agent.session(".", opts) +``` + +--- + +## 5. 工具系统 + +### 5.1 内置工具(16个) + +#### 文件工具 + +| 工具 | 说明 | 示例 | +|------|------|------| +| `read` | 读取文件内容 | `read: /path/to/file.py` | +| `write` | 写入文件 | `write: /path/to/file.py` | +| `edit` | 编辑文件 | `edit: /path/to/file.py` | +| `patch` | 应用补丁 | `patch: /path/to/file.py` | + +#### 搜索工具 + +| 工具 | 说明 | 示例 | +|------|------|------| +| `grep` | 文本搜索 | `grep: "function name"` | +| `glob` | 文件匹配 | `glob: "**/*.py"` | +| `ls` | 目录列表 | `ls: /path/to/dir` | + +#### 其他工具 + +| 工具 | 说明 | +|------|------| +| `bash` | 执行 Shell 命令 | +| `web_fetch` | 抓取网页内容 | +| `web_search` | 执行网络搜索 | +| `git_worktree` | Git 工作树操作 | + +### 5.2 委派工具 + +| 工具 | 说明 | +|------|------| +| `task` | 委派给单个代理 | +| `parallel_task` | 并行委派多个任务 | +| `run_team` | 运行代理团队 | +| `batch` | 批量执行任务 | +| `Skill` | 调用特定 Skill | + +### 5.3 插件工具 + +```python +# 启用 AgenticSearch - 自然语言代码搜索 +from a3s_code import AgenticSearch +opts.plugins = [AgenticSearch()] + +# 启用 AgenticParse - 增强解析 +from a3s_code import AgenticParse +opts.plugins = [AgenticParse()] +``` + +--- + +## 6. Skills 系统 + +Skills 是 Markdown 文件,用于塑造 LLM 行为。 + +### 6.1 Skill 文件结构 + +```markdown +--- +name: safe-reviewer +description: 审查代码而不修改文件 +allowed-tools: "read(*), grep(*), glob(*)" +--- + +审查工作空间中的代码。你可以读取和搜索文件,但不能写入、编辑或执行任何操作。 + +审查清单: +1. 检查潜在的安全问题 +2. 验证错误处理 +3. 评估代码可读性 +4. 提供改进建议 +``` + +### 6.2 使用 Skills + +```python +opts = SessionOptions() +opts.skill_dirs = ["./skills"] +opts.builtin_skills = True # 启用内置 Skills +session = agent.session(".", opts) +``` + +### 6.3 内置 Skills + +| Skill | 功能 | +|-------|------| +| `agentic-search` | 智能代码搜索 | +| `code-search` | 代码搜索辅助 | +| `code-review` | 代码审查 | +| `explain-code` | 代码解释 | +| `find-bugs` | 缺陷检测 | +| `builtin-tools` | 工具使用指导 | +| `delegate-task` | 任务委派 | +| `find-skills` | Skill 发现 | + +--- + +## 7. 多 Agent 协作 + +### 7.1 单个子代理 + +```python +result = session.send('task: 探索代码库并总结架构') +``` + +### 7.2 并行任务 + +```python +result = session.send('parallel_task: [审计安全性, 检查性能, 审查测试]') +``` + +### 7.3 代理团队 + +```python +# 运行代理团队(负责人分解 → 执行者执行 → 审查者验证) +result = session.send('run_team: 重构认证模块') +``` + +### 7.4 代理类型 + +| 类型 | 描述 | +|------|------| +| `explore` | 只读探索 | +| `general` | 完整功能 | +| `plan` | 仅分析 | + +--- + +## 8. 安全与权限 + +### 8.1 权限策略 + +```python +from a3s_code import SessionOptions, PermissionPolicy, PermissionRule + +opts = SessionOptions() +opts.permission_policy = PermissionPolicy( + allow=[ + PermissionRule("read(*)"), + PermissionRule("grep(*)") + ], + deny=[ + PermissionRule("bash(*)") + ], + default_decision="deny", +) +session = agent.session(".", opts) +``` + +### 8.2 人机确认 (HITL) + +```python +# 在每个工具调用前提示确认 +opts.hitl_enabled = True +``` + +### 8.3 安全特性 + +| 特性 | 说明 | +|------|------| +| **显式权限** | 默认拒绝,需明确授权 | +| **人机确认** | 工具调用前提示确认 | +| **Skill 限制** | `allowed-tools` 限制可调用工具 | +| **AHP 集成** | 运行时拦截和清理工具调用 | +| **自动压缩** | 达到令牌限制前自动压缩上下文 | +| **熔断器** | 3次连续失败后停止,防止无限重试 | +| **延续注入** | 防止 LLM 提前停止任务 | + +--- + +## 9. 斜杠命令 + +在会话中输入 `/help` 查看可用命令: + +| 命令 | 说明 | +|------|------| +| `/help` | 列出可用命令 | +| `/model [provider/model]` | 显示或切换当前模型 | +| `/cost` | 显示令牌使用和估计成本 | +| `/clear` | 清除对话历史 | +| `/compact` | 手动触发上下文压缩 | +| `/tools` | 列出已注册工具 | +| `/loop [interval] ` | 安排重复提示 | +| `/cron-list` | 列出计划任务 | +| `/cron-cancel ` | 取消计划任务 | + +### 9.1 自定义命令 + +```python +session.register_command( + "status", + "显示状态", + lambda args, ctx: f"模型: {ctx['model']}" +) +result = session.send("/status") +``` + +--- + +## 10. 计划任务 + +### 10.1 使用斜杠命令 + +```python +# 每5分钟检查测试状态 +session.send('/loop 5m 检查测试是否仍在通过') +``` + +### 10.2 程序化 API + +```python +# 安排任务(间隔300秒) +task_id = session.schedule_task('总结上次检查以来的 git 日志', 300) + +# 列出计划任务 +tasks = session.list_scheduled_tasks() + +# 取消任务 +session.cancel_scheduled_task(task_id) +``` + +### 10.3 间隔语法 + +- `30s` - 30秒 +- `5m` - 5分钟 +- `2h` - 2小时 +- `1d` - 1天 + +限制:每会话最多50个任务,3天后自动过期。 + +--- + +## 11. 会话管理 + +### 11.1 BTW - 临时问题 + +询问旁支问题而不影响对话历史: + +```python +btw = session.btw("PostgreSQL 默认端口是多少?") +print(btw.answer) # "5432" +print(btw.total_tokens) # 仅此次查询的令牌使用 +# 主对话继续 - btw 问题不在历史中 +``` + +### 11.2 会话持久化 + +```python +from a3s_code import SessionOptions, FileSessionStore, FileMemoryStore + +opts = SessionOptions() +opts.session_store = FileSessionStore('./sessions') +opts.memory_store = FileMemoryStore('./memory') +opts.session_id = 'my-session' +opts.auto_save = True + +session = agent.session(".", opts) + +# 恢复会话 +resumed = agent.resume_session('my-session', opts) +``` + +### 11.3 多提供商切换 + +```python +# 按会话切换模型 +session = agent.session(".", model="openai/gpt-4o") +``` + +--- + +# 第二部分:开发者指南 + +## 12. 架构概览 + +### 12.1 系统架构 + +``` +┌─────────────────────────────────────────────────────────────┐ +│ A3S Code │ +├─────────────────────────────────────────────────────────────┤ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ +│ │ Python SDK │ │ Node.js SDK │ │ Rust Core │ │ +│ │ (PyO3) │ │ (NAPI) │ │ │ │ +│ └──────────────┘ └──────────────┘ └──────────────┘ │ +├─────────────────────────────────────────────────────────────┤ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ +│ │ Agent │ │ Session │ │ AgentLoop │ │ +│ │ (配置管理) │ │ (状态管理) │ │ (执行循环) │ │ +│ └──────────────┘ └──────────────┘ └──────────────┘ │ +├─────────────────────────────────────────────────────────────┤ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ +│ │ LlmClient │ │ ToolExecutor │ │SkillRegistry │ │ +│ │ (LLM 通信) │ │ (工具执行) │ │ (技能管理) │ │ +│ └──────────────┘ └──────────────┘ └──────────────┘ │ +├─────────────────────────────────────────────────────────────┤ +│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ +│ │PluginManager │ │ HookSystem │ │Permissions │ │ +│ │ (插件管理) │ │ (钩子系统) │ │ (权限控制) │ │ +│ └──────────────┘ └──────────────┘ └──────────────┘ │ +└─────────────────────────────────────────────────────────────┘ +``` + +### 12.2 核心模块 + +| 模块 | 路径 | 说明 | +|------|------|------| +| `agent.rs` | `core/src/` | Agent 主逻辑 | +| `session.rs` | `core/src/session/` | 会话管理 | +| `tools/` | `core/src/tools/` | 工具实现 | +| `skills/` | `core/src/skills/` | Skill 系统 | +| `llm/` | `core/src/llm/` | LLM 客户端 | +| `permissions.rs` | `core/src/` | 权限控制 | +| `hooks/` | `core/src/hooks/` | 钩子系统 | + +--- + +## 13. 开发环境搭建 + +### 13.1 前置要求 + +```bash +# Rust +curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh + +# Python (用于 Python SDK) +python -m pip install maturin + +# Node.js (用于 Node.js SDK) +npm install -g napi-rs +``` + +### 13.2 克隆与构建 + +```bash +git clone +cd a3s-code + +# 构建核心 +cargo build --release + +# 构建 Python SDK +cd sdk/python +maturin develop + +# 构建 Node.js SDK +cd sdk/node +npm install +npm run build +``` + +### 13.3 开发工具 + +```bash +# 运行测试 +cargo test + +# 代码检查 +cargo clippy + +# 格式化 +cargo fmt + +# 使用 just 执行任务 +just --list +``` + +--- + +## 14. 核心模块解析 + +### 14.1 Agent 模块 (`agent.rs`) + +```rust +// Agent 结构 +pub struct Agent { + config: Config, + provider_registry: ProviderRegistry, +} + +impl Agent { + // 创建 Agent + pub fn create(config_path: &str) -> Result; + + // 创建会话 + pub fn session(&self, workspace: &str) -> Session; + + // 恢复会话 + pub fn resume_session(&self, session_id: &str) -> Result; +} +``` + +### 14.2 Session 模块 (`session/`) + +```rust +pub struct Session { + id: String, + workspace: PathBuf, + tool_executor: ToolExecutor, + llm_client: LlmClient, + skill_registry: SkillRegistry, +} + +impl Session { + // 发送消息 + pub fn send(&mut self, prompt: &str) -> Result; + + // BTW 查询 + pub fn btw(&self, question: &str) -> Result; + + // 计划任务 + pub fn schedule_task(&mut self, task: &str, interval_secs: u64) -> String; +} +``` + +### 14.3 Tool 模块 (`tools/`) + +```rust +// Tool trait +pub trait Tool: Send + Sync { + fn name(&self) -> &str; + fn description(&self) -> &str; + fn execute(&self, input: ToolInput) -> Result; +} + +// 内置工具 +pub mod file_tools; // read, write, edit, patch +pub mod search_tools; // grep, glob, ls +pub mod shell_tools; // bash +pub mod web_tools; // web_fetch, web_search +``` + +### 14.4 Skill 模块 (`skills/`) + +```rust +pub struct Skill { + name: String, + description: String, + allowed_tools: Vec, + content: String, +} + +pub struct SkillRegistry { + skills: Vec, + builtin_enabled: bool, +} +``` + +--- + +## 15. 扩展开发 + +### 15.1 创建自定义工具 + +```rust +use a3s_code_core::tools::{Tool, ToolInput, ToolOutput}; + +pub struct MyTool; + +impl Tool for MyTool { + fn name(&self) -> &str { + "my_tool" + } + + fn description(&self) -> &str { + "我的自定义工具描述" + } + + fn execute(&self, input: ToolInput) -> Result { + // 实现逻辑 + Ok(ToolOutput::new("结果")) + } +} +``` + +### 15.2 创建自定义 Skill + +在 `skills/` 目录创建 Markdown 文件: + +```markdown +--- +name: my-skill +description: 我的自定义 Skill +allowed-tools: "read(*), grep(*)" +--- + +# 我的 Skill + +这是 Skill 的详细说明,LLM 将使用这些信息来执行任务。 + +## 使用场景 + +1. 场景一 +2. 场景二 + +## 示例 + +``` +示例代码或命令 +``` +``` + +### 15.3 扩展现有工具 + +```rust +// 扩展现有工具的行为 +pub trait ToolExtension { + fn pre_execute(&self, input: &ToolInput) -> Result<()>; + fn post_execute(&self, output: &ToolOutput) -> Result<()>; +} +``` + +--- + +## 16. Hook 系统 + +### 16.1 可用钩子事件 + +| 事件 | 说明 | 可拦截 | +|------|------|--------| +| `PreToolUse` | 工具使用前 | ✅ | +| `PostToolUse` | 工具使用后 | ❌ | +| `GenerateStart` | 生成开始前 | ✅ | +| `GenerateEnd` | 生成结束后 | ❌ | +| `SessionStart` | 会话开始时 | ❌ | +| `SessionEnd` | 会话结束时 | ❌ | +| `SkillLoad` | Skill 加载时 | ❌ | +| `SkillUnload` | Skill 卸载时 | ❌ | +| `PrePrompt` | 提示前 | ✅ | +| `PostResponse` | 响应后 | ❌ | +| `OnError` | 错误发生时 | ❌ | + +### 16.2 实现 HookHandler + +```rust +use a3s_code::HookHandler; + +struct MyHook; + +impl HookHandler for MyHook { + fn pre_tool_use(&self, tool_name: &str, tool_input: &Value, ctx: &Context) -> HookResult { + if tool_name == "bash" && tool_input.contains("rm -rf") { + return HookResult::block("拒绝破坏性命令"); + } + HookResult::continue_() + } + + fn generate_start(&self, prompt: &str, ctx: &Context) -> HookResult { + // 修改提示或记录日志 + HookResult::continue_() + } +} +``` + +### 16.3 使用钩子 + +```python +from a3s_code import SessionOptions, HookHandler + +class SecurityHook(HookHandler): + def pre_tool_use(self, tool_name, tool_input, ctx): + # 安全检查逻辑 + return self.continue_() + +opts = SessionOptions() +opts.hook_handler = SecurityHook() +session = agent.session(".", opts) +``` + +--- + +## 17. 插件开发 + +### 17.1 插件结构 + +```rust +pub trait Plugin: Send + Sync { + fn name(&self) -> &str; + fn initialize(&mut self, ctx: &PluginContext) -> Result<()>; + fn tools(&self) -> Vec>; + fn skills(&self) -> Vec; +} +``` + +### 17.2 实现插件 + +```rust +use a3s_code_core::plugin::{Plugin, PluginContext}; + +pub struct MyPlugin; + +impl Plugin for MyPlugin { + fn name(&self) -> &str { + "my-plugin" + } + + fn initialize(&mut self, ctx: &PluginContext) -> Result<()> { + // 初始化逻辑 + Ok(()) + } + + fn tools(&self) -> Vec> { + vec![ + Box::new(MyTool), + ] + } + + fn skills(&self) -> Vec { + vec![ + Skill::new("my-skill", "描述", "..."), + ] + } +} +``` + +### 17.3 注册插件 + +```python +from a3s_code import SessionOptions + +opts = SessionOptions() +opts.plugins = [MyPlugin()] +session = agent.session(".", opts) +``` + +--- + +## 18. 测试与调试 + +### 18.1 单元测试 + +```rust +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_my_tool() { + let tool = MyTool; + let input = ToolInput::new(json!({"key": "value"})); + let output = tool.execute(input).unwrap(); + assert_eq!(output.text(), "expected"); + } +} +``` + +### 18.2 集成测试 + +```python +import pytest +from a3s_code import Agent, SessionOptions + +@pytest.fixture +def agent(): + return Agent.create("test-agent.hcl") + +def test_session_send(agent): + session = agent.session("./test-workspace") + result = session.send("Hello") + assert result.text is not None +``` + +### 18.3 调试技巧 + +```bash +# 启用详细日志 +export RUST_LOG=debug +export A3S_DEBUG=1 + +# 使用 just 运行特定测试 +just test-core +just test-python + +# 性能分析 +cargo flamegraph +``` + +### 18.4 故障排除 + +| 问题 | 解决方案 | +|------|----------| +| 模型连接失败 | 检查 API 密钥和网络 | +| 工具权限被拒绝 | 检查 PermissionPolicy 配置 | +| 会话无法恢复 | 验证 session_store 路径 | +| 插件加载失败 | 检查插件初始化日志 | + +--- + +## 19. 贡献指南 + +### 19.1 代码规范 + +- 遵循 Rust 标准代码风格 +- 使用 `cargo fmt` 格式化代码 +- 使用 `cargo clippy` 检查代码 +- 所有公共 API 必须有文档注释 + +### 19.2 提交规范 + +``` +feat: 新功能 +fix: 修复问题 +docs: 文档更新 +style: 代码格式调整 +refactor: 重构 +test: 测试相关 +chore: 构建/工具相关 +``` + +### 19.3 Pull Request 流程 + +1. Fork 仓库 +2. 创建功能分支 (`git checkout -b feature/amazing-feature`) +3. 提交更改 (`git commit -m 'feat: 添加 amazing 功能'`) +4. 推送到分支 (`git push origin feature/amazing-feature`) +5. 创建 Pull Request + +### 19.4 文档更新 + +- 更新 API 文档 +- 更新用户手册 +- 添加示例代码 +- 更新 CHANGELOG + +--- + +## 附录 + +### A. 配置参考 + +完整的 `agent.hcl` 配置示例见项目根目录的 `agent.example.hcl`。 + +### B. API 参考 + +详细 API 文档:[a3s.dev/docs/code](https://a3s.dev/docs/code) + +### C. 示例代码 + +更多示例见 `examples/` 目录。 + +### D. 相关资源 + +- [官方文档](https://a3s.dev/docs/code) +- [GitHub 仓库](https://github.com/a3s-lab/a3s-code) +- [Crates.io](https://crates.io/crates/a3s-code-core) +- [PyPI](https://pypi.org/project/a3s-code) +- [npm](https://www.npmjs.com/package/@a3s-lab/code) + +--- + +**许可证**: MIT +**版本**: 详见各 SDK 的 CHANGELOG + +*本手册最后更新: 2026-03-24* From ac3fb81b37cd4cafbf6f0930e4bc801cc4da5a30 Mon Sep 17 00:00:00 2001 From: Hefeng Zhou Date: Tue, 24 Mar 2026 20:11:57 +0800 Subject: [PATCH 2/2] Update manual --- manual/USER_GUIDE.md | 727 ++++++++++++++++++ ...R_DEVELOPER_MANUAL.md => USER_GUIDE_CN.md} | 0 2 files changed, 727 insertions(+) create mode 100644 manual/USER_GUIDE.md rename manual/{USER_DEVELOPER_MANUAL.md => USER_GUIDE_CN.md} (100%) diff --git a/manual/USER_GUIDE.md b/manual/USER_GUIDE.md new file mode 100644 index 0000000..89177c0 --- /dev/null +++ b/manual/USER_GUIDE.md @@ -0,0 +1,727 @@ +# A3S Code User & Developer Guide + +> **Agentic Agent Framework** - A3S Code is a Rust library with native Python and Node.js bindings + +--- + +## Table of Contents + +- [Part 1: User Guide](#part-1-user-guide) + - [1. Introduction](#1-introduction) + - [2. Installation & Configuration](#2-installation--configuration) + - [3. Quick Start](#3-quick-start) + - [4. Core Concepts](#4-core-concepts) + - [5. Tools System](#5-tools-system) + - [6. Skills System](#6-skills-system) + - [7. Multi-Agent Collaboration](#7-multi-agent-collaboration) + - [8. Security & Permissions](#8-security--permissions) + - [9. Slash Commands](#9-slash-commands) + - [10. Scheduled Tasks](#10-scheduled-tasks) + - [11. Session Management](#11-session-management) +- [Part 2: Developer Guide](#part-2-developer-guide) + - [12. Architecture Overview](#12-architecture-overview) + - [13. Development Environment](#13-development-environment) + - [14. Core Modules](#14-core-modules) + - [15. Extension Development](#15-extension-development) + - [16. Hook System](#16-hook-system) + - [17. Plugin Development](#17-plugin-development) + - [18. Testing & Debugging](#18-testing--debugging) + - [19. Contributing Guidelines](#19-contributing-guidelines) + +--- + +# Part 1: User Guide + +## 1. Introduction + +A3S Code is a powerful **Agentic Agent Framework** that enables Large Language Models (LLMs) to: + +- **File Operations** - Read, write, edit, and patch files +- **Code Search** - Search codebases using Grep, Glob, and more +- **Command Execution** - Run shell commands in sandboxed environments +- **Web Access** - Web scraping and search capabilities +- **Task Delegation** - Distribute tasks to sub-agents or multi-agent teams + +### Supported Platforms + +| Platform | Installation | +|----------|-------------| +| Python | `pip install a3s-code` | +| Node.js | `npm install @a3s-lab/code` | +| Rust | `cargo add a3s-code-core` | + +### Supported LLM Providers + +- **Anthropic** (Claude series) +- **OpenAI** (GPT series) +- **DeepSeek** +- **Kimi** (Moonshot) +- **Together** +- **Groq** + +## 2. Installation & Configuration + +### 2.1 Python Installation + +```bash +pip install a3s-code +``` + +### 2.2 Node.js Installation + +```bash +npm install @a3s-lab/code +``` + +### 2.3 Agent Configuration (agent.hcl) + +Create `agent.hcl` configuration file: + +```hcl +# Default model +default_model = "anthropic/claude-sonnet-4-20250514" + +# LLM Provider Configuration +providers { + name = "anthropic" + api_key = env("ANTHROPIC_API_KEY") +} + +providers { + name = "openai" + api_key = env("OPENAI_API_KEY") +} + +# Storage backend: "memory", "file", or "custom" +storage_backend = "file" + +# Sessions directory +sessions_dir = "./sessions" + +# Skill directories +skill_dirs = ["./skills"] + +# Maximum tool execution rounds +max_tool_rounds = 50 +``` + +### 2.4 Environment Variables + +```bash +export ANTHROPIC_API_KEY="your-key-here" +export OPENAI_API_KEY="your-key-here" +``` + +## 3. Quick Start + +### 3.1 Python Example + +```python +from a3s_code import Agent + +# Create agent +agent = Agent.create("agent.hcl") + +# Create session +session = agent.session("/my-project") + +# Send request +result = session.send("Analyze project architecture") +print(result.text) +``` + +### 3.2 Node.js Example + +```typescript +import { Agent } from '@a3s-lab/code'; + +const agent = await Agent.create('agent.hcl'); +const session = agent.session('/my-project'); + +const result = await session.send('Analyze project architecture'); +console.log(result.text); +``` + +### 3.3 First Tasks + +```python +# Find authentication error handling +result = session.send("Find all places handling authentication errors") + +# Review code quality +result = session.send("Review main.py code quality and suggest improvements") + +# Run tests +result = session.send("Run test suite and report results") +``` + +## 4. Core Concepts + +### 4.1 Architecture Layers + +``` +Agent (Config + Provider Registry) + └── Session (Workspace + Tools + LLM) + └── AgentLoop (Turn-based Execution) + ├── LlmClient → Send messages, receive tool calls + ├── ToolExecutor → Run tools, enforce permissions + ├── SkillRegistry → Inject skills into system prompt + └── PluginManager → Load optional tool+skill bundles +``` + +### 4.2 Core Components + +| Component | Description | +|-----------|-------------| +| **Agent** | Top-level configuration and factory | +| **Session** | Workspace container with tools, LLM client, and state | +| **AgentLoop** | Execution loop managing LLM and tool interactions | +| **Skill** | Markdown files defining behavior and capabilities | +| **Tool** | Functions the agent can invoke | + +### 4.3 SessionOptions Configuration + +```python +from a3s_code import Agent, SessionOptions + +opts = SessionOptions() + +# Specify model +opts.model = "openai/gpt-4o" + +# Enable built-in skills +opts.builtin_skills = True + +# Load custom skills +opts.skill_dirs = ["./skills"] + +# Add plugins +from a3s_code import AgenticSearch, AgenticParse +opts.plugins = [AgenticSearch(), AgenticParse()] + +session = agent.session(".", opts) +``` + + +## 5. Tools System + +### 5.1 Built-in Tools (16 total) + +#### File Tools + +| Tool | Description | Example | +|------|-------------|---------| +| `read` | Read file content | `read: /path/to/file.py` | +| `write` | Write file | `write: /path/to/file.py` | +| `edit` | Edit file | `edit: /path/to/file.py` | +| `patch` | Apply patch | `patch: /path/to/file.py` | + +#### Search Tools + +| Tool | Description | Example | +|------|-------------|---------| +| `grep` | Text search | `grep: "function name"` | +| `glob` | File matching | `glob: "**/*.py"` | +| `ls` | Directory listing | `ls: /path/to/dir` | + +#### Other Tools + +| Tool | Description | +|------|-------------| +| `bash` | Execute shell commands | +| `web_fetch` | Fetch web page content | +| `web_search` | Perform web search | +| `git_worktree` | Git worktree operations | + +### 5.2 Delegation Tools + +| Tool | Description | +|------|-------------| +| `task` | Delegate to single agent | +| `parallel_task` | Delegate multiple tasks in parallel | +| `run_team` | Run agent team | +| `batch` | Batch execute tasks | +| `Skill` | Invoke specific skill | + +### 5.3 Plugin Tools + +```python +# Enable AgenticSearch - Natural language code search +from a3s_code import AgenticSearch +opts.plugins = [AgenticSearch()] + +# Enable AgenticParse - Enhanced parsing +from a3s_code import AgenticParse +opts.plugins = [AgenticParse()] +``` + +## 6. Skills System + +Skills are Markdown files that shape LLM behavior. + +### 6.1 Skill File Structure + +```markdown +--- +name: safe-reviewer +description: Review code without modifying files +allowed-tools: "read(*), grep(*), glob(*)" +--- + +Review code in the workspace. You may read and search files, +but you must not write, edit, or execute anything. + +Review checklist: +1. Check for potential security issues +2. Verify error handling +3. Evaluate code readability +4. Provide improvement suggestions +``` + +### 6.2 Using Skills + +```python +opts = SessionOptions() +opts.skill_dirs = ["./skills"] +opts.builtin_skills = True # Enable built-in skills +session = agent.session(".", opts) +``` + +### 6.3 Built-in Skills + +| Skill | Function | +|-------|----------| +| `agentic-search` | Intelligent code search | +| `code-search` | Code search assistance | +| `code-review` | Code review | +| `explain-code` | Code explanation | +| `find-bugs` | Bug detection | +| `builtin-tools` | Tool usage guidance | +| `delegate-task` | Task delegation | +| `find-skills` | Skill discovery | + +## 7. Multi-Agent Collaboration + +### 7.1 Single Sub-agent + +```python +result = session.send('task: explore codebase and summarize architecture') +``` + +### 7.2 Parallel Tasks + +```python +result = session.send('parallel_task: [audit security, check performance, review tests]') +``` + +### 7.3 Agent Teams + +```python +# Run agent team (lead decomposes -> workers execute -> reviewer validates) +result = session.send('run_team: refactor authentication module') +``` + +### 7.4 Agent Types + +| Type | Description | +|------|-------------| +| `explore` | Read-only exploration | +| `general` | Full capabilities | +| `plan` | Analysis only | + +## 8. Security & Permissions + +### 8.1 Permission Policy + +```python +from a3s_code import SessionOptions, PermissionPolicy, PermissionRule + +opts = SessionOptions() +opts.permission_policy = PermissionPolicy( + allow=[ + PermissionRule("read(*)"), + PermissionRule("grep(*)") + ], + deny=[ + PermissionRule("bash(*)") + ], + default_decision="deny", +) +session = agent.session(".", opts) +``` + +### 8.2 Human-in-the-Loop (HITL) + +```python +# Prompt confirmation before each tool call +opts.hitl_enabled = True +``` + +### 8.3 Security Features + +| Feature | Description | +|---------|-------------| +| **Explicit Permissions** | Deny by default, explicit allow required | +| **Human Confirmation** | Prompt before tool execution | +| **Skill Restrictions** | `allowed-tools` limits callable tools | +| **AHP Integration** | Runtime interception and sanitization | +| **Auto-compact** | Auto compress context before token limits | +| **Circuit Breaker** | Stop after 3 consecutive failures | + + +## 9. Slash Commands + +Type `/help` in any session to see available commands: + +| Command | Description | +|---------|-------------| +| `/help` | List available commands | +| `/model [provider/model]` | Show or switch current model | +| `/cost` | Show token usage and estimated cost | +| `/clear` | Clear conversation history | +| `/compact` | Manually trigger context compaction | +| `/tools` | List registered tools | +| `/loop [interval] ` | Schedule recurring prompt | +| `/cron-list` | List scheduled tasks | +| `/cron-cancel ` | Cancel scheduled task | + +### 9.1 Custom Commands + +```python +session.register_command( + "status", + "Show status", + lambda args, ctx: f"Model: {ctx['model']}" +) +result = session.send("/status") +``` + +## 10. Scheduled Tasks + +### 10.1 Using Slash Commands + +```python +# Check test status every 5 minutes +session.send('/loop 5m check if tests are still passing') +``` + +### 10.2 Programmatic API + +```python +# Schedule task (300 second interval) +task_id = session.schedule_task('summarize git log since last check', 300) + +# List scheduled tasks +tasks = session.list_scheduled_tasks() + +# Cancel task +session.cancel_scheduled_task(task_id) +``` + +### 10.3 Interval Syntax + +- `30s` - 30 seconds +- `5m` - 5 minutes +- `2h` - 2 hours +- `1d` - 1 day + +Limit: Max 50 tasks per session, auto-expire after 3 days. + +## 11. Session Management + +### 11.1 BTW - Side Questions + +Ask side questions without affecting conversation history: + +```python +btw = session.btw("What is PostgreSQL default port?") +print(btw.answer) # "5432" +print(btw.total_tokens) # Token usage for this query only +# Main conversation continues - btw question not in history +``` + +### 11.2 Session Persistence + +```python +from a3s_code import SessionOptions, FileSessionStore, FileMemoryStore + +opts = SessionOptions() +opts.session_store = FileSessionStore('./sessions') +opts.memory_store = FileMemoryStore('./memory') +opts.session_id = 'my-session' +opts.auto_save = True + +session = agent.session(".", opts) + +# Resume session +resumed = agent.resume_session('my-session', opts) +``` + +### 11.3 Multi-Provider Switching + +```python +# Switch model per session +session = agent.session(".", model="openai/gpt-4o") +``` + +--- + +# Part 2: Developer Guide + +## 12. Architecture Overview + +### 12.1 System Architecture + +``` +A3S Code +├── Python SDK (PyO3) +├── Node.js SDK (NAPI) +└── Rust Core + ├── Agent (Configuration) + ├── Session (State Management) + └── AgentLoop (Execution) + ├── LlmClient + ├── ToolExecutor + ├── SkillRegistry + └── PluginManager +``` + +### 12.2 Core Modules + +| Module | Path | Description | +|--------|------|-------------| +| `agent.rs` | `core/src/` | Agent main logic | +| `session.rs` | `core/src/session/` | Session management | +| `tools/` | `core/src/tools/` | Tool implementations | +| `skills/` | `core/src/skills/` | Skill system | +| `llm/` | `core/src/llm/` | LLM clients | +| `permissions.rs` | `core/src/` | Permission control | +| `hooks/` | `core/src/hooks/` | Hook system | + +## 13. Development Environment + +### 13.1 Prerequisites + +```bash +# Rust +curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh + +# Python (for Python SDK) +python -m pip install maturin + +# Node.js (for Node.js SDK) +npm install -g napi-rs +``` + +### 13.2 Clone and Build + +```bash +git clone +cd a3s-code + +# Build core +cargo build --release + +# Build Python SDK +cd sdk/python +maturin develop + +# Build Node.js SDK +cd sdk/node +npm install +npm run build +``` + +### 13.3 Development Tools + +```bash +# Run tests +cargo test + +# Linting +cargo clippy + +# Formatting +cargo fmt + +# Use just for tasks +just --list +``` + + +## 14. Core Modules + +### 14.1 Agent Module (`agent.rs`) + +```rust +pub struct Agent { + config: Config, + provider_registry: ProviderRegistry, +} + +impl Agent { + pub fn create(config_path: &str) -> Result; + pub fn session(&self, workspace: &str) -> Session; + pub fn resume_session(&self, session_id: &str) -> Result; +} +``` + +### 14.2 Session Module (`session/`) + +```rust +pub struct Session { + id: String, + workspace: PathBuf, + tool_executor: ToolExecutor, + llm_client: LlmClient, + skill_registry: SkillRegistry, +} + +impl Session { + pub fn send(&mut self, prompt: &str) -> Result; + pub fn btw(&self, question: &str) -> Result; + pub fn schedule_task(&mut self, task: &str, interval_secs: u64) -> String; +} +``` + +### 14.3 Tool Module (`tools/`) + +```rust +pub trait Tool: Send + Sync { + fn name(&self) -> &str; + fn description(&self) -> &str; + fn execute(&self, input: ToolInput) -> Result; +} +``` + +## 15. Extension Development + +### 15.1 Creating Custom Tools + +```rust +use a3s_code_core::tools::{Tool, ToolInput, ToolOutput}; + +pub struct MyTool; + +impl Tool for MyTool { + fn name(&self) -> &str { "my_tool" } + fn description(&self) -> &str { "My custom tool description" } + fn execute(&self, input: ToolInput) -> Result { + Ok(ToolOutput::new("result")) + } +} +``` + +### 15.2 Creating Custom Skills + +Create Markdown file in `skills/` directory: + +```markdown +--- +name: my-skill +description: My custom skill +allowed-tools: "read(*), grep(*)" +--- + +# My Skill + +Detailed description for LLM to use when executing tasks. +``` + +## 16. Hook System + +### 16.1 Available Hook Events + +| Event | Description | Blockable | +|-------|-------------|-----------| +| `PreToolUse` | Before tool use | Yes | +| `PostToolUse` | After tool use | No | +| `GenerateStart` | Before generation | Yes | +| `GenerateEnd` | After generation | No | +| `SessionStart` | Session start | No | +| `SessionEnd` | Session end | No | + +### 16.2 Implementing HookHandler + +```rust +use a3s_code::HookHandler; + +struct MyHook; + +impl HookHandler for MyHook { + fn pre_tool_use(&self, tool_name: &str, tool_input: &Value, ctx: &Context) -> HookResult { + if tool_name == "bash" && tool_input.contains("rm -rf") { + return HookResult::block("Refusing destructive command"); + } + HookResult::continue_() + } +} +``` + +## 17. Plugin Development + +### 17.1 Plugin Structure + +```rust +pub trait Plugin: Send + Sync { + fn name(&self) -> &str; + fn initialize(&mut self, ctx: &PluginContext) -> Result<()>; + fn tools(&self) -> Vec>; + fn skills(&self) -> Vec; +} +``` + +## 18. Testing & Debugging + +### 18.1 Unit Tests + +```rust +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_my_tool() { + let tool = MyTool; + let input = ToolInput::new(json!({"key": "value"})); + let output = tool.execute(input).unwrap(); + assert_eq!(output.text(), "expected"); + } +} +``` + +### 18.2 Debugging Tips + +```bash +# Enable verbose logs +export RUST_LOG=debug +export A3S_DEBUG=1 +``` + +## 19. Contributing Guidelines + +### 19.1 Code Style + +- Follow Rust standard style +- Use `cargo fmt` for formatting +- Use `cargo clippy` for linting +- Document all public APIs + +### 19.2 Commit Convention + +``` +feat: new feature +fix: bug fix +docs: documentation +style: formatting +refactor: refactoring +test: testing +chore: build/tools +``` + +--- + +**License**: MIT +**Version**: See CHANGELOG in each SDK + +*Last Updated: 2026-03-24* diff --git a/manual/USER_DEVELOPER_MANUAL.md b/manual/USER_GUIDE_CN.md similarity index 100% rename from manual/USER_DEVELOPER_MANUAL.md rename to manual/USER_GUIDE_CN.md