@saber2pr/ai-agent 0.0.6 → 0.0.7

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
@@ -10,6 +10,7 @@ export interface AgentOptions {
10
10
  tools?: any[];
11
11
  /** 注入到 System Prompt 中的额外指令/规则/上下文 */
12
12
  extraSystemPrompt?: any;
13
+ maxTokens?: number;
13
14
  }
14
15
  export default class McpAgent {
15
16
  private openai;
@@ -20,6 +21,7 @@ export default class McpAgent {
20
21
  private engine;
21
22
  private encoder;
22
23
  private extraTools;
24
+ private maxTokens;
23
25
  constructor(options?: AgentOptions);
24
26
  /**
25
27
  * 计算当前消息列表的总 Token 消耗
@@ -36,6 +38,11 @@ export default class McpAgent {
36
38
  private loadMcpConfigs;
37
39
  init(): Promise<void>;
38
40
  private processChat;
41
+ /**
42
+ * 裁剪上下文消息列表
43
+ * 保留第一条 System 消息,并移除中间的旧消息直到低于阈值
44
+ */
45
+ private pruneMessages;
39
46
  /**
40
47
  * 简易 Loading 动画辅助函数
41
48
  */
package/lib/agent.js CHANGED
@@ -56,11 +56,25 @@ class McpAgent {
56
56
  this.extraTools = [];
57
57
  this.engine = new ts_context_mcp_1.PromptEngine((options === null || options === void 0 ? void 0 : options.targetDir) || process.cwd());
58
58
  this.extraTools = (options === null || options === void 0 ? void 0 : options.tools) || []; // 接收外部传入的工具
59
- let baseSystemPrompt = `你是一个专业的 AI 代码架构师。
60
- 你可以访问本地文件系统并利用 AST (抽象语法树) 技术分析代码。
61
- 你的核心目标是提供准确的代码结构、依赖关系和逻辑分析。
62
- 请先使用 get_repo_map 查看项目整体代码结构。
63
- 请优先使用 read_skeleton 查看结构,只有在必要时才使用 read_full_code 或 get_method_body。`;
59
+ this.maxTokens = (options === null || options === void 0 ? void 0 : options.maxTokens) || 100000; // 默认 100k
60
+ let baseSystemPrompt = `你是一个专业的 AI 代码架构师,具备深度的源码分析与工程化处理能力。
61
+
62
+ ### 核心操作规范:
63
+ 1. **全局扫描(强制首选)**:在开始任何分析任务前,你【必须】首先调用 'get_repo_map'。这是你理解项目目录结构、技术栈及模块关系的唯一权威来源。
64
+ 2. **循序渐进的分析路径**:
65
+ - 优先使用 'read_skeleton' 提取接口、类和函数签名,以最低的 Token 成本建立代码逻辑视图。
66
+ - 仅在需要深入分析具体业务逻辑、提取精准代码块或进行代码修改建议时,才使用 'read_full_code' 或 'get_method_body'。
67
+ 3. **真实性原则**:
68
+ - 所有的代码分析、行号定位和逻辑推断必须基于工具返回的真实内容,严禁基于文件名进行虚假猜测。
69
+ - 如果工具返回结果为空或报错,应尝试调整路径或更换工具。
70
+
71
+ ### 技术能力:
72
+ - 精通 TypeScript/JavaScript 及其 AST 结构,能准确识别各种复杂的声明与调用关系。
73
+ - 能够理解代码间的依赖链路,并结合项目上下文给出合理的架构建议。
74
+
75
+ ### 执行准则:
76
+ - **任务导向**:直接通过工具链解决问题,减少不必要的中间对话。
77
+ - **自主决策**:根据任务需求自主选择最合适的工具组合,无需每一步都向用户请示。`;
64
78
  // 2. 拼接额外指令
65
79
  if (options === null || options === void 0 ? void 0 : options.extraSystemPrompt) {
66
80
  const extra = typeof options.extraSystemPrompt === 'string'
@@ -211,7 +225,13 @@ class McpAgent {
211
225
  required: ["filePath", "methodName"],
212
226
  },
213
227
  },
214
- _handler: async ({ filePath, methodName }) => this.engine.getMethodImplementation(filePath, methodName),
228
+ _handler: async ({ filePath, methodName }) => {
229
+ // --- 新增:同样的 Token 守卫 ---
230
+ if (this.calculateTokens() > this.maxTokens) {
231
+ return `[SYSTEM WARNING]: Token 消耗已达上限,禁止获取详细方法体。请利用已获取的 Skeleton 信息进行分析。`;
232
+ }
233
+ return this.engine.getMethodImplementation(filePath, methodName);
234
+ },
215
235
  },
216
236
  {
217
237
  type: "function",
@@ -228,6 +248,11 @@ class McpAgent {
228
248
  },
229
249
  // 核心实现:直接利用 fs 读取
230
250
  _handler: async ({ filePath }) => {
251
+ // --- 新增:Token 守卫 ---
252
+ const currentTokens = this.calculateTokens();
253
+ if (currentTokens > this.maxTokens) {
254
+ return `[SYSTEM WARNING]: 当前上下文已达到 ${currentTokens} tokens (上限 ${this.maxTokens})。为了保证系统稳定,已拦截 read_full_code。请立即根据已知信息进行总结或停止阅读更多代码。`;
255
+ }
231
256
  try {
232
257
  if (typeof filePath !== 'string' || !filePath) {
233
258
  return "Error: filePath 不能为空";
@@ -329,9 +354,18 @@ class McpAgent {
329
354
  var _a;
330
355
  this.messages.push({ role: 'user', content: userInput });
331
356
  while (true) {
357
+ // --- 新增:发送请求前先检查并裁剪 ---
358
+ this.pruneMessages();
332
359
  // 打印当前上下文的累计 Token
333
360
  const currentInputTokens = this.calculateTokens();
334
361
  console.log(`\n📊 当前上下文累计: ${currentInputTokens} tokens`);
362
+ // 如果接近上限(如 80%),在消息队列中插入一条隐含的系统指令
363
+ if (currentInputTokens > this.maxTokens * 0.8 && currentInputTokens <= this.maxTokens) {
364
+ this.messages.push({
365
+ role: "system",
366
+ content: "注意:上下文即将耗尽。请停止读取新文件,优先处理现有信息并尽快输出结果。"
367
+ });
368
+ }
335
369
  const stopLoading = this.showLoading("🤖 Agent 正在思考...");
336
370
  let response;
337
371
  try {
@@ -388,6 +422,24 @@ class McpAgent {
388
422
  }
389
423
  }
390
424
  }
425
+ /**
426
+ * 裁剪上下文消息列表
427
+ * 保留第一条 System 消息,并移除中间的旧消息直到低于阈值
428
+ */
429
+ pruneMessages() {
430
+ const currentTokens = this.calculateTokens();
431
+ if (currentTokens <= this.maxTokens)
432
+ return;
433
+ console.log(`\n⚠️ 上下文达到限制 (${currentTokens} tokens),正在自动裁剪...`);
434
+ // 策略:保留索引 0 (System),从索引 1 开始删除
435
+ // 每次删除一对 (通常是助理请求 + 工具回复,或者用户提问 + 助理回答)
436
+ while (this.calculateTokens() > this.maxTokens && this.messages.length > 2) {
437
+ // 始终保留系统提示词 (index 0) 和最后一条消息 (保持对话连贯)
438
+ // 删除索引为 1 的消息
439
+ this.messages.splice(1, 1);
440
+ }
441
+ console.log(`✅ 裁剪完成,当前上下文: ${this.calculateTokens()} tokens`);
442
+ }
391
443
  /**
392
444
  * 简易 Loading 动画辅助函数
393
445
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@saber2pr/ai-agent",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
4
4
  "description": "AI Assistant CLI.",
5
5
  "author": "saber2pr",
6
6
  "license": "ISC",