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