@fefeding/aicmd 0.1.7 → 0.1.14

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.
Files changed (45) hide show
  1. package/dist/public/.vite/manifest.json +17 -17
  2. package/dist/public/favicon.ico +0 -0
  3. package/dist/public/index.css +80 -0
  4. package/dist/public/index.js +149 -23
  5. package/dist/public/views.css +309 -221
  6. package/dist/public/views.js +1743 -1605
  7. package/dist/public/vue.js +5120 -5120
  8. package/dist/server/index.d.ts.map +1 -1
  9. package/dist/server/index.js +13 -1
  10. package/dist/server/index.js.map +1 -1
  11. package/dist/server/index.ts +12 -1
  12. package/dist/server/model/connection.entity.d.ts +4 -0
  13. package/dist/server/model/connection.entity.d.ts.map +1 -1
  14. package/dist/server/model/connection.entity.js +4 -0
  15. package/dist/server/model/connection.entity.js.map +1 -1
  16. package/dist/server/model/connection.entity.ts +6 -0
  17. package/dist/server/service/ai.service.d.ts +17 -1
  18. package/dist/server/service/ai.service.d.ts.map +1 -1
  19. package/dist/server/service/ai.service.js +189 -106
  20. package/dist/server/service/ai.service.js.map +1 -1
  21. package/dist/server/service/ai.service.ts +198 -114
  22. package/dist/server/service/connection.service.d.ts +13 -2
  23. package/dist/server/service/connection.service.d.ts.map +1 -1
  24. package/dist/server/service/connection.service.js +153 -19
  25. package/dist/server/service/connection.service.js.map +1 -1
  26. package/dist/server/service/connection.service.ts +163 -22
  27. package/dist/server/service/ssh.service.d.ts +39 -0
  28. package/dist/server/service/ssh.service.d.ts.map +1 -1
  29. package/dist/server/service/ssh.service.js +419 -9
  30. package/dist/server/service/ssh.service.js.map +1 -1
  31. package/dist/server/service/ssh.service.ts +425 -9
  32. package/dist/server/utils/data-dir.d.ts +7 -0
  33. package/dist/server/utils/data-dir.d.ts.map +1 -1
  34. package/dist/server/utils/data-dir.js +38 -2
  35. package/dist/server/utils/data-dir.js.map +1 -1
  36. package/dist/server/utils/data-dir.ts +33 -2
  37. package/dist/view/index.html +19 -21
  38. package/electron/main.js +73 -11
  39. package/electron/preload.js +34 -0
  40. package/electron/updater.js +181 -0
  41. package/package.json +6 -4
  42. package/server.js +128 -3
  43. package/view/index.html +0 -9
  44. package/view/modules/header.tpl +0 -14
  45. package/view/modules/initial_state.tpl +0 -20
@@ -57,7 +57,11 @@ class AIService {
57
57
  configPath;
58
58
  config;
59
59
  historyDir;
60
+ /** LLM 上下文消息持久化目录(项目执行目录下 data/messages) */
61
+ messagesDir;
60
62
  chatHistories = new Map();
63
+ /** 已从文件加载过的 sessionId 集合 */
64
+ loadedSessions = new Set();
61
65
  agentStates = new Map();
62
66
  toolRegistry = new Map();
63
67
  sshService;
@@ -66,41 +70,41 @@ class AIService {
66
70
  MAX_HISTORY_AGE = 24 * 60 * 60 * 1000;
67
71
  MAX_MESSAGES = 50;
68
72
  MAX_AGENT_ITERATIONS = 15;
69
- // Agent 系统提示词
70
- AGENT_SYSTEM_PROMPT = `你是一个强大的 AI 终端 Agent,可以直接操作用户的终端 Shell。
73
+ // Agent system prompt (English default, language adapts to user input)
74
+ AGENT_SYSTEM_PROMPT = `You are a powerful AI terminal Agent that can directly operate the user's terminal Shell.
71
75
 
72
- 你的能力:
73
- 1. 通过 execute_command 工具直接在终端执行命令
74
- 2. 通过 read_terminal 工具读取终端当前输出
75
- 3. 理解命令执行结果并据此做出决策
76
- 4. 自动完成多步骤任务
77
- 5. 生成脚本文件来执行复杂或长步骤的操作
76
+ Your capabilities:
77
+ 1. Execute commands directly in the terminal via the execute_command tool
78
+ 2. Read the terminal's current output via the read_terminal tool
79
+ 3. Understand command execution results and make decisions accordingly
80
+ 4. Automatically complete multi-step tasks
81
+ 5. Generate script files to execute complex or multi-step operations
78
82
 
79
- 工作原则:
80
- 1. **直接行动**:当用户要求执行操作时,直接使用工具执行,不要只是建议命令
81
- 2. **验证结果**:执行命令后,检查输出确认是否成功
82
- 3. **安全第一**:rm 命令会自动将文件移动到回收站(~/.aicmd/.trash/)而非永久删除,极端破坏性操作会被阻止。对于其他危险操作(格式化、覆写磁盘等),在 content 中先说明风险,让用户确认后再执行
83
- 4. **分步执行**:复杂任务分步完成,每步执行后检查结果
84
- 5. **错误处理**:如果命令失败,分析原因并尝试修复或使用替代方案
83
+ Working principles:
84
+ 1. **Take action**: When the user asks you to do something, use tools to execute directly, don't just suggest commands
85
+ 2. **Verify results**: After executing a command, check the output to confirm success
86
+ 3. **Safety first**: rm commands automatically move files to a recycle bin (~/.aicmd/.trash/) instead of permanent deletion; extremely destructive operations will be blocked. For other dangerous operations (format, overwrite disk, etc.), explain the risk in content first and let the user confirm before executing
87
+ 4. **Step-by-step**: Complete complex tasks step by step, checking results after each step
88
+ 5. **Error handling**: If a command fails, analyze the cause and try to fix it or use an alternative
85
89
 
86
- 脚本策略(重要):
87
- 当任务符合以下任一条件时,生成脚本文件而不是逐条执行命令:
88
- - 步骤超过 3 个且步骤间有依赖关系
89
- - 需要循环、条件判断、错误处理等逻辑
90
- - 需要处理大量文件或批量操作
91
- - 需要解析文本/日志/JSON 等复杂数据
90
+ Script strategy (important):
91
+ Generate a script file instead of executing commands one by one when the task meets any of the following conditions:
92
+ - More than 3 steps with dependencies between them
93
+ - Requires loops, conditionals, error handling, or other logic
94
+ - Needs to process large numbers of files or batch operations
95
+ - Needs to parse text/logs/JSON or other complex data
92
96
 
93
- 脚本执行流程:
94
- 1. 先用 \`which python3 node bash\` 检测可用语言(Windows: \`where python node powershell\`)
95
- 2. 优先使用系统环境信息中已知的语言
96
- 3. 根据平台创建并执行脚本:
97
+ Script execution flow:
98
+ 1. First detect available languages with \`which python3 node bash\` (Windows: \`where python node powershell\`)
99
+ 2. Prefer languages already known from system environment info
100
+ 3. Create and execute the script based on the platform:
97
101
 
98
102
  **Linux/macOS (Bash):**
99
103
  \`\`\`
100
104
  cat > /tmp/_ai_task.sh << 'SCRIPT_EOF'
101
105
  #!/bin/bash
102
106
  set -e
103
- # 脚本内容...
107
+ # script content...
104
108
  SCRIPT_EOF
105
109
  chmod +x /tmp/_ai_task.sh && bash /tmp/_ai_task.sh
106
110
  \`\`\`
@@ -108,39 +112,41 @@ chmod +x /tmp/_ai_task.sh && bash /tmp/_ai_task.sh
108
112
  **Windows (PowerShell):**
109
113
  \`\`\`powershell
110
114
  Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
111
- # PowerShell 脚本内容...
115
+ # PowerShell script content...
112
116
  '@
113
117
  & $env:TEMP\_ai_task.ps1
114
118
  \`\`\`
115
119
 
116
- 4. 执行脚本并检查结果
117
- 5. 清理临时文件
120
+ 4. Execute the script and check results
121
+ 5. Clean up temporary files
118
122
 
119
- 语言选择优先级:
120
- - Shell/Bash (Linux/macOS):系统管理、文件操作、进程管理
121
- - PowerShell (Windows):系统管理、文件操作、进程管理、WMI/CIM 查询
122
- - Python:日志分析、数据处理、文本解析、复杂逻辑(跨平台)
123
- - Node.js:JSON 处理、HTTP 请求、复杂数据转换(跨平台)
123
+ Language selection priority:
124
+ - Shell/Bash (Linux/macOS): system admin, file ops, process management
125
+ - PowerShell (Windows): system admin, file ops, process management, WMI/CIM queries
126
+ - Python: log analysis, data processing, text parsing, complex logic (cross-platform)
127
+ - Node.js: JSON processing, HTTP requests, complex data transformation (cross-platform)
124
128
 
125
- 跨平台注意:
126
- - 根据系统环境信息中的 OS 和 Shell 字段判断目标平台
127
- - Linux: OS=Linux,使用 bash 命令
128
- - macOS: OS=Darwin,没有 \`free\`/\`ss\`/\`systemctl\`,用 \`vm_stat\`/\`lsof\`/\`launchctl\` 替代
129
- - Windows: Shell=PowerShell,使用 PowerShell cmdlet,临时文件用 \`$env:TEMP\`
130
- - 写脚本时先判断平台再选择对应命令
129
+ Cross-platform notes:
130
+ - Determine target platform from OS and Shell fields in system environment info
131
+ - Linux: OS=Linux, use bash commands
132
+ - macOS: OS=Darwin, no \`free\`/\`ss\`/\`systemctl\`, use \`vm_stat\`/\`lsof\`/\`launchctl\` instead
133
+ - Windows: Shell=PowerShell, use PowerShell cmdlets, temp files in \`$env:TEMP\`
134
+ - Always check platform first before selecting commands when writing scripts
131
135
 
132
- 回复格式(重要):
133
- - 使用 Markdown 格式
134
- - 工具调用前只需一句话说明要做什么,不要解释命令细节
135
- - 任务完成后用简短的结论说明结果,不要重复命令输出、不要列举执行步骤、不要加多余的解释
136
- - 如果操作成功,直接说结果(如“已创建”“已停止”“发现3个错误”)
137
- - 如果操作失败,说明原因和建议的修复方式
138
- - 禁止废话,禁止套话,禁止总结已经显而易见的信息
139
- - 使用中文回复`;
136
+ Response format (important):
137
+ - Use Markdown format
138
+ - Before tool calls, just one sentence explaining what you're about to do, don't explain command details
139
+ - After task completion, give a brief conclusion of the results, don't repeat command output, don't list execution steps, don't add unnecessary explanations
140
+ - If the operation succeeds, state the result directly (e.g., "Created", "Stopped", "Found 3 errors")
141
+ - If the operation fails, explain the cause and suggested fix
142
+ - No fluff, no filler, no summarizing what's already obvious
143
+
144
+ **Language rule (CRITICAL)**: Always respond in the SAME language as the user's message. If the user writes in Chinese, respond in Chinese. If the user writes in English, respond in English. Match the user's language exactly.`;
140
145
  constructor(sshService, skillService, auditService) {
141
146
  this.configDir = (0, data_dir_1.getDataDir)();
142
147
  this.configPath = (0, data_dir_1.getDataPath)('ai-config.json');
143
148
  this.historyDir = (0, data_dir_1.getDataPath)('ai-history');
149
+ this.messagesDir = path.resolve('data', 'messages');
144
150
  this.config = this.getDefaultConfig();
145
151
  this.sshService = sshService;
146
152
  this.skillService = skillService;
@@ -152,6 +158,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
152
158
  fs.mkdirSync(this.historyDir, { recursive: true });
153
159
  }
154
160
  catch (_) { /* ignore */ }
161
+ (0, data_dir_1.ensureDir)(this.messagesDir);
155
162
  this.cleanupOldHistories();
156
163
  this.registerBuiltinTools();
157
164
  }
@@ -217,7 +224,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
217
224
  async testConfig(config) {
218
225
  const testConfig = { ...this.config, ...config };
219
226
  if (!testConfig.apiKey) {
220
- return { success: false, message: 'API Key 未配置' };
227
+ return { success: false, message: 'API Key not configured' };
221
228
  }
222
229
  try {
223
230
  const response = await axios_1.default.post(`${testConfig.baseUrl}/chat/completions`, {
@@ -232,12 +239,12 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
232
239
  timeout: 30000,
233
240
  });
234
241
  if (response.data?.choices?.[0]?.message?.content) {
235
- return { success: true, message: '连接成功,模型可用' };
242
+ return { success: true, message: 'Connection successful, model available' };
236
243
  }
237
- return { success: false, message: '响应格式异常' };
244
+ return { success: false, message: 'Unexpected response format' };
238
245
  }
239
246
  catch (error) {
240
- const message = error.response?.data?.error?.message || error.message || '连接失败';
247
+ const message = error.response?.data?.error?.message || error.message || 'Connection failed';
241
248
  return { success: false, message };
242
249
  }
243
250
  }
@@ -259,22 +266,22 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
259
266
  * 注册内置工具
260
267
  */
261
268
  registerBuiltinTools() {
262
- // execute_command - 执行 shell 命令
269
+ // execute_command - Execute shell command
263
270
  this.registerTool('execute_command', {
264
271
  type: 'function',
265
272
  function: {
266
273
  name: 'execute_command',
267
- description: '在当前终端 Shell 中执行命令并返回输出。支持任意 bash/zsh 命令。',
274
+ description: 'Execute a command in the current terminal Shell and return the output. Supports any bash/zsh/powershell commands.',
268
275
  parameters: {
269
276
  type: 'object',
270
277
  properties: {
271
278
  command: {
272
279
  type: 'string',
273
- description: '要执行的 shell 命令',
280
+ description: 'The shell command to execute',
274
281
  },
275
282
  timeout: {
276
283
  type: 'number',
277
- description: '等待输出的时间(毫秒),默认 2000,对于耗时命令可以设大一些',
284
+ description: 'Time to wait for output in milliseconds, default 2000. Increase for long-running commands',
278
285
  },
279
286
  },
280
287
  required: ['command'],
@@ -283,12 +290,12 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
283
290
  }, async (args, sessionId) => {
284
291
  return this.executeCommand(args.command, sessionId, args.timeout || 2000);
285
292
  });
286
- // read_terminal - 读取终端输出
293
+ // read_terminal - Read terminal output
287
294
  this.registerTool('read_terminal', {
288
295
  type: 'function',
289
296
  function: {
290
297
  name: 'read_terminal',
291
- description: '读取终端当前的输出内容(最近 50 行),用于了解终端当前状态。',
298
+ description: 'Read the current terminal output (last 50 lines), useful for understanding the terminal state.',
292
299
  parameters: {
293
300
  type: 'object',
294
301
  properties: {},
@@ -339,7 +346,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
339
346
  ];
340
347
  for (const pattern of blocked) {
341
348
  if (pattern.test(trimmed)) {
342
- return { safe: false, reason: 'BLOCKED: 极度危险的破坏性操作,已阻止执行' };
349
+ return { safe: false, reason: 'BLOCKED: Extremely dangerous destructive operation' };
343
350
  }
344
351
  }
345
352
  // rm 命令改写为移动到回收站
@@ -370,7 +377,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
370
377
  ];
371
378
  for (const pattern of blocked) {
372
379
  if (pattern.test(trimmed)) {
373
- return { safe: false, reason: 'BLOCKED: 极度危险的破坏性操作,已阻止执行' };
380
+ return { safe: false, reason: 'BLOCKED: Extremely dangerous destructive operation' };
374
381
  }
375
382
  }
376
383
  // Remove-Item / del / rd 改写为移动到回收站
@@ -400,13 +407,13 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
400
407
  */
401
408
  async executeCommand(command, sessionId, timeout) {
402
409
  if (!this.sshService) {
403
- return '错误: SSH 服务不可用';
410
+ return 'Error: SSH service not available';
404
411
  }
405
412
  const session = this.sshService.getSession(sessionId);
406
413
  if (!session) {
407
- return `错误: 会话 ${sessionId} 不存在`;
414
+ return `Error: Session ${sessionId} not found`;
408
415
  }
409
- // 安全检查:拦截/改写危险命令
416
+ // Safety check: block/rewrite dangerous commands
410
417
  const check = await this.sanitizeCommand(command, sessionId);
411
418
  if (!check.safe) {
412
419
  return check.reason;
@@ -416,31 +423,30 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
416
423
  console.log(`[AIService] Safety: rewrote "${command}" -> "${actualCommand}"`);
417
424
  }
418
425
  try {
419
- // 启动输出捕获
426
+ // Start output capture
420
427
  const outputPromise = this.sshService.captureOutput(sessionId, timeout);
421
- // 写入命令
428
+ // Write command
422
429
  this.sshService.writeData(sessionId, actualCommand + '\n');
423
- // 等待输出
430
+ // Wait for output
424
431
  const output = await outputPromise;
425
- // 清理输出:去除命令回显和空白
432
+ // Clean output: remove command echo and whitespace
426
433
  const lines = output.split('\n');
427
- // 尝试去掉第一行的命令回显
428
434
  if (lines.length > 0 && lines[0].trim().includes(actualCommand.trim().substring(0, 20))) {
429
435
  lines.shift();
430
436
  }
431
437
  const cleanOutput = lines.join('\n').trim();
432
438
  if (!cleanOutput) {
433
- return '(命令执行完成,无输出)';
439
+ return '(Command executed, no output)';
434
440
  }
435
- // 限制输出长度,避免过长
441
+ // Limit output length
436
442
  const maxLength = 5000;
437
443
  if (cleanOutput.length > maxLength) {
438
- return cleanOutput.substring(0, maxLength) + `\n... (输出被截断,共 ${cleanOutput.length} 字符)`;
444
+ return cleanOutput.substring(0, maxLength) + `\n... (output truncated, ${cleanOutput.length} chars total)`;
439
445
  }
440
446
  return cleanOutput;
441
447
  }
442
448
  catch (error) {
443
- return `执行命令失败: ${error.message}`;
449
+ return `Command execution failed: ${error.message}`;
444
450
  }
445
451
  }
446
452
  /**
@@ -448,29 +454,34 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
448
454
  */
449
455
  async readTerminal(sessionId) {
450
456
  if (!this.sshService) {
451
- return '错误: SSH 服务不可用';
457
+ return 'Error: SSH service not available';
452
458
  }
453
459
  try {
454
- // 短暂捕获以获取当前缓冲区内容
455
460
  const output = await this.sshService.captureOutput(sessionId, 500);
456
461
  if (!output.trim()) {
457
- return '(终端当前无输出)';
462
+ return '(No terminal output)';
458
463
  }
459
464
  const lines = output.split('\n').filter(l => l.trim());
460
- // 返回最后 50 行
461
465
  const last50 = lines.slice(-50);
462
466
  return last50.join('\n');
463
467
  }
464
468
  catch (error) {
465
- return `读取终端失败: ${error.message}`;
469
+ return `Failed to read terminal: ${error.message}`;
466
470
  }
467
471
  }
468
472
  // ========== 对话历史 ==========
469
473
  getOrCreateHistory(sessionId) {
470
474
  let history = this.chatHistories.get(sessionId);
471
475
  if (!history) {
472
- history = { sessionId, messages: [], lastActive: Date.now() };
476
+ // 首次访问,尝试从文件加载
477
+ const saved = this.loadChatMessages(sessionId);
478
+ history = {
479
+ sessionId,
480
+ messages: saved || [],
481
+ lastActive: Date.now(),
482
+ };
473
483
  this.chatHistories.set(sessionId, history);
484
+ this.loadedSessions.add(sessionId);
474
485
  }
475
486
  history.lastActive = Date.now();
476
487
  return history;
@@ -480,16 +491,79 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
480
491
  while (history.messages.length > this.MAX_MESSAGES) {
481
492
  history.messages.shift();
482
493
  }
494
+ // 持久化到文件
495
+ this.saveChatMessages(history.sessionId, history.messages);
483
496
  }
484
497
  clearHistory(sessionId) {
485
498
  this.chatHistories.delete(sessionId);
499
+ this.loadedSessions.delete(sessionId);
486
500
  this.deleteDisplayHistoryFile(sessionId);
501
+ this.deleteChatMessagesFile(sessionId);
487
502
  }
488
503
  getHistory(sessionId) {
489
504
  const history = this.chatHistories.get(sessionId);
490
505
  return history ? [...history.messages] : null;
491
506
  }
492
- // ========== 对话历史持久化 ==========
507
+ // ========== LLM 上下文消息持久化 ==========
508
+ /**
509
+ * 保存 LLM 上下文消息到 data/messages/{sessionId}.json
510
+ */
511
+ saveChatMessages(sessionId, messages) {
512
+ try {
513
+ (0, data_dir_1.ensureDir)(this.messagesDir);
514
+ const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, '_');
515
+ const filePath = path.join(this.messagesDir, `${safe}.json`);
516
+ const data = {
517
+ sessionId,
518
+ updatedAt: Date.now(),
519
+ messages,
520
+ };
521
+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');
522
+ }
523
+ catch (_) {
524
+ // 静默失败,不影响主流程
525
+ }
526
+ }
527
+ /**
528
+ * 从 data/messages/{sessionId}.json 加载 LLM 上下文消息
529
+ */
530
+ loadChatMessages(sessionId) {
531
+ try {
532
+ if (!fs.existsSync(this.messagesDir))
533
+ return null;
534
+ const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, '_');
535
+ const filePath = path.join(this.messagesDir, `${safe}.json`);
536
+ if (!fs.existsSync(filePath))
537
+ return null;
538
+ const raw = fs.readFileSync(filePath, 'utf-8');
539
+ const data = JSON.parse(raw);
540
+ if (data && Array.isArray(data.messages)) {
541
+ return data.messages.length > this.MAX_MESSAGES
542
+ ? data.messages.slice(data.messages.length - this.MAX_MESSAGES)
543
+ : data.messages;
544
+ }
545
+ return null;
546
+ }
547
+ catch (_) {
548
+ return null;
549
+ }
550
+ }
551
+ /**
552
+ * 删除 LLM 上下文消息文件
553
+ */
554
+ deleteChatMessagesFile(sessionId) {
555
+ try {
556
+ const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, '_');
557
+ const filePath = path.join(this.messagesDir, `${safe}.json`);
558
+ if (fs.existsSync(filePath)) {
559
+ fs.unlinkSync(filePath);
560
+ }
561
+ }
562
+ catch (_) {
563
+ // 静默失败
564
+ }
565
+ }
566
+ // ========== 对话历史持久化(前端显示) ==========
493
567
  /**
494
568
  * 保存前端显示消息到文件(含元数据)
495
569
  */
@@ -585,6 +659,10 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
585
659
  if (fs.existsSync(filePath)) {
586
660
  fs.unlinkSync(filePath);
587
661
  }
662
+ // 同步删除 LLM 上下文消息文件
663
+ this.deleteChatMessagesFile(sessionId);
664
+ this.chatHistories.delete(sessionId);
665
+ this.loadedSessions.delete(sessionId);
588
666
  }
589
667
  catch (error) {
590
668
  console.error('[AIService] Failed to delete display history:', error);
@@ -611,15 +689,15 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
611
689
  * 运行 Agent
612
690
  * Agent 循环:调用 LLM → 处理 tool_calls → 执行工具 → 反馈结果 → 重复直到完成
613
691
  */
614
- async agentRun(sessionId, userMessage, context, eventCallback, skillId) {
692
+ async agentRun(sessionId, userMessage, context, eventCallback, skillId, locale) {
615
693
  if (!this.config.apiKey) {
616
- eventCallback({ type: 'error', error: 'AI 未配置 API Key,请在设置中填写' });
694
+ eventCallback({ type: 'error', error: 'API Key not configured. Please set it in AI settings.' });
617
695
  return;
618
696
  }
619
- // 检查是否有正在运行的 agent
697
+ // Check for running agent
620
698
  const existingState = this.agentStates.get(sessionId);
621
699
  if (existingState?.running) {
622
- eventCallback({ type: 'error', error: 'Agent 正在运行中,请先等待完成或停止' });
700
+ eventCallback({ type: 'error', error: 'Agent is already running. Please wait or stop it first.' });
623
701
  return;
624
702
  }
625
703
  // 设置运行状态
@@ -627,29 +705,34 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
627
705
  this.agentStates.set(sessionId, state);
628
706
  const history = this.getOrCreateHistory(sessionId);
629
707
  const tools = this.getToolDefinitions();
630
- // 构建系统提示词
708
+ // Build system prompt
631
709
  let systemPrompt = this.AGENT_SYSTEM_PROMPT;
632
- // 自动注入系统环境上下文(首次对话自动采集)
710
+ // Inject locale hint if provided (fallback when user language is ambiguous)
711
+ if (locale) {
712
+ const langName = locale.startsWith('zh') ? 'Chinese' : locale.startsWith('ja') ? 'Japanese' : locale.startsWith('ko') ? 'Korean' : 'English';
713
+ systemPrompt += `\n\n[User's UI language preference: ${langName} (${locale}). If the user's message language is ambiguous, prefer responding in ${langName}.]`;
714
+ }
715
+ // Inject system environment context
633
716
  const sysContext = await this.getSessionContext(sessionId);
634
- if (sysContext && sysContext !== '无法采集系统信息') {
717
+ if (sysContext && sysContext !== 'Failed to collect system info') {
635
718
  systemPrompt += `\n\n${sysContext}`;
636
719
  }
637
- // 如果有 Skill,追加 Skill 指令
720
+ // If Skill is provided, append Skill instructions
638
721
  if (skillId && this.skillService) {
639
722
  const skill = this.skillService.getSkill(skillId);
640
723
  if (skill) {
641
- systemPrompt += `\n\n## 当前任务指令(Skill: ${skill.name})\n\n${skill.content}`;
724
+ systemPrompt += `\n\n## Current Task Instructions (Skill: ${skill.name})\n\n${skill.content}`;
642
725
  }
643
726
  }
644
727
  // 构建消息列表
645
728
  const messages = [
646
729
  { role: 'system', content: systemPrompt },
647
730
  ];
648
- // 添加终端上下文
731
+ // Add terminal context
649
732
  if (context) {
650
733
  messages.push({
651
734
  role: 'system',
652
- content: `当前终端最近的输出内容:\n\`\`\`\n${context}\n\`\`\``,
735
+ content: `Recent terminal output:\n\`\`\`\n${context}\n\`\`\``,
653
736
  });
654
737
  }
655
738
  // 添加历史消息
@@ -660,9 +743,9 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
660
743
  messages.push(userMsg);
661
744
  try {
662
745
  for (let iteration = 0; iteration < this.MAX_AGENT_ITERATIONS; iteration++) {
663
- // 检查是否被中断
746
+ // Check if aborted
664
747
  if (state.aborted) {
665
- eventCallback({ type: 'done', content: '(Agent 已被用户中断)' });
748
+ eventCallback({ type: 'done', content: '(Agent stopped by user)' });
666
749
  break;
667
750
  }
668
751
  eventCallback({ type: 'thinking' });
@@ -672,12 +755,12 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
672
755
  response = await this.callLLM(messages, tools);
673
756
  }
674
757
  catch (error) {
675
- eventCallback({ type: 'error', error: `LLM 调用失败: ${error.message}` });
758
+ eventCallback({ type: 'error', error: `LLM call failed: ${error.message}` });
676
759
  break;
677
760
  }
678
761
  const assistantMessage = response.choices?.[0]?.message;
679
762
  if (!assistantMessage) {
680
- eventCallback({ type: 'error', error: 'LLM 响应为空' });
763
+ eventCallback({ type: 'error', error: 'LLM response is empty' });
681
764
  break;
682
765
  }
683
766
  // 添加 assistant 消息到历史
@@ -720,18 +803,18 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
720
803
  let result;
721
804
  let toolStatus = 'success';
722
805
  if (!tool) {
723
- result = `错误: 未知工具 "${toolName}"`;
806
+ result = `Error: Unknown tool "${toolName}"`;
724
807
  toolStatus = 'error';
725
808
  }
726
809
  else {
727
810
  try {
728
811
  result = await tool.executor(toolArgs, sessionId);
729
- if (result.startsWith('错误:') || result.startsWith('工具执行失败:')) {
812
+ if (result.startsWith('Error:') || result.startsWith('Tool execution failed:')) {
730
813
  toolStatus = 'error';
731
814
  }
732
815
  }
733
816
  catch (error) {
734
- result = `工具执行失败: ${error.message}`;
817
+ result = `Tool execution failed: ${error.message}`;
735
818
  toolStatus = 'error';
736
819
  }
737
820
  }
@@ -766,14 +849,14 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
766
849
  messages.push(toolMsg);
767
850
  this.addMessage(history, toolMsg);
768
851
  }
769
- // 如果是最后一次迭代且仍有 tool_calls,发送完成
852
+ // Last iteration with remaining tool_calls
770
853
  if (iteration === this.MAX_AGENT_ITERATIONS - 1) {
771
- eventCallback({ type: 'done', content: '已达到最大执行次数限制' });
854
+ eventCallback({ type: 'done', content: 'Max iterations reached' });
772
855
  }
773
856
  }
774
857
  }
775
858
  catch (error) {
776
- eventCallback({ type: 'error', error: error.message || 'Agent 运行异常' });
859
+ eventCallback({ type: 'error', error: error.message || 'Agent runtime error' });
777
860
  }
778
861
  finally {
779
862
  state.running = false;
@@ -818,7 +901,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
818
901
  // ========== 旧版兼容(非 Agent 模式的简单对话) ==========
819
902
  async chat(sessionId, userMessage, context) {
820
903
  if (!this.config.apiKey) {
821
- throw new Error('AI 未配置 API Key,请在设置中填写');
904
+ throw new Error('API Key not configured. Please set it in AI settings.');
822
905
  }
823
906
  const history = this.getOrCreateHistory(sessionId);
824
907
  const messages = [
@@ -827,7 +910,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
827
910
  if (context) {
828
911
  messages.push({
829
912
  role: 'system',
830
- content: `当前终端最近的输出内容:\n\`\`\`\n${context}\n\`\`\``,
913
+ content: `Recent terminal output:\n\`\`\`\n${context}\n\`\`\``,
831
914
  });
832
915
  }
833
916
  messages.push(...history.messages);
@@ -851,17 +934,17 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
851
934
  this.addMessage(history, { role: 'assistant', content: assistantMessage });
852
935
  return assistantMessage;
853
936
  }
854
- throw new Error('AI 响应为空');
937
+ throw new Error('AI response is empty');
855
938
  }
856
939
  catch (error) {
857
940
  history.messages.pop();
858
- const message = error.response?.data?.error?.message || error.message || 'AI 请求失败';
941
+ const message = error.response?.data?.error?.message || error.message || 'AI request failed';
859
942
  throw new Error(message);
860
943
  }
861
944
  }
862
945
  async *chatStream(sessionId, userMessage, context) {
863
946
  if (!this.config.apiKey) {
864
- throw new Error('AI 未配置 API Key,请在设置中填写');
947
+ throw new Error('API Key not configured. Please set it in AI settings.');
865
948
  }
866
949
  const history = this.getOrCreateHistory(sessionId);
867
950
  const messages = [
@@ -870,7 +953,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
870
953
  if (context) {
871
954
  messages.push({
872
955
  role: 'system',
873
- content: `当前终端最近的输出内容:\n\`\`\`\n${context}\n\`\`\``,
956
+ content: `Recent terminal output:\n\`\`\`\n${context}\n\`\`\``,
874
957
  });
875
958
  }
876
959
  messages.push(...history.messages);
@@ -917,7 +1000,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
917
1000
  }
918
1001
  catch (error) {
919
1002
  history.messages.pop();
920
- const message = error.response?.data?.error?.message || error.message || 'AI 请求失败';
1003
+ const message = error.response?.data?.error?.message || error.message || 'AI request failed';
921
1004
  throw new Error(message);
922
1005
  }
923
1006
  }