@fefeding/aicmd 0.1.7 → 0.1.12

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 (41) 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 +1733 -1595
  7. package/dist/public/vue.js +5120 -5120
  8. package/dist/server/model/connection.entity.d.ts +4 -0
  9. package/dist/server/model/connection.entity.d.ts.map +1 -1
  10. package/dist/server/model/connection.entity.js +4 -0
  11. package/dist/server/model/connection.entity.js.map +1 -1
  12. package/dist/server/model/connection.entity.ts +6 -0
  13. package/dist/server/service/ai.service.d.ts +17 -1
  14. package/dist/server/service/ai.service.d.ts.map +1 -1
  15. package/dist/server/service/ai.service.js +189 -106
  16. package/dist/server/service/ai.service.js.map +1 -1
  17. package/dist/server/service/ai.service.ts +198 -114
  18. package/dist/server/service/connection.service.d.ts +13 -2
  19. package/dist/server/service/connection.service.d.ts.map +1 -1
  20. package/dist/server/service/connection.service.js +114 -14
  21. package/dist/server/service/connection.service.js.map +1 -1
  22. package/dist/server/service/connection.service.ts +125 -15
  23. package/dist/server/service/ssh.service.d.ts +18 -0
  24. package/dist/server/service/ssh.service.d.ts.map +1 -1
  25. package/dist/server/service/ssh.service.js +344 -7
  26. package/dist/server/service/ssh.service.js.map +1 -1
  27. package/dist/server/service/ssh.service.ts +345 -7
  28. package/dist/server/utils/data-dir.d.ts +7 -0
  29. package/dist/server/utils/data-dir.d.ts.map +1 -1
  30. package/dist/server/utils/data-dir.js +29 -0
  31. package/dist/server/utils/data-dir.js.map +1 -1
  32. package/dist/server/utils/data-dir.ts +24 -0
  33. package/dist/view/index.html +19 -21
  34. package/electron/main.js +10 -0
  35. package/electron/preload.js +29 -0
  36. package/electron/updater.js +181 -0
  37. package/package.json +6 -5
  38. package/server.js +128 -3
  39. package/view/index.html +0 -9
  40. package/view/modules/header.tpl +0 -14
  41. package/view/modules/initial_state.tpl +0 -20
@@ -2,7 +2,7 @@ import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import * as os from 'os';
4
4
  import axios from 'axios';
5
- import { getDataDir, getDataPath, ensureDataDir } from '../utils/data-dir';
5
+ import { getDataDir, getDataPath, ensureDataDir, ensureDir } from '../utils/data-dir';
6
6
  import { AuditService, type AuditEntry } from './audit.service';
7
7
 
8
8
  /**
@@ -157,7 +157,11 @@ export class AIService {
157
157
  private configPath: string;
158
158
  private config: AIConfig;
159
159
  private historyDir: string;
160
+ /** LLM 上下文消息持久化目录(项目执行目录下 data/messages) */
161
+ private messagesDir: string;
160
162
  private chatHistories: Map<string, ChatHistory> = new Map();
163
+ /** 已从文件加载过的 sessionId 集合 */
164
+ private loadedSessions = new Set<string>();
161
165
  private agentStates: Map<string, AgentRunState> = new Map();
162
166
  private toolRegistry: Map<string, RegisteredTool> = new Map();
163
167
  private sshService?: ISSHService;
@@ -167,41 +171,41 @@ export class AIService {
167
171
  private readonly MAX_MESSAGES = 50;
168
172
  private readonly MAX_AGENT_ITERATIONS = 15;
169
173
 
170
- // Agent 系统提示词
171
- private readonly AGENT_SYSTEM_PROMPT = `你是一个强大的 AI 终端 Agent,可以直接操作用户的终端 Shell。
172
-
173
- 你的能力:
174
- 1. 通过 execute_command 工具直接在终端执行命令
175
- 2. 通过 read_terminal 工具读取终端当前输出
176
- 3. 理解命令执行结果并据此做出决策
177
- 4. 自动完成多步骤任务
178
- 5. 生成脚本文件来执行复杂或长步骤的操作
179
-
180
- 工作原则:
181
- 1. **直接行动**:当用户要求执行操作时,直接使用工具执行,不要只是建议命令
182
- 2. **验证结果**:执行命令后,检查输出确认是否成功
183
- 3. **安全第一**:rm 命令会自动将文件移动到回收站(~/.aicmd/.trash/)而非永久删除,极端破坏性操作会被阻止。对于其他危险操作(格式化、覆写磁盘等),在 content 中先说明风险,让用户确认后再执行
184
- 4. **分步执行**:复杂任务分步完成,每步执行后检查结果
185
- 5. **错误处理**:如果命令失败,分析原因并尝试修复或使用替代方案
186
-
187
- 脚本策略(重要):
188
- 当任务符合以下任一条件时,生成脚本文件而不是逐条执行命令:
189
- - 步骤超过 3 个且步骤间有依赖关系
190
- - 需要循环、条件判断、错误处理等逻辑
191
- - 需要处理大量文件或批量操作
192
- - 需要解析文本/日志/JSON 等复杂数据
193
-
194
- 脚本执行流程:
195
- 1. 先用 \`which python3 node bash\` 检测可用语言(Windows: \`where python node powershell\`)
196
- 2. 优先使用系统环境信息中已知的语言
197
- 3. 根据平台创建并执行脚本:
174
+ // Agent system prompt (English default, language adapts to user input)
175
+ private readonly AGENT_SYSTEM_PROMPT = `You are a powerful AI terminal Agent that can directly operate the user's terminal Shell.
176
+
177
+ Your capabilities:
178
+ 1. Execute commands directly in the terminal via the execute_command tool
179
+ 2. Read the terminal's current output via the read_terminal tool
180
+ 3. Understand command execution results and make decisions accordingly
181
+ 4. Automatically complete multi-step tasks
182
+ 5. Generate script files to execute complex or multi-step operations
183
+
184
+ Working principles:
185
+ 1. **Take action**: When the user asks you to do something, use tools to execute directly, don't just suggest commands
186
+ 2. **Verify results**: After executing a command, check the output to confirm success
187
+ 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
188
+ 4. **Step-by-step**: Complete complex tasks step by step, checking results after each step
189
+ 5. **Error handling**: If a command fails, analyze the cause and try to fix it or use an alternative
190
+
191
+ Script strategy (important):
192
+ Generate a script file instead of executing commands one by one when the task meets any of the following conditions:
193
+ - More than 3 steps with dependencies between them
194
+ - Requires loops, conditionals, error handling, or other logic
195
+ - Needs to process large numbers of files or batch operations
196
+ - Needs to parse text/logs/JSON or other complex data
197
+
198
+ Script execution flow:
199
+ 1. First detect available languages with \`which python3 node bash\` (Windows: \`where python node powershell\`)
200
+ 2. Prefer languages already known from system environment info
201
+ 3. Create and execute the script based on the platform:
198
202
 
199
203
  **Linux/macOS (Bash):**
200
204
  \`\`\`
201
205
  cat > /tmp/_ai_task.sh << 'SCRIPT_EOF'
202
206
  #!/bin/bash
203
207
  set -e
204
- # 脚本内容...
208
+ # script content...
205
209
  SCRIPT_EOF
206
210
  chmod +x /tmp/_ai_task.sh && bash /tmp/_ai_task.sh
207
211
  \`\`\`
@@ -209,40 +213,42 @@ chmod +x /tmp/_ai_task.sh && bash /tmp/_ai_task.sh
209
213
  **Windows (PowerShell):**
210
214
  \`\`\`powershell
211
215
  Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
212
- # PowerShell 脚本内容...
216
+ # PowerShell script content...
213
217
  '@
214
218
  & $env:TEMP\_ai_task.ps1
215
219
  \`\`\`
216
220
 
217
- 4. 执行脚本并检查结果
218
- 5. 清理临时文件
219
-
220
- 语言选择优先级:
221
- - Shell/Bash (Linux/macOS):系统管理、文件操作、进程管理
222
- - PowerShell (Windows):系统管理、文件操作、进程管理、WMI/CIM 查询
223
- - Python:日志分析、数据处理、文本解析、复杂逻辑(跨平台)
224
- - Node.js:JSON 处理、HTTP 请求、复杂数据转换(跨平台)
225
-
226
- 跨平台注意:
227
- - 根据系统环境信息中的 OS 和 Shell 字段判断目标平台
228
- - Linux: OS=Linux,使用 bash 命令
229
- - macOS: OS=Darwin,没有 \`free\`/\`ss\`/\`systemctl\`,用 \`vm_stat\`/\`lsof\`/\`launchctl\` 替代
230
- - Windows: Shell=PowerShell,使用 PowerShell cmdlet,临时文件用 \`$env:TEMP\`
231
- - 写脚本时先判断平台再选择对应命令
232
-
233
- 回复格式(重要):
234
- - 使用 Markdown 格式
235
- - 工具调用前只需一句话说明要做什么,不要解释命令细节
236
- - 任务完成后用简短的结论说明结果,不要重复命令输出、不要列举执行步骤、不要加多余的解释
237
- - 如果操作成功,直接说结果(如“已创建”“已停止”“发现3个错误”)
238
- - 如果操作失败,说明原因和建议的修复方式
239
- - 禁止废话,禁止套话,禁止总结已经显而易见的信息
240
- - 使用中文回复`;
221
+ 4. Execute the script and check results
222
+ 5. Clean up temporary files
223
+
224
+ Language selection priority:
225
+ - Shell/Bash (Linux/macOS): system admin, file ops, process management
226
+ - PowerShell (Windows): system admin, file ops, process management, WMI/CIM queries
227
+ - Python: log analysis, data processing, text parsing, complex logic (cross-platform)
228
+ - Node.js: JSON processing, HTTP requests, complex data transformation (cross-platform)
229
+
230
+ Cross-platform notes:
231
+ - Determine target platform from OS and Shell fields in system environment info
232
+ - Linux: OS=Linux, use bash commands
233
+ - macOS: OS=Darwin, no \`free\`/\`ss\`/\`systemctl\`, use \`vm_stat\`/\`lsof\`/\`launchctl\` instead
234
+ - Windows: Shell=PowerShell, use PowerShell cmdlets, temp files in \`$env:TEMP\`
235
+ - Always check platform first before selecting commands when writing scripts
236
+
237
+ Response format (important):
238
+ - Use Markdown format
239
+ - Before tool calls, just one sentence explaining what you're about to do, don't explain command details
240
+ - 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
241
+ - If the operation succeeds, state the result directly (e.g., "Created", "Stopped", "Found 3 errors")
242
+ - If the operation fails, explain the cause and suggested fix
243
+ - No fluff, no filler, no summarizing what's already obvious
244
+
245
+ **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.`;
241
246
 
242
247
  constructor(sshService?: ISSHService, skillService?: ISkillService, auditService?: AuditService) {
243
248
  this.configDir = getDataDir();
244
249
  this.configPath = getDataPath('ai-config.json');
245
250
  this.historyDir = getDataPath('ai-history');
251
+ this.messagesDir = path.resolve('data', 'messages');
246
252
  this.config = this.getDefaultConfig();
247
253
  this.sshService = sshService;
248
254
  this.skillService = skillService;
@@ -250,6 +256,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
250
256
  this.loadConfig();
251
257
  // 确保历史目录存在
252
258
  try { if (!fs.existsSync(this.historyDir)) fs.mkdirSync(this.historyDir, { recursive: true }); } catch (_) { /* ignore */ }
259
+ ensureDir(this.messagesDir);
253
260
  this.cleanupOldHistories();
254
261
  this.registerBuiltinTools();
255
262
  }
@@ -322,7 +329,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
322
329
  async testConfig(config?: Partial<AIConfig>): Promise<{ success: boolean; message: string }> {
323
330
  const testConfig = { ...this.config, ...config };
324
331
  if (!testConfig.apiKey) {
325
- return { success: false, message: 'API Key 未配置' };
332
+ return { success: false, message: 'API Key not configured' };
326
333
  }
327
334
  try {
328
335
  const response = await axios.post(
@@ -341,11 +348,11 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
341
348
  }
342
349
  );
343
350
  if (response.data?.choices?.[0]?.message?.content) {
344
- return { success: true, message: '连接成功,模型可用' };
351
+ return { success: true, message: 'Connection successful, model available' };
345
352
  }
346
- return { success: false, message: '响应格式异常' };
353
+ return { success: false, message: 'Unexpected response format' };
347
354
  } catch (error: any) {
348
- const message = error.response?.data?.error?.message || error.message || '连接失败';
355
+ const message = error.response?.data?.error?.message || error.message || 'Connection failed';
349
356
  return { success: false, message };
350
357
  }
351
358
  }
@@ -371,22 +378,22 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
371
378
  * 注册内置工具
372
379
  */
373
380
  private registerBuiltinTools(): void {
374
- // execute_command - 执行 shell 命令
381
+ // execute_command - Execute shell command
375
382
  this.registerTool('execute_command', {
376
383
  type: 'function',
377
384
  function: {
378
385
  name: 'execute_command',
379
- description: '在当前终端 Shell 中执行命令并返回输出。支持任意 bash/zsh 命令。',
386
+ description: 'Execute a command in the current terminal Shell and return the output. Supports any bash/zsh/powershell commands.',
380
387
  parameters: {
381
388
  type: 'object',
382
389
  properties: {
383
390
  command: {
384
391
  type: 'string',
385
- description: '要执行的 shell 命令',
392
+ description: 'The shell command to execute',
386
393
  },
387
394
  timeout: {
388
395
  type: 'number',
389
- description: '等待输出的时间(毫秒),默认 2000,对于耗时命令可以设大一些',
396
+ description: 'Time to wait for output in milliseconds, default 2000. Increase for long-running commands',
390
397
  },
391
398
  },
392
399
  required: ['command'],
@@ -396,12 +403,12 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
396
403
  return this.executeCommand(args.command, sessionId, args.timeout || 2000);
397
404
  });
398
405
 
399
- // read_terminal - 读取终端输出
406
+ // read_terminal - Read terminal output
400
407
  this.registerTool('read_terminal', {
401
408
  type: 'function',
402
409
  function: {
403
410
  name: 'read_terminal',
404
- description: '读取终端当前的输出内容(最近 50 行),用于了解终端当前状态。',
411
+ description: 'Read the current terminal output (last 50 lines), useful for understanding the terminal state.',
405
412
  parameters: {
406
413
  type: 'object',
407
414
  properties: {},
@@ -455,7 +462,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
455
462
  ];
456
463
  for (const pattern of blocked) {
457
464
  if (pattern.test(trimmed)) {
458
- return { safe: false, reason: 'BLOCKED: 极度危险的破坏性操作,已阻止执行' };
465
+ return { safe: false, reason: 'BLOCKED: Extremely dangerous destructive operation' };
459
466
  }
460
467
  }
461
468
 
@@ -490,7 +497,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
490
497
  ];
491
498
  for (const pattern of blocked) {
492
499
  if (pattern.test(trimmed)) {
493
- return { safe: false, reason: 'BLOCKED: 极度危险的破坏性操作,已阻止执行' };
500
+ return { safe: false, reason: 'BLOCKED: Extremely dangerous destructive operation' };
494
501
  }
495
502
  }
496
503
 
@@ -523,14 +530,14 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
523
530
  */
524
531
  private async executeCommand(command: string, sessionId: string, timeout: number): Promise<string> {
525
532
  if (!this.sshService) {
526
- return '错误: SSH 服务不可用';
533
+ return 'Error: SSH service not available';
527
534
  }
528
535
  const session = this.sshService.getSession(sessionId);
529
536
  if (!session) {
530
- return `错误: 会话 ${sessionId} 不存在`;
537
+ return `Error: Session ${sessionId} not found`;
531
538
  }
532
539
 
533
- // 安全检查:拦截/改写危险命令
540
+ // Safety check: block/rewrite dangerous commands
534
541
  const check = await this.sanitizeCommand(command, sessionId);
535
542
  if (!check.safe) {
536
543
  return check.reason!;
@@ -541,34 +548,33 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
541
548
  }
542
549
 
543
550
  try {
544
- // 启动输出捕获
551
+ // Start output capture
545
552
  const outputPromise = this.sshService.captureOutput(sessionId, timeout);
546
- // 写入命令
553
+ // Write command
547
554
  this.sshService.writeData(sessionId, actualCommand + '\n');
548
- // 等待输出
555
+ // Wait for output
549
556
  const output = await outputPromise;
550
557
 
551
- // 清理输出:去除命令回显和空白
558
+ // Clean output: remove command echo and whitespace
552
559
  const lines = output.split('\n');
553
- // 尝试去掉第一行的命令回显
554
560
  if (lines.length > 0 && lines[0].trim().includes(actualCommand.trim().substring(0, 20))) {
555
561
  lines.shift();
556
562
  }
557
563
  const cleanOutput = lines.join('\n').trim();
558
564
 
559
565
  if (!cleanOutput) {
560
- return '(命令执行完成,无输出)';
566
+ return '(Command executed, no output)';
561
567
  }
562
568
 
563
- // 限制输出长度,避免过长
569
+ // Limit output length
564
570
  const maxLength = 5000;
565
571
  if (cleanOutput.length > maxLength) {
566
- return cleanOutput.substring(0, maxLength) + `\n... (输出被截断,共 ${cleanOutput.length} 字符)`;
572
+ return cleanOutput.substring(0, maxLength) + `\n... (output truncated, ${cleanOutput.length} chars total)`;
567
573
  }
568
574
 
569
575
  return cleanOutput;
570
576
  } catch (error: any) {
571
- return `执行命令失败: ${error.message}`;
577
+ return `Command execution failed: ${error.message}`;
572
578
  }
573
579
  }
574
580
 
@@ -577,20 +583,18 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
577
583
  */
578
584
  private async readTerminal(sessionId: string): Promise<string> {
579
585
  if (!this.sshService) {
580
- return '错误: SSH 服务不可用';
586
+ return 'Error: SSH service not available';
581
587
  }
582
588
  try {
583
- // 短暂捕获以获取当前缓冲区内容
584
589
  const output = await this.sshService.captureOutput(sessionId, 500);
585
590
  if (!output.trim()) {
586
- return '(终端当前无输出)';
591
+ return '(No terminal output)';
587
592
  }
588
593
  const lines = output.split('\n').filter(l => l.trim());
589
- // 返回最后 50 行
590
594
  const last50 = lines.slice(-50);
591
595
  return last50.join('\n');
592
596
  } catch (error: any) {
593
- return `读取终端失败: ${error.message}`;
597
+ return `Failed to read terminal: ${error.message}`;
594
598
  }
595
599
  }
596
600
 
@@ -599,8 +603,15 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
599
603
  private getOrCreateHistory(sessionId: string): ChatHistory {
600
604
  let history = this.chatHistories.get(sessionId);
601
605
  if (!history) {
602
- history = { sessionId, messages: [], lastActive: Date.now() };
606
+ // 首次访问,尝试从文件加载
607
+ const saved = this.loadChatMessages(sessionId);
608
+ history = {
609
+ sessionId,
610
+ messages: saved || [],
611
+ lastActive: Date.now(),
612
+ };
603
613
  this.chatHistories.set(sessionId, history);
614
+ this.loadedSessions.add(sessionId);
604
615
  }
605
616
  history.lastActive = Date.now();
606
617
  return history;
@@ -611,11 +622,15 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
611
622
  while (history.messages.length > this.MAX_MESSAGES) {
612
623
  history.messages.shift();
613
624
  }
625
+ // 持久化到文件
626
+ this.saveChatMessages(history.sessionId, history.messages);
614
627
  }
615
628
 
616
629
  clearHistory(sessionId: string): void {
617
630
  this.chatHistories.delete(sessionId);
631
+ this.loadedSessions.delete(sessionId);
618
632
  this.deleteDisplayHistoryFile(sessionId);
633
+ this.deleteChatMessagesFile(sessionId);
619
634
  }
620
635
 
621
636
  getHistory(sessionId: string): ChatMessage[] | null {
@@ -623,7 +638,65 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
623
638
  return history ? [...history.messages] : null;
624
639
  }
625
640
 
626
- // ========== 对话历史持久化 ==========
641
+ // ========== LLM 上下文消息持久化 ==========
642
+
643
+ /**
644
+ * 保存 LLM 上下文消息到 data/messages/{sessionId}.json
645
+ */
646
+ private saveChatMessages(sessionId: string, messages: ChatMessage[]): void {
647
+ try {
648
+ ensureDir(this.messagesDir);
649
+ const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, '_');
650
+ const filePath = path.join(this.messagesDir, `${safe}.json`);
651
+ const data = {
652
+ sessionId,
653
+ updatedAt: Date.now(),
654
+ messages,
655
+ };
656
+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');
657
+ } catch (_) {
658
+ // 静默失败,不影响主流程
659
+ }
660
+ }
661
+
662
+ /**
663
+ * 从 data/messages/{sessionId}.json 加载 LLM 上下文消息
664
+ */
665
+ private loadChatMessages(sessionId: string): ChatMessage[] | null {
666
+ try {
667
+ if (!fs.existsSync(this.messagesDir)) return null;
668
+ const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, '_');
669
+ const filePath = path.join(this.messagesDir, `${safe}.json`);
670
+ if (!fs.existsSync(filePath)) return null;
671
+ const raw = fs.readFileSync(filePath, 'utf-8');
672
+ const data = JSON.parse(raw);
673
+ if (data && Array.isArray(data.messages)) {
674
+ return data.messages.length > this.MAX_MESSAGES
675
+ ? data.messages.slice(data.messages.length - this.MAX_MESSAGES)
676
+ : data.messages;
677
+ }
678
+ return null;
679
+ } catch (_) {
680
+ return null;
681
+ }
682
+ }
683
+
684
+ /**
685
+ * 删除 LLM 上下文消息文件
686
+ */
687
+ private deleteChatMessagesFile(sessionId: string): void {
688
+ try {
689
+ const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, '_');
690
+ const filePath = path.join(this.messagesDir, `${safe}.json`);
691
+ if (fs.existsSync(filePath)) {
692
+ fs.unlinkSync(filePath);
693
+ }
694
+ } catch (_) {
695
+ // 静默失败
696
+ }
697
+ }
698
+
699
+ // ========== 对话历史持久化(前端显示) ==========
627
700
 
628
701
  /**
629
702
  * 保存前端显示消息到文件(含元数据)
@@ -715,6 +788,10 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
715
788
  if (fs.existsSync(filePath)) {
716
789
  fs.unlinkSync(filePath);
717
790
  }
791
+ // 同步删除 LLM 上下文消息文件
792
+ this.deleteChatMessagesFile(sessionId);
793
+ this.chatHistories.delete(sessionId);
794
+ this.loadedSessions.delete(sessionId);
718
795
  } catch (error) {
719
796
  console.error('[AIService] Failed to delete display history:', error);
720
797
  }
@@ -747,17 +824,18 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
747
824
  userMessage: string,
748
825
  context: string | undefined,
749
826
  eventCallback: AgentEventCallback,
750
- skillId?: string
827
+ skillId?: string,
828
+ locale?: string
751
829
  ): Promise<void> {
752
830
  if (!this.config.apiKey) {
753
- eventCallback({ type: 'error', error: 'AI 未配置 API Key,请在设置中填写' });
831
+ eventCallback({ type: 'error', error: 'API Key not configured. Please set it in AI settings.' });
754
832
  return;
755
833
  }
756
834
 
757
- // 检查是否有正在运行的 agent
835
+ // Check for running agent
758
836
  const existingState = this.agentStates.get(sessionId);
759
837
  if (existingState?.running) {
760
- eventCallback({ type: 'error', error: 'Agent 正在运行中,请先等待完成或停止' });
838
+ eventCallback({ type: 'error', error: 'Agent is already running. Please wait or stop it first.' });
761
839
  return;
762
840
  }
763
841
 
@@ -768,20 +846,26 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
768
846
  const history = this.getOrCreateHistory(sessionId);
769
847
  const tools = this.getToolDefinitions();
770
848
 
771
- // 构建系统提示词
849
+ // Build system prompt
772
850
  let systemPrompt = this.AGENT_SYSTEM_PROMPT;
773
851
 
774
- // 自动注入系统环境上下文(首次对话自动采集)
852
+ // Inject locale hint if provided (fallback when user language is ambiguous)
853
+ if (locale) {
854
+ const langName = locale.startsWith('zh') ? 'Chinese' : locale.startsWith('ja') ? 'Japanese' : locale.startsWith('ko') ? 'Korean' : 'English';
855
+ systemPrompt += `\n\n[User's UI language preference: ${langName} (${locale}). If the user's message language is ambiguous, prefer responding in ${langName}.]`;
856
+ }
857
+
858
+ // Inject system environment context
775
859
  const sysContext = await this.getSessionContext(sessionId);
776
- if (sysContext && sysContext !== '无法采集系统信息') {
860
+ if (sysContext && sysContext !== 'Failed to collect system info') {
777
861
  systemPrompt += `\n\n${sysContext}`;
778
862
  }
779
863
 
780
- // 如果有 Skill,追加 Skill 指令
864
+ // If Skill is provided, append Skill instructions
781
865
  if (skillId && this.skillService) {
782
866
  const skill = this.skillService.getSkill(skillId);
783
867
  if (skill) {
784
- systemPrompt += `\n\n## 当前任务指令(Skill: ${skill.name})\n\n${skill.content}`;
868
+ systemPrompt += `\n\n## Current Task Instructions (Skill: ${skill.name})\n\n${skill.content}`;
785
869
  }
786
870
  }
787
871
 
@@ -790,11 +874,11 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
790
874
  { role: 'system', content: systemPrompt },
791
875
  ];
792
876
 
793
- // 添加终端上下文
877
+ // Add terminal context
794
878
  if (context) {
795
879
  messages.push({
796
880
  role: 'system',
797
- content: `当前终端最近的输出内容:\n\`\`\`\n${context}\n\`\`\``,
881
+ content: `Recent terminal output:\n\`\`\`\n${context}\n\`\`\``,
798
882
  });
799
883
  }
800
884
 
@@ -808,9 +892,9 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
808
892
 
809
893
  try {
810
894
  for (let iteration = 0; iteration < this.MAX_AGENT_ITERATIONS; iteration++) {
811
- // 检查是否被中断
895
+ // Check if aborted
812
896
  if (state.aborted) {
813
- eventCallback({ type: 'done', content: '(Agent 已被用户中断)' });
897
+ eventCallback({ type: 'done', content: '(Agent stopped by user)' });
814
898
  break;
815
899
  }
816
900
 
@@ -821,13 +905,13 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
821
905
  try {
822
906
  response = await this.callLLM(messages, tools);
823
907
  } catch (error: any) {
824
- eventCallback({ type: 'error', error: `LLM 调用失败: ${error.message}` });
908
+ eventCallback({ type: 'error', error: `LLM call failed: ${error.message}` });
825
909
  break;
826
910
  }
827
911
 
828
912
  const assistantMessage = response.choices?.[0]?.message;
829
913
  if (!assistantMessage) {
830
- eventCallback({ type: 'error', error: 'LLM 响应为空' });
914
+ eventCallback({ type: 'error', error: 'LLM response is empty' });
831
915
  break;
832
916
  }
833
917
 
@@ -876,16 +960,16 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
876
960
  let result: string;
877
961
  let toolStatus: AuditEntry['status'] = 'success';
878
962
  if (!tool) {
879
- result = `错误: 未知工具 "${toolName}"`;
963
+ result = `Error: Unknown tool "${toolName}"`;
880
964
  toolStatus = 'error';
881
965
  } else {
882
966
  try {
883
967
  result = await tool.executor(toolArgs, sessionId);
884
- if (result.startsWith('错误:') || result.startsWith('工具执行失败:')) {
968
+ if (result.startsWith('Error:') || result.startsWith('Tool execution failed:')) {
885
969
  toolStatus = 'error';
886
970
  }
887
971
  } catch (error: any) {
888
- result = `工具执行失败: ${error.message}`;
972
+ result = `Tool execution failed: ${error.message}`;
889
973
  toolStatus = 'error';
890
974
  }
891
975
  }
@@ -923,13 +1007,13 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
923
1007
  this.addMessage(history, toolMsg);
924
1008
  }
925
1009
 
926
- // 如果是最后一次迭代且仍有 tool_calls,发送完成
1010
+ // Last iteration with remaining tool_calls
927
1011
  if (iteration === this.MAX_AGENT_ITERATIONS - 1) {
928
- eventCallback({ type: 'done', content: '已达到最大执行次数限制' });
1012
+ eventCallback({ type: 'done', content: 'Max iterations reached' });
929
1013
  }
930
1014
  }
931
1015
  } catch (error: any) {
932
- eventCallback({ type: 'error', error: error.message || 'Agent 运行异常' });
1016
+ eventCallback({ type: 'error', error: error.message || 'Agent runtime error' });
933
1017
  } finally {
934
1018
  state.running = false;
935
1019
  this.agentStates.delete(sessionId);
@@ -984,7 +1068,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
984
1068
 
985
1069
  async chat(sessionId: string, userMessage: string, context?: string): Promise<string> {
986
1070
  if (!this.config.apiKey) {
987
- throw new Error('AI 未配置 API Key,请在设置中填写');
1071
+ throw new Error('API Key not configured. Please set it in AI settings.');
988
1072
  }
989
1073
 
990
1074
  const history = this.getOrCreateHistory(sessionId);
@@ -995,7 +1079,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
995
1079
  if (context) {
996
1080
  messages.push({
997
1081
  role: 'system',
998
- content: `当前终端最近的输出内容:\n\`\`\`\n${context}\n\`\`\``,
1082
+ content: `Recent terminal output:\n\`\`\`\n${context}\n\`\`\``,
999
1083
  });
1000
1084
  }
1001
1085
 
@@ -1026,10 +1110,10 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
1026
1110
  this.addMessage(history, { role: 'assistant', content: assistantMessage });
1027
1111
  return assistantMessage;
1028
1112
  }
1029
- throw new Error('AI 响应为空');
1113
+ throw new Error('AI response is empty');
1030
1114
  } catch (error: any) {
1031
1115
  history.messages.pop();
1032
- const message = error.response?.data?.error?.message || error.message || 'AI 请求失败';
1116
+ const message = error.response?.data?.error?.message || error.message || 'AI request failed';
1033
1117
  throw new Error(message);
1034
1118
  }
1035
1119
  }
@@ -1040,7 +1124,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
1040
1124
  context?: string
1041
1125
  ): AsyncGenerator<string, void, unknown> {
1042
1126
  if (!this.config.apiKey) {
1043
- throw new Error('AI 未配置 API Key,请在设置中填写');
1127
+ throw new Error('API Key not configured. Please set it in AI settings.');
1044
1128
  }
1045
1129
 
1046
1130
  const history = this.getOrCreateHistory(sessionId);
@@ -1051,7 +1135,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
1051
1135
  if (context) {
1052
1136
  messages.push({
1053
1137
  role: 'system',
1054
- content: `当前终端最近的输出内容:\n\`\`\`\n${context}\n\`\`\``,
1138
+ content: `Recent terminal output:\n\`\`\`\n${context}\n\`\`\``,
1055
1139
  });
1056
1140
  }
1057
1141
 
@@ -1103,7 +1187,7 @@ Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
1103
1187
  }
1104
1188
  } catch (error: any) {
1105
1189
  history.messages.pop();
1106
- const message = error.response?.data?.error?.message || error.message || 'AI 请求失败';
1190
+ const message = error.response?.data?.error?.message || error.message || 'AI request failed';
1107
1191
  throw new Error(message);
1108
1192
  }
1109
1193
  }
@@ -47,10 +47,21 @@ export declare class ConnectionService {
47
47
  */
48
48
  private getLocalSSHKey;
49
49
  /**
50
- * 将 OpenSSH 格式的私钥转换为 PEM 格式
51
- * ssh2 库不支持 OpenSSH 格式,需要转换
50
+ * Detect SSH agent socket for agent forwarding
51
+ * - Linux/macOS: SSH_AUTH_SOCK environment variable
52
+ * - Windows: OpenSSH agent pipe
53
+ */
54
+ private getSSHAgentSocket;
55
+ /**
56
+ * 处理私钥格式
57
+ * ssh2 库对 OpenSSH 格式支持不完善,需要转换为 PEM 格式
52
58
  */
53
59
  private convertToPEM;
60
+ /**
61
+ * 使用 ssh-keygen 将 OpenSSH 格式私钥转换为 PEM 格式
62
+ * 通过复制到临时文件来避免修改原始密钥
63
+ */
64
+ private convertWithSSHKeygen;
54
65
  /**
55
66
  * 保存连接配置到文件
56
67
  */
@@ -1 +1 @@
1
- {"version":3,"file":"connection.service.d.ts","sourceRoot":"","sources":["../../../server/service/connection.service.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAG9D;;;GAGG;AACH,qBAAa,iBAAiB;IAE5B;;;OAGG;IACH,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;;IAMpC;;OAEG;IACG,IAAI;IAOV;;OAEG;IACG,iBAAiB,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAatD;;OAEG;IACG,iBAAiB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC;IAKrE;;OAEG;IACG,aAAa,CAAC,UAAU,EAAE,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAoB5E;;OAEG;IACG,gBAAgB,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAkBjG;;OAEG;IACG,gBAAgB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAWjD;;OAEG;IACG,cAAc,CAAC,UAAU,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC;IA0BpE;;OAEG;IACH,YAAY,CAAC,UAAU,EAAE,gBAAgB,GAAG,GAAG;IA4B/C;;OAEG;IACH,OAAO,CAAC,cAAc;IAkDtB;;;OAGG;IACH,OAAO,CAAC,YAAY;IAkBpB;;OAEG;YACW,eAAe;IAa7B;;OAEG;IACH,OAAO,CAAC,UAAU;CAGnB"}
1
+ {"version":3,"file":"connection.service.d.ts","sourceRoot":"","sources":["../../../server/service/connection.service.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAI9D;;;GAGG;AACH,qBAAa,iBAAiB;IAE5B;;;OAGG;IACH,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;;IAMpC;;OAEG;IACG,IAAI;IAOV;;OAEG;IACG,iBAAiB,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAatD;;OAEG;IACG,iBAAiB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC;IAKrE;;OAEG;IACG,aAAa,CAAC,UAAU,EAAE,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAoB5E;;OAEG;IACG,gBAAgB,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAkBjG;;OAEG;IACG,gBAAgB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAWjD;;OAEG;IACG,cAAc,CAAC,UAAU,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC;IA0BpE;;OAEG;IACH,YAAY,CAAC,UAAU,EAAE,gBAAgB,GAAG,GAAG;IA8C/C;;OAEG;IACH,OAAO,CAAC,cAAc;IAmDtB;;;;OAIG;IACH,OAAO,CAAC,iBAAiB;IAoBzB;;;OAGG;IACH,OAAO,CAAC,YAAY;IAqCpB;;;OAGG;IACH,OAAO,CAAC,oBAAoB;IA0C5B;;OAEG;YACW,eAAe;IAa7B;;OAEG;IACH,OAAO,CAAC,UAAU;CAGnB"}