@fefeding/aicmd 0.1.16 → 1.0.3

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.
@@ -1,17 +1,23 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import * as os from 'os';
4
- import axios from 'axios';
5
- import { getDataDir, getDataPath, ensureDataDir, ensureDir } from '../utils/data-dir';
6
- import { AuditService, type AuditEntry } from './audit.service';
7
- import { assessDangerousCommand } from '../utils/shell';
8
4
  import * as crypto from 'crypto';
5
+ import { getDataDir, getDataPath, ensureDir } from '../utils/data-dir';
6
+ import { AuditService } from './audit.service';
7
+ import { assessDangerousCommand } from '../utils/shell';
8
+ import {
9
+ AgentEngine, ToolRegistry, ContextManager, SecurityGuard,
10
+ createLLMProvider,
11
+ } from '@cicctencent/agent-core';
12
+ import type {
13
+ LLMProvider, AgentEvent as CoreAgentEvent,
14
+ Message, ToolContext, ToolDefinition,
15
+ } from '@cicctencent/agent-core';
9
16
 
10
17
  const ENCRYPTED_PREFIX = 'enc:v1:';
11
18
 
12
- /**
13
- * AI 配置接口
14
- */
19
+ // ========== 公共导出类型 ==========
20
+
15
21
  export interface AIConfig {
16
22
  enabled: boolean;
17
23
  apiKey: string;
@@ -21,37 +27,10 @@ export interface AIConfig {
21
27
  temperature?: number;
22
28
  }
23
29
 
24
- /**
25
- * 对话消息接口(支持 tool calling)
26
- */
27
- export interface ChatMessage {
28
- role: 'system' | 'user' | 'assistant' | 'tool';
29
- content: string | null;
30
- tool_calls?: ToolCall[];
31
- tool_call_id?: string;
32
- name?: string;
33
- }
34
-
35
- /**
36
- * 工具调用接口(OpenAI function calling 格式)
37
- */
38
- export interface ToolCall {
39
- id: string;
40
- type: 'function';
41
- function: {
42
- name: string;
43
- arguments: string;
44
- };
45
- }
46
-
47
- /**
48
- * Agent 事件类型
49
- */
30
+ /** Agent 事件类型 */
50
31
  export type AgentEventType = 'thinking' | 'message' | 'tool_call' | 'tool_result' | 'audit_entry' | 'done' | 'error' | 'system_info';
51
32
 
52
- /**
53
- * Agent 事件
54
- */
33
+ /** Agent 事件(应用层简化格式) */
55
34
  export interface AgentEvent {
56
35
  type: AgentEventType;
57
36
  content?: string;
@@ -62,38 +41,12 @@ export interface AgentEvent {
62
41
  auditEntry?: any;
63
42
  }
64
43
 
65
- /** Agent 事件回调 */
66
44
  export type AgentEventCallback = (event: AgentEvent) => void;
67
45
 
68
- /**
69
- * 工具定义(OpenAI tools 格式)
70
- */
71
- export interface ToolDefinition {
72
- type: 'function';
73
- function: {
74
- name: string;
75
- description: string;
76
- parameters: object;
77
- };
78
- }
79
-
80
- /** 工具执行器 */
81
46
  export type ToolExecutor = (args: any, sessionId: string) => Promise<string>;
82
47
 
83
- /** 已注册的工具 */
84
- interface RegisteredTool {
85
- definition: ToolDefinition;
86
- executor: ToolExecutor;
87
- }
88
-
89
- /** 对话历史 */
90
- interface ChatHistory {
91
- sessionId: string;
92
- messages: ChatMessage[];
93
- lastActive: number;
94
- }
48
+ // ========== 显示消息 & 历史 ==========
95
49
 
96
- /** 前端显示消息(持久化用) */
97
50
  export interface DisplayMessage {
98
51
  role: 'user' | 'assistant';
99
52
  content: string;
@@ -110,7 +63,6 @@ export interface DisplayAgentStep {
110
63
  collapsed?: boolean;
111
64
  }
112
65
 
113
- /** 历史文件元数据 */
114
66
  export interface HistoryMeta {
115
67
  sessionId: string;
116
68
  sessionName?: string;
@@ -119,28 +71,13 @@ export interface HistoryMeta {
119
71
  preview: string;
120
72
  }
121
73
 
122
- /** 历史文件完整结构 */
123
74
  interface HistoryFile {
124
75
  meta: HistoryMeta;
125
76
  messages: DisplayMessage[];
126
77
  }
127
78
 
128
- /** Agent 运行状态 */
129
- interface AgentRunState {
130
- running: boolean;
131
- aborted: boolean;
132
- }
133
-
134
- // 去除 ANSI 转义序列
135
- function stripAnsi(text: string): string {
136
- return text
137
- .replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '')
138
- .replace(/\x1B\].*?\x07/g, '')
139
- .replace(/\x1B\[[\?]?[0-9;]*[hlm]/g, '')
140
- .replace(/\r/g, '');
141
- }
79
+ // ========== 服务依赖接口 ==========
142
80
 
143
- // SSHService 接口(避免循环依赖)
144
81
  interface ISSHService {
145
82
  writeData(sessionId: string, data: string | Buffer): boolean;
146
83
  captureOutput(sessionId: string, timeoutMs?: number): Promise<string>;
@@ -148,35 +85,13 @@ interface ISSHService {
148
85
  getSystemContext(sessionId: string): Promise<string>;
149
86
  }
150
87
 
151
- // SkillService 接口
152
88
  interface ISkillService {
153
89
  getSkill(id: string): { name: string; content: string } | undefined;
154
90
  }
155
91
 
156
- /**
157
- * AI Agent 服务 - 支持工具调用和自主操作终端
158
- */
159
- export class AIService {
160
- private configDir: string;
161
- private configPath: string;
162
- private config: AIConfig;
163
- private historyDir: string;
164
- /** LLM 上下文消息持久化目录(项目执行目录下 data/messages) */
165
- private messagesDir: string;
166
- private chatHistories: Map<string, ChatHistory> = new Map();
167
- /** 已从文件加载过的 sessionId 集合 */
168
- private loadedSessions = new Set<string>();
169
- private agentStates: Map<string, AgentRunState> = new Map();
170
- private toolRegistry: Map<string, RegisteredTool> = new Map();
171
- private sshService?: ISSHService;
172
- private skillService?: ISkillService;
173
- private auditService?: AuditService;
174
- private readonly MAX_HISTORY_AGE = 24 * 60 * 60 * 1000;
175
- private readonly MAX_MESSAGES = 50;
176
- private readonly MAX_AGENT_ITERATIONS = 15;
92
+ // ========== Agent System Prompt ==========
177
93
 
178
- // Agent system prompt (English default, language adapts to user input)
179
- private readonly AGENT_SYSTEM_PROMPT = `You are a powerful AI terminal Agent that can directly operate the user's terminal Shell.
94
+ const AGENT_SYSTEM_PROMPT = `You are a powerful AI terminal Agent that can directly operate the user's terminal Shell.
180
95
 
181
96
  Your capabilities:
182
97
  1. Execute commands directly in the terminal via the execute_command tool
@@ -216,10 +131,10 @@ chmod +x /tmp/_ai_task.sh && bash /tmp/_ai_task.sh
216
131
 
217
132
  **Windows (PowerShell):**
218
133
  \`\`\`powershell
219
- Set-Content -Path $env:TEMP\_ai_task.ps1 -Value @'
134
+ Set-Content -Path $env:TEMP\\_ai_task.ps1 -Value @'
220
135
  # PowerShell script content...
221
136
  '@
222
- & $env:TEMP\_ai_task.ps1
137
+ & $env:TEMP\\_ai_task.ps1
223
138
  \`\`\`
224
139
 
225
140
  4. Execute the script and check results
@@ -248,6 +163,35 @@ Response format (important):
248
163
 
249
164
  **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.`;
250
165
 
166
+
167
+ // ============================================================
168
+ // AIService — 底层 AI 能力委托给 @cicctencent/agent-core
169
+ // ============================================================
170
+
171
+ export class AIService {
172
+ // ---- 配置 & 持久化 ----
173
+ private configDir: string;
174
+ private configPath: string;
175
+ private config: AIConfig;
176
+ private historyDir: string;
177
+ private messagesDir: string;
178
+
179
+ // ---- agent-core 组件 ----
180
+ private llmProvider?: LLMProvider;
181
+ private toolRegistry: ToolRegistry;
182
+ private contextManager: ContextManager;
183
+ private securityGuard: SecurityGuard;
184
+ private engine?: AgentEngine;
185
+ private abortControllers = new Map<string, AbortController>();
186
+
187
+ // ---- 状态 ----
188
+ private loadedSessions = new Set<string>();
189
+ private sshService?: ISSHService;
190
+ private skillService?: ISkillService;
191
+ private auditService?: AuditService;
192
+ private readonly MAX_MESSAGES = 50;
193
+ private readonly MAX_AGENT_ITERATIONS = 15;
194
+
251
195
  constructor(sshService?: ISSHService, skillService?: ISkillService, auditService?: AuditService) {
252
196
  this.configDir = getDataDir();
253
197
  this.configPath = getDataPath('ai-config.json');
@@ -257,22 +201,98 @@ Response format (important):
257
201
  this.sshService = sshService;
258
202
  this.skillService = skillService;
259
203
  this.auditService = auditService;
204
+
205
+ // 初始化 agent-core 组件
206
+ this.toolRegistry = new ToolRegistry();
207
+ this.contextManager = new ContextManager();
208
+ this.securityGuard = new SecurityGuard({
209
+ trashDir: '~/.aicmd/.trash',
210
+ deleteProtection: true,
211
+ });
212
+ // agent-core 0.1.4 已内置 Windows 黑名单(format C:, clear-disk, rd /s, Remove-Item drive root)
213
+ // 无需再手动添加
214
+
260
215
  this.loadConfig();
261
- // 确保历史目录存在
262
216
  try { if (!fs.existsSync(this.historyDir)) fs.mkdirSync(this.historyDir, { recursive: true }); } catch (_) { /* ignore */ }
263
217
  ensureDir(this.messagesDir);
264
- this.cleanupOldHistories();
265
218
  this.registerBuiltinTools();
266
219
  }
267
220
 
221
+ // ========== LLM Provider & Engine 懒初始化 ==========
222
+
223
+ private ensureLLMProvider(): LLMProvider | undefined {
224
+ if (!this.config.apiKey) return undefined;
225
+ if (!this.llmProvider) {
226
+ this.llmProvider = createLLMProvider({
227
+ provider: 'openai',
228
+ model: this.config.model,
229
+ apiKey: this.config.apiKey,
230
+ baseUrl: this.config.baseUrl,
231
+ temperature: this.config.temperature,
232
+ maxTokens: this.config.maxTokens,
233
+ });
234
+ }
235
+ return this.llmProvider;
236
+ }
237
+
238
+ private resetProviderAndEngine(): void {
239
+ this.llmProvider = undefined;
240
+ this.engine = undefined;
241
+ }
242
+
243
+ private getEngine(): AgentEngine | undefined {
244
+ const provider = this.ensureLLMProvider();
245
+ if (!provider) return undefined;
246
+ if (!this.engine) {
247
+ this.engine = new AgentEngine({
248
+ llmProvider: provider,
249
+ toolRegistry: this.toolRegistry,
250
+ contextManager: this.contextManager,
251
+ securityGuard: this.securityGuard,
252
+ basePrompt: AGENT_SYSTEM_PROMPT,
253
+ maxIterations: this.MAX_AGENT_ITERATIONS,
254
+ maxMessages: this.MAX_MESSAGES,
255
+ hooks: this.buildHooks(),
256
+ });
257
+ }
258
+ return this.engine;
259
+ }
260
+
261
+ private buildHooks(): import('@cicctencent/agent-core').Hook[] {
262
+ if (!this.auditService) return [];
263
+ const auditService = this.auditService;
264
+ const sshService = this.sshService;
265
+ return [{
266
+ name: 'audit-tool-call',
267
+ event: 'after_tool' as const,
268
+ handler: async (ctx) => {
269
+ try {
270
+ const command = ctx.tool === 'execute_command'
271
+ ? (ctx.args?.command as string || '')
272
+ : JSON.stringify(ctx.args);
273
+ const auditEntry = auditService.log({
274
+ sessionId: ctx.sessionId,
275
+ sessionName: sshService?.getSession(ctx.sessionId)?.name,
276
+ connectionId: sshService?.getSession(ctx.sessionId)?.connectionId,
277
+ userMessage: '',
278
+ tool: ctx.tool || '',
279
+ command,
280
+ result: (ctx.result || '').substring(0, 5000),
281
+ duration: ctx.duration || 0,
282
+ status: ctx.isError ? 'error' : 'success',
283
+ });
284
+ } catch { /* 审计失败不影响主流程 */ }
285
+ },
286
+ }];
287
+ }
288
+
289
+ // ========== 配置管理 ==========
290
+
268
291
  private getDefaultConfig(): AIConfig {
269
292
  return {
270
- enabled: true,
271
- apiKey: '',
293
+ enabled: true, apiKey: '',
272
294
  baseUrl: 'https://api.openai.com/v1',
273
- model: 'gpt-4o-mini',
274
- maxTokens: 4000,
275
- temperature: 0.3,
295
+ model: 'gpt-4o-mini', maxTokens: 4000, temperature: 0.3,
276
296
  };
277
297
  }
278
298
 
@@ -283,22 +303,15 @@ Response format (important):
283
303
  const savedConfig = this.decryptConfig(JSON.parse(data));
284
304
  this.config = { ...this.getDefaultConfig(), ...savedConfig };
285
305
  }
286
- } catch (error) {
287
- console.error('[AIService] Failed to load config:', error);
288
- }
306
+ } catch (error) { console.error('[AIService] Failed to load config:', error); }
289
307
  }
290
308
 
291
309
  private saveConfig(): void {
292
310
  try {
293
- if (!fs.existsSync(this.configDir)) {
294
- fs.mkdirSync(this.configDir, { recursive: true });
295
- }
311
+ if (!fs.existsSync(this.configDir)) fs.mkdirSync(this.configDir, { recursive: true });
296
312
  fs.writeFileSync(this.configPath, JSON.stringify(this.encryptConfig(this.config), null, 2), { encoding: 'utf-8', mode: 0o600 });
297
313
  try { fs.chmodSync(this.configPath, 0o600); } catch (_) { /* ignore */ }
298
- } catch (error) {
299
- console.error('[AIService] Failed to save config:', error);
300
- throw error;
301
- }
314
+ } catch (error) { console.error('[AIService] Failed to save config:', error); throw error; }
302
315
  }
303
316
 
304
317
  private encryptConfig(config: AIConfig): AIConfig {
@@ -356,16 +369,7 @@ Response format (important):
356
369
  }
357
370
  }
358
371
 
359
- private cleanupOldHistories(): void {
360
- const now = Date.now();
361
- for (const [sessionId, history] of this.chatHistories) {
362
- if (now - history.lastActive > this.MAX_HISTORY_AGE) {
363
- this.chatHistories.delete(sessionId);
364
- }
365
- }
366
- }
367
-
368
- // ========== 配置管理 ==========
372
+ // ========== 公共配置 API ==========
369
373
 
370
374
  getConfig(): AIConfig {
371
375
  const maskedConfig = { ...this.config };
@@ -376,439 +380,416 @@ Response format (important):
376
380
  return maskedConfig;
377
381
  }
378
382
 
379
- getFullConfig(): AIConfig {
380
- return { ...this.config };
381
- }
383
+ getFullConfig(): AIConfig { return { ...this.config }; }
382
384
 
383
385
  updateConfig(updates: Partial<AIConfig>): AIConfig {
384
386
  this.config = { ...this.config, ...updates };
385
387
  this.saveConfig();
388
+ this.resetProviderAndEngine();
386
389
  return this.getConfig();
387
390
  }
388
391
 
389
392
  async testConfig(config?: Partial<AIConfig>): Promise<{ success: boolean; message: string }> {
390
- const testConfig = { ...this.config, ...config };
391
- if (!testConfig.apiKey) {
392
- return { success: false, message: 'API Key not configured' };
393
- }
393
+ const testCfg = { ...this.config, ...config };
394
+ if (!testCfg.apiKey) return { success: false, message: 'API Key not configured' };
394
395
  try {
395
- const response = await axios.post(
396
- `${testConfig.baseUrl}/chat/completions`,
397
- {
398
- model: testConfig.model,
399
- messages: [{ role: 'user', content: 'Hello' }],
400
- max_tokens: 10,
401
- },
402
- {
403
- headers: {
404
- 'Authorization': `Bearer ${testConfig.apiKey}`,
405
- 'Content-Type': 'application/json',
406
- },
407
- timeout: 30000,
408
- }
409
- );
410
- if (response.data?.choices?.[0]?.message?.content) {
411
- return { success: true, message: 'Connection successful, model available' };
412
- }
413
- return { success: false, message: 'Unexpected response format' };
396
+ const provider = createLLMProvider({
397
+ provider: 'openai', model: testCfg.model,
398
+ apiKey: testCfg.apiKey, baseUrl: testCfg.baseUrl,
399
+ });
400
+ const ok = await provider.ping();
401
+ return ok
402
+ ? { success: true, message: 'Connection successful, model available' }
403
+ : { success: false, message: 'Connection failed or model unavailable' };
414
404
  } catch (error: any) {
415
- const message = error.response?.data?.error?.message || error.message || 'Connection failed';
416
- return { success: false, message };
405
+ return { success: false, message: error.message || 'Connection failed' };
417
406
  }
418
407
  }
419
408
 
420
- // ========== 工具注册表 ==========
409
+ // ========== 工具注册 ==========
421
410
 
422
- /**
423
- * 注册工具
424
- */
425
411
  registerTool(name: string, definition: ToolDefinition, executor: ToolExecutor): void {
426
- this.toolRegistry.set(name, { definition, executor });
412
+ this.toolRegistry.register({
413
+ definition,
414
+ executor: (args, _ctx) => executor(args, _ctx.sessionId),
415
+ category: 'custom',
416
+ });
427
417
  console.log(`[AIService] Tool registered: ${name}`);
428
418
  }
429
419
 
430
- /**
431
- * 获取所有工具定义(OpenAI tools 格式)
432
- */
433
420
  getToolDefinitions(): ToolDefinition[] {
434
- return Array.from(this.toolRegistry.values()).map(t => t.definition);
421
+ return this.toolRegistry.getDefinitions();
435
422
  }
436
423
 
437
- /**
438
- * 注册内置工具
439
- */
440
424
  private registerBuiltinTools(): void {
441
- // execute_command - Execute shell command
442
- this.registerTool('execute_command', {
443
- type: 'function',
444
- function: {
445
- name: 'execute_command',
446
- description: 'Execute a command in the current terminal Shell and return the output. Supports any bash/zsh/powershell commands.',
447
- parameters: {
448
- type: 'object',
449
- properties: {
450
- command: {
451
- type: 'string',
452
- description: 'The shell command to execute',
453
- },
454
- timeout: {
455
- type: 'number',
456
- description: 'Time to wait for output in milliseconds, default 2000. Increase for long-running commands',
425
+ // execute_command
426
+ this.toolRegistry.register({
427
+ definition: {
428
+ type: 'function',
429
+ function: {
430
+ name: 'execute_command',
431
+ description: 'Execute a command in the current terminal Shell and return the output. Supports any bash/zsh/powershell commands.',
432
+ parameters: {
433
+ type: 'object',
434
+ properties: {
435
+ command: { type: 'string', description: 'The shell command to execute' },
436
+ timeout: { type: 'number', description: 'Time to wait for output in milliseconds, default 2000. Increase for long-running commands' },
457
437
  },
438
+ required: ['command'],
458
439
  },
459
- required: ['command'],
460
440
  },
461
441
  },
462
- }, async (args: { command: string; timeout?: number }, sessionId: string) => {
463
- return this.executeCommand(args.command, sessionId, args.timeout || 2000);
442
+ executor: async (args: Record<string, unknown>, ctx: ToolContext) => {
443
+ return this.executeCommand(args.command as string, ctx.sessionId, (args.timeout as number) || 2000);
444
+ },
445
+ category: 'builtin',
464
446
  });
465
447
 
466
- // read_terminal - Read terminal output
467
- this.registerTool('read_terminal', {
468
- type: 'function',
469
- function: {
470
- name: 'read_terminal',
471
- description: 'Read the current terminal output (last 50 lines), useful for understanding the terminal state.',
472
- parameters: {
473
- type: 'object',
474
- properties: {},
448
+ // read_terminal
449
+ this.toolRegistry.register({
450
+ definition: {
451
+ type: 'function',
452
+ function: {
453
+ name: 'read_terminal',
454
+ description: 'Read the current terminal output (last 50 lines), useful for understanding the terminal state.',
455
+ parameters: { type: 'object', properties: {} },
475
456
  },
476
457
  },
477
- }, async (_args: any, sessionId: string) => {
478
- return this.readTerminal(sessionId);
458
+ executor: async (_args: Record<string, unknown>, ctx: ToolContext) => {
459
+ return this.readTerminal(ctx.sessionId);
460
+ },
461
+ category: 'builtin',
479
462
  });
480
463
  }
481
464
 
482
- // ========== 工具执行器 ==========
465
+ // ========== 命令安全检查 ==========
483
466
 
484
- /**
485
- * 检测会话是否为 Windows 环境
486
- */
487
467
  private async isWindowsSession(sessionId: string): Promise<boolean> {
488
468
  if (!this.sshService) return false;
489
469
  try {
490
470
  const ctx = await this.sshService.getSystemContext(sessionId);
491
471
  return /OS:.*Windows|Shell:.*PowerShell|Shell:.*pwsh/i.test(ctx);
492
- } catch {
493
- return false;
494
- }
472
+ } catch { return false; }
495
473
  }
496
474
 
497
- /**
498
- * 危险命令拦截:将 rm/Remove-Item 转换为移动到回收站,阻止极端破坏性操作
499
- */
500
475
  private async sanitizeCommand(command: string, sessionId: string): Promise<{ safe: boolean; rewritten?: string; reason?: string }> {
501
476
  const trimmed = command.trim();
502
477
  const risk = assessDangerousCommand(trimmed);
503
- if (!risk.safe) {
504
- return risk;
505
- }
478
+ if (!risk.safe) return risk;
506
479
  const isWin = await this.isWindowsSession(sessionId);
507
-
508
- if (isWin) {
509
- return this.sanitizeWindowsCommand(trimmed);
510
- }
511
- return this.sanitizeUnixCommand(trimmed);
480
+ return isWin ? this.sanitizeWindowsCommand(trimmed) : { safe: true };
512
481
  }
513
482
 
514
- /**
515
- * Unix (Linux/macOS) 命令安全检查
516
- */
517
- private sanitizeUnixCommand(trimmed: string): { safe: boolean; rewritten?: string; reason?: string } {
518
- // 绝对禁止的命令
519
- const blocked = [
520
- /^rm\s+(-[a-zA-Z]*\s+)*\/$/m,
521
- /^rm\s+(-[a-zA-Z]*\s+)*\/\s*$/m,
522
- /^rm\s+-[a-zA-Z]*r[a-zA-Z]*\s+\/\s*$/m,
523
- /mkfs\./,
524
- /^dd\s+.*of=\/dev\/[sh]d/m,
525
- /^:\(\)\s*\{\s*:\|:\s*&\s*\}\s*;\s*:/,
526
- ];
527
- for (const pattern of blocked) {
528
- if (pattern.test(trimmed)) {
529
- return { safe: false, reason: 'BLOCKED: Extremely dangerous destructive operation' };
530
- }
531
- }
532
-
533
- // rm 命令改写为移动到回收站
534
- const rmMatch = trimmed.match(/^(sudo\s+)?rm\s+((?:-[a-zA-Z]+\s+)*)(.+)$/s);
535
- if (rmMatch) {
536
- const sudo = rmMatch[1] || '';
537
- const targets = rmMatch[3].trim();
538
- const trashDir = '~/.aicmd/.trash';
539
- const ts = Date.now();
540
- const firstTarget = targets.split(/\s+/)[0];
541
- const rewritten = `${sudo}mkdir -p ${trashDir} && ${sudo}mv ${targets} ${trashDir}/_del_${ts}_$(basename ${firstTarget}) 2>/dev/null || ${sudo}mv ${targets} ${trashDir}/_del_${ts}`;
542
- return { safe: true, rewritten };
543
- }
544
-
545
- return { safe: true };
546
- }
547
-
548
- /**
549
- * Windows (PowerShell) 命令安全检查
550
- */
551
483
  private sanitizeWindowsCommand(trimmed: string): { safe: boolean; rewritten?: string; reason?: string } {
552
- const lower = trimmed.toLowerCase();
553
-
554
- // 绝对禁止的操作
555
484
  const blocked = [
556
- /format\s+[a-z]:/i, // format C:
557
- /clear-disk/i, // Clear-Disk
558
- /remove-item\s+.*[a-z]:\\\s*$/i, // Remove-Item C:\
559
- /remove-item\s+.*-recurse.*[a-z]:\\\s*$/i, // Remove-Item -Recurse C:\
560
- /rd\s+\/s\s+[a-z]:\\\s*$/i, // rd /s C:\
485
+ /format\s+[a-z]:/i, /clear-disk/i,
486
+ /remove-item\s+.*[a-z]:\s*$/i, /remove-item\s+.*-recurse.*[a-z]:\s*$/i,
487
+ /rd\s+\/s\s+[a-z]:\s*$/i,
561
488
  ];
562
489
  for (const pattern of blocked) {
563
- if (pattern.test(trimmed)) {
564
- return { safe: false, reason: 'BLOCKED: Extremely dangerous destructive operation' };
565
- }
490
+ if (pattern.test(trimmed)) return { safe: false, reason: 'BLOCKED: Extremely dangerous destructive operation' };
566
491
  }
567
-
568
- // Remove-Item / del / rd 改写为移动到回收站
569
- const removePatterns = [
570
- /^(Remove-Item|ri|del|rd)\s+(.+)$/i,
571
- ];
492
+ const removePatterns = [/^(Remove-Item|ri|del|rd)\s+(.+)$/i];
572
493
  for (const pattern of removePatterns) {
573
494
  const match = trimmed.match(pattern);
574
495
  if (match) {
575
496
  const targets = match[2]
576
- .replace(/-Recurse/gi, '')
577
- .replace(/-Force/gi, '')
578
- .replace(/-Confirm:\$false/gi, '')
579
- .replace(/\/s/gi, '')
580
- .replace(/\/q/gi, '')
581
- .trim();
497
+ .replace(/-Recurse/gi, '').replace(/-Force/gi, '').replace(/-Confirm:\$false/gi, '')
498
+ .replace(/\/s/gi, '').replace(/\/q/gi, '').trim();
582
499
  const trashDir = '$env:USERPROFILE\\.aicmd\\.trash';
583
500
  const ts = Date.now();
584
- const rewritten = `New-Item -ItemType Directory -Force -Path "${trashDir}" | Out-Null; Move-Item -Path ${targets} -Destination "${trashDir}\\_del_${ts}" -Force`;
585
- return { safe: true, rewritten };
501
+ return {
502
+ safe: true,
503
+ rewritten: `New-Item -ItemType Directory -Force -Path "${trashDir}" | Out-Null; Move-Item -Path ${targets} -Destination "${trashDir}\\_del_${ts}" -Force`,
504
+ };
586
505
  }
587
506
  }
588
-
589
507
  return { safe: true };
590
508
  }
591
509
 
592
- /**
593
- * 执行命令并捕获输出
594
- */
510
+ // ========== 工具执行 ==========
511
+
595
512
  private async executeCommand(command: string, sessionId: string, timeout: number): Promise<string> {
596
- if (!this.sshService) {
597
- return 'Error: SSH service not available';
598
- }
513
+ if (!this.sshService) return 'Error: SSH service not available';
599
514
  const session = this.sshService.getSession(sessionId);
600
- if (!session) {
601
- return `Error: Session ${sessionId} not found`;
602
- }
515
+ if (!session) return `Error: Session ${sessionId} not found`;
603
516
 
604
- // Safety check: block/rewrite dangerous commands
605
517
  const check = await this.sanitizeCommand(command, sessionId);
606
- if (!check.safe) {
607
- return check.reason!;
608
- }
518
+ if (!check.safe) return check.reason!;
609
519
  const actualCommand = check.rewritten || command;
610
- if (check.rewritten) {
611
- console.log(`[AIService] Safety: rewrote "${command}" -> "${actualCommand}"`);
612
- }
520
+ if (check.rewritten) console.log(`[AIService] Safety: rewrote "${command}" -> "${actualCommand}"`);
613
521
 
614
522
  try {
615
- // Start output capture
616
523
  const outputPromise = this.sshService.captureOutput(sessionId, timeout);
617
- // Write command
618
524
  this.sshService.writeData(sessionId, actualCommand + '\n');
619
- // Wait for output
620
525
  const output = await outputPromise;
621
526
 
622
- // Clean output: remove command echo and whitespace
623
527
  const lines = output.split('\n');
624
- if (lines.length > 0 && lines[0].trim().includes(actualCommand.trim().substring(0, 20))) {
625
- lines.shift();
626
- }
528
+ if (lines.length > 0 && lines[0].trim().includes(actualCommand.trim().substring(0, 20))) lines.shift();
627
529
  const cleanOutput = lines.join('\n').trim();
530
+ if (!cleanOutput) return '(Command executed, no output)';
628
531
 
629
- if (!cleanOutput) {
630
- return '(Command executed, no output)';
631
- }
632
-
633
- // Limit output length
634
532
  const maxLength = 5000;
635
533
  if (cleanOutput.length > maxLength) {
636
534
  return cleanOutput.substring(0, maxLength) + `\n... (output truncated, ${cleanOutput.length} chars total)`;
637
535
  }
638
-
639
536
  return cleanOutput;
640
537
  } catch (error: any) {
641
538
  return `Command execution failed: ${error.message}`;
642
539
  }
643
540
  }
644
541
 
645
- /**
646
- * 读取终端当前输出
647
- */
648
542
  private async readTerminal(sessionId: string): Promise<string> {
649
- if (!this.sshService) {
650
- return 'Error: SSH service not available';
651
- }
543
+ if (!this.sshService) return 'Error: SSH service not available';
652
544
  try {
653
545
  const output = await this.sshService.captureOutput(sessionId, 500);
654
- if (!output.trim()) {
655
- return '(No terminal output)';
656
- }
657
- const lines = output.split('\n').filter(l => l.trim());
658
- const last50 = lines.slice(-50);
659
- return last50.join('\n');
546
+ if (!output.trim()) return '(No terminal output)';
547
+ return output.split('\n').filter(l => l.trim()).slice(-50).join('\n');
660
548
  } catch (error: any) {
661
549
  return `Failed to read terminal: ${error.message}`;
662
550
  }
663
551
  }
664
552
 
665
- // ========== 对话历史 ==========
553
+ // ========== 系统环境上下文 ==========
554
+
555
+ private async getSessionContext(sessionId: string): Promise<string> {
556
+ if (!this.sshService) return '';
557
+ try { return await this.sshService.getSystemContext(sessionId); }
558
+ catch (error) { console.warn('[AIService] Failed to get system context:', error); return ''; }
559
+ }
560
+
561
+ // ========== Core → App 事件映射 ==========
562
+
563
+ private mapCoreEvent(event: CoreAgentEvent): AgentEvent | null {
564
+ switch (event.type) {
565
+ case 'thinking': return { type: 'thinking', content: event.content };
566
+ case 'tool_call': return { type: 'tool_call', tool: event.tool, args: event.args };
567
+ case 'tool_result': return { type: 'tool_result', tool: event.tool, result: event.result };
568
+ case 'message': return { type: 'message', content: event.content };
569
+ case 'done': return { type: 'done', content: event.content };
570
+ case 'error': return { type: 'error', error: event.error };
571
+ default: return null;
572
+ }
573
+ }
574
+
575
+ // ========== Agent 核心循环 ==========
666
576
 
667
- private getOrCreateHistory(sessionId: string): ChatHistory {
668
- let history = this.chatHistories.get(sessionId);
669
- if (!history) {
670
- // 首次访问,尝试从文件加载
671
- const saved = this.loadChatMessages(sessionId);
672
- history = {
577
+ async agentRun(
578
+ sessionId: string,
579
+ userMessage: string,
580
+ context: string | undefined,
581
+ eventCallback: AgentEventCallback,
582
+ skillId?: string,
583
+ locale?: string,
584
+ ): Promise<void> {
585
+ const engine = this.getEngine();
586
+ if (!engine) {
587
+ eventCallback({ type: 'error', error: 'API Key not configured. Please set it in AI settings.' });
588
+ return;
589
+ }
590
+
591
+ // 构建 system prompt 覆盖片段
592
+ let systemPromptOverride = '';
593
+
594
+ if (locale) {
595
+ const langName = locale.startsWith('zh') ? 'Chinese' : locale.startsWith('ja') ? 'Japanese' : locale.startsWith('ko') ? 'Korean' : 'English';
596
+ systemPromptOverride += `\n\n[User's UI language preference: ${langName} (${locale}). If the user's message language is ambiguous, prefer responding in ${langName}.]`;
597
+ }
598
+
599
+ const sysContext = await this.getSessionContext(sessionId);
600
+ if (sysContext && sysContext !== 'Failed to collect system info') {
601
+ systemPromptOverride += `\n\n${sysContext}`;
602
+ }
603
+
604
+ if (skillId && this.skillService) {
605
+ const skill = this.skillService.getSkill(skillId);
606
+ if (skill) {
607
+ systemPromptOverride += `\n\n## Current Task Instructions (Skill: ${skill.name})\n\n${skill.content}`;
608
+ }
609
+ }
610
+
611
+ // 加载并注入会话历史
612
+ const savedHistory = this.loadChatMessages(sessionId);
613
+ if (savedHistory && savedHistory.length > 0) {
614
+ engine.setHistory(sessionId, savedHistory);
615
+ }
616
+
617
+ // AbortController 管理
618
+ const ctrl = new AbortController();
619
+ this.abortControllers.set(sessionId, ctrl);
620
+
621
+ try {
622
+ const eventStream = engine.run({
673
623
  sessionId,
674
- messages: saved || [],
675
- lastActive: Date.now(),
676
- };
677
- this.chatHistories.set(sessionId, history);
678
- this.loadedSessions.add(sessionId);
624
+ message: userMessage,
625
+ context: context ? { sessionId, terminalOutput: context } : { sessionId },
626
+ abortSignal: ctrl.signal,
627
+ systemPromptOverride: systemPromptOverride || undefined,
628
+ skillId,
629
+ });
630
+
631
+ for await (const coreEvent of eventStream) {
632
+ const mapped = this.mapCoreEvent(coreEvent);
633
+ if (mapped) eventCallback(mapped);
634
+ }
635
+ } catch (error: any) {
636
+ eventCallback({ type: 'error', error: error.message || 'Agent runtime error' });
637
+ } finally {
638
+ this.abortControllers.delete(sessionId);
639
+ // 持久化 LLM 上下文消息
640
+ try {
641
+ const snapshot = engine.getHistorySnapshot(sessionId);
642
+ if (snapshot && snapshot.length > 0) this.saveChatMessages(sessionId, snapshot);
643
+ } catch { /* ignore */ }
679
644
  }
680
- history.lastActive = Date.now();
681
- return history;
682
645
  }
683
646
 
684
- private addMessage(history: ChatHistory, message: ChatMessage): void {
685
- history.messages.push(message);
686
- while (history.messages.length > this.MAX_MESSAGES) {
687
- history.messages.shift();
647
+ stopAgent(sessionId: string): boolean {
648
+ const ctrl = this.abortControllers.get(sessionId);
649
+ if (ctrl) {
650
+ ctrl.abort();
651
+ this.engine?.abort(sessionId);
652
+ return true;
688
653
  }
689
- // 持久化到文件
690
- this.saveChatMessages(history.sessionId, history.messages);
654
+ return false;
691
655
  }
692
656
 
657
+ // ========== 非 Agent 对话 ==========
658
+
659
+ async chat(sessionId: string, userMessage: string, context?: string): Promise<string> {
660
+ const provider = this.ensureLLMProvider();
661
+ if (!provider) throw new Error('API Key not configured. Please set it in AI settings.');
662
+
663
+ const history = this.loadChatMessages(sessionId) || [];
664
+ const messages: Message[] = [{ role: 'system', content: AGENT_SYSTEM_PROMPT }];
665
+ if (context) messages.push({ role: 'system', content: `Recent terminal output:\n\`\`\`\n${context}\n\`\`\`` });
666
+ messages.push(...history);
667
+ messages.push({ role: 'user', content: userMessage });
668
+ history.push({ role: 'user', content: userMessage });
669
+
670
+ try {
671
+ const response = await provider.chat({
672
+ messages,
673
+ maxTokens: this.config.maxTokens,
674
+ temperature: this.config.temperature,
675
+ });
676
+ const content = response.choices?.[0]?.message?.content;
677
+ if (content) {
678
+ history.push({ role: 'assistant', content });
679
+ this.saveChatMessages(sessionId, history);
680
+ return content;
681
+ }
682
+ throw new Error('AI response is empty');
683
+ } catch (error: any) {
684
+ history.pop();
685
+ throw new Error(error.response?.data?.error?.message || error.message || 'AI request failed');
686
+ }
687
+ }
688
+
689
+ async *chatStream(
690
+ sessionId: string,
691
+ userMessage: string,
692
+ context?: string,
693
+ ): AsyncGenerator<string, void, unknown> {
694
+ const provider = this.ensureLLMProvider();
695
+ if (!provider) throw new Error('API Key not configured. Please set it in AI settings.');
696
+
697
+ const history = this.loadChatMessages(sessionId) || [];
698
+ const messages: Message[] = [{ role: 'system', content: AGENT_SYSTEM_PROMPT }];
699
+ if (context) messages.push({ role: 'system', content: `Recent terminal output:\n\`\`\`\n${context}\n\`\`\`` });
700
+ messages.push(...history);
701
+ messages.push({ role: 'user', content: userMessage });
702
+ history.push({ role: 'user', content: userMessage });
703
+
704
+ let fullResponse = '';
705
+ try {
706
+ const stream = provider.chatStream({
707
+ messages,
708
+ maxTokens: this.config.maxTokens,
709
+ temperature: this.config.temperature,
710
+ });
711
+ for await (const chunk of stream) {
712
+ const content = chunk.delta?.content;
713
+ if (content) { fullResponse += content; yield content; }
714
+ }
715
+ if (fullResponse) {
716
+ history.push({ role: 'assistant', content: fullResponse });
717
+ this.saveChatMessages(sessionId, history);
718
+ }
719
+ } catch (error: any) {
720
+ history.pop();
721
+ throw new Error(error.response?.data?.error?.message || error.message || 'AI request failed');
722
+ }
723
+ }
724
+
725
+ // ========== LLM 上下文消息持久化 ==========
726
+
693
727
  clearHistory(sessionId: string): void {
694
- this.chatHistories.delete(sessionId);
695
728
  this.loadedSessions.delete(sessionId);
696
729
  this.deleteDisplayHistoryFile(sessionId);
697
730
  this.deleteChatMessagesFile(sessionId);
731
+ this.engine?.setHistory(sessionId, []);
698
732
  }
699
733
 
700
- getHistory(sessionId: string): ChatMessage[] | null {
701
- const history = this.chatHistories.get(sessionId);
702
- return history ? [...history.messages] : null;
734
+ getHistory(sessionId: string): Message[] | null {
735
+ return this.loadChatMessages(sessionId);
703
736
  }
704
737
 
705
- // ========== LLM 上下文消息持久化 ==========
706
-
707
- /**
708
- * 保存 LLM 上下文消息到 data/messages/{sessionId}.json
709
- */
710
- private saveChatMessages(sessionId: string, messages: ChatMessage[]): void {
738
+ private saveChatMessages(sessionId: string, messages: Message[]): void {
711
739
  try {
712
740
  ensureDir(this.messagesDir);
713
741
  const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, '_');
714
742
  const filePath = path.join(this.messagesDir, `${safe}.json`);
715
- const data = {
716
- sessionId,
717
- updatedAt: Date.now(),
718
- messages,
719
- };
720
- fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');
721
- } catch (_) {
722
- // 静默失败,不影响主流程
723
- }
743
+ fs.writeFileSync(filePath, JSON.stringify({ sessionId, updatedAt: Date.now(), messages }, null, 2), 'utf-8');
744
+ } catch { /* 静默失败 */ }
724
745
  }
725
746
 
726
- /**
727
- * 从 data/messages/{sessionId}.json 加载 LLM 上下文消息
728
- */
729
- private loadChatMessages(sessionId: string): ChatMessage[] | null {
747
+ private loadChatMessages(sessionId: string): Message[] | null {
730
748
  try {
731
749
  if (!fs.existsSync(this.messagesDir)) return null;
732
750
  const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, '_');
733
751
  const filePath = path.join(this.messagesDir, `${safe}.json`);
734
752
  if (!fs.existsSync(filePath)) return null;
735
- const raw = fs.readFileSync(filePath, 'utf-8');
736
- const data = JSON.parse(raw);
737
- if (data && Array.isArray(data.messages)) {
738
- return data.messages.length > this.MAX_MESSAGES
739
- ? data.messages.slice(data.messages.length - this.MAX_MESSAGES)
740
- : data.messages;
741
- }
753
+ const data = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
754
+ if (data && Array.isArray(data.messages)) return data.messages.slice(-this.MAX_MESSAGES);
742
755
  return null;
743
- } catch (_) {
744
- return null;
745
- }
756
+ } catch { return null; }
746
757
  }
747
758
 
748
- /**
749
- * 删除 LLM 上下文消息文件
750
- */
751
759
  private deleteChatMessagesFile(sessionId: string): void {
752
760
  try {
753
761
  const safe = sessionId.replace(/[^a-zA-Z0-9_-]/g, '_');
754
762
  const filePath = path.join(this.messagesDir, `${safe}.json`);
755
- if (fs.existsSync(filePath)) {
756
- fs.unlinkSync(filePath);
757
- }
758
- } catch (_) {
759
- // 静默失败
760
- }
763
+ if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
764
+ } catch { /* 静默失败 */ }
761
765
  }
762
766
 
763
767
  // ========== 对话历史持久化(前端显示) ==========
764
768
 
765
- /**
766
- * 保存前端显示消息到文件(含元数据)
767
- */
768
769
  saveDisplayHistory(sessionId: string, displayMessages: DisplayMessage[], sessionName?: string): void {
769
770
  try {
770
771
  const filePath = path.join(this.historyDir, `${sessionId}.json`);
771
772
  const firstUser = displayMessages.find(m => m.role === 'user');
772
773
  const preview = firstUser ? (firstUser.content || '').substring(0, 80) : '';
773
774
  const fileData: HistoryFile = {
774
- meta: {
775
- sessionId,
776
- sessionName: sessionName || '',
777
- savedAt: Date.now(),
778
- messageCount: displayMessages.length,
779
- preview,
780
- },
775
+ meta: { sessionId, sessionName: sessionName || '', savedAt: Date.now(), messageCount: displayMessages.length, preview },
781
776
  messages: displayMessages,
782
777
  };
783
778
  fs.writeFileSync(filePath, JSON.stringify(fileData, null, 2), 'utf-8');
784
- } catch (error) {
785
- console.error('[AIService] Failed to save display history:', error);
786
- }
779
+ } catch (error) { console.error('[AIService] Failed to save display history:', error); }
787
780
  }
788
781
 
789
- /**
790
- * 加载前端显示消息(兼容新旧格式)
791
- */
792
782
  loadDisplayHistory(sessionId: string): DisplayMessage[] | null {
793
783
  try {
794
784
  const filePath = path.join(this.historyDir, `${sessionId}.json`);
795
785
  if (!fs.existsSync(filePath)) return null;
796
- const raw = fs.readFileSync(filePath, 'utf-8');
797
- const data = JSON.parse(raw);
798
- if (data && Array.isArray(data.messages)) {
799
- return data.messages;
800
- }
786
+ const data = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
787
+ if (data && Array.isArray(data.messages)) return data.messages;
801
788
  if (Array.isArray(data)) return data;
802
789
  return null;
803
- } catch (error) {
804
- console.error('[AIService] Failed to load display history:', error);
805
- return null;
806
- }
790
+ } catch { return null; }
807
791
  }
808
792
 
809
- /**
810
- * 列出所有历史对话(仅元数据)
811
- */
812
793
  listDisplayHistories(): HistoryMeta[] {
813
794
  const results: HistoryMeta[] = [];
814
795
  try {
@@ -816,443 +797,33 @@ Response format (important):
816
797
  const files = fs.readdirSync(this.historyDir).filter(f => f.endsWith('.json'));
817
798
  for (const file of files) {
818
799
  try {
819
- const filePath = path.join(this.historyDir, file);
820
- const raw = fs.readFileSync(filePath, 'utf-8');
821
- const data = JSON.parse(raw);
800
+ const fp = path.join(this.historyDir, file);
801
+ const data = JSON.parse(fs.readFileSync(fp, 'utf-8'));
822
802
  if (data?.meta) {
823
803
  results.push(data.meta);
824
804
  } else if (Array.isArray(data)) {
825
- // 兼容旧格式(纯数组)
826
- const sessionId = path.basename(file, '.json');
805
+ const sid = path.basename(file, '.json');
827
806
  const firstUser = data.find((m: any) => m.role === 'user');
828
807
  results.push({
829
- sessionId,
830
- sessionName: '',
831
- savedAt: fs.statSync(filePath).mtimeMs,
808
+ sessionId: sid, sessionName: '',
809
+ savedAt: fs.statSync(fp).mtimeMs,
832
810
  messageCount: data.length,
833
811
  preview: firstUser ? (firstUser.content || '').substring(0, 80) : '',
834
812
  });
835
813
  }
836
- } catch (_) { /* 跳过损坏的文件 */ }
814
+ } catch { /* 跳过损坏的文件 */ }
837
815
  }
838
- } catch (error) {
839
- console.error('[AIService] Failed to list histories:', error);
840
- }
841
- // 按保存时间倒序
816
+ } catch (error) { console.error('[AIService] Failed to list histories:', error); }
842
817
  results.sort((a, b) => b.savedAt - a.savedAt);
843
818
  return results;
844
819
  }
845
820
 
846
- /**
847
- * 删除持久化的对话历史
848
- */
849
821
  deleteDisplayHistoryFile(sessionId: string): void {
850
822
  try {
851
823
  const filePath = path.join(this.historyDir, `${sessionId}.json`);
852
- if (fs.existsSync(filePath)) {
853
- fs.unlinkSync(filePath);
854
- }
855
- // 同步删除 LLM 上下文消息文件
824
+ if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
856
825
  this.deleteChatMessagesFile(sessionId);
857
- this.chatHistories.delete(sessionId);
858
826
  this.loadedSessions.delete(sessionId);
859
- } catch (error) {
860
- console.error('[AIService] Failed to delete display history:', error);
861
- }
862
- }
863
-
864
- // ========== 系统环境上下文 ==========
865
-
866
- /**
867
- * 获取会话的系统上下文(从 sshService 的 session 元数据获取)
868
- * 保证每次对话都带上系统环境信息
869
- */
870
- private async getSessionContext(sessionId: string): Promise<string> {
871
- if (!this.sshService) return '';
872
- try {
873
- return await this.sshService.getSystemContext(sessionId);
874
- } catch (error) {
875
- console.warn('[AIService] Failed to get system context:', error);
876
- return '';
877
- }
878
- }
879
-
880
- // ========== Agent 核心循环 ==========
881
-
882
- /**
883
- * 运行 Agent
884
- * Agent 循环:调用 LLM → 处理 tool_calls → 执行工具 → 反馈结果 → 重复直到完成
885
- */
886
- async agentRun(
887
- sessionId: string,
888
- userMessage: string,
889
- context: string | undefined,
890
- eventCallback: AgentEventCallback,
891
- skillId?: string,
892
- locale?: string
893
- ): Promise<void> {
894
- if (!this.config.apiKey) {
895
- eventCallback({ type: 'error', error: 'API Key not configured. Please set it in AI settings.' });
896
- return;
897
- }
898
-
899
- // Check for running agent
900
- const existingState = this.agentStates.get(sessionId);
901
- if (existingState?.running) {
902
- eventCallback({ type: 'error', error: 'Agent is already running. Please wait or stop it first.' });
903
- return;
904
- }
905
-
906
- // 设置运行状态
907
- const state: AgentRunState = { running: true, aborted: false };
908
- this.agentStates.set(sessionId, state);
909
-
910
- const history = this.getOrCreateHistory(sessionId);
911
- const tools = this.getToolDefinitions();
912
-
913
- // Build system prompt
914
- let systemPrompt = this.AGENT_SYSTEM_PROMPT;
915
-
916
- // Inject locale hint if provided (fallback when user language is ambiguous)
917
- if (locale) {
918
- const langName = locale.startsWith('zh') ? 'Chinese' : locale.startsWith('ja') ? 'Japanese' : locale.startsWith('ko') ? 'Korean' : 'English';
919
- systemPrompt += `\n\n[User's UI language preference: ${langName} (${locale}). If the user's message language is ambiguous, prefer responding in ${langName}.]`;
920
- }
921
-
922
- // Inject system environment context
923
- const sysContext = await this.getSessionContext(sessionId);
924
- if (sysContext && sysContext !== 'Failed to collect system info') {
925
- systemPrompt += `\n\n${sysContext}`;
926
- }
927
-
928
- // If Skill is provided, append Skill instructions
929
- if (skillId && this.skillService) {
930
- const skill = this.skillService.getSkill(skillId);
931
- if (skill) {
932
- systemPrompt += `\n\n## Current Task Instructions (Skill: ${skill.name})\n\n${skill.content}`;
933
- }
934
- }
935
-
936
- // 构建消息列表
937
- const messages: ChatMessage[] = [
938
- { role: 'system', content: systemPrompt },
939
- ];
940
-
941
- // Add terminal context
942
- if (context) {
943
- messages.push({
944
- role: 'system',
945
- content: `Recent terminal output:\n\`\`\`\n${context}\n\`\`\``,
946
- });
947
- }
948
-
949
- // 添加历史消息
950
- messages.push(...history.messages);
951
-
952
- // 添加用户消息
953
- const userMsg: ChatMessage = { role: 'user', content: userMessage };
954
- this.addMessage(history, userMsg);
955
- messages.push(userMsg);
956
-
957
- try {
958
- for (let iteration = 0; iteration < this.MAX_AGENT_ITERATIONS; iteration++) {
959
- // Check if aborted
960
- if (state.aborted) {
961
- eventCallback({ type: 'done', content: '(Agent stopped by user)' });
962
- break;
963
- }
964
-
965
- eventCallback({ type: 'thinking' });
966
-
967
- // 调用 LLM
968
- let response;
969
- try {
970
- response = await this.callLLM(messages, tools);
971
- } catch (error: any) {
972
- eventCallback({ type: 'error', error: `LLM call failed: ${error.message}` });
973
- break;
974
- }
975
-
976
- const assistantMessage = response.choices?.[0]?.message;
977
- if (!assistantMessage) {
978
- eventCallback({ type: 'error', error: 'LLM response is empty' });
979
- break;
980
- }
981
-
982
- // 添加 assistant 消息到历史
983
- const assistantMsg: ChatMessage = {
984
- role: 'assistant',
985
- content: assistantMessage.content,
986
- };
987
- if (assistantMessage.tool_calls?.length) {
988
- assistantMsg.tool_calls = assistantMessage.tool_calls;
989
- }
990
- this.addMessage(history, assistantMsg);
991
- messages.push(assistantMsg);
992
-
993
- // 如果有文本内容,推送给用户
994
- if (assistantMessage.content) {
995
- eventCallback({ type: 'message', content: assistantMessage.content });
996
- }
997
-
998
- // 如果没有 tool_calls,Agent 完成
999
- if (!assistantMessage.tool_calls || assistantMessage.tool_calls.length === 0) {
1000
- eventCallback({ type: 'done' });
1001
- break;
1002
- }
1003
-
1004
- // 处理 tool_calls
1005
- for (const toolCall of assistantMessage.tool_calls) {
1006
- if (state.aborted) break;
1007
-
1008
- const toolName = toolCall.function.name;
1009
- let toolArgs: any = {};
1010
- try {
1011
- toolArgs = JSON.parse(toolCall.function.arguments || '{}');
1012
- } catch {
1013
- toolArgs = {};
1014
- }
1015
-
1016
- // 推送工具调用事件
1017
- eventCallback({ type: 'tool_call', tool: toolName, args: toolArgs });
1018
-
1019
- // 审计:记录工具调用开始时间
1020
- const toolStartTime = Date.now();
1021
-
1022
- // 执行工具
1023
- const tool = this.toolRegistry.get(toolName);
1024
- let result: string;
1025
- let toolStatus: AuditEntry['status'] = 'success';
1026
- if (!tool) {
1027
- result = `Error: Unknown tool "${toolName}"`;
1028
- toolStatus = 'error';
1029
- } else {
1030
- try {
1031
- result = await tool.executor(toolArgs, sessionId);
1032
- if (result.startsWith('Error:') || result.startsWith('Tool execution failed:')) {
1033
- toolStatus = 'error';
1034
- }
1035
- } catch (error: any) {
1036
- result = `Tool execution failed: ${error.message}`;
1037
- toolStatus = 'error';
1038
- }
1039
- }
1040
-
1041
- // 审计:记录工具执行结果
1042
- if (this.auditService) {
1043
- const command = toolName === 'execute_command' ? (toolArgs.command || '') : JSON.stringify(toolArgs);
1044
- try {
1045
- const auditEntry = this.auditService.log({
1046
- sessionId,
1047
- sessionName: this.sshService?.getSession(sessionId)?.name,
1048
- connectionId: this.sshService?.getSession(sessionId)?.connectionId,
1049
- userMessage,
1050
- tool: toolName,
1051
- command,
1052
- result: result.substring(0, 5000), // 截断过长输出
1053
- duration: Date.now() - toolStartTime,
1054
- status: toolStatus,
1055
- });
1056
- // 推送审计事件给前端
1057
- eventCallback({ type: 'audit_entry', auditEntry });
1058
- } catch { /* 审计失败不影响主流程 */ }
1059
- }
1060
-
1061
- // 推送工具结果事件
1062
- eventCallback({ type: 'tool_result', tool: toolName, result });
1063
-
1064
- // 添加工具结果到消息列表
1065
- const toolMsg: ChatMessage = {
1066
- role: 'tool',
1067
- content: result,
1068
- tool_call_id: toolCall.id,
1069
- };
1070
- messages.push(toolMsg);
1071
- this.addMessage(history, toolMsg);
1072
- }
1073
-
1074
- // Last iteration with remaining tool_calls
1075
- if (iteration === this.MAX_AGENT_ITERATIONS - 1) {
1076
- eventCallback({ type: 'done', content: 'Max iterations reached' });
1077
- }
1078
- }
1079
- } catch (error: any) {
1080
- eventCallback({ type: 'error', error: error.message || 'Agent runtime error' });
1081
- } finally {
1082
- state.running = false;
1083
- this.agentStates.delete(sessionId);
1084
- }
1085
- }
1086
-
1087
- /**
1088
- * 停止 Agent
1089
- */
1090
- stopAgent(sessionId: string): boolean {
1091
- const state = this.agentStates.get(sessionId);
1092
- if (state?.running) {
1093
- state.aborted = true;
1094
- return true;
1095
- }
1096
- return false;
1097
- }
1098
-
1099
- /**
1100
- * 调用 OpenAI API(非流式,用于 Agent 循环)
1101
- */
1102
- private async callLLM(messages: ChatMessage[], tools: ToolDefinition[]): Promise<any> {
1103
- const requestBody: any = {
1104
- model: this.config.model,
1105
- messages,
1106
- max_tokens: this.config.maxTokens || 4000,
1107
- temperature: this.config.temperature || 0.3,
1108
- };
1109
-
1110
- // 只有注册了工具才传 tools 参数
1111
- if (tools.length > 0) {
1112
- requestBody.tools = tools;
1113
- requestBody.tool_choice = 'auto';
1114
- }
1115
-
1116
- const response = await axios.post(
1117
- `${this.config.baseUrl}/chat/completions`,
1118
- requestBody,
1119
- {
1120
- headers: {
1121
- 'Authorization': `Bearer ${this.config.apiKey}`,
1122
- 'Content-Type': 'application/json',
1123
- },
1124
- timeout: 120000, // Agent 需要更长的超时
1125
- }
1126
- );
1127
-
1128
- return response.data;
1129
- }
1130
-
1131
- // ========== 旧版兼容(非 Agent 模式的简单对话) ==========
1132
-
1133
- async chat(sessionId: string, userMessage: string, context?: string): Promise<string> {
1134
- if (!this.config.apiKey) {
1135
- throw new Error('API Key not configured. Please set it in AI settings.');
1136
- }
1137
-
1138
- const history = this.getOrCreateHistory(sessionId);
1139
- const messages: ChatMessage[] = [
1140
- { role: 'system', content: this.AGENT_SYSTEM_PROMPT },
1141
- ];
1142
-
1143
- if (context) {
1144
- messages.push({
1145
- role: 'system',
1146
- content: `Recent terminal output:\n\`\`\`\n${context}\n\`\`\``,
1147
- });
1148
- }
1149
-
1150
- messages.push(...history.messages);
1151
- this.addMessage(history, { role: 'user', content: userMessage });
1152
- messages.push({ role: 'user', content: userMessage });
1153
-
1154
- try {
1155
- const response = await axios.post(
1156
- `${this.config.baseUrl}/chat/completions`,
1157
- {
1158
- model: this.config.model,
1159
- messages,
1160
- max_tokens: this.config.maxTokens || 4000,
1161
- temperature: this.config.temperature || 0.3,
1162
- },
1163
- {
1164
- headers: {
1165
- 'Authorization': `Bearer ${this.config.apiKey}`,
1166
- 'Content-Type': 'application/json',
1167
- },
1168
- timeout: 60000,
1169
- }
1170
- );
1171
-
1172
- const assistantMessage = response.data?.choices?.[0]?.message?.content;
1173
- if (assistantMessage) {
1174
- this.addMessage(history, { role: 'assistant', content: assistantMessage });
1175
- return assistantMessage;
1176
- }
1177
- throw new Error('AI response is empty');
1178
- } catch (error: any) {
1179
- history.messages.pop();
1180
- const message = error.response?.data?.error?.message || error.message || 'AI request failed';
1181
- throw new Error(message);
1182
- }
1183
- }
1184
-
1185
- async *chatStream(
1186
- sessionId: string,
1187
- userMessage: string,
1188
- context?: string
1189
- ): AsyncGenerator<string, void, unknown> {
1190
- if (!this.config.apiKey) {
1191
- throw new Error('API Key not configured. Please set it in AI settings.');
1192
- }
1193
-
1194
- const history = this.getOrCreateHistory(sessionId);
1195
- const messages: ChatMessage[] = [
1196
- { role: 'system', content: this.AGENT_SYSTEM_PROMPT },
1197
- ];
1198
-
1199
- if (context) {
1200
- messages.push({
1201
- role: 'system',
1202
- content: `Recent terminal output:\n\`\`\`\n${context}\n\`\`\``,
1203
- });
1204
- }
1205
-
1206
- messages.push(...history.messages);
1207
- this.addMessage(history, { role: 'user', content: userMessage });
1208
- messages.push({ role: 'user', content: userMessage });
1209
-
1210
- let fullResponse = '';
1211
- try {
1212
- const response = await axios.post(
1213
- `${this.config.baseUrl}/chat/completions`,
1214
- {
1215
- model: this.config.model,
1216
- messages,
1217
- max_tokens: this.config.maxTokens || 4000,
1218
- temperature: this.config.temperature || 0.3,
1219
- stream: true,
1220
- },
1221
- {
1222
- headers: {
1223
- 'Authorization': `Bearer ${this.config.apiKey}`,
1224
- 'Content-Type': 'application/json',
1225
- },
1226
- responseType: 'stream',
1227
- timeout: 60000,
1228
- }
1229
- );
1230
-
1231
- for await (const chunk of response.data) {
1232
- const lines = chunk.toString().split('\n');
1233
- for (const line of lines) {
1234
- if (line.startsWith('data: ')) {
1235
- const data = line.slice(6).trim();
1236
- if (data === '[DONE]') break;
1237
- try {
1238
- const parsed = JSON.parse(data);
1239
- const content = parsed.choices?.[0]?.delta?.content;
1240
- if (content) {
1241
- fullResponse += content;
1242
- yield content;
1243
- }
1244
- } catch { /* ignore */ }
1245
- }
1246
- }
1247
- }
1248
-
1249
- if (fullResponse) {
1250
- this.addMessage(history, { role: 'assistant', content: fullResponse });
1251
- }
1252
- } catch (error: any) {
1253
- history.messages.pop();
1254
- const message = error.response?.data?.error?.message || error.message || 'AI request failed';
1255
- throw new Error(message);
1256
- }
827
+ } catch (error) { console.error('[AIService] Failed to delete display history:', error); }
1257
828
  }
1258
829
  }