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