@saber2pr/ai-agent 0.0.4 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/agent.d.ts CHANGED
@@ -5,7 +5,13 @@ export default class McpAgent {
5
5
  private allTools;
6
6
  private messages;
7
7
  private engine;
8
+ private encoder;
8
9
  constructor();
10
+ /**
11
+ * 计算当前消息列表的总 Token 消耗
12
+ * 兼容多模态内容 (Content Parts) 和 工具调用 (Tool Calls)
13
+ */
14
+ private calculateTokens;
9
15
  /**
10
16
  * 核心功能:内置代码分析工具
11
17
  * 这里的逻辑直接调用 PromptEngine,不走网络请求,效率极高
@@ -14,10 +20,10 @@ export default class McpAgent {
14
20
  private ensureApiConfig;
15
21
  private loadMcpConfigs;
16
22
  init(): Promise<void>;
23
+ private processChat;
17
24
  /**
18
- * 核心交互循环 (Reasoning Loop)
19
- * 允许 AI 连续调用工具来解决复杂代码问题
25
+ * 简易 Loading 动画辅助函数
20
26
  */
21
- private processChat;
27
+ private showLoading;
22
28
  start(): Promise<void>;
23
29
  }
package/lib/agent.js CHANGED
@@ -44,6 +44,7 @@ const path_1 = __importDefault(require("path"));
44
44
  const os_1 = __importDefault(require("os"));
45
45
  const readline = __importStar(require("readline"));
46
46
  const ts_context_mcp_1 = require("@saber2pr/ts-context-mcp"); // 引入我们的核心引擎
47
+ const js_tiktoken_1 = require("js-tiktoken");
47
48
  const CONFIG_FILE = path_1.default.join(os_1.default.homedir(), ".saber2pr-agent.json");
48
49
  class McpAgent {
49
50
  constructor() {
@@ -51,6 +52,7 @@ class McpAgent {
51
52
  this.clients = [];
52
53
  this.allTools = [];
53
54
  this.messages = [];
55
+ this.encoder = (0, js_tiktoken_1.getEncoding)("cl100k_base");
54
56
  // 默认以当前工作目录为分析目标
55
57
  this.engine = new ts_context_mcp_1.PromptEngine(process.cwd());
56
58
  this.messages.push({
@@ -58,11 +60,54 @@ class McpAgent {
58
60
  content: `你是一个专业的 AI 代码架构师。
59
61
  你可以访问本地文件系统并利用 AST (抽象语法树) 技术分析代码。
60
62
  你的核心目标是提供准确的代码结构、依赖关系和逻辑分析。
63
+ 请先使用 get_repo_map 查看项目整体代码结构。
61
64
  请优先使用 read_skeleton 查看结构,只有在必要时才使用 read_full_code 或 get_method_body。`,
62
65
  });
63
66
  // 初始化内置工具
64
67
  this.registerBuiltinTools();
65
68
  }
69
+ /**
70
+ * 计算当前消息列表的总 Token 消耗
71
+ * 兼容多模态内容 (Content Parts) 和 工具调用 (Tool Calls)
72
+ */
73
+ calculateTokens() {
74
+ let total = 0;
75
+ for (const msg of this.messages) {
76
+ // 1. 处理消息内容 (Content)
77
+ if (msg.content) {
78
+ if (typeof msg.content === "string") {
79
+ // 普通文本消息
80
+ total += this.encoder.encode(msg.content).length;
81
+ }
82
+ else if (Array.isArray(msg.content)) {
83
+ // 多模态/复合内容消息 (ChatCompletionContentPart[])
84
+ for (const part of msg.content) {
85
+ if (part.type === "text" && "text" in part) {
86
+ total += this.encoder.encode(part.text || "").length;
87
+ }
88
+ // 注意:图片 (image_url) 的 Token 计算通常基于分辨率,tiktoken 无法计算
89
+ }
90
+ }
91
+ }
92
+ // 2. 处理助手角色发出的工具调用请求 (Assistant Tool Calls)
93
+ // 这是为了统计 AI 发出的指令所占用的 Token
94
+ if (msg.role === "assistant" && msg.tool_calls) {
95
+ for (const call of msg.tool_calls) {
96
+ if (call.type === "function") {
97
+ // 统计函数名和参数字符串
98
+ total += this.encoder.encode(call.function.name).length;
99
+ total += this.encoder.encode(call.function.arguments).length;
100
+ }
101
+ }
102
+ }
103
+ // 3. 处理工具返回的结果 (Tool Role)
104
+ // 在 processChat 中,我们确保了工具返回的 result 最终被转为了 string
105
+ if (msg.role === "tool" && typeof msg.content === "string") {
106
+ total += this.encoder.encode(msg.content).length;
107
+ }
108
+ }
109
+ return total;
110
+ }
66
111
  /**
67
112
  * 核心功能:内置代码分析工具
68
113
  * 这里的逻辑直接调用 PromptEngine,不走网络请求,效率极高
@@ -109,7 +154,25 @@ class McpAgent {
109
154
  required: ["filePath"],
110
155
  },
111
156
  },
112
- _handler: async ({ filePath }) => this.engine.getSkeleton(filePath),
157
+ _handler: async (args) => {
158
+ // 1. 严格路径守卫:防止 undefined 或空字符串进入 path 模块
159
+ const pathArg = args === null || args === void 0 ? void 0 : args.filePath;
160
+ if (typeof pathArg !== 'string' || pathArg.trim() === '') {
161
+ return `Error: 参数 'filePath' 无效。收到的是: ${JSON.stringify(pathArg)}`;
162
+ }
163
+ try {
164
+ // 2. 刷新引擎状态,确保分析的是最新的文件内容
165
+ this.engine.refresh();
166
+ // 3. 执行获取
167
+ const result = this.engine.getSkeleton(pathArg);
168
+ // 4. 空值回退:防止 getSkeleton 返回 null 导致后续统计 Token 时崩溃
169
+ return result || `// Warning: 文件 ${pathArg} 存在但未找到任何可提取的结构。`;
170
+ }
171
+ catch (error) {
172
+ // 5. 捕获 AST 级别的 match 错误
173
+ return `Error: 解析文件 ${pathArg} 时发生内部错误: ${error.message}`;
174
+ }
175
+ },
113
176
  },
114
177
  {
115
178
  type: "function",
@@ -127,6 +190,41 @@ class McpAgent {
127
190
  },
128
191
  _handler: async ({ filePath, methodName }) => this.engine.getMethodImplementation(filePath, methodName),
129
192
  },
193
+ {
194
+ type: "function",
195
+ function: {
196
+ name: "read_full_code",
197
+ description: "读取指定文件的完整源代码内容。当需要分析具体实现逻辑或查找硬编码字符串时使用。",
198
+ parameters: {
199
+ type: "object",
200
+ properties: {
201
+ filePath: { type: "string", description: "文件相对路径" },
202
+ },
203
+ required: ["filePath"],
204
+ },
205
+ },
206
+ // 核心实现:直接利用 fs 读取
207
+ _handler: async ({ filePath }) => {
208
+ try {
209
+ if (typeof filePath !== 'string' || !filePath) {
210
+ return "Error: filePath 不能为空";
211
+ }
212
+ // 拼合绝对路径
213
+ const fullPath = path_1.default.resolve(this.engine.getRootDir(), filePath);
214
+ // 安全检查:防止 AI 尝试读取项目外的敏感文件
215
+ if (!fullPath.startsWith(this.engine.getRootDir())) {
216
+ return "Error: 权限拒绝,禁止访问项目目录外的文件。";
217
+ }
218
+ if (!fs_1.default.existsSync(fullPath)) {
219
+ return `Error: 文件不存在: ${filePath}`;
220
+ }
221
+ return fs_1.default.readFileSync(fullPath, "utf-8");
222
+ }
223
+ catch (err) {
224
+ return `Error: 读取文件失败: ${err.message}`;
225
+ }
226
+ },
227
+ },
130
228
  ];
131
229
  this.allTools.push(...builtinTools);
132
230
  }
@@ -200,50 +298,84 @@ class McpAgent {
200
298
  }
201
299
  }
202
300
  }
203
- /**
204
- * 核心交互循环 (Reasoning Loop)
205
- * 允许 AI 连续调用工具来解决复杂代码问题
206
- */
207
301
  async processChat(userInput) {
208
- this.messages.push({ role: "user", content: userInput });
302
+ var _a;
303
+ this.messages.push({ role: 'user', content: userInput });
209
304
  while (true) {
210
- const response = await this.openai.chat.completions.create({
211
- model: this.modelName,
212
- messages: this.messages,
213
- tools: this.allTools.map(({ _handler, _client, _originalName, ...rest }) => rest),
214
- tool_choice: "auto",
215
- });
305
+ // 打印当前上下文的累计 Token
306
+ const currentInputTokens = this.calculateTokens();
307
+ console.log(`\n📊 当前上下文累计: ${currentInputTokens} tokens`);
308
+ const stopLoading = this.showLoading("🤖 Agent 正在思考...");
309
+ let response;
310
+ try {
311
+ response = await this.openai.chat.completions.create({
312
+ model: this.modelName,
313
+ messages: this.messages,
314
+ tools: this.allTools.map(({ _handler, _client, _originalName, ...rest }) => rest),
315
+ tool_choice: 'auto'
316
+ });
317
+ }
318
+ finally {
319
+ stopLoading();
320
+ }
216
321
  const message = response.choices[0].message;
217
322
  this.messages.push(message);
323
+ // 计算本次 AI 回复生成的 Token
324
+ const completionTokens = ((_a = response.usage) === null || _a === void 0 ? void 0 : _a.completion_tokens) ||
325
+ (message.content ? this.encoder.encode(message.content).length : 0);
326
+ console.log(`✨ AI 回复消耗: ${completionTokens} tokens`);
218
327
  if (!message.tool_calls) {
219
328
  console.log(`\n🤖 Agent: ${message.content}`);
220
329
  break;
221
330
  }
222
- console.log(`\n⚙️ 正在思考并执行 ${message.tool_calls.length} 个操作...`);
331
+ console.log(`\n⚙️ 正在执行 ${message.tool_calls.length} 个操作...`);
223
332
  for (const call of message.tool_calls) {
224
- const tool = this.allTools.find((t) => t.function.name === call.function.name);
333
+ const tool = this.allTools.find(t => t.function.name === call.function.name);
334
+ const args = JSON.parse(call.function.arguments);
335
+ // 打印文件路径提示
336
+ if (args.filePath) {
337
+ console.log(` 📂 正在查看文件: ${args.filePath}`);
338
+ }
339
+ console.log(` 🛠️ 执行: ${call.function.name}`);
225
340
  let result;
226
341
  if (tool === null || tool === void 0 ? void 0 : tool._handler) {
227
- // 执行内置 PromptEngine 工具
228
- result = await tool._handler(JSON.parse(call.function.arguments));
342
+ result = await tool._handler(args);
229
343
  }
230
344
  else if ((tool === null || tool === void 0 ? void 0 : tool._client) && tool._originalName) {
231
- // 执行外部 MCP 工具
232
345
  const mcpRes = await tool._client.callTool({
233
346
  name: tool._originalName,
234
- arguments: JSON.parse(call.function.arguments),
347
+ arguments: args
235
348
  });
236
349
  result = mcpRes.content;
237
350
  }
351
+ const resultContent = typeof result === "string" ? result : JSON.stringify(result);
352
+ // 打印工具返回结果的 Token 消耗
353
+ const toolResultTokens = this.encoder.encode(resultContent).length;
354
+ console.log(` 📝 工具输出: ${toolResultTokens} tokens`);
238
355
  this.messages.push({
239
- role: "tool",
356
+ role: 'tool',
240
357
  tool_call_id: call.id,
241
- content: typeof result === "string" ? result : JSON.stringify(result),
358
+ content: resultContent
242
359
  });
243
- console.log(` - 完成: ${call.function.name}`);
360
+ console.log(` 完成: ${call.function.name}`);
244
361
  }
245
362
  }
246
363
  }
364
+ /**
365
+ * 简易 Loading 动画辅助函数
366
+ */
367
+ showLoading(text) {
368
+ const chars = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
369
+ let i = 0;
370
+ const timer = setInterval(() => {
371
+ process.stdout.write(`\r${chars[i]} ${text}`);
372
+ i = (i + 1) % chars.length;
373
+ }, 80);
374
+ return () => {
375
+ clearInterval(timer);
376
+ process.stdout.write('\r\x1b[K'); // 清除当前行
377
+ };
378
+ }
247
379
  async start() {
248
380
  await this.init();
249
381
  const rl = readline.createInterface({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@saber2pr/ai-agent",
3
- "version": "0.0.4",
3
+ "version": "0.0.5",
4
4
  "description": "AI Assistant CLI.",
5
5
  "author": "saber2pr",
6
6
  "license": "ISC",
@@ -22,7 +22,8 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@modelcontextprotocol/sdk": "^1.25.3",
25
- "@saber2pr/ts-context-mcp": "^0.0.5",
25
+ "@saber2pr/ts-context-mcp": "^0.0.6",
26
+ "js-tiktoken": "^1.0.21",
26
27
  "openai": "^6.16.0"
27
28
  },
28
29
  "devDependencies": {