diff --git a/.gitignore b/.gitignore index 8699b86..e3fb01e 100644 --- a/.gitignore +++ b/.gitignore @@ -49,5 +49,8 @@ packages/desktop/src-tauri/Cargo.lock ai-open/ # Design docs (internal) -docs/ +/docs/ .astro/ + +# Exclude website docs pages from ignore +!packages/website/src/pages/docs/ diff --git a/packages/website/src/components/DocsSidebar.astro b/packages/website/src/components/DocsSidebar.astro index 4eec219..1215a27 100644 --- a/packages/website/src/components/DocsSidebar.astro +++ b/packages/website/src/components/DocsSidebar.astro @@ -10,24 +10,41 @@ const navigation = [ title: '开始', items: [ { title: '概览', href: '/docs' }, + { title: '快速开始', href: '/docs/quickstart' }, { title: '架构设计', href: '/docs/architecture' }, ], }, { - title: '已完成功能', + title: '核心功能', items: [ + { title: 'Agent 系统', href: '/docs/core/agent' }, + { title: '工具系统', href: '/docs/core/tools' }, { title: '编辑模式', href: '/docs/features/edit-modes' }, { title: 'Checkpoint 系统', href: '/docs/features/checkpoint' }, - { title: '多模型支持', href: '/docs/features/multi-model' }, { title: '会话管理', href: '/docs/features/chat-history' }, - { title: '仓库地图', href: '/docs/features/repo-map' }, - { title: '浏览器 GUI', href: '/docs/features/browser-gui' }, + { title: 'MCP 集成', href: '/docs/core/mcp' }, ], }, { - title: '规划中功能', + title: 'API 参考', items: [ + { title: 'REST API', href: '/docs/api/rest' }, + { title: 'WebSocket', href: '/docs/api/websocket' }, + { title: 'SDK 使用', href: '/docs/api/sdk' }, + ], + }, + { + title: '更多功能', + items: [ + { title: '多模型支持', href: '/docs/features/multi-model' }, + { title: '仓库地图', href: '/docs/features/repo-map' }, + { title: '浏览器 GUI', href: '/docs/features/browser-gui' }, { title: '配置管理', href: '/docs/features/configuration' }, + ], + }, + { + title: '规划中', + items: [ { title: 'Linting 集成', href: '/docs/features/linting' }, { title: '测试集成', href: '/docs/features/testing' }, { title: 'Watch 模式', href: '/docs/features/watch-mode' }, diff --git a/packages/website/src/pages/docs/api/rest.astro b/packages/website/src/pages/docs/api/rest.astro new file mode 100644 index 0000000..0d4049b --- /dev/null +++ b/packages/website/src/pages/docs/api/rest.astro @@ -0,0 +1,270 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

REST API

+ +

+ AI Terminal Assistant Server 提供完整的 REST API,用于会话管理、消息发送、工具操作等。 + 默认运行在 http://localhost:3000。 +

+ +

认证

+ +

远程模式下需要 Token 认证:

+ +
# Header 方式
+curl -H "Authorization: Bearer your_token" http://localhost:3000/api/sessions
+
+# Query 参数方式 (用于 WebSocket)
+ws://localhost:3000/api/ws/session-id?token=your_token
+ +

会话管理

+ +

列出会话

+ +
GET /api/sessions
+ +

响应:

+
{
+  "success": true,
+  "data": [
+    {
+      "id": "session-123",
+      "name": "my-session",
+      "status": "idle",
+      "createdAt": "2025-01-01T00:00:00Z",
+      "updatedAt": "2025-01-01T00:00:00Z"
+    }
+  ]
+}
+ +

创建会话

+ +
POST /api/sessions
+Content-Type: application/json
+
+{
+  "name": "my-session",
+  "workDir": "/path/to/project"
+}
+ +

响应:

+
{
+  "success": true,
+  "data": {
+    "id": "session-123",
+    "name": "my-session",
+    "status": "idle",
+    "workDir": "/path/to/project"
+  }
+}
+ +

获取会话详情

+ +
GET /api/sessions/:id
+ +

删除会话

+ +
DELETE /api/sessions/:id
+ +

消息管理

+ +

获取消息历史

+ +
GET /api/sessions/:id/messages
+ +

响应:

+
{
+  "success": true,
+  "data": [
+    {
+      "id": "msg-001",
+      "role": "user",
+      "content": "你好",
+      "timestamp": 1704067200000
+    },
+    {
+      "id": "msg-002",
+      "role": "assistant",
+      "content": "你好!有什么可以帮助你的?",
+      "timestamp": 1704067201000
+    }
+  ]
+}
+ +

发送消息 (非流式)

+ +
POST /api/sessions/:id/messages
+Content-Type: application/json
+
+{
+  "content": "帮我写一个排序函数"
+}
+ +

注意: 推荐使用 WebSocket 进行流式对话。

+ +

工具操作

+ +

列出可用工具

+ +
GET /api/tools
+ +

响应:

+
{
+  "success": true,
+  "data": [
+    {
+      "name": "read_file",
+      "description": "读取文件内容",
+      "parameters": {
+        "type": "object",
+        "properties": {
+          "path": { "type": "string" }
+        }
+      }
+    }
+  ]
+}
+ +

获取工具详情

+ +
GET /api/tools/:name
+ +

执行工具

+ +
POST /api/tools/:name/execute
+Content-Type: application/json
+
+{
+  "sessionId": "session-123",
+  "params": {
+    "path": "/project/src/index.ts"
+  }
+}
+ +

文件操作

+ +

获取工作目录信息

+ +
GET /api/files
+ +

列出目录内容

+ +
GET /api/files/list?path=/project/src
+ +

读取文件

+ +
GET /api/files/read?path=/project/package.json
+ +

获取文件信息

+ +
GET /api/files/stat?path=/project/src/index.ts
+ +

获取目录树

+ +
GET /api/files/tree?path=/project&depth=3
+ +

配置管理

+ +

获取配置

+ +
GET /api/config
+ +

响应:

+
{
+  "success": true,
+  "data": {
+    "model": "claude-sonnet-4-20250514",
+    "maxTokens": 4096,
+    "temperature": 0.7,
+    "workDir": "/project"
+  }
+}
+ +

更新配置

+ +
PUT /api/config
+Content-Type: application/json
+
+{
+  "model": "claude-opus-4-20250514",
+  "maxTokens": 8192
+}
+ +

检查点操作

+ +

列出检查点

+ +
GET /api/sessions/:id/checkpoints
+ +

创建检查点

+ +
POST /api/sessions/:id/checkpoints
+Content-Type: application/json
+
+{
+  "description": "保存当前状态"
+}
+ +

恢复检查点

+ +
POST /api/sessions/:id/checkpoints/:cpId/restore
+ +

健康检查

+ +
GET /health
+ +

响应:

+
{
+  "status": "ok",
+  "timestamp": 1704067200000
+}
+ +

错误响应

+ +

所有错误响应遵循统一格式:

+ +
{
+  "success": false,
+  "error": {
+    "code": "NOT_FOUND",
+    "message": "Session not found"
+  }
+}
+ +

状态码

+ + + + + + + + + + + + + + + + + +
状态码说明
200成功
201创建成功
400请求参数错误
401未认证
403权限不足
404资源不存在
500服务器错误
+ +

相关文档

+ +
+ +

WebSocket API

+

实时流式对话

+
+ + +

SDK 使用

+

JavaScript/TypeScript SDK

+
+
+
diff --git a/packages/website/src/pages/docs/api/sdk.astro b/packages/website/src/pages/docs/api/sdk.astro new file mode 100644 index 0000000..fbae61e --- /dev/null +++ b/packages/website/src/pages/docs/api/sdk.astro @@ -0,0 +1,315 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

SDK 使用

+ +

+ AI Terminal Assistant 提供 JavaScript/TypeScript SDK,简化与 Server 的交互。 + SDK 封装了 REST API 和 WebSocket 通信。 +

+ +

安装

+ +
# npm
+npm install @ai-assistant/sdk
+
+# pnpm
+pnpm add @ai-assistant/sdk
+
+# yarn
+yarn add @ai-assistant/sdk
+ +

快速开始

+ +
import { AIAssistantClient } from '@ai-assistant/sdk';
+
+// 创建客户端
+const client = new AIAssistantClient({
+  baseUrl: 'http://localhost:3000',
+  token: 'your-token'  // 可选,远程模式需要
+});
+
+// 创建会话
+const session = await client.sessions.create({
+  name: 'my-session',
+  workDir: '/path/to/project'
+});
+
+// 流式对话
+await client.chat(session.id, '帮我写一个 Hello World', {
+  onChunk: (chunk) => {
+    process.stdout.write(chunk);
+  },
+  onToolCall: (tool) => {
+    console.log(`调用工具: ${tool.name}`);
+  },
+  onComplete: () => {
+    console.log('完成');
+  }
+});
+ +

客户端配置

+ +
interface ClientConfig {
+  // 服务器地址
+  baseUrl: string;
+
+  // 认证 Token (远程模式需要)
+  token?: string;
+
+  // 请求超时 (毫秒)
+  timeout?: number;
+
+  // 自动重连
+  autoReconnect?: boolean;
+
+  // 最大重连次数
+  maxReconnectAttempts?: number;
+}
+
+const client = new AIAssistantClient({
+  baseUrl: 'http://localhost:3000',
+  token: 'your-token',
+  timeout: 30000,
+  autoReconnect: true,
+  maxReconnectAttempts: 5
+});
+ +

会话管理

+ +
// 列出所有会话
+const sessions = await client.sessions.list();
+
+// 创建会话
+const session = await client.sessions.create({
+  name: 'coding-session',
+  workDir: '/project'
+});
+
+// 获取会话
+const session = await client.sessions.get('session-id');
+
+// 删除会话
+await client.sessions.delete('session-id');
+
+// 获取消息历史
+const messages = await client.sessions.getMessages('session-id');
+ +

对话交互

+ +

流式对话

+ +
// 基本用法
+await client.chat(sessionId, '你好', {
+  onChunk: (chunk) => console.log(chunk)
+});
+
+// 完整回调
+await client.chat(sessionId, '帮我优化代码', {
+  onChunk: (chunk) => {
+    // 文本块
+    process.stdout.write(chunk);
+  },
+  onToolCall: (tool) => {
+    // 工具调用开始
+    console.log(`\\n[调用 ${tool.name}]`);
+  },
+  onToolResult: (result) => {
+    // 工具执行结果
+    console.log(`[结果: ${result.success ? '成功' : '失败'}]`);
+  },
+  onPermissionRequest: async (request) => {
+    // 权限请求
+    return confirm(`允许 ${request.tool}?`);
+  },
+  onComplete: () => {
+    // 完成
+    console.log('\\n--- 完成 ---');
+  },
+  onError: (error) => {
+    // 错误
+    console.error('错误:', error.message);
+  }
+});
+ +

发送带附件的消息

+ +
// 发送图片
+await client.chat(sessionId, [
+  { type: 'text', text: '这个 UI 有什么问题?' },
+  { type: 'image', path: '/path/to/screenshot.png' }
+]);
+
+// 发送文件引用
+await client.chat(sessionId, [
+  { type: 'text', text: '帮我优化这个文件' },
+  { type: 'file', path: '/project/src/index.ts' }
+]);
+ +

取消生成

+ +
// 开始对话
+const controller = client.chat(sessionId, '写一篇长文章', {
+  onChunk: (chunk) => console.log(chunk)
+});
+
+// 取消
+setTimeout(() => {
+  controller.cancel();
+}, 5000);
+ +

工具操作

+ +
// 列出可用工具
+const tools = await client.tools.list();
+
+// 获取工具详情
+const tool = await client.tools.get('read_file');
+
+// 手动执行工具
+const result = await client.tools.execute('read_file', {
+  sessionId: 'session-id',
+  params: {
+    path: '/project/package.json'
+  }
+});
+ +

文件操作

+ +
// 列出目录
+const files = await client.files.list('/project/src');
+
+// 读取文件
+const content = await client.files.read('/project/package.json');
+
+// 获取文件信息
+const stat = await client.files.stat('/project/src/index.ts');
+
+// 获取目录树
+const tree = await client.files.tree('/project', { depth: 3 });
+ +

配置管理

+ +
// 获取配置
+const config = await client.config.get();
+
+// 更新配置
+await client.config.update({
+  model: 'claude-opus-4-20250514',
+  maxTokens: 8192
+});
+ +

检查点操作

+ +
// 列出检查点
+const checkpoints = await client.checkpoints.list(sessionId);
+
+// 创建检查点
+const cp = await client.checkpoints.create(sessionId, {
+  description: '保存当前状态'
+});
+
+// 恢复检查点
+await client.checkpoints.restore(sessionId, checkpointId);
+
+// 查看差异
+const diff = await client.checkpoints.diff(sessionId, checkpointId);
+ +

事件监听

+ +
// 监听状态变化
+client.on('status', (status) => {
+  console.log(`状态: ${status}`);
+});
+
+// 监听连接事件
+client.on('connected', () => {
+  console.log('已连接');
+});
+
+client.on('disconnected', () => {
+  console.log('已断开');
+});
+
+// 监听错误
+client.on('error', (error) => {
+  console.error('错误:', error);
+});
+ +

TypeScript 类型

+ +
import type {
+  Session,
+  Message,
+  Tool,
+  Checkpoint,
+  Config,
+  ChatOptions,
+  ToolCallInfo,
+  PermissionRequest
+} from '@ai-assistant/sdk';
+
+// 所有类型都有完整的 TypeScript 定义
+ +

错误处理

+ +
import { AIAssistantError, NetworkError, AuthError } from '@ai-assistant/sdk';
+
+try {
+  await client.chat(sessionId, 'hello');
+} catch (error) {
+  if (error instanceof AuthError) {
+    console.error('认证失败,请检查 Token');
+  } else if (error instanceof NetworkError) {
+    console.error('网络错误,请检查连接');
+  } else if (error instanceof AIAssistantError) {
+    console.error('服务错误:', error.message);
+  }
+}
+ +

在 React 中使用

+ +
import { useState, useEffect } from 'react';
+import { AIAssistantClient } from '@ai-assistant/sdk';
+
+function useChat(sessionId: string) {
+  const [messages, setMessages] = useState<string[]>([]);
+  const [isLoading, setIsLoading] = useState(false);
+  const client = useMemo(() => new AIAssistantClient({
+    baseUrl: 'http://localhost:3000'
+  }), []);
+
+  const sendMessage = async (content: string) => {
+    setIsLoading(true);
+    let response = '';
+
+    await client.chat(sessionId, content, {
+      onChunk: (chunk) => {
+        response += chunk;
+        setMessages(prev => [...prev.slice(0, -1), response]);
+      },
+      onComplete: () => {
+        setIsLoading(false);
+      }
+    });
+  };
+
+  return { messages, sendMessage, isLoading };
+}
+ +

相关文档

+ +
+ +

REST API

+

底层 REST API 文档

+
+ + +

WebSocket API

+

底层 WebSocket 协议

+
+
+
diff --git a/packages/website/src/pages/docs/api/websocket.astro b/packages/website/src/pages/docs/api/websocket.astro new file mode 100644 index 0000000..8d3e706 --- /dev/null +++ b/packages/website/src/pages/docs/api/websocket.astro @@ -0,0 +1,265 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

WebSocket API

+ +

+ WebSocket 是与 AI Terminal Assistant 进行实时对话的推荐方式。 + 支持流式响应、工具调用反馈、状态更新等。 +

+ +

连接

+ +
// 基本连接
+const ws = new WebSocket('ws://localhost:3000/api/ws/session-123');
+
+// 带认证连接
+const ws = new WebSocket('ws://localhost:3000/api/ws/session-123?token=your_token');
+
+ws.onopen = () => {
+  console.log('已连接');
+};
+
+ws.onclose = () => {
+  console.log('连接关闭');
+};
+ +

消息格式

+ +

客户端 → 服务端

+ +
interface ClientMessage {
+  type: 'message' | 'cancel' | 'tool_response' | 'permission_response';
+  payload: any;
+}
+ +

服务端 → 客户端

+ +
interface ServerMessage {
+  type: 'chunk' | 'tool_call' | 'tool_result' | 'done' | 'error' |
+        'status' | 'permission_request';
+  payload: any;
+}
+ +

发送消息

+ +
// 发送用户消息
+ws.send(JSON.stringify({
+  type: 'message',
+  payload: {
+    content: '帮我写一个快速排序函数'
+  }
+}));
+
+// 发送带图片的消息
+ws.send(JSON.stringify({
+  type: 'message',
+  payload: {
+    content: [
+      { type: 'text', text: '这个界面有什么问题?' },
+      { type: 'image', source: { type: 'base64', data: '...' } }
+    ]
+  }
+}));
+ +

接收消息

+ +
ws.onmessage = (event) => {
+  const message = JSON.parse(event.data);
+
+  switch (message.type) {
+    case 'chunk':
+      // 流式文本块
+      process.stdout.write(message.payload.content);
+      break;
+
+    case 'tool_call':
+      // AI 调用了工具
+      console.log(`工具调用: ${message.payload.name}`);
+      console.log(`参数: ${JSON.stringify(message.payload.params)}`);
+      break;
+
+    case 'tool_result':
+      // 工具执行结果
+      console.log(`工具结果: ${message.payload.result}`);
+      break;
+
+    case 'permission_request':
+      // 权限请求
+      handlePermissionRequest(message.payload);
+      break;
+
+    case 'done':
+      // 对话完成
+      console.log('\\n对话完成');
+      break;
+
+    case 'error':
+      // 错误
+      console.error(`错误: ${message.payload.message}`);
+      break;
+  }
+};
+ +

取消生成

+ +
// 取消当前生成
+ws.send(JSON.stringify({
+  type: 'cancel',
+  payload: {}
+}));
+ +

权限响应

+ +
// 当收到 permission_request 时
+function handlePermissionRequest(request) {
+  // 显示权限请求给用户
+  const approved = confirm(`允许执行 ${request.tool}?`);
+
+  // 发送权限响应
+  ws.send(JSON.stringify({
+    type: 'permission_response',
+    payload: {
+      requestId: request.id,
+      approved: approved
+    }
+  }));
+}
+ +

完整示例

+ +
class ChatClient {
+  constructor(sessionId, token) {
+    this.sessionId = sessionId;
+    this.token = token;
+    this.ws = null;
+  }
+
+  connect() {
+    const url = `ws://localhost:3000/api/ws/${this.sessionId}`;
+    this.ws = new WebSocket(this.token ? `${url}?token=${this.token}` : url);
+
+    this.ws.onopen = () => {
+      console.log('已连接到 AI Assistant');
+    };
+
+    this.ws.onmessage = (event) => {
+      this.handleMessage(JSON.parse(event.data));
+    };
+
+    this.ws.onerror = (error) => {
+      console.error('WebSocket 错误:', error);
+    };
+
+    this.ws.onclose = () => {
+      console.log('连接已关闭');
+    };
+  }
+
+  send(content) {
+    this.ws.send(JSON.stringify({
+      type: 'message',
+      payload: { content }
+    }));
+  }
+
+  cancel() {
+    this.ws.send(JSON.stringify({
+      type: 'cancel',
+      payload: {}
+    }));
+  }
+
+  handleMessage(message) {
+    switch (message.type) {
+      case 'chunk':
+        this.onChunk?.(message.payload.content);
+        break;
+      case 'tool_call':
+        this.onToolCall?.(message.payload);
+        break;
+      case 'tool_result':
+        this.onToolResult?.(message.payload);
+        break;
+      case 'done':
+        this.onDone?.();
+        break;
+      case 'error':
+        this.onError?.(message.payload);
+        break;
+    }
+  }
+
+  close() {
+    this.ws?.close();
+  }
+}
+
+// 使用示例
+const client = new ChatClient('session-123', 'your-token');
+
+client.onChunk = (content) => process.stdout.write(content);
+client.onToolCall = (tool) => console.log(`\\n[调用工具: ${tool.name}]`);
+client.onDone = () => console.log('\\n--- 完成 ---');
+
+client.connect();
+client.send('帮我分析这个项目的结构');
+ +

心跳保活

+ +
// 服务端会定期发送 ping,客户端需要响应 pong
+// 大多数 WebSocket 库会自动处理
+
+// 如果需要手动处理:
+setInterval(() => {
+  if (ws.readyState === WebSocket.OPEN) {
+    ws.send(JSON.stringify({ type: 'ping' }));
+  }
+}, 30000);
+ +

重连策略

+ +
class ReconnectingClient extends ChatClient {
+  constructor(sessionId, token) {
+    super(sessionId, token);
+    this.reconnectAttempts = 0;
+    this.maxReconnectAttempts = 5;
+  }
+
+  connect() {
+    super.connect();
+
+    this.ws.onclose = () => {
+      if (this.reconnectAttempts < this.maxReconnectAttempts) {
+        const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
+        console.log(`${delay/1000}秒后重连...`);
+        setTimeout(() => {
+          this.reconnectAttempts++;
+          this.connect();
+        }, delay);
+      }
+    };
+
+    this.ws.onopen = () => {
+      this.reconnectAttempts = 0;
+      console.log('已连接');
+    };
+  }
+}
+ +

相关文档

+ +
+ +

REST API

+

会话和工具管理

+
+ + +

SDK 使用

+

封装好的客户端 SDK

+
+
+
diff --git a/packages/website/src/pages/docs/architecture.astro b/packages/website/src/pages/docs/architecture.astro new file mode 100644 index 0000000..13eebaa --- /dev/null +++ b/packages/website/src/pages/docs/architecture.astro @@ -0,0 +1,351 @@ +--- +import DocsLayout from '../../layouts/DocsLayout.astro'; +--- + + +

GUI + Server/Client 架构设计方案

+ +
+ 融合 OpenHands 和 OpenCode 的架构优势,实现多端统一的 AI 编程助手 +
+ +

1. 设计目标

+ + +

2. 整体架构图

+
┌─────────────────────────────────────────────────────────────┐
+│                        客户端层                              │
+├─────────────┬─────────────┬─────────────┬──────────────────┤
+│   Web App   │  Tauri App  │  TUI CLI    │  Mobile (PWA)    │
+│  (React)    │ (macOS/Win) │ (Terminal)  │  (响应式Web)      │
+└──────┬──────┴──────┬──────┴──────┬──────┴────────┬─────────┘
+       │             │             │               │
+       └─────────────┴──────┬──────┴───────────────┘
+                            │
+                    ┌───────▼───────┐
+                    │   统一 API    │
+                    │ REST + WS/SSE │
+                    └───────┬───────┘
+                            │
+┌───────────────────────────▼─────────────────────────────────┐
+│                       Server 核心层                          │
+├─────────────────────────────────────────────────────────────┤
+│  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────────────┐ │
+│  │ Session │  │  Agent  │  │  Tools  │  │ Event Bus (SSE) │ │
+│  │ Manager │  │  Core   │  │ Registry│  │                 │ │
+│  └─────────┘  └─────────┘  └─────────┘  └─────────────────┘ │
+│  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────────────┐ │
+│  │   LLM   │  │   LSP   │  │  File   │  │   Checkpoint    │ │
+│  │Provider │  │ Service │  │ System  │  │    System       │ │
+│  └─────────┘  └─────────┘  └─────────┘  └─────────────────┘ │
+└─────────────────────────────────────────────────────────────┘
+ +

3. 通信协议

+ + + + + + + + + + + + + + + + + + + + + +
协议用途
REST APICRUD 操作:会话管理、配置、历史记录
WebSocket双向实时:对话流、工具执行反馈
SSE单向推送:状态更新、日志流、进度通知
+ +

4. Monorepo 目录结构

+
ai-terminal-assistant/                    # 一个 Git 仓库,多个包
+├── packages/
+│   ├── core/                             # @ai-assistant/core
+│   │   └── src/
+│   │       ├── agent/                    # Agent 系统
+│   │       ├── tools/                    # 工具注册
+│   │       ├── editors/                  # 编辑器系统
+│   │       ├── lsp/                      # LSP 集成
+│   │       ├── checkpoint/               # 检查点系统
+│   │       └── hooks/                    # Hook 系统
+│   │
+│   ├── server/                           # @ai-assistant/server
+│   │   └── src/
+│   │       ├── routes/                   # API 路由
+│   │       ├── ws.ts                     # WebSocket
+│   │       └── sse.ts                    # SSE 事件流
+│   │
+│   ├── cli/                              # @ai-assistant/cli
+│   │   └── src/
+│   │       ├── commands/                 # 命令: serve, attach
+│   │       └── tui/                      # 终端 UI 组件
+│   │
+│   ├── web/                              # @ai-assistant/web
+│   │   └── src/
+│   │       ├── api/                      # API Client
+│   │       ├── components/               # React 组件
+│   │       └── pages/                    # 页面
+│   │
+│   └── desktop/                          # @ai-assistant/desktop
+│       ├── src/                          # 复用 web 组件
+│       └── src-tauri/                    # Tauri Rust 后端
+│
+├── pnpm-workspace.yaml
+└── package.json
+ +

5. 包依赖关系

+
                    ┌─────────────┐
+                    │    sdk      │  ← 对外发布,无依赖
+                    └─────────────┘
+                           ▲
+        ┌──────────────────┼──────────────────┐
+        │                  │                  │
+┌───────┴───────┐  ┌───────┴───────┐  ┌───────┴───────┐
+│     web       │  │    desktop    │  │     cli       │
+│  (React SPA)  │  │   (Tauri)     │  │  (终端入口)    │
+└───────┬───────┘  └───────┬───────┘  └───────┬───────┘
+        │                  │                  │
+        └──────────────────┼──────────────────┘
+                           │
+                    ┌──────▼──────┐
+                    │   server    │  ← HTTP API
+                    └──────┬──────┘
+                           │
+                    ┌──────▼──────┐
+                    │    core     │  ← Agent/Tools/LSP
+                    └─────────────┘
+ +

6. Server API 设计

+ +

6.1 REST API

+
// 会话管理
+GET    /api/sessions              // 列出所有会话
+POST   /api/sessions              // 创建新会话
+GET    /api/sessions/:id          // 获取会话详情
+DELETE /api/sessions/:id          // 删除会话
+
+// 消息交互
+POST   /api/sessions/:id/messages // 发送消息
+GET    /api/sessions/:id/messages // 获取历史消息
+
+// 工具操作
+GET    /api/tools                 // 列出可用工具
+POST   /api/tools/:name/execute   // 执行工具
+
+// 配置
+GET    /api/config                // 获取配置
+PUT    /api/config                // 更新配置
+ +

6.2 WebSocket 协议

+
// 客户端 -> 服务端
+interface ClientMessage {
+  type: "message" | "cancel" | "tool_response";
+  sessionId: string;
+  payload: any;
+}
+
+// 服务端 -> 客户端
+interface ServerMessage {
+  type: "chunk" | "tool_call" | "tool_result" | "done" | "error";
+  sessionId: string;
+  payload: any;
+}
+ +

7. 技术选型

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
组件选择理由
Server 框架Hono + BunTypeScript 原生,SSE/WS 支持好,性能优秀
桌面框架Tauri比 Electron 轻 10x,安全性好,Rust 后端
Web 框架React + Vite生态成熟,可复用到 Tauri
TUI 框架blessed功能完整,组件化开发
Monorepopnpm workspaces简单高效,原生支持
状态管理Zustand轻量,支持多端
+ +

8. 运行模式

+ +

8.1 本地模式 (默认)

+
# TUI 模式 - 内嵌 Server
+ai-assistant
+
+# Web 模式 - 启动本地 Web UI
+ai-assistant --web
+ai-assistant --web --port 3000
+ +

8.2 Server 模式 (远程控制)

+
# 启动 headless server
+ai-assistant serve --port 3000 --host 0.0.0.0
+
+# 从其他设备连接
+ai-assistant attach --host 192.168.1.100:3000
+
+# 或通过浏览器访问
+# http://192.168.1.100:3000
+ +

8.3 桌面模式

+
# 启动桌面应用 (内嵌 Server)
+ai-assistant-desktop
+
+# 桌面应用连接远程 Server
+ai-assistant-desktop --remote 192.168.1.100:3000
+ +

9. 实现路线图

+ +

Phase 1: Server 层 (基础) ✅ 已完成

+ + +

Phase 2: CLI 重构 ✅ 已完成

+ + +

Phase 3: Web 前端 ✅ 已完成

+ + +

Phase 4: 桌面应用 ✅ 已完成

+ + +

Phase 5: 移动端优化 ✅ 已完成

+ + +

10. 安全考虑

+ +

10.1 本地模式

+ + +

10.2 远程模式

+ + +

10.3 权限控制

+
interface Permission {
+  // 文件系统访问范围
+  allowedPaths: string[];
+  deniedPaths: string[];
+
+  // 工具权限
+  allowedTools: string[];
+
+  // 命令执行
+  allowShellCommands: boolean;
+  shellCommandPatterns: string[];
+}
+ +

11. 已实现的 API 端点

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
方法路径说明
GET/health健康检查
GET/api/sessions列出会话
POST/api/sessions创建会话
GET/api/sessions/:id获取会话
DELETE/api/sessions/:id删除会话
GET/api/sessions/:id/messages获取消息
POST/api/sessions/:id/messages发送消息
GET/api/sessions/:id/eventsSSE 事件流
GET/api/tools列出工具
GET/api/tools/:name工具详情
POST/api/tools/:name/execute执行工具
GET/api/config获取配置
PUT/PATCH/api/config更新配置
GET/api/files获取工作目录信息
GET/api/files/list列出目录内容
GET/api/files/read读取文件内容
GET/api/files/tree获取目录树
WS/api/ws/:sessionIdWebSocket
+ +

12. 参考资料

+ +
diff --git a/packages/website/src/pages/docs/core/agent.astro b/packages/website/src/pages/docs/core/agent.astro new file mode 100644 index 0000000..f2f9029 --- /dev/null +++ b/packages/website/src/pages/docs/core/agent.astro @@ -0,0 +1,231 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

Agent 系统

+ +

✅ 核心功能 - 完整实现

+ +

+ Agent 是 AI Terminal Assistant 的核心引擎,负责处理用户消息、调用工具、管理上下文。 + 基于 Vercel AI SDK 构建,支持流式响应和多种 LLM 提供商。 +

+ +

核心特性

+ + + +

架构概览

+ +
┌─────────────────────────────────────────────────────────────┐
+│                         Agent                                │
+├─────────────────────────────────────────────────────────────┤
+│  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────────────┐ │
+│  │ Provider│  │  Tools  │  │ Session │  │   Checkpoint    │ │
+│  │ Registry│  │ Registry│  │ Manager │  │    Manager      │ │
+│  └─────────┘  └─────────┘  └─────────┘  └─────────────────┘ │
+│  ┌─────────┐  ┌─────────┐  ┌─────────┐  ┌─────────────────┐ │
+│  │  Hooks  │  │   MCP   │  │   LSP   │  │    RepoMap      │ │
+│  │ Manager │  │  Client │  │ Service │  │   Generator     │ │
+│  └─────────┘  └─────────┘  └─────────┘  └─────────────────┘ │
+└─────────────────────────────────────────────────────────────┘
+ +

基本用法

+ +
import { Agent, toolRegistry } from '@ai-assistant/core';
+
+// 创建 Agent 实例
+const agent = new Agent({
+  apiKey: process.env.ANTHROPIC_API_KEY,
+  model: 'claude-sonnet-4-20250514',
+  maxTokens: 4096,
+  temperature: 0.7
+});
+
+// 流式对话
+const response = await agent.chat('帮我优化这段代码', {
+  onChunk: (chunk) => {
+    // 处理流式输出
+    process.stdout.write(chunk.content);
+  },
+  onToolCall: (toolCall) => {
+    // 工具调用回调
+    console.log(`调用工具: ${toolCall.name}`);
+  },
+  onComplete: (response) => {
+    // 完成回调
+    console.log('对话完成');
+  }
+});
+ +

配置选项

+ +
interface AgentConfig {
+  // 必需
+  apiKey: string;              // API 密钥
+
+  // 模型配置
+  model?: string;              // 模型名称 (默认: claude-sonnet-4-20250514)
+  maxTokens?: number;          // 最大输出 token (默认: 4096)
+  temperature?: number;        // 温度参数 (默认: 0.7)
+
+  // 系统配置
+  systemPrompt?: string;       // 自定义系统提示词
+  tools?: Tool[];              // 可用工具列表
+  workDir?: string;            // 工作目录
+
+  // 高级配置
+  hooks?: HookConfig;          // Hook 配置
+  checkpointDir?: string;      // 检查点目录
+  mcpServers?: MCPServerConfig[]; // MCP 服务器配置
+}
+ +

Agent 预设

+ +

内置多种 Agent 预设,适用于不同场景:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
预设说明适用场景
general通用编程助手日常编程任务
plan任务规划模式复杂任务分解
code-reviewer代码审查专家代码审查、优化建议
refactor重构专家代码重构、架构优化
+ +

消息处理流程

+ +
用户消息
+    │
+    ▼
+┌─────────────────┐
+│  消息预处理      │  ← 文件提及解析、上下文注入
+└────────┬────────┘
+         │
+         ▼
+┌─────────────────┐
+│  RepoMap 生成   │  ← 智能代码上下文
+└────────┬────────┘
+         │
+         ▼
+┌─────────────────┐
+│  LLM 调用       │  ← 流式响应
+└────────┬────────┘
+         │
+    ┌────┴────┐
+    │         │
+    ▼         ▼
+  文本      工具调用
+  输出        │
+              ▼
+         ┌─────────────────┐
+         │  工具执行        │  ← Checkpoint 自动创建
+         └────────┬────────┘
+                  │
+                  ▼
+         ┌─────────────────┐
+         │  结果返回 LLM    │
+         └────────┬────────┘
+                  │
+                  ▼
+              继续生成...
+ +

上下文管理

+ +

Agent 使用三层存储架构管理消息:

+ +
// 消息层级
+interface Message {
+  id: string;
+  role: 'user' | 'assistant' | 'system';
+  parts: Part[];      // 消息包含多个部分
+  timestamp: number;
+}
+
+// 部分类型
+type Part =
+  | TextPart         // 文本内容
+  | ToolPart         // 工具调用
+  | ReasoningPart    // 推理过程
+  | ImagePart;       // 图片内容
+ +

Vision 支持

+ +
// 发送带图片的消息
+await agent.chat([
+  {
+    type: 'text',
+    content: '这个界面有什么问题?'
+  },
+  {
+    type: 'image',
+    source: {
+      type: 'file',
+      path: '/path/to/screenshot.png'
+    }
+  }
+]);
+ +

代码位置

+ + + + + + + + + + + + + + + +
模块文件说明
Agent 主类core/agent.tsAgent 核心实现
配置管理core/config.ts配置加载和验证
类型定义types/index.ts所有类型定义
Providerproviders/多模型提供商
+ +

相关文档

+ +
+ +

工具系统

+

了解 23+ 内置工具

+
+ + +

Checkpoint 系统

+

安全的代码回滚机制

+
+
+
diff --git a/packages/website/src/pages/docs/core/mcp.astro b/packages/website/src/pages/docs/core/mcp.astro new file mode 100644 index 0000000..8b541e5 --- /dev/null +++ b/packages/website/src/pages/docs/core/mcp.astro @@ -0,0 +1,258 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

MCP 集成

+ +

✅ 核心功能 - 完整实现

+ +

+ Model Context Protocol (MCP) 是一个开放协议,允许 AI 应用与外部数据源和工具进行标准化交互。 + AI Terminal Assistant 完整支持 MCP,可以通过外部服务器扩展 AI 能力。 +

+ +

核心特性

+ + + +

架构概览

+ +
┌─────────────────────────────────────────────────────────────┐
+│                    AI Terminal Assistant                     │
+├─────────────────────────────────────────────────────────────┤
+│                       MCP Client                             │
+│  ┌───────────┐  ┌───────────┐  ┌───────────┐               │
+│  │  Tools    │  │ Resources │  │  Prompts  │               │
+│  │  Manager  │  │  Manager  │  │  Manager  │               │
+│  └─────┬─────┘  └─────┬─────┘  └─────┬─────┘               │
+│        │              │              │                       │
+│        └──────────────┼──────────────┘                       │
+│                       │                                      │
+│              ┌────────▼────────┐                             │
+│              │  Transport Layer │  ← stdio / SSE / WebSocket│
+│              └────────┬────────┘                             │
+└───────────────────────┼─────────────────────────────────────┘
+                        │
+        ┌───────────────┼───────────────┐
+        │               │               │
+        ▼               ▼               ▼
+┌─────────────┐ ┌─────────────┐ ┌─────────────┐
+│  Filesystem │ │   GitHub    │ │   Custom    │
+│   Server    │ │   Server    │ │   Server    │
+└─────────────┘ └─────────────┘ └─────────────┘
+ +

配置 MCP 服务器

+ +

配置文件

+ +

在项目根目录创建 mcp.json 或在 .ai-assistant/ 目录下配置:

+ +
{
+  "mcpServers": {
+    "filesystem": {
+      "command": "npx",
+      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/dir"],
+      "env": {}
+    },
+    "github": {
+      "command": "npx",
+      "args": ["-y", "@modelcontextprotocol/server-github"],
+      "env": {
+        "GITHUB_TOKEN": "your_github_token"
+      }
+    },
+    "sqlite": {
+      "command": "uvx",
+      "args": ["mcp-server-sqlite", "--db-path", "/path/to/database.db"]
+    }
+  }
+}
+ +

代码配置

+ +
import { MCPClient } from '@ai-assistant/core/mcp';
+
+// 创建 MCP 客户端
+const mcpClient = new MCPClient();
+
+// 连接服务器
+await mcpClient.connect({
+  name: 'filesystem',
+  command: 'npx',
+  args: ['-y', '@modelcontextprotocol/server-filesystem', '/project'],
+  env: {}
+});
+
+// 获取可用工具
+const tools = await mcpClient.listTools();
+console.log('可用工具:', tools);
+
+// 调用工具
+const result = await mcpClient.callTool('read_file', {
+  path: '/project/package.json'
+});
+ +

官方 MCP 服务器

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
服务器功能安装命令
@modelcontextprotocol/server-filesystem文件系统访问npx -y @modelcontextprotocol/server-filesystem
@modelcontextprotocol/server-githubGitHub APInpx -y @modelcontextprotocol/server-github
@modelcontextprotocol/server-postgresPostgreSQL 数据库npx -y @modelcontextprotocol/server-postgres
mcp-server-sqliteSQLite 数据库uvx mcp-server-sqlite
@modelcontextprotocol/server-slackSlack 集成npx -y @modelcontextprotocol/server-slack
+ +

工具自动注册

+ +

MCP 服务器的工具会自动注册到 Agent 的工具系统:

+ +
// 初始化 Agent 时传入 MCP 配置
+const agent = new Agent({
+  apiKey: process.env.ANTHROPIC_API_KEY,
+  mcpServers: [
+    {
+      name: 'github',
+      command: 'npx',
+      args: ['-y', '@modelcontextprotocol/server-github']
+    }
+  ]
+});
+
+// Agent 可以直接使用 MCP 工具
+await agent.chat('创建一个新的 GitHub issue');
+// AI 将自动调用 github 服务器的 create_issue 工具
+ +

资源访问

+ +
// 列出可用资源
+const resources = await mcpClient.listResources();
+
+// 读取资源
+const content = await mcpClient.readResource('file:///project/README.md');
+
+// 订阅资源变化
+mcpClient.subscribeResource('file:///project/config.json', (update) => {
+  console.log('配置已更新:', update);
+});
+ +

提示模板

+ +
// 列出可用提示模板
+const prompts = await mcpClient.listPrompts();
+
+// 获取提示
+const prompt = await mcpClient.getPrompt('code-review', {
+  file: 'src/index.ts'
+});
+
+// 使用提示
+await agent.chat(prompt.messages);
+ +

创建自定义 MCP 服务器

+ +
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
+
+const server = new Server(
+  { name: 'my-server', version: '1.0.0' },
+  { capabilities: { tools: {} } }
+);
+
+// 注册工具
+server.setRequestHandler('tools/list', async () => ({
+  tools: [
+    {
+      name: 'my_tool',
+      description: '自定义工具',
+      inputSchema: {
+        type: 'object',
+        properties: {
+          input: { type: 'string' }
+        },
+        required: ['input']
+      }
+    }
+  ]
+}));
+
+server.setRequestHandler('tools/call', async (request) => {
+  if (request.params.name === 'my_tool') {
+    return {
+      content: [{
+        type: 'text',
+        text: `处理结果: ${request.params.arguments.input}`
+      }]
+    };
+  }
+});
+
+// 启动服务器
+const transport = new StdioServerTransport();
+await server.connect(transport);
+ +

代码位置

+ + + + + + + + + + + + + + +
模块文件说明
MCP 客户端mcp/client.tsMCP 客户端实现
协议定义mcp/protocol.ts协议类型定义
传输层mcp/transport.tsstdio/SSE 传输
+ +

相关文档

+ +
+ +

工具系统

+

了解内置工具系统

+
+ + +

MCP 官方文档 ↗

+

Model Context Protocol 官方文档

+
+
+
diff --git a/packages/website/src/pages/docs/core/tools.astro b/packages/website/src/pages/docs/core/tools.astro new file mode 100644 index 0000000..3825a69 --- /dev/null +++ b/packages/website/src/pages/docs/core/tools.astro @@ -0,0 +1,280 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

工具系统

+ +

✅ 核心功能 - 23+ 内置工具

+ +

+ 工具系统是 AI Terminal Assistant 的核心能力,允许 AI 执行各种操作: + 文件读写、代码搜索、Shell 命令、Git 操作等。 +

+ +

工具分类

+ +

文件操作

+ + + + + + + + + + + + + + + + + + +
工具名功能说明
read_file读取文件支持文本、图片、PDF
write_file写入文件创建或覆盖文件
edit_file编辑文件Search-Replace 模式
delete_file删除文件安全删除
move_file移动/重命名文件移动
copy_file复制文件文件复制
list_directory列出目录目录浏览
+ +

代码搜索

+ + + + + + + + + + + + + + + +
工具名功能说明
grep内容搜索正则表达式搜索
glob文件匹配按模式查找文件
find_definition定义查找LSP 集成
find_references引用查找LSP 集成
+ +

Shell 执行

+ + + + + + + + + + + + + +
工具名功能说明
bash执行命令Shell 命令执行
background_bash后台执行长时间运行任务
+ +

Git 操作

+ + + + + + + + + + + + + + + +
工具名功能说明
git_status查看状态工作区状态
git_diff查看差异文件变更对比
git_log提交历史查看 Git 日志
git_commit提交更改创建 Git 提交
+ +

Web 工具

+ + + + + + + + + + + + + +
工具名功能说明
web_search网页搜索Tavily API 集成
web_fetch获取网页抓取网页内容
+ +

系统工具

+ + + + + + + + + + + + + + + +
工具名功能说明
think思考AI 内部推理
ask_user询问用户交互式确认
checkpoint检查点创建恢复点
todo任务管理任务追踪
+ +

工具注册

+ +
import { toolRegistry } from '@ai-assistant/core/tools';
+import { z } from 'zod';
+
+// 注册自定义工具
+toolRegistry.register({
+  name: 'my_custom_tool',
+  description: '自定义工具描述',
+  parameters: z.object({
+    input: z.string().describe('输入参数'),
+    options: z.object({
+      format: z.enum(['json', 'text']).optional()
+    }).optional()
+  }),
+  execute: async (params) => {
+    // 工具实现
+    const result = await doSomething(params.input);
+    return {
+      success: true,
+      result: result
+    };
+  }
+});
+ +

工具权限

+ +

工具执行遵循权限控制机制:

+ +
interface PermissionConfig {
+  // 允许的路径
+  allowedPaths: string[];
+  deniedPaths: string[];
+
+  // 工具权限
+  allowedTools: string[];
+  deniedTools: string[];
+
+  // Shell 命令
+  allowShellCommands: boolean;
+  shellCommandPatterns: string[];
+
+  // 自动批准规则
+  autoApproveRules: AutoApproveRule[];
+}
+ +

工具执行流程

+ +
AI 请求工具调用
+       │
+       ▼
+┌─────────────────┐
+│  权限检查        │  ← 检查工具是否允许
+└────────┬────────┘
+         │
+    允许  │  拒绝
+    ┌────┴────┐
+    │         │
+    ▼         ▼
+┌──────────┐  返回
+│ 创建检查点 │  错误
+└────┬─────┘
+     │
+     ▼
+┌─────────────────┐
+│  执行工具        │
+└────────┬────────┘
+         │
+    成功  │  失败
+    ┌────┴────┐
+    │         │
+    ▼         ▼
+  返回      返回
+  结果      错误
+ +

工具描述文件

+ +

每个工具都有独立的描述文件,位于 tools/descriptions/

+ +
# read_file
+
+读取指定路径的文件内容。
+
+## 参数
+
+- `path` (string, 必需): 文件的绝对路径
+- `encoding` (string, 可选): 文件编码,默认 utf-8
+
+## 返回值
+
+文件内容字符串,或 base64 编码的二进制数据。
+
+## 示例
+
+读取配置文件:
+```json
+{
+  "path": "/project/config.json"
+}
+```
+ +

MCP 工具扩展

+ +

通过 Model Context Protocol 集成外部工具:

+ +
// 配置 MCP 服务器
+const mcpConfig = {
+  servers: [
+    {
+      name: 'filesystem',
+      command: 'npx',
+      args: ['-y', '@modelcontextprotocol/server-filesystem']
+    },
+    {
+      name: 'github',
+      command: 'npx',
+      args: ['-y', '@modelcontextprotocol/server-github']
+    }
+  ]
+};
+
+// 初始化后,MCP 工具自动注册到 toolRegistry
+ +

代码位置

+ + + + + + + + + + + + + + + + + +
模块文件说明
工具注册tools/registry.ts工具注册系统
文件工具tools/file.ts文件操作
搜索工具tools/search.ts代码搜索
Shell 工具tools/bash.ts命令执行
Git 工具tools/git.tsGit 操作
工具描述tools/descriptions/工具文档
+ +

相关文档

+ +
+ +

Agent 系统

+

了解 Agent 如何调用工具

+
+ + +

MCP 集成

+

扩展更多外部工具

+
+
+
diff --git a/packages/website/src/pages/docs/features/browser-gui.astro b/packages/website/src/pages/docs/features/browser-gui.astro new file mode 100644 index 0000000..6366080 --- /dev/null +++ b/packages/website/src/pages/docs/features/browser-gui.astro @@ -0,0 +1,67 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

浏览器 GUI (Browser GUI)

+ +

基于浏览器的图形界面,允许用户通过 Web 界面与 AI 交互。对于不熟悉命令行的用户更加友好,也支持更丰富的展示效果。

+ +

核心功能

+ + +

技术栈

+ + + + + + + + + + + + + + +
组件选择
前端框架React + TypeScript
构建工具Vite
样式Tailwind CSS
状态管理Zustand
实时通信WebSocket
+ +

核心组件

+ + +

启动命令

+
# 开发模式
+pnpm web:dev
+
+# 构建生产版本
+pnpm web:build
+
+# 预览构建结果
+pnpm web:preview
+ +

实现状态

+

优先级: 低 | 状态: 已完成

+ +

已完成功能

+ +
diff --git a/packages/website/src/pages/docs/features/chat-history.astro b/packages/website/src/pages/docs/features/chat-history.astro new file mode 100644 index 0000000..d482c8d --- /dev/null +++ b/packages/website/src/pages/docs/features/chat-history.astro @@ -0,0 +1,91 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

会话管理 (Session Management)

+ +

✅ 已完成 - 三层存储架构已实现

+ +

完整的会话管理系统,包括消息存储、自动保存、上下文压缩等功能。代码位于 packages/core/src/session/packages/core/src/context/

+ +

已实现功能

+ + +

设计方案

+ +

类型定义

+
export interface ChatMessage {
+  id: string;
+  timestamp: Date;
+  role: 'user' | 'assistant' | 'system';
+  content: string;
+  metadata?: {
+    model?: string;
+    tokens?: number;
+    toolCalls?: ToolCall[];
+    editedFiles?: string[];
+  };
+}
+
+export interface ChatSession {
+  id: string;
+  startTime: Date;
+  endTime?: Date;
+  messages: ChatMessage[];
+  workdir: string;
+  summary?: string;
+}
+ +

历史管理器

+
export class ChatHistoryManager {
+  startSession(workdir: string): ChatSession;
+  addMessage(message: ChatMessage): void;
+  getContext(tokenBudget: number): ChatMessage[];
+  search(query: string): SearchResult[];
+  restoreSession(sessionId: string): ChatSession | null;
+  save(): Promise<void>;
+  load(): Promise<void>;
+}
+ +

配置示例

+
# .ai-assistant.yml
+history:
+  enabled: true
+  saveDir: .ai-assistant/history
+  maxSessions: 100
+  maxMessagesPerSession: 1000
+  autoSave: true
+  saveInterval: 5000
+  exportFormat: markdown
+  contextTokenBudget: 50000
+ +

模块结构

+ + + + + + + + + + + + + + +
模块位置功能
SessionManagersession/manager.ts会话管理,消息存储,项目管理
SessionStoragesession/storage/三层存储结构,持久化存储
MessageConvertersession/message-converter.ts消息格式转换,API 格式适配
Parts Systemsession/parts.ts消息片段系统(Text、Tool、Reasoning 等)
CompressionManagercontext/manager.ts上下文压缩管理
TokenCountercontext/token-counter.tsToken 计数工具
Prunecontext/prune.ts消息清理策略
Compactioncontext/compaction.ts消息压缩策略
+ +

待完善功能

+ +
diff --git a/packages/website/src/pages/docs/features/checkpoint.astro b/packages/website/src/pages/docs/features/checkpoint.astro new file mode 100644 index 0000000..159be49 --- /dev/null +++ b/packages/website/src/pages/docs/features/checkpoint.astro @@ -0,0 +1,96 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

Checkpoint 系统

+ +

✅ 已完成 - 核心功能及增强功能全部实现

+ +

完整的检查点系统,基于 Shadow Git 架构,提供安全可靠的代码恢复能力。代码位于 packages/core/src/checkpoint/

+ +

当前架构

+
┌─────────────────────────────────────────────────────────────┐
+│                    CheckpointManager                         │
+│  - createCheckpoint()     - rollback()                      │
+│  - listCheckpoints()      - undo()                          │
+│  - getDiff()              - cleanup()                       │
+└─────────────────────────────────────────────────────────────┘
+                              │
+                              ▼
+┌─────────────────────────────────────────────────────────────┐
+│                       ShadowGit                              │
+│  Storage: ~/.ai-assist/checkpoints/<cwdHash>/.git/          │
+│  - createCommit()         - resetHard()                     │
+│  - getDiffSummary()       - checkoutFiles()                 │
+│  - getFileDiff()          - getFileContent()                │
+└─────────────────────────────────────────────────────────────┘
+ +

已有功能

+ + + + + + + + + + + + + + +
功能状态
Shadow Git 隔离存储已实现
自动检查点触发已实现
手动检查点已实现
差异查看已实现
完整回滚已实现
选择性回滚已实现
自动清理已实现
事件系统已实现
+ +

已实现功能

+ +

核心安全 (P0)

+ + +

可用性增强 (P1)

+ + +

体验优化 (P2)

+ + +

待实现 (P3)

+ + +

三种恢复模式

+
enum RestoreMode {
+  AI_CHANGES_ONLY = 'ai_changes_only',   // 仅恢复 AI 修改
+  WORKSPACE_ONLY = 'workspace_only',     // 仅恢复工作区变更
+  FULL = 'full'                          // 完整恢复
+}
+ +

模块结构

+ + + + + + + + + + + + + + +
模块功能
manager.ts检查点核心管理器
shadow-git.tsShadow Git 架构实现
safety.ts7点安全检查机制
session-tracker.ts会话级别追踪和统计
checkpoint-rollback.ts回滚和撤销回滚功能
lfs.tsGit LFS 大文件支持
path-validator.ts工作区路径验证
commit-message.ts智能提交消息生成
+
diff --git a/packages/website/src/pages/docs/features/configuration.astro b/packages/website/src/pages/docs/features/configuration.astro new file mode 100644 index 0000000..13b00b2 --- /dev/null +++ b/packages/website/src/pages/docs/features/configuration.astro @@ -0,0 +1,90 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

配置管理 (Configuration Management)

+ +

灵活的配置管理系统,支持多种配置来源和优先级,让用户可以根据项目、环境和个人偏好定制工具行为。

+ +

配置来源(优先级从高到低)

+
    +
  1. 命令行参数 - 最高优先级
  2. +
  3. 环境变量 - AI_ASSISTANT_* 前缀
  4. +
  5. 项目配置文件 - .ai-assistant.yml
  6. +
  7. 用户配置文件 - ~/.ai-assistant.yml
  8. +
  9. 默认值 - 代码中的默认配置
  10. +
+ +

配置文件格式

+
# .ai-assistant.yml
+
+# 模型设置
+model: claude-3-5-sonnet
+
+# 自动化
+auto-commit: true
+auto-lint: true
+auto-test: false
+
+# 编辑模式
+edit-mode: search-replace
+
+# Git 集成
+git:
+  enabled: true
+  auto-commit:
+    enabled: true
+    mode: batch
+    batch-delay: 3000
+
+# Linting
+linting:
+  enabled: true
+  auto-fix: true
+  max-fix-attempts: 3
+
+# 测试
+testing:
+  enabled: true
+  command: npm test
+  auto-run: false
+
+# 历史记录
+history:
+  enabled: true
+  save-dir: .ai-assistant/history
+  max-sessions: 100
+
+# 日志
+log-level: info
+ +

环境变量

+
# 通过环境变量设置
+export AI_ASSISTANT_MODEL=gpt-4
+export AI_ASSISTANT_AUTO_COMMIT=true
+export AI_ASSISTANT_API_KEY=sk-xxx
+ +

命令行参数

+
ai-assistant --model claude-3-opus --auto-lint --no-auto-commit
+ +

设计方案

+
export class ConfigManager {
+  private sources: ConfigSource[] = [];
+
+  addSource(source: ConfigSource): void;
+  load(): Promise<AgentConfig>;
+  get<K extends keyof AgentConfig>(key: K): AgentConfig[K];
+  set<K extends keyof AgentConfig>(key: K, value: AgentConfig[K]): void;
+}
+
+export interface ConfigSource {
+  name: string;
+  priority: number;
+  load(): Promise<Partial<AgentConfig>>;
+}
+ +

实现状态

+

优先级: 高 | 状态: 待实现

+

配置管理是基础架构,应该尽早实现以支持其他功能的可配置性。

+
diff --git a/packages/website/src/pages/docs/features/edit-modes.astro b/packages/website/src/pages/docs/features/edit-modes.astro new file mode 100644 index 0000000..6101d11 --- /dev/null +++ b/packages/website/src/pages/docs/features/edit-modes.astro @@ -0,0 +1,92 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

编辑模式 (Edit Modes)

+ +

✅ 已完成 - 三种编辑模式全部实现

+ +

AI 以不同的方式修改代码,在准确性、效率和 token 消耗之间有不同的权衡。编辑系统位于 packages/core/src/editors/

+ +

支持的编辑模式

+ +

1. Whole 模式

+ + +

2. Diff 模式

+ + +

3. Search-Replace 模式

+ + +

4. Architect 模式

+ + +

设计方案

+ +
// src/editors/types.ts
+export type EditMode = 'whole' | 'diff' | 'search-replace';
+
+export interface EditResult {
+  success: boolean;
+  filePath: string;
+  originalContent?: string;
+  newContent?: string;
+  error?: string;
+}
+
+export interface Editor {
+  mode: EditMode;
+  parse(response: string): Edit[];
+  apply(edit: Edit): Promise<EditResult>;
+}
+ +

实现状态

+ + + + + + + + + + + + + + + + + + +
功能状态代码位置
Whole 模式✅ 已实现editors/whole.ts
Diff 模式✅ 已实现editors/diff.ts
Search-Replace 模式✅ 已实现editors/search-replace.ts
统一编辑接口✅ 已实现editors/index.ts
编辑解析器✅ 已实现editors/parsers.ts
编辑验证器✅ 已实现editors/validator.ts
编辑应用器✅ 已实现editors/applier.ts
Architect 模式📋 规划中-
+ +

相关模块

+ +
diff --git a/packages/website/src/pages/docs/features/linting.astro b/packages/website/src/pages/docs/features/linting.astro new file mode 100644 index 0000000..3c62d38 --- /dev/null +++ b/packages/website/src/pages/docs/features/linting.astro @@ -0,0 +1,75 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

Linting 集成 (Linting Integration)

+ +

在 AI 编辑代码后自动运行 linter,检测并修复语法和风格错误,确保 AI 生成的代码符合项目标准。

+ +

工作流程

+
    +
  1. AI 编辑代码文件
  2. +
  3. 自动运行配置的 linter
  4. +
  5. 解析 linter 输出
  6. +
  7. 如果有错误,将错误反馈给 AI
  8. +
  9. AI 尝试修复错误
  10. +
  11. 重复直到通过或达到最大尝试次数
  12. +
+ +

设计方案

+ +

类型定义

+
export interface LintError {
+  file: string;
+  line: number;
+  column: number;
+  severity: 'error' | 'warning' | 'info';
+  message: string;
+  rule?: string;
+  source: string;
+}
+
+export interface LinterConfig {
+  enabled: boolean;
+  command: string;
+  args?: string[];
+  parseOutput: (output: string) => LintError[];
+}
+ +

默认 Linter 配置

+
export const DEFAULT_LINTERS = {
+  '.ts': {
+    command: 'npx',
+    args: ['eslint', '--format', 'json', '{file}'],
+    parseOutput: parseESLintOutput,
+  },
+  '.py': {
+    command: 'python',
+    args: ['-m', 'flake8', '--format', 'json', '{file}'],
+    parseOutput: parseFlake8Output,
+  },
+  '.go': {
+    command: 'golint',
+    args: ['{file}'],
+    parseOutput: parseGolintOutput,
+  },
+  '.rs': {
+    command: 'cargo',
+    args: ['clippy', '--message-format', 'json'],
+    parseOutput: parseCargoOutput,
+  },
+};
+ +

配置示例

+
# .ai-assistant.yml
+linting:
+  enabled: true
+  autoFix: true
+  maxFixAttempts: 3
+  ignoreRules: ['no-console']
+  ignorePatterns: ['*.test.ts']
+ +

实现状态

+

优先级: 高 | 状态: 待实现

+
diff --git a/packages/website/src/pages/docs/features/multi-model.astro b/packages/website/src/pages/docs/features/multi-model.astro new file mode 100644 index 0000000..785ae26 --- /dev/null +++ b/packages/website/src/pages/docs/features/multi-model.astro @@ -0,0 +1,107 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

多模型支持 (Multi-Model Support)

+ +

✅ 已完成 - Provider 注册系统已实现

+ +

通过 Provider 注册系统支持多种 AI 模型提供商。代码位于 packages/core/src/provider/

+ +

支持的提供商

+ + +

设计方案

+ +

模型配置

+
export interface ModelConfig {
+  id: string;
+  provider: ModelProvider;
+  name: string;
+  capabilities: {
+    maxContextTokens: number;
+    maxOutputTokens: number;
+    supportsImages: boolean;
+    supportsTools: boolean;
+    supportStreaming: boolean;
+  };
+  editFormat: EditMode;
+  useRepoMap: boolean;
+  pricing?: {
+    inputPer1kTokens: number;
+    outputPer1kTokens: number;
+  };
+}
+
+export type ModelProvider =
+  | 'anthropic'
+  | 'openai'
+  | 'google'
+  | 'deepseek'
+  | 'azure'
+  | 'ollama'
+  | 'openrouter';
+ +

Architect 模式

+
export class ArchitectMode {
+  private plannerModel: ModelConfig;  // 规划模型 (更强)
+  private editorModel: ModelConfig;   // 执行模型 (更快/便宜)
+
+  async execute(task: Task): Promise<Result> {
+    // 1. 使用规划模型分析任务
+    const plan = await this.plan(task);
+    // 2. 使用编辑模型执行每个步骤
+    const results = await this.executeSteps(plan.steps);
+    return this.summarize(results);
+  }
+}
+ +

配置示例

+
const config = {
+  models: {
+    default: 'claude-3-5-sonnet',
+    taskModels: {
+      planning: 'claude-3-opus',
+      coding: 'claude-3-5-sonnet',
+      review: 'gpt-4',
+      quick: 'claude-3-haiku',
+    },
+    architect: {
+      planner: 'claude-3-opus',
+      editor: 'claude-3-haiku',
+    },
+  },
+};
+ +

实现状态

+ + + + + + + + + + + + +
功能状态代码位置
Provider 注册系统✅ 已实现provider/registry.ts
Anthropic 支持✅ 已实现provider/builtin/
OpenAI 兼容提供商✅ 已实现provider/utils.ts
Provider 配置管理✅ 已实现provider/config.ts
连接测试✅ 已实现provider/utils.ts
Architect 模式📋 规划中-
+ +

模块结构

+ +
diff --git a/packages/website/src/pages/docs/features/repo-map.astro b/packages/website/src/pages/docs/features/repo-map.astro new file mode 100644 index 0000000..7b8081a --- /dev/null +++ b/packages/website/src/pages/docs/features/repo-map.astro @@ -0,0 +1,73 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

仓库地图 (Repo Map)

+ +

✅ 已完成 - AST 解析和 PageRank 排序已实现

+ +

使用 tree-sitter 进行源代码分析,生成精确的代码结构图。代码位于 packages/core/src/repomap/

+ +

核心功能

+ +

1. Tree-sitter 解析

+ + +

2. 智能排序

+ + +

3. Token 优化

+ + +

增强建议

+ +

引用分析

+
export interface Reference {
+  from: SymbolLocation;
+  to: SymbolLocation;
+  type: 'call' | 'import' | 'extend' | 'implement';
+}
+
+export class ReferenceAnalyzer {
+  analyzeReferences(files: FileSymbols[]): Reference[];
+  buildReferenceGraph(references: Reference[]): ReferenceGraph;
+}
+ +

相关性排序

+
export class RelevanceRanker {
+  rankByRelevance(
+    targetFiles: string[],
+    allFiles: FileSymbols[],
+    references: Reference[]
+  ): RankedFile[];
+
+  calculateRelevance(file: FileSymbols, context: TaskContext): number;
+}
+ +

实现状态

+ + + + + + + + + + + +
功能状态
Tree-sitter AST 解析✅ 已实现
PageRank 相关性排序✅ 已实现
多语言支持✅ 已实现
Token 预算管理✅ 已实现
符号提取✅ 已实现
+
diff --git a/packages/website/src/pages/docs/features/testing.astro b/packages/website/src/pages/docs/features/testing.astro new file mode 100644 index 0000000..847370e --- /dev/null +++ b/packages/website/src/pages/docs/features/testing.astro @@ -0,0 +1,75 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

测试集成 (Test Integration)

+ +

在代码修改后自动运行测试,并在测试失败时将错误信息反馈给 AI 进行修复,形成"编辑-测试-修复"的闭环。

+ +

工作流程

+
    +
  1. AI 编辑代码
  2. +
  3. 运行相关测试
  4. +
  5. 如果测试失败,解析错误信息
  6. +
  7. 将错误反馈给 AI
  8. +
  9. AI 修复代码
  10. +
  11. 重复直到测试通过或达到限制
  12. +
+ +

设计方案

+ +

类型定义

+
export interface TestResult {
+  success: boolean;
+  passed: number;
+  failed: number;
+  skipped: number;
+  duration: number;
+  failures: TestFailure[];
+  output: string;
+}
+
+export interface TestFailure {
+  testName: string;
+  file?: string;
+  line?: number;
+  message: string;
+  stack?: string;
+  expected?: string;
+  actual?: string;
+}
+ +

默认测试配置

+
export const DEFAULT_TEST_CONFIGS = {
+  jest: {
+    command: 'npx',
+    args: ['jest', '--json', '--testLocationInResults'],
+    testFilePatterns: ['**/*.test.ts', '**/*.spec.ts'],
+  },
+  vitest: {
+    command: 'npx',
+    args: ['vitest', 'run', '--reporter=json'],
+    testFilePatterns: ['**/*.test.ts', '**/*.spec.ts'],
+  },
+  pytest: {
+    command: 'python',
+    args: ['-m', 'pytest', '--tb=short', '-v'],
+    testFilePatterns: ['**/test_*.py', '**/*_test.py'],
+  },
+};
+ +

配置示例

+
# .ai-assistant.yml
+testing:
+  enabled: true
+  runner: vitest
+  autoRun: true
+  autoFix: true
+  maxFixAttempts: 3
+  timeout: 60000
+  runRelatedOnly: true
+ +

实现状态

+

优先级: 高 | 状态: 待实现

+
diff --git a/packages/website/src/pages/docs/features/voice-input.astro b/packages/website/src/pages/docs/features/voice-input.astro new file mode 100644 index 0000000..6c69db1 --- /dev/null +++ b/packages/website/src/pages/docs/features/voice-input.astro @@ -0,0 +1,58 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

语音输入 (Voice Input)

+ +

支持语音输入功能,用户可以通过语音与 AI 交互。对于快速描述需求、解放双手编程等场景非常有用。

+ +

核心功能

+ + +

支持的提供商

+ + +

设计方案

+
export interface VoiceConfig {
+  enabled: boolean;
+  provider: 'whisper' | 'google' | 'azure' | 'local';
+  language?: string;
+  sampleRate: number;
+  channels: number;
+  silenceThreshold: number;
+  silenceDuration: number;
+}
+
+export interface VoiceManager {
+  startRecording(): Promise<void>;
+  stopAndTranscribe(): Promise<string>;
+  voiceToText(): Promise<string>;
+}
+ +

配置示例

+
# .ai-assistant.yml
+voice:
+  enabled: false
+  provider: whisper
+  language: zh-CN
+  sampleRate: 16000
+  channels: 1
+  silenceThreshold: 0.5
+  silenceDuration: 1500
+  hotkey: space
+ +

实现状态

+

优先级: 低 | 状态: 待实现

+

语音输入是"锦上添花"的功能,建议在核心功能完善后再考虑实现。

+
diff --git a/packages/website/src/pages/docs/features/watch-mode.astro b/packages/website/src/pages/docs/features/watch-mode.astro new file mode 100644 index 0000000..b5cb103 --- /dev/null +++ b/packages/website/src/pages/docs/features/watch-mode.astro @@ -0,0 +1,72 @@ +--- +import DocsLayout from '../../../layouts/DocsLayout.astro'; +--- + + +

Watch 模式 (Watch Mode)

+ +

允许用户在代码中添加特殊注释(如 # AI: fix this),文件保存时 AI 会自动检测并处理这些注释请求。提供无需离开编辑器就能与 AI 交互的方式。

+ +

核心功能

+ + +

支持的注释格式

+
# AI: 请优化这个函数
+# AI! 这里有 bug,请修复
+# FIXME: AI 请重构这段代码
+# TODO: AI 添加错误处理
+ +
// AI: 请优化这个函数
+// AI! 这里有 bug,请修复
+/* AI: 重构这段代码 */
+ +

设计方案

+ +

类型定义

+
export interface AIComment {
+  content: string;
+  line: number;
+  column: number;
+  filePath: string;
+  original: string;
+  type: 'request' | 'todo' | 'fixme' | 'question';
+}
+
+export interface WatchConfig {
+  enabled: boolean;
+  patterns: string[];
+  ignorePatterns: string[];
+  debounceMs: number;
+  autoProcess: boolean;
+  confirmBeforeEdit: boolean;
+}
+ +

使用示例

+
// 在代码中添加注释
+function calculateTotal(items: Item[]): number {
+  // AI: 请优化这个函数的性能
+  let total = 0;
+  for (const item of items) {
+    total += item.price * item.quantity;
+  }
+  return total;
+}
+ +

配置示例

+
# .ai-assistant.yml
+watch:
+  enabled: false
+  patterns: ['**/*.ts', '**/*.tsx', '**/*.py']
+  ignorePatterns: ['node_modules/**', 'dist/**']
+  debounceMs: 1000
+  autoProcess: true
+  confirmBeforeEdit: false
+ +

实现状态

+

优先级: 中 | 状态: 待实现

+
diff --git a/packages/website/src/pages/docs/index.astro b/packages/website/src/pages/docs/index.astro new file mode 100644 index 0000000..17a29f8 --- /dev/null +++ b/packages/website/src/pages/docs/index.astro @@ -0,0 +1,194 @@ +--- +import DocsLayout from '../../layouts/DocsLayout.astro'; +--- + + +

AI Terminal Assistant 文档

+ +

+ 欢迎来到 AI Terminal Assistant 文档。这是一个功能完整的终端 AI 编程助手, + 支持流式对话、工具调用、代码检查点、多模型支持等特性。 +

+ +

项目简介

+ +

+ AI Terminal Assistant 采用 Monorepo 架构,核心引擎已实现完整的 Agent 系统、 + 工具链、检查点和扩展机制。支持 Web、桌面、CLI 多端访问。 +

+ +
+
ai-terminal-assistant/
+├── packages/
+│   ├── core/       # 核心引擎:Agent、工具、LSP、Checkpoint
+│   ├── server/     # HTTP 服务器:REST API、WebSocket、SSE
+│   ├── cli/        # 命令行界面
+│   ├── web/        # React 前端
+│   └── desktop/    # Tauri 桌面应用
+└── docs/           # 设计文档
+
+ +

核心能力

+ +
+
+
+

Agent 系统

+

完整的 Agent 引擎,支持流式响应、工具调用、Vision 处理、Plan 模式

+
+ +
+
🛠️
+

工具系统

+

23+ 内置工具(Shell、文件、Git、搜索、Web 等),支持动态加载和语义搜索

+
+ +
+
💾
+

Checkpoint 系统

+

Shadow Git 架构、7点安全检查、创建/恢复/撤销恢复

+
+ +
+
🔌
+

MCP 集成

+

完整的 Model Context Protocol 支持,通过外部工具扩展 AI 能力

+
+
+ +

快速导航

+ +
+ +

🚀 快速开始

+

5 分钟内启动并运行

+
+ + +

🏗️ 架构设计

+

了解系统架构和模块设计

+
+ + +

🤖 Agent 系统

+

深入了解 AI Agent 引擎

+
+ + +

📡 API 参考

+

REST API 和 WebSocket 文档

+
+
+ +

功能状态

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
功能状态描述
Agent 系统✅ 已完成流式响应、工具调用、多轮对话、Vision 支持
工具系统✅ 已完成23+ 内置工具,支持动态加载
编辑模式✅ 已完成Whole、Search-Replace、Diff 三种模式
Checkpoint✅ 已完成Shadow Git 架构,7点安全检查
会话管理✅ 已完成三层存储、自动保存、消息压缩
MCP 集成✅ 已完成完整的 Model Context Protocol 支持
多模型支持✅ 已完成Claude、OpenAI、DeepSeek 等
Web GUI✅ 已完成React 前端 + WebSocket 实时通信
配置管理🔧 部分实现支持配置加载,完整多层配置待完善
Linting 集成📋 规划中代码编辑后自动运行 linter
测试集成📋 规划中代码修改后自动运行测试
+ +

开发路线图

+ +

✅ 已完成

+ + +

🚧 进行中

+
    +
  1. 配置管理增强 - 完善多层配置系统
  2. +
  3. LSP 深度集成 - 代码诊断和补全
  4. +
+ +

📋 计划中

+
    +
  1. Linting 集成 - 代码编辑后自动运行 linter
  2. +
  3. 测试集成 - 代码修改后自动运行测试
  4. +
  5. Watch 模式 - 文件监控和 AI 注释处理
  6. +
  7. 语音输入 - 语音转文字交互
  8. +
+ +

获取帮助

+ +
+ +

GitHub

+

源代码和 Issues

+
+ + +

Discord

+

社区讨论

+
+ + +

快速开始

+

开始使用

+
+
+
diff --git a/packages/website/src/pages/docs/quickstart.astro b/packages/website/src/pages/docs/quickstart.astro new file mode 100644 index 0000000..303d60b --- /dev/null +++ b/packages/website/src/pages/docs/quickstart.astro @@ -0,0 +1,140 @@ +--- +import DocsLayout from '../../layouts/DocsLayout.astro'; +--- + + +

快速开始

+ +

+ 本指南将帮助你在几分钟内启动并运行 AI Terminal Assistant。 +

+ +

前置要求

+ + + +

安装

+ +

1. 克隆仓库

+ +
# 克隆项目
+git clone https://github.com/your-username/ai-terminal-assistant.git
+cd ai-terminal-assistant
+
+# 安装依赖
+pnpm install
+ +

2. 配置环境变量

+ +
# 创建 .env 文件
+cp .env.example .env
+
+# 编辑 .env 文件,添加你的 API Key
+ANTHROPIC_API_KEY=your_api_key_here
+ +

3. 构建项目

+ +
# 构建所有包
+pnpm build
+
+# 或只构建需要的包
+pnpm --filter @ai-assistant/core build
+pnpm --filter @ai-assistant/server build
+ +

启动服务

+ +

方式一:开发模式

+ +
# 启动 HTTP 服务器 (端口 3000)
+pnpm server:dev
+
+# 在另一个终端启动 Web UI (端口 5173)
+cd packages/web && pnpm dev
+ +

然后在浏览器中打开 http://localhost:5173

+ +

方式二:CLI 命令

+ +
# 启动服务器
+cd packages/cli && bun run src/index.ts serve --port 3000
+
+# 从另一个终端连接
+cd packages/cli && bun run src/index.ts attach http://localhost:3000
+ +

方式三:远程模式

+ +
# 启动可远程访问的服务器 (自动生成 Token)
+bun run packages/server/src/bin/server.ts --host 0.0.0.0 --port 3000
+
+# 使用自定义 Token
+bun run packages/server/src/bin/server.ts --host 0.0.0.0 --token your_secret_token
+ +

基本使用

+ +

创建会话

+ +
# REST API 创建会话
+curl -X POST http://localhost:3000/api/sessions \
+  -H "Content-Type: application/json" \
+  -d '{"name": "my-session"}'
+ +

发送消息

+ +

通过 WebSocket 连接到 /api/ws/:sessionId 进行实时对话:

+ +
const ws = new WebSocket('ws://localhost:3000/api/ws/session-id');
+
+ws.onopen = () => {
+  ws.send(JSON.stringify({
+    type: 'message',
+    payload: { content: '帮我写一个 Hello World 函数' }
+  }));
+};
+
+ws.onmessage = (event) => {
+  const data = JSON.parse(event.data);
+  if (data.type === 'chunk') {
+    console.log(data.payload.content);
+  }
+};
+ +

项目结构

+ +
ai-terminal-assistant/
+├── packages/
+│   ├── core/       # 核心引擎:Agent、工具、LSP、Checkpoint
+│   ├── server/     # HTTP 服务器:REST API、WebSocket、SSE
+│   ├── cli/        # 命令行界面:serve、attach 命令
+│   ├── web/        # React 前端:Vite + Tailwind CSS
+│   └── desktop/    # Tauri 桌面应用
+├── docs/           # 设计文档
+└── pnpm-workspace.yaml
+ +

下一步

+ +
+ +

架构设计

+

了解系统架构和模块设计

+
+ + +

Agent 系统

+

深入了解 AI Agent 引擎

+
+ + +

工具系统

+

探索 23+ 内置工具

+
+ + +

API 参考

+

完整的 REST API 文档

+
+
+