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