pi-web-ui 0.105.0 → 0.106.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +58 -1
  2. package/README.md +193 -797
  3. package/README.zh-CN.md +186 -625
  4. package/README.zh-TW.md +781 -0
  5. package/bin/frp-manager.mjs +1488 -0
  6. package/bin/pi-web-ui.mjs +27 -0
  7. package/deploy/nginx-subpath.conf +16 -1
  8. package/dist/server/agent-service-daemon.js +34 -0
  9. package/dist/server/agent-service.js +227 -44
  10. package/dist/server/claim-files-tool.js +8 -1
  11. package/dist/server/client-state.js +146 -32
  12. package/dist/server/conversation-read-tool.js +12 -4
  13. package/dist/server/delegate-task.js +9 -1
  14. package/dist/server/dispatch-domain-handlers.js +15 -0
  15. package/dist/server/dsh/dsh-agent-service.js +838 -241
  16. package/dist/server/dsh/dsh-client.js +59 -18
  17. package/dist/server/dsh/dsh-market-service.js +233 -0
  18. package/dist/server/dsh/dsh-serialize.js +11 -3
  19. package/dist/server/dsh/dsh-sessions.js +64 -2
  20. package/dist/server/dsh/preset-clones.js +12 -1
  21. package/dist/server/dsh/runtime/goal-rpc.mjs +183 -45
  22. package/dist/server/engine-capabilities.js +72 -0
  23. package/dist/server/engine-probe.js +243 -0
  24. package/dist/server/goal-service.js +23 -12
  25. package/dist/server/i18n.js +20 -1
  26. package/dist/server/index.js +171 -66
  27. package/dist/server/locales.js +1 -0
  28. package/dist/server/mcp-agent-tool.js +10 -7
  29. package/dist/server/mcp-bridge.js +428 -24
  30. package/dist/server/model-admin.js +172 -74
  31. package/dist/server/model-resolver.js +221 -0
  32. package/dist/server/plugin-installer.js +4 -2
  33. package/dist/server/plugins.js +71 -11
  34. package/dist/server/present-files-tool.js +10 -2
  35. package/dist/server/preset-fields.js +14 -0
  36. package/dist/server/preset-share.js +2 -0
  37. package/dist/server/protocol-version.js +1 -1
  38. package/dist/server/schedule-agent-tool.js +2 -1
  39. package/dist/server/scm-commitmsg.js +3 -2
  40. package/dist/server/settings-service.js +10 -2
  41. package/dist/server/skill-discovery.js +161 -0
  42. package/dist/server/skill-tool.js +2 -1
  43. package/dist/server/slash-commands.js +154 -73
  44. package/dist/server/subagent-templates-hant.js +215 -0
  45. package/dist/server/subagent-templates.js +49 -2
  46. package/dist/server/subagents.js +22 -12
  47. package/dist/server/terminals.js +2 -2
  48. package/dist/server/tool-manager.js +3 -0
  49. package/dist/server/universal/driver-base.js +56 -0
  50. package/dist/server/universal/drivers/claude-code.js +462 -0
  51. package/dist/server/universal/drivers/dsh-driver.js +376 -0
  52. package/dist/server/universal/drivers/mock-driver.js +103 -0
  53. package/dist/server/universal/index.js +10 -0
  54. package/dist/server/universal/session-store.js +100 -0
  55. package/dist/server/universal/universal-attachments.js +175 -0
  56. package/dist/server/universal/universal-service.js +149 -0
  57. package/dist/server/universal/universal-session.js +2610 -0
  58. package/dist/server/universal/universal-types.js +4 -0
  59. package/dist/server/update-check.js +4 -1
  60. package/dist/server/worktree-service.js +1 -1
  61. package/dist/server/worktree-tool.js +9 -7
  62. package/package.json +3 -2
  63. package/plugin-sdk/index.d.ts +12 -2
  64. package/plugins/catalog.json +39 -5
  65. package/themes/dark-teal.css +20 -23
  66. package/themes/md-preview.css +1 -2
  67. package/themes/wallpaper-obsidian.css +693 -0
  68. package/web/dist/assets/{TerminalPanel-B9exeXrl.js → TerminalPanel-CfxKLDW9.js} +2 -2
  69. package/web/dist/assets/index-BtcP6BDk.css +1 -0
  70. package/web/dist/assets/index-XVtCzcHR.js +690 -0
  71. package/web/dist/index.html +2 -2
  72. package/web/dist/sw.js +1 -1
  73. package/web/dist/assets/index-BQC6lADz.css +0 -1
  74. package/web/dist/assets/index-D79IKG33.js +0 -690
@@ -0,0 +1,2610 @@
1
+ /**
2
+ * universal-session.ts — 通用 Agent 会话控制器(实现 DispatchSession)。
3
+ *
4
+ * 职责:
5
+ * 1. 桥接 BaseAgentDriver 与 Web 前端 Wire 协议;
6
+ * 2. 自动维护严格线性的 UiMessage[] 历史与流式 streamingMessage;
7
+ * 3. 60ms 节流下发 snapshot / message_delta,实现高帧率低开销的前端流式渲染;
8
+ * 4. 无缝复用宿主 FilesService(文件树/预览/SCM/上传)、TerminalManager(终端)与 BgServerTracker(后台服务)。
9
+ */
10
+ import { randomUUID } from "node:crypto";
11
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { FilesService } from "../files-service.js";
15
+ import { TerminalManager, makePersistentTerminalTools, TERMINAL_TOOLS_GUIDANCE } from "../terminals.js";
16
+ import { TERMINAL_TOOL_NAMES } from "../tool-manager.js";
17
+ import { BgServerTracker } from "../bg-servers.js";
18
+ import { ModelAdminService } from "../model-admin.js";
19
+ import { WebUIContext } from "../webui-context.js";
20
+ import { ClaudeCodeDriver, probeClaudeCode } from "./drivers/claude-code.js";
21
+ import { normalizeUiLayout, settingsPresetToUi } from "../client-state.js";
22
+ import { readModelsJson } from "../model-resolver.js";
23
+ import { DEFAULT_UNIVERSAL_CAPABILITIES } from "../engine-capabilities.js";
24
+ import { unsupportedToolInfo } from "../tool-info.js";
25
+ import { SandboxManager } from "../sandbox-service.js";
26
+ import { getWorktreeContext, removeWorktree } from "../worktree-service.js";
27
+ import { MarkerService } from "../marker-service.js";
28
+ import { SlashCommandsService, parseSlash } from "../slash-commands.js";
29
+ import { discoverDiskSkills, readSkillInstruction } from "../skill-discovery.js";
30
+ import { scanAtMentions, createAttachmentUiMessages, formatPromptWithSkills } from "./universal-attachments.js";
31
+ import { scmCommitContext } from "../scm.js";
32
+ import { buildCommitMsgInput, sanitizeCommitMessage } from "../scm-commitmsg.js";
33
+ import { getAppVersion } from "../pkg-info.js";
34
+ import { SubagentTemplatesStore, DEFAULT_TEMPLATES, pickTemplatePrompt, } from "../subagent-templates.js";
35
+ import { subagentTitle, isSubagentTerminal, computeWaitCapMs, makeSubagentTools, } from "../subagents.js";
36
+ import { recordSubagentHandoff, formatSubagentHandoffMessage, } from "../subagent-handoff.js";
37
+ import { pick } from "../i18n.js";
38
+ import { fetchRemoteSkillMarket, fetchRemoteSkillContent, fetchRemoteMcpMarket } from "../market-service.js";
39
+ import { exportPresetVia, importPresetVia, importPresetFromUrlVia, pushPresetCatalogVia, sharePresetVia, } from "../preset-share.js";
40
+ const SNAPSHOT_INTERVAL_MS = 60;
41
+ export class UniversalSession {
42
+ cwd;
43
+ clientId;
44
+ sinks = new Set();
45
+ store;
46
+ stateStore;
47
+ driver;
48
+ sandboxes;
49
+ markerSvc;
50
+ worktreeInfo = null;
51
+ dataDir;
52
+ files;
53
+ terminals;
54
+ bg;
55
+ modelAdmin;
56
+ agentDir;
57
+ slash;
58
+ pluginCommandsProvider;
59
+ onQuit;
60
+ subagentTemplates;
61
+ skillsCache = [];
62
+ disposed = false;
63
+ rev = 1;
64
+ version = 1;
65
+ activeConvId;
66
+ conversations = new Map();
67
+ isStreaming = false;
68
+ streamingMessage = null;
69
+ streamingThinking = "";
70
+ streamingText = "";
71
+ deltaSeq = 0;
72
+ snapshotTimer = null;
73
+ pendingToolResults = [];
74
+ sessionDrafts = new Map();
75
+ followUpQueue = [];
76
+ engine;
77
+ currentModel = "claude-3-7-sonnet-20250219";
78
+ thinkingLevel = "medium";
79
+ lang = "zh";
80
+ modelsMap = new Map();
81
+ driverFactory;
82
+ subagentDrivers = new Map();
83
+ subagentHandoffs = [];
84
+ subagentWaitListeners = new Set();
85
+ subagentHost;
86
+ webUi;
87
+ constructor(opts) {
88
+ this.clientId = opts.clientId;
89
+ this.cwd = opts.cwd;
90
+ this.dataDir = opts.dataDir ?? opts.stateStore?.dataDir ?? "";
91
+ this.agentDir = opts.agentDir ?? process.env.PI_CODING_AGENT_DIR ?? "";
92
+ this.engine = opts.engine ?? (opts.driver.id === "claude-code" ? "claude" : opts.driver.id);
93
+ this.sinks.add(opts.send);
94
+ this.store = opts.store;
95
+ this.stateStore = opts.stateStore;
96
+ this.driver = opts.driver;
97
+ this.driverFactory = opts.driverFactory;
98
+ this.pluginCommandsProvider = opts.pluginCommandsProvider;
99
+ this.onQuit = opts.onQuit;
100
+ this.sandboxes = new SandboxManager(this.dataDir);
101
+ void this.refreshWorktreeInfo();
102
+ this.lang = opts.lang ?? "zh";
103
+ this.webUi = new WebUIContext((msg) => this.send(msg));
104
+ const templatesPath = join(this.dataDir || process.env.PI_WEB_DATA_DIR || join(homedir(), ".pi-web"), "subagent-templates.json");
105
+ this.subagentTemplates = new SubagentTemplatesStore(templatesPath);
106
+ this.subagentHost = {
107
+ spawnSubagent: async (prompt, type, cwd, templateName, model, parentId, persist) => {
108
+ const { convId } = await this.spawnSubagent(prompt, type, cwd, templateName, model, parentId, persist);
109
+ return convId;
110
+ },
111
+ getSubagent: (convId) => {
112
+ const conv = this.conversations.get(convId);
113
+ if (!conv || !conv.isSubagent)
114
+ return undefined;
115
+ return this.subagentToSnapshot(conv);
116
+ },
117
+ listSubagents: (scope) => this.listSubagents(scope),
118
+ steerSubagent: (convId, message) => this.steerSubagent(convId, message),
119
+ stopSubagent: (convId) => this.stopSubagent(convId),
120
+ listTemplates: () => this.subagentTemplates
121
+ .list()
122
+ .filter((t) => t.enabled !== false)
123
+ .map((t) => ({
124
+ name: t.name,
125
+ description: t.description,
126
+ descriptionEn: t.descriptionEn,
127
+ model: t.model,
128
+ thinkingLevel: t.thinkingLevel,
129
+ })),
130
+ isTemplateUsable: (name) => {
131
+ const t = this.subagentTemplates.get(name);
132
+ return !!t && t.enabled !== false;
133
+ },
134
+ getWatchdogTimeoutMs: () => 20 * 60_000,
135
+ handoffSubagent: (fromRunId, toRunId, payload) => this.handoffSubagent(fromRunId, toRunId, payload),
136
+ lang: () => this.lang,
137
+ };
138
+ this.slash = new SlashCommandsService({
139
+ emit: (msg) => this.send(msg),
140
+ cwd: () => this.cwd,
141
+ newChat: () => this.newChat(),
142
+ prompt: (text) => this.prompt(text),
143
+ setModel: (id) => this.setModel(id),
144
+ setCwd: (path) => this.setCwd(path),
145
+ setThinking: (level) => this.setThinking(level),
146
+ renameSession: async (name) => {
147
+ await this.renameConversation(this.activeConvId, name);
148
+ this.emitNotice("info", `已重命名当前会话为「${name}」`, `Renamed current session to "${name}"`);
149
+ },
150
+ getSessionName: () => this.activeConv.title,
151
+ refreshSessions: () => this.refreshSessions(),
152
+ onQuit: () => this.onQuit?.() ?? false,
153
+ getModel: () => this.resolveCurrentModelInfo(),
154
+ getAvailableModels: async () => this.listAvailableModelsForSlash(),
155
+ getSkills: async () => this.collectUniversalSkills(),
156
+ getExtraCommands: async () => {
157
+ const driverCmds = this.driver.getSlashCommands ? await this.driver.getSlashCommands() : [];
158
+ const subagentCmd = {
159
+ name: "subagent",
160
+ description: this.lang === "zh"
161
+ ? "派发后台异步轻量子代理执行任务(用法: /subagent <提示词>)"
162
+ : "Spawn a background subagent to execute a task (/subagent <prompt>)",
163
+ argumentHint: "<提示词>",
164
+ argumentHintEn: "<prompt>",
165
+ source: "builtin",
166
+ };
167
+ return [subagentCmd, ...driverCmds];
168
+ },
169
+ execExtraCommand: async (name, args) => this.driver.execSlashCommand
170
+ ? await this.driver.execSlashCommand(name, args, {
171
+ emitNotice: (lvl, txt, txtEn) => this.emitNotice(lvl, txt, txtEn),
172
+ })
173
+ : false,
174
+ compact: async (args) => {
175
+ await this.compactActiveConversation(args);
176
+ },
177
+ reload: async () => {
178
+ await this.reloadSessionResources();
179
+ },
180
+ pluginCommands: () => this.pluginCommandsProvider?.() ?? [],
181
+ execPluginCommand: async (name, args) => {
182
+ const def = this.pluginCommandsProvider?.().find((c) => c.name === name);
183
+ if (!def)
184
+ return false;
185
+ try {
186
+ const result = await def.run(args, {
187
+ clientId: this.clientId,
188
+ uiContext: this.webUi,
189
+ webUi: this.webUi,
190
+ });
191
+ if (typeof result === "string" && result.trim()) {
192
+ this.emitNotice("info", result, result);
193
+ }
194
+ }
195
+ catch (err) {
196
+ const msg = err.message;
197
+ this.emitNotice("error", `插件命令 /${name} 执行失败:${msg}`, `Plugin command /${name} failed: ${msg}`);
198
+ }
199
+ return true;
200
+ },
201
+ });
202
+ const markerStateStore = this.stateStore ??
203
+ {
204
+ getMarkerSettings: () => ({ markersEnabled: true, disabledMarkers: [] }),
205
+ saveMarkerSettings: () => { },
206
+ };
207
+ this.markerSvc = new MarkerService({
208
+ clientId: this.clientId,
209
+ stateStore: markerStateStore,
210
+ emit: (msg) => this.send(msg),
211
+ isDisposed: () => this.disposed,
212
+ getActiveConversationId: () => this.activeConvId,
213
+ getSessionManager: () => undefined,
214
+ renameConversation: (convId, title) => {
215
+ void this.renameConversation(convId, title);
216
+ },
217
+ refreshMarkers: () => this.flushSnapshot(),
218
+ onActionsChange: (convId) => {
219
+ if (convId === this.activeConvId)
220
+ this.flushSnapshot();
221
+ },
222
+ lang: () => this.getLang(),
223
+ });
224
+ if (opts.driver.id === "claude-code") {
225
+ this.currentModel = "claude-3-7-sonnet-20250219";
226
+ this.seedDefaultClaudeModels();
227
+ }
228
+ else if (opts.driver.id === "dsh") {
229
+ this.currentModel = "deepseek/deepseek-v4-flash";
230
+ this.thinkingLevel = "high";
231
+ this.seedDefaultDshModels();
232
+ }
233
+ else {
234
+ this.currentModel = opts.driver.currentModel ?? "default";
235
+ }
236
+ // 恢复上次使用的模型(按引擎独立记录:项目记忆优先 > 全局默认)
237
+ const savedModel = opts.stateStore?.getProjectModel(opts.clientId, opts.cwd, this.engine) ??
238
+ opts.stateStore?.getDefaultModel(this.engine);
239
+ if (savedModel) {
240
+ this.currentModel = savedModel;
241
+ }
242
+ this.modelAdmin = new ModelAdminService({
243
+ agentDir: this.agentDir,
244
+ emit: (msg) => this.send(msg),
245
+ flushSnapshot: () => this.flushSnapshot(),
246
+ isDisposed: () => this.disposed,
247
+ pushModels: async () => this.listModels(),
248
+ });
249
+ this.files = new FilesService({
250
+ emit: (msg) => this.send(msg),
251
+ isDisposed: () => this.disposed,
252
+ getCwd: () => this.cwd,
253
+ getActiveCwd: () => this.cwd,
254
+ });
255
+ this.terminals = new TerminalManager((msg) => this.send(msg), this.cwd, () => this.getLang());
256
+ this.bg = new BgServerTracker({
257
+ emit: (msg) => this.send(msg),
258
+ flushSnapshot: () => this.flushSnapshot(),
259
+ isDisposed: () => this.disposed,
260
+ pluginTasks: () => [],
261
+ cleanupMinutes: () => 0,
262
+ });
263
+ // 加载现有会话或创建初始会话
264
+ const existing = this.store.listConversations(this.cwd);
265
+ if (existing.length > 0) {
266
+ for (const conv of existing) {
267
+ this.conversations.set(conv.id, conv);
268
+ }
269
+ this.activeConvId = existing[0].id;
270
+ }
271
+ else {
272
+ const initialConv = this.createEmptyConversation("新对话");
273
+ this.activeConvId = initialConv.id;
274
+ this.conversations.set(initialConv.id, initialConv);
275
+ this.store.saveConversation(this.cwd, initialConv);
276
+ }
277
+ // 若驱动为 Claude Code,异步探测环境并下发安装指引
278
+ if (this.driver instanceof ClaudeCodeDriver) {
279
+ void probeClaudeCode().then((probe) => {
280
+ if (!probe.installed && !this.disposed) {
281
+ this.emitNotice("warning", "未检测到全局安装的 Claude Code CLI。请在终端执行 npm i -g @anthropic-ai/claude-code 安装并运行 claude 登录。", "Claude Code CLI not found; run: npm i -g @anthropic-ai/claude-code and log in with claude.");
282
+ }
283
+ });
284
+ }
285
+ }
286
+ seedDefaultClaudeModels() {
287
+ const defaults = [
288
+ { id: "claude-3-7-sonnet-20250219", name: "Claude 3.7 Sonnet" },
289
+ { id: "claude-3-5-sonnet-20241022", name: "Claude 3.5 Sonnet" },
290
+ { id: "claude-3-5-haiku-20241022", name: "Claude 3.5 Haiku" },
291
+ { id: "claude-3-opus-20240229", name: "Claude 3 Opus" },
292
+ ];
293
+ for (const d of defaults) {
294
+ const canonicalId = `${this.driver.id}/${d.id}`;
295
+ const entry = { id: d.id, name: d.name, provider: this.driver.id, vision: true };
296
+ this.modelsMap.set(canonicalId, entry);
297
+ this.modelsMap.set(d.id, entry);
298
+ }
299
+ }
300
+ seedDefaultDshModels() {
301
+ const defaults = [
302
+ { id: "deepseek-v4-flash", name: "DeepSeek V4 Flash", vision: false },
303
+ { id: "deepseek-v4-pro", name: "DeepSeek V4 Pro", vision: false },
304
+ { id: "deepseek-v4-flash-vision-exp", name: "DeepSeek V4 Flash Vision (exp)", vision: true },
305
+ ];
306
+ for (const d of defaults) {
307
+ const canonicalId = `deepseek/${d.id}`;
308
+ const entry = { id: d.id, name: d.name, provider: "deepseek", vision: d.vision };
309
+ this.modelsMap.set(canonicalId, entry);
310
+ this.modelsMap.set(d.id, entry);
311
+ }
312
+ }
313
+ resolveCurrentModelInfo() {
314
+ const found = this.modelsMap.get(this.currentModel);
315
+ if (found)
316
+ return found;
317
+ if (this.currentModel.includes("/")) {
318
+ const slash = this.currentModel.indexOf("/");
319
+ const provider = this.currentModel.slice(0, slash);
320
+ const bareId = this.currentModel.slice(slash + 1);
321
+ return {
322
+ id: bareId,
323
+ name: bareId,
324
+ provider,
325
+ vision: true,
326
+ };
327
+ }
328
+ return {
329
+ id: this.currentModel,
330
+ name: this.currentModel === "claude-3-7-sonnet-20250219"
331
+ ? "Claude 3.7 Sonnet"
332
+ : this.currentModel === "deepseek-v4-flash"
333
+ ? "DeepSeek V4 Flash"
334
+ : this.currentModel,
335
+ provider: this.driver.id === "dsh" ? "deepseek" : this.driver.id,
336
+ vision: true,
337
+ };
338
+ }
339
+ resolveCurrentModelContextWindow() {
340
+ const { providers } = readModelsJson(this.agentDir);
341
+ for (const p of Object.values(providers)) {
342
+ if (Array.isArray(p.models)) {
343
+ for (const m of p.models) {
344
+ const row = m;
345
+ if (typeof row.id === "string" &&
346
+ (row.id === this.currentModel || this.currentModel.endsWith(`/${row.id}`))) {
347
+ if (typeof row.contextWindow === "number" && row.contextWindow > 0) {
348
+ return row.contextWindow;
349
+ }
350
+ }
351
+ }
352
+ }
353
+ }
354
+ return 200_000;
355
+ }
356
+ get activeConv() {
357
+ let conv = this.conversations.get(this.activeConvId);
358
+ if (!conv) {
359
+ conv = this.createEmptyConversation("新对话");
360
+ this.activeConvId = conv.id;
361
+ this.conversations.set(conv.id, conv);
362
+ }
363
+ return conv;
364
+ }
365
+ createEmptyConversation(title, ephemeral = false) {
366
+ const now = Date.now();
367
+ return {
368
+ id: `uconv-${now}-${randomUUID().slice(0, 8)}`,
369
+ title,
370
+ createdAt: now,
371
+ updatedAt: now,
372
+ messages: [],
373
+ isEphemeral: Boolean(ephemeral),
374
+ stats: {
375
+ tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
376
+ cost: 0,
377
+ contextUsage: { tokens: null, contextWindow: this.resolveCurrentModelContextWindow(), percent: null },
378
+ },
379
+ };
380
+ }
381
+ attachSink(send) {
382
+ this.sinks.add(send);
383
+ this.pushSettings();
384
+ void this.pushSlashCommands();
385
+ const defModel = this.stateStore?.getDefaultModel(this.engine);
386
+ if (defModel) {
387
+ send({ type: "default_model", modelId: defModel });
388
+ }
389
+ const terminals = this.terminals.list();
390
+ if (terminals.length > 0) {
391
+ this.send({ type: "terminal_list", conversationId: this.activeConvId, terminals });
392
+ }
393
+ this.bg.push();
394
+ void this.refreshSessions();
395
+ }
396
+ detachSink(send) {
397
+ this.sinks.delete(send);
398
+ }
399
+ sinkCount() {
400
+ return this.sinks.size;
401
+ }
402
+ send(msg) {
403
+ for (const sink of this.sinks) {
404
+ try {
405
+ sink(msg);
406
+ }
407
+ catch {
408
+ /* ignore send error on broken pipe */
409
+ }
410
+ }
411
+ }
412
+ flushSnapshot(_forceFull = false) {
413
+ if (this.disposed)
414
+ return;
415
+ this.rev++;
416
+ this.version++;
417
+ const conv = this.activeConv;
418
+ const curModel = this.resolveCurrentModelInfo();
419
+ const win = this.resolveCurrentModelContextWindow();
420
+ const convStats = conv.stats ?? {
421
+ tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
422
+ cost: 0,
423
+ contextUsage: { tokens: null, contextWindow: win, percent: null },
424
+ };
425
+ const contextUsage = {
426
+ ...convStats.contextUsage,
427
+ contextWindow: win,
428
+ percent: convStats.contextUsage.tokens !== null && win > 0
429
+ ? Math.min(100, Math.round((convStats.contextUsage.tokens / win) * 100))
430
+ : null,
431
+ };
432
+ const state = {
433
+ clientId: this.clientId,
434
+ cwd: this.cwd,
435
+ sessionId: conv.id,
436
+ sessionFile: conv.id,
437
+ conversationId: conv.id,
438
+ rev: this.rev,
439
+ messages: conv.messages,
440
+ streamingMessage: this.streamingMessage,
441
+ isStreaming: this.isStreaming,
442
+ isEphemeral: Boolean(conv.isEphemeral),
443
+ draft: this.sessionDrafts.get(conv.id) ?? null,
444
+ model: {
445
+ id: curModel.id,
446
+ name: curModel.name,
447
+ provider: curModel.provider,
448
+ vision: curModel.vision,
449
+ },
450
+ thinkingLevel: this.thinkingLevel,
451
+ availableThinkingLevels: ["off", "low", "medium", "high"],
452
+ queue: {
453
+ steering: [],
454
+ followUp: this.followUpQueue.map((q) => q.text),
455
+ },
456
+ tools: [],
457
+ version: this.version,
458
+ engineCapabilities: this.driver.getEngineCapabilities?.() ?? DEFAULT_UNIVERSAL_CAPABILITIES,
459
+ sandbox: this.sandboxes.getByCwd(this.cwd) ?? null,
460
+ worktree: this.worktreeInfo,
461
+ workspaceRoots: this.stateStore?.getWorkspaceRoots(this.clientId, this.cwd) ?? [],
462
+ actionSuggestions: this.markerSvc.getActionSuggestions(conv.id) ?? null,
463
+ subagentHandoffs: this.subagentHandoffs.length > 0 ? [...this.subagentHandoffs] : undefined,
464
+ piConfigured: true,
465
+ piAgentInstalled: true,
466
+ stats: {
467
+ totalMessages: conv.messages.length,
468
+ tokens: convStats.tokens,
469
+ cost: convStats.cost,
470
+ contextUsage,
471
+ },
472
+ };
473
+ this.send({ type: "snapshot", state });
474
+ }
475
+ getCapabilities() {
476
+ return this.driver.getEngineCapabilities?.() ?? DEFAULT_UNIVERSAL_CAPABILITIES;
477
+ }
478
+ scheduleThrottledSnapshot() {
479
+ if (this.snapshotTimer)
480
+ return;
481
+ this.snapshotTimer = setTimeout(() => {
482
+ this.snapshotTimer = null;
483
+ this.flushSnapshot();
484
+ }, SNAPSHOT_INTERVAL_MS);
485
+ }
486
+ // ---------------------------------------------------------------------------
487
+ // 核心 Prompt 流程
488
+ // ---------------------------------------------------------------------------
489
+ static isDefaultTitle(title) {
490
+ const t = (title ?? "").trim();
491
+ return !t || t === "新对话" || t === "New chat" || t === "New Chat" || t === "对话" || t === "Chat";
492
+ }
493
+ async prompt(text, attachments, _queue) {
494
+ if (this.isStreaming) {
495
+ if (_queue === true) {
496
+ this.followUpQueue.push({ text, attachments });
497
+ this.flushSnapshot();
498
+ this.emitNotice("info", "已加入排队,将在当前回复生成完成后自动发送", "Queued — will send after current response settles");
499
+ return;
500
+ }
501
+ // 插队(steer):中断当前轮次并提交新问题
502
+ this.emitNotice("info", "正在插队,中断当前生成并提交新问题...", "Steering: aborting current turn and submitting prompt...");
503
+ await this.abort();
504
+ }
505
+ // 1. 拦截与执行斜杠命令(内置 / 插件 / 驱动扩展 / 技能指令 / 子代理命令)
506
+ const slash = parseSlash(text);
507
+ if (slash) {
508
+ if (slash.name === "subagent" || slash.name.startsWith("subagent:")) {
509
+ const type = slash.name.startsWith("subagent:") ? slash.name.slice(9) : "general";
510
+ const subPrompt = slash.args.trim();
511
+ if (!subPrompt) {
512
+ this.emitNotice("warning", "请提供子代理的任务指令,如 /subagent 探索当前代码库", "Please provide a prompt for the subagent, e.g. /subagent explore code repository");
513
+ return;
514
+ }
515
+ try {
516
+ const { convId } = await this.spawnSubagent(subPrompt, type, this.cwd);
517
+ this.emitNotice("info", `已派发子代理(ID: ${convId.slice(0, 8)}),可在左侧对话列表查看其流式进展`, `Spawned subagent (${convId.slice(0, 8)}). Track its progress in the left conversation list`);
518
+ }
519
+ catch (err) {
520
+ const msg = err instanceof Error ? err.message : String(err);
521
+ this.emitNotice("error", `派发子代理失败: ${msg}`, `Failed to spawn subagent: ${msg}`);
522
+ }
523
+ return;
524
+ }
525
+ if (slash.name.startsWith("skill:")) {
526
+ const skillName = slash.name.slice(6);
527
+ const skills = await this.collectUniversalSkills();
528
+ const found = skills.find((s) => s.name.toLowerCase() === skillName.toLowerCase() ||
529
+ `skill:${s.name}`.toLowerCase() === slash.name.toLowerCase());
530
+ if (found) {
531
+ const instruction = readSkillInstruction(found.filePath);
532
+ const skillPrompt = instruction
533
+ ? `[Skill: ${found.name}]\n${instruction}\n\n[User Prompt]\n${slash.args || "执行此技能"}`
534
+ : slash.args || text;
535
+ return this.prompt(skillPrompt, attachments, _queue);
536
+ }
537
+ }
538
+ const handled = await this.slash.exec(slash.name, slash.args);
539
+ if (handled)
540
+ return;
541
+ }
542
+ this.isStreaming = true;
543
+ const conv = this.activeConv;
544
+ const now = Date.now();
545
+ // 2. 扫描用户文本中的 @ 提及(文件路径与技能指令)
546
+ const availableSkills = await this.collectUniversalSkills();
547
+ const scanResult = scanAtMentions(text, this.cwd, availableSkills, attachments ?? []);
548
+ const effectiveAttachments = [...(attachments ?? []), ...scanResult.detectedAttachments];
549
+ const finalPrompt = formatPromptWithSkills(text, scanResult.detectedSkills);
550
+ // 3. 自动根据首条提问为新会话命名(首条提问立即刷新左侧栏运行与历史列表)
551
+ const hasNoUserMessages = !conv.messages.some((m) => m.role === "user");
552
+ if (UniversalSession.isDefaultTitle(conv.title) && hasNoUserMessages && text.trim()) {
553
+ const trimmed = text.trim().replace(/\s+/g, " ");
554
+ const cleanTitle = trimmed.length > 30 ? `${trimmed.slice(0, 30)}…` : trimmed;
555
+ conv.title = cleanTitle;
556
+ if (this.stateStore) {
557
+ this.stateStore.saveSessionTitle(this.cwd, conv.id, cleanTitle);
558
+ }
559
+ if (!conv.isEphemeral) {
560
+ this.store.saveConversation(this.cwd, conv);
561
+ }
562
+ void this.refreshSessions();
563
+ }
564
+ // 4. 插入用户消息以及附件卡片(保证 Web UI 附件卡片折叠呈现与历史复原)
565
+ const userMsg = {
566
+ id: `u-${now}-${randomUUID().slice(0, 6)}`,
567
+ role: "user",
568
+ content: [{ type: "text", text }],
569
+ timestamp: now,
570
+ };
571
+ conv.messages.push(userMsg);
572
+ if (effectiveAttachments.length > 0) {
573
+ const attCards = createAttachmentUiMessages(effectiveAttachments, now);
574
+ for (const card of attCards) {
575
+ conv.messages.push(card);
576
+ }
577
+ }
578
+ conv.updatedAt = now;
579
+ if (!conv.isEphemeral) {
580
+ this.store.saveConversation(this.cwd, conv);
581
+ }
582
+ // 用户发送了提示词,消费并清除当前会话的草稿
583
+ this.sessionDrafts.delete(conv.id);
584
+ // 确保底层驱动与当前对话的 driverSessionId 上下文同步(保证多轮对话连续且新建对话隔离)
585
+ if (conv.driverSessionId) {
586
+ await this.driver.resumeSession(conv.driverSessionId);
587
+ }
588
+ else {
589
+ const sid = await this.driver.createSession();
590
+ conv.driverSessionId = sid;
591
+ if (!conv.isEphemeral) {
592
+ this.store.saveConversation(this.cwd, conv);
593
+ }
594
+ }
595
+ // 3. 准备助手流式消息
596
+ const assistantMsgId = `a-${now}-${randomUUID().slice(0, 6)}`;
597
+ this.streamingThinking = "";
598
+ this.streamingText = "";
599
+ this.streamingMessage = {
600
+ id: assistantMsgId,
601
+ role: "assistant",
602
+ content: [],
603
+ timestamp: now,
604
+ model: this.currentModel,
605
+ };
606
+ this.flushSnapshot();
607
+ // 4. 构建 AgentEventSink(时序保真:思考 -> 前置正文 -> 工具调用 -> 总结正文)
608
+ const sink = {
609
+ onThinkingDelta: (delta) => {
610
+ this.streamingThinking += delta;
611
+ if (!this.streamingMessage)
612
+ return;
613
+ let thinkBlock = this.streamingMessage.content.find((b) => b.type === "thinking");
614
+ if (!thinkBlock) {
615
+ thinkBlock = { type: "thinking", thinking: "" };
616
+ this.streamingMessage.content.unshift(thinkBlock);
617
+ }
618
+ thinkBlock.thinking = this.streamingThinking;
619
+ this.emitDelta({ type: "thinking_delta", delta });
620
+ this.scheduleThrottledSnapshot();
621
+ },
622
+ onTextDelta: (delta) => {
623
+ this.streamingText += delta;
624
+ if (!this.streamingMessage)
625
+ return;
626
+ const lastBlock = this.streamingMessage.content[this.streamingMessage.content.length - 1];
627
+ if (lastBlock && lastBlock.type === "text" && !lastBlock.truncated) {
628
+ lastBlock.text += delta;
629
+ }
630
+ else {
631
+ this.streamingMessage.content.push({ type: "text", text: delta });
632
+ }
633
+ this.emitDelta({ type: "text_delta", delta });
634
+ this.scheduleThrottledSnapshot();
635
+ },
636
+ onToolStart: (callId, toolName, args) => {
637
+ if (!this.streamingMessage)
638
+ return;
639
+ const toolBlock = {
640
+ type: "toolCall",
641
+ id: callId,
642
+ name: toolName,
643
+ argumentsText: JSON.stringify(args, null, 2),
644
+ };
645
+ this.streamingMessage.content.push(toolBlock);
646
+ this.scheduleThrottledSnapshot();
647
+ },
648
+ onToolEnd: (callId, result) => {
649
+ const toolMsg = {
650
+ id: `t-${callId}`,
651
+ role: "toolResult",
652
+ toolCallId: callId,
653
+ content: [{ type: "text", text: result.output ?? result.error ?? "" }],
654
+ isError: Boolean(result.error),
655
+ timestamp: Date.now(),
656
+ };
657
+ this.pendingToolResults.push(toolMsg);
658
+ this.scheduleThrottledSnapshot();
659
+ },
660
+ onTurnComplete: (meta) => {
661
+ this.finalizeTurn(meta);
662
+ },
663
+ onError: (err) => {
664
+ const errText = typeof err === "string" ? err : err.message;
665
+ this.emitNotice("error", `执行出错: ${errText}`, `Execution error: ${errText}`);
666
+ this.finalizeTurn();
667
+ },
668
+ };
669
+ try {
670
+ await this.driver.sendPrompt(finalPrompt, effectiveAttachments, sink);
671
+ }
672
+ catch (err) {
673
+ const msg = err instanceof Error ? err.message : String(err);
674
+ this.emitNotice("error", `驱动执行异常: ${msg}`, `Driver execution error: ${msg}`);
675
+ this.finalizeTurn();
676
+ }
677
+ }
678
+ updateStreamingContent() {
679
+ if (!this.streamingMessage)
680
+ return;
681
+ const content = [];
682
+ if (this.streamingThinking) {
683
+ content.push({ type: "thinking", thinking: this.streamingThinking });
684
+ }
685
+ if (this.streamingText) {
686
+ content.push({ type: "text", text: this.streamingText });
687
+ }
688
+ // 保留之前追加的 toolCall blocks
689
+ for (const b of this.streamingMessage.content) {
690
+ if (b.type === "toolCall") {
691
+ content.push(b);
692
+ }
693
+ }
694
+ this.streamingMessage.content = content;
695
+ }
696
+ emitDelta(assistantMessageEvent) {
697
+ if (!this.streamingMessage)
698
+ return;
699
+ this.send({
700
+ type: "message_delta",
701
+ conversationId: this.activeConvId,
702
+ seq: ++this.deltaSeq,
703
+ messageId: this.streamingMessage.id,
704
+ usage: null,
705
+ assistantMessageEvent,
706
+ });
707
+ }
708
+ finalizeTurn(meta) {
709
+ if (this.snapshotTimer) {
710
+ clearTimeout(this.snapshotTimer);
711
+ this.snapshotTimer = null;
712
+ }
713
+ if (this.streamingMessage) {
714
+ this.activeConv.messages.push(this.streamingMessage);
715
+ this.streamingMessage = null;
716
+ }
717
+ if (this.pendingToolResults.length > 0) {
718
+ this.activeConv.messages.push(...this.pendingToolResults);
719
+ this.pendingToolResults = [];
720
+ }
721
+ // 累计会话统计与上下文占用(底座统一驱动底栏上下文环、Token 计数、缓存命中率与累计成本)
722
+ const conv = this.activeConv;
723
+ if (!conv.stats) {
724
+ conv.stats = {
725
+ tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
726
+ cost: 0,
727
+ contextUsage: { tokens: null, contextWindow: this.resolveCurrentModelContextWindow(), percent: null },
728
+ };
729
+ }
730
+ if (meta?.usage) {
731
+ const u = meta.usage;
732
+ conv.stats.tokens.input += u.inputTokens ?? 0;
733
+ conv.stats.tokens.output += u.outputTokens ?? 0;
734
+ conv.stats.tokens.cacheRead += u.cacheReadTokens ?? 0;
735
+ conv.stats.tokens.cacheWrite += u.cacheWriteTokens ?? 0;
736
+ conv.stats.tokens.total = conv.stats.tokens.input + conv.stats.tokens.output;
737
+ const turnCost = meta.costUSD ?? u.costUSD ?? 0;
738
+ conv.stats.cost += turnCost;
739
+ const win = meta.contextWindow ?? u.contextWindow ?? this.resolveCurrentModelContextWindow();
740
+ const promptTokens = (u.inputTokens ?? 0) + (u.cacheReadTokens ?? 0) + (u.cacheWriteTokens ?? 0);
741
+ const turnOutput = u.outputTokens ?? 0;
742
+ const totalCtx = meta.contextTokens ?? u.contextTokens ?? (promptTokens > 0 ? promptTokens + turnOutput : null);
743
+ conv.stats.contextUsage = {
744
+ tokens: totalCtx,
745
+ contextWindow: win,
746
+ percent: totalCtx !== null && win > 0 ? Math.min(100, Math.round((totalCtx / win) * 100)) : null,
747
+ };
748
+ }
749
+ // 回写 Claude 分配的 session ID(保证多轮上下文连续)
750
+ if (typeof this.driver.getActiveSessionId === "function") {
751
+ const activeSid = this.driver.getActiveSessionId();
752
+ if (activeSid && this.activeConv.driverSessionId !== activeSid) {
753
+ this.activeConv.driverSessionId = activeSid;
754
+ }
755
+ }
756
+ this.isStreaming = false;
757
+ this.streamingThinking = "";
758
+ this.streamingText = "";
759
+ this.activeConv.updatedAt = Date.now();
760
+ if (!this.activeConv.isEphemeral) {
761
+ this.store.saveConversation(this.cwd, this.activeConv);
762
+ }
763
+ // 解析本轮生成的内联标记(如 [[conv:rename:...]] / [[action:suggest:...]])
764
+ if (this.streamingText && this.streamingText.includes("[[")) {
765
+ void this.markerSvc.handleAssistantText(this.activeConv.id, this.streamingText);
766
+ }
767
+ this.flushSnapshot();
768
+ void this.refreshSessions();
769
+ // 检查排队消息并自动处理
770
+ if (this.followUpQueue.length > 0) {
771
+ const next = this.followUpQueue.shift();
772
+ this.flushSnapshot(true);
773
+ void this.prompt(next.text, next.attachments);
774
+ }
775
+ }
776
+ async abort() {
777
+ if (this.isStreaming) {
778
+ await this.driver.abort();
779
+ this.finalizeTurn();
780
+ this.emitNotice("info", "已停止生成", "Generation stopped");
781
+ }
782
+ }
783
+ async abortBash() {
784
+ await this.abort();
785
+ }
786
+ async retryLast() {
787
+ const conv = this.activeConv;
788
+ // 找到最后一条 user 消息重新发送
789
+ for (let i = conv.messages.length - 1; i >= 0; i--) {
790
+ const m = conv.messages[i];
791
+ if (m.role === "user") {
792
+ const textBlock = m.content.find((b) => b.type === "text");
793
+ if (textBlock && "text" in textBlock && typeof textBlock.text === "string") {
794
+ await this.prompt(textBlock.text);
795
+ return;
796
+ }
797
+ }
798
+ }
799
+ }
800
+ removeQueued() {
801
+ /* 通用底座暂无插队队列 */
802
+ }
803
+ // ---------------------------------------------------------------------------
804
+ // 对话生命周期
805
+ // ---------------------------------------------------------------------------
806
+ async newChat(_preset, ephemeral = false) {
807
+ const newConv = this.createEmptyConversation("新对话", Boolean(ephemeral));
808
+ this.conversations.set(newConv.id, newConv);
809
+ this.activeConvId = newConv.id;
810
+ if (!newConv.isEphemeral) {
811
+ this.store.saveConversation(this.cwd, newConv);
812
+ }
813
+ this.flushSnapshot(true);
814
+ void this.refreshSessions();
815
+ return true;
816
+ }
817
+ async switchConversation(id) {
818
+ let conv = this.conversations.get(id);
819
+ if (!conv) {
820
+ conv = this.store.loadConversation(this.cwd, id) ?? undefined;
821
+ if (conv)
822
+ this.conversations.set(conv.id, conv);
823
+ }
824
+ if (conv) {
825
+ this.activeConvId = conv.id;
826
+ }
827
+ else {
828
+ this.emitNotice("warning", "未能找到目标会话,已保持在当前对话", "Target conversation not found, staying on current conversation");
829
+ }
830
+ this.flushSnapshot(true);
831
+ }
832
+ async switchSession(path, sessionId) {
833
+ const targetId = sessionId || path;
834
+ if (targetId) {
835
+ await this.switchConversation(targetId);
836
+ }
837
+ else {
838
+ this.flushSnapshot(true);
839
+ }
840
+ this.send({
841
+ type: "transition_progress",
842
+ kind: "session",
843
+ target: path,
844
+ phase: "done",
845
+ progress: 100,
846
+ text: "会话加载完成",
847
+ textEn: "Session loaded",
848
+ });
849
+ }
850
+ async renameConversation(id, name) {
851
+ const trimmed = (name ?? "").trim();
852
+ if (!trimmed)
853
+ return;
854
+ const conv = this.conversations.get(id);
855
+ if (conv) {
856
+ conv.title = trimmed;
857
+ conv.updatedAt = Date.now();
858
+ if (!conv.isEphemeral) {
859
+ this.store.saveConversation(this.cwd, conv);
860
+ }
861
+ if (this.stateStore) {
862
+ this.stateStore.saveSessionTitle(this.cwd, id, trimmed);
863
+ }
864
+ this.flushSnapshot();
865
+ void this.refreshSessions();
866
+ }
867
+ }
868
+ async renameSession(path, name) {
869
+ const trimmed = (name ?? "").trim();
870
+ if (!trimmed)
871
+ return;
872
+ const id = path.trim() || this.activeConvId;
873
+ const conv = this.conversations.get(id) ?? (this.activeConvId === id ? this.activeConv : null);
874
+ if (conv) {
875
+ conv.title = trimmed;
876
+ conv.updatedAt = Date.now();
877
+ if (!conv.isEphemeral) {
878
+ this.store.saveConversation(this.cwd, conv);
879
+ }
880
+ this.flushSnapshot();
881
+ void this.refreshSessions();
882
+ }
883
+ }
884
+ async deleteSession(path) {
885
+ await this.dismissConversation(path);
886
+ }
887
+ async dismissConversation(id, withFinishedSubagents = false, force = false) {
888
+ const conv = this.conversations.get(id);
889
+ if (!conv)
890
+ return;
891
+ // 若指定 withFinishedSubagents,级联清理该父会话下的已结束子代理
892
+ if (withFinishedSubagents) {
893
+ const kids = Array.from(this.conversations.values()).filter((c) => c.isSubagent && c.subagentParentId === id && !c.subagentStreaming);
894
+ for (const kid of kids) {
895
+ await this.dismissConversation(kid.id, false, force);
896
+ }
897
+ }
898
+ // 若清理的本身是运行中的子代理,立即中止并清理其驱动
899
+ if (conv.isSubagent && conv.subagentStreaming) {
900
+ await this.stopSubagent(id);
901
+ }
902
+ if (!conv.isEphemeral) {
903
+ this.store.deleteConversation(this.cwd, id);
904
+ }
905
+ this.conversations.delete(id);
906
+ this.sessionDrafts.delete(id);
907
+ if (this.activeConvId === id) {
908
+ const nonSubagents = Array.from(this.conversations.values()).filter((c) => !c.isSubagent);
909
+ if (nonSubagents.length > 0) {
910
+ this.activeConvId = nonSubagents[0].id;
911
+ }
912
+ else {
913
+ const anyRemaining = Array.from(this.conversations.values());
914
+ if (anyRemaining.length > 0) {
915
+ this.activeConvId = anyRemaining[0].id;
916
+ }
917
+ else {
918
+ await this.newChat();
919
+ return;
920
+ }
921
+ }
922
+ }
923
+ this.flushSnapshot();
924
+ void this.refreshSessions();
925
+ }
926
+ async dismissFinishedSubagents(parentId) {
927
+ const targets = Array.from(this.conversations.values()).filter((c) => c.isSubagent && !c.subagentStreaming && (!parentId || c.subagentParentId === parentId));
928
+ for (const t of targets) {
929
+ await this.dismissConversation(t.id, false, true);
930
+ }
931
+ }
932
+ async pinSession(path, pinned) {
933
+ const targetId = path.trim() || this.activeConvId;
934
+ await this.setConversationPinned(targetId, pinned);
935
+ }
936
+ async setConversationPinned(id, pinned) {
937
+ const conv = this.conversations.get(id);
938
+ if (conv) {
939
+ conv.pinned = pinned;
940
+ if (!conv.isEphemeral) {
941
+ this.store.pinConversation(this.cwd, id, pinned);
942
+ }
943
+ if (this.stateStore) {
944
+ this.stateStore.setSessionPinned(this.cwd, id, pinned);
945
+ }
946
+ this.flushSnapshot();
947
+ void this.refreshSessions();
948
+ }
949
+ }
950
+ saveDraft(sessionId, text, ts) {
951
+ if (!text) {
952
+ this.sessionDrafts.delete(sessionId);
953
+ }
954
+ else {
955
+ this.sessionDrafts.set(sessionId, { text, ts: ts || Date.now() });
956
+ }
957
+ }
958
+ async rollbackSession(messageId, conversationId, _restoreWorkspace) {
959
+ let targetConv = conversationId
960
+ ? (this.conversations.get(conversationId) ?? this.store.loadConversation(this.cwd, conversationId) ?? undefined)
961
+ : undefined;
962
+ if (!targetConv) {
963
+ targetConv = this.activeConv;
964
+ }
965
+ const idx = targetConv.messages.findIndex((m) => m.id === messageId);
966
+ if (idx < 0) {
967
+ this.emitNotice("error", "找不到指定的回滚目标消息", "Rollback target message not found");
968
+ this.flushSnapshot();
969
+ return;
970
+ }
971
+ // 回滚截断到该消息之前
972
+ targetConv.messages = targetConv.messages.slice(0, idx);
973
+ targetConv.updatedAt = Date.now();
974
+ if (!targetConv.isEphemeral) {
975
+ this.store.saveConversation(this.cwd, targetConv);
976
+ }
977
+ this.flushSnapshot(true);
978
+ void this.refreshSessions();
979
+ this.emitNotice("info", "已回滚到指定历史位置", "Rolled back to message");
980
+ }
981
+ async persistConversation(id) {
982
+ const conv = this.conversations.get(id) ?? (this.activeConvId === id ? this.activeConv : null);
983
+ if (!conv) {
984
+ this.emitNotice("warning", "该对话不存在或已关闭", "This conversation does not exist or is already closed");
985
+ return;
986
+ }
987
+ if (!conv.isEphemeral) {
988
+ this.emitNotice("info", `对话「${conv.title}」已是持久化对话,无需固化`, `Conversation "${conv.title}" is already persistent`);
989
+ return;
990
+ }
991
+ conv.isEphemeral = false;
992
+ conv.updatedAt = Date.now();
993
+ this.store.saveConversation(this.cwd, conv);
994
+ this.flushSnapshot(true);
995
+ void this.refreshSessions();
996
+ this.emitNotice("info", `临时对话「${conv.title}」已转为正式对话`, `Ephemeral conversation "${conv.title}" persisted`);
997
+ }
998
+ async forkSession(messageId, position = "before", targetConvId) {
999
+ let targetConv = targetConvId
1000
+ ? (this.conversations.get(targetConvId) ?? this.store.loadConversation(this.cwd, targetConvId) ?? undefined)
1001
+ : undefined;
1002
+ if (!targetConv) {
1003
+ targetConv = this.activeConv;
1004
+ }
1005
+ const idx = targetConv.messages.findIndex((m) => m.id === messageId);
1006
+ if (idx < 0) {
1007
+ this.emitNotice("error", "找不到指定的消息节点(可能不在当前分支)", "Message node to fork from not found");
1008
+ this.flushSnapshot();
1009
+ return;
1010
+ }
1011
+ const count = position === "at" ? idx + 1 : idx;
1012
+ const forkedMessages = structuredClone(targetConv.messages.slice(0, count));
1013
+ const forkedConv = this.createEmptyConversation(`${targetConv.title} (分支)`, Boolean(targetConv.isEphemeral));
1014
+ forkedConv.messages = forkedMessages;
1015
+ if (forkedMessages.length > 0) {
1016
+ forkedConv.updatedAt = Date.now();
1017
+ }
1018
+ this.conversations.set(forkedConv.id, forkedConv);
1019
+ if (!forkedConv.isEphemeral) {
1020
+ this.store.saveConversation(this.cwd, forkedConv);
1021
+ }
1022
+ this.activeConvId = forkedConv.id;
1023
+ this.flushSnapshot(true);
1024
+ void this.refreshSessions();
1025
+ this.emitNotice("info", "已从指定消息分叉新会话", "Forked new session from message");
1026
+ }
1027
+ async editMessage(messageId, text, attachments) {
1028
+ if (this.isStreaming) {
1029
+ this.emitNotice("warning", "当前轮次正在生成中,请等待完成或点击停止", "Generation in progress, please wait or abort");
1030
+ return;
1031
+ }
1032
+ const trimmed = text.trim();
1033
+ const hasAttachments = Boolean(attachments && attachments.length > 0);
1034
+ if (!trimmed && !hasAttachments) {
1035
+ this.emitNotice("warning", "编辑内容为空,已取消", "Edited content is empty — cancelled");
1036
+ this.flushSnapshot();
1037
+ return;
1038
+ }
1039
+ const conv = this.activeConv;
1040
+ const idx = conv.messages.findIndex((m) => m.id === messageId);
1041
+ if (idx < 0) {
1042
+ this.emitNotice("warning", "找不到要编辑的消息", "Message to edit not found");
1043
+ this.flushSnapshot();
1044
+ return;
1045
+ }
1046
+ // 截断到编辑点之前的所有历史消息,fork 一个新的 UniversalConversation
1047
+ const headMessages = structuredClone(conv.messages.slice(0, idx));
1048
+ const forkedConv = this.createEmptyConversation(conv.title, Boolean(conv.isEphemeral));
1049
+ forkedConv.messages = headMessages;
1050
+ if (headMessages.length > 0) {
1051
+ forkedConv.updatedAt = Date.now();
1052
+ }
1053
+ this.conversations.set(forkedConv.id, forkedConv);
1054
+ if (!forkedConv.isEphemeral) {
1055
+ this.store.saveConversation(this.cwd, forkedConv);
1056
+ }
1057
+ this.activeConvId = forkedConv.id;
1058
+ this.flushSnapshot(true);
1059
+ void this.refreshSessions();
1060
+ // 将编辑后的内容作为新 prompt 投递执行,实现无缝编辑重试
1061
+ await this.prompt(text, attachments);
1062
+ }
1063
+ async refreshSessions() {
1064
+ const memoryConvs = Array.from(this.conversations.values());
1065
+ const diskConvs = this.store.listConversations(this.cwd);
1066
+ const convMap = new Map();
1067
+ for (const c of diskConvs) {
1068
+ convMap.set(c.id, c);
1069
+ }
1070
+ for (const c of memoryConvs) {
1071
+ convMap.set(c.id, c);
1072
+ }
1073
+ for (const c of convMap.values()) {
1074
+ const savedTitle = this.stateStore?.getSessionTitle(this.cwd, c.id);
1075
+ if (savedTitle && !UniversalSession.isDefaultTitle(savedTitle)) {
1076
+ c.title = savedTitle;
1077
+ }
1078
+ }
1079
+ const allList = Array.from(convMap.values()).sort((a, b) => b.updatedAt - a.updatedAt);
1080
+ const convs = allList.map((c) => ({
1081
+ id: c.id,
1082
+ title: c.title,
1083
+ updatedAt: c.updatedAt,
1084
+ createdAt: c.createdAt,
1085
+ pinned: Boolean(c.pinned),
1086
+ sessionPath: c.id,
1087
+ active: c.id === this.activeConvId,
1088
+ cwd: this.cwd,
1089
+ messageCount: c.messages.length,
1090
+ isStreaming: Boolean(c.id === this.activeConvId ? this.isStreaming : c.subagentStreaming),
1091
+ isSubagent: Boolean(c.isSubagent),
1092
+ subagentType: c.subagentType,
1093
+ subagentParentId: c.subagentParentId,
1094
+ subagentState: c.subagentState,
1095
+ subagentStreaming: c.subagentStreaming,
1096
+ subagentError: c.subagentError,
1097
+ subagentCanceled: c.subagentCanceled,
1098
+ isEphemeral: Boolean(c.isEphemeral),
1099
+ }));
1100
+ this.send({ type: "conversations", conversations: convs, activeId: this.activeConvId });
1101
+ // 左侧栏历史对话读取的是 sessions 消息(轻量临时子代理不污染长期历史列表):
1102
+ const sessionSummaries = allList
1103
+ .filter((c) => !c.isSubagent || !c.isEphemeral)
1104
+ .map((c) => {
1105
+ const firstUser = c.messages.find((m) => m.role === "user");
1106
+ const firstText = firstUser?.content.find((b) => b.type === "text");
1107
+ const firstMsg = firstText && "text" in firstText && typeof firstText.text === "string"
1108
+ ? firstText.text
1109
+ : c.title;
1110
+ const displayName = this.resolveSessionDisplayName(c, firstMsg);
1111
+ return {
1112
+ path: c.id,
1113
+ sessionId: c.id,
1114
+ name: c.title,
1115
+ displayName,
1116
+ firstMessage: firstMsg,
1117
+ messageCount: c.messages.length,
1118
+ modified: c.updatedAt,
1119
+ pinned: Boolean(c.pinned),
1120
+ };
1121
+ });
1122
+ this.send({ type: "sessions", sessions: sessionSummaries });
1123
+ }
1124
+ /** 引擎自属的会话展示名解析回调(定制 Universal/Claude 的首条截断 + 自定义命名策略) */
1125
+ resolveSessionDisplayName(conv, firstMsg) {
1126
+ if (conv.title && !UniversalSession.isDefaultTitle(conv.title)) {
1127
+ return conv.title;
1128
+ }
1129
+ if (firstMsg && !UniversalSession.isDefaultTitle(firstMsg)) {
1130
+ const t = firstMsg.trim().replace(/\s+/g, " ");
1131
+ return t.length > 30 ? `${t.slice(0, 30)}…` : t;
1132
+ }
1133
+ return conv.title || (this.lang === "zh" ? "新对话" : "New chat");
1134
+ }
1135
+ async pushProjects() {
1136
+ /* 由外层统一处理 */
1137
+ }
1138
+ async removeProject() {
1139
+ /* 由外层统一处理 */
1140
+ }
1141
+ async searchSessions(query, reqId) {
1142
+ const q = query.trim().toLowerCase();
1143
+ if (!q) {
1144
+ this.send({ type: "session_search_results", reqId, query, ok: true, results: [] });
1145
+ return;
1146
+ }
1147
+ try {
1148
+ const memoryConvs = Array.from(this.conversations.values());
1149
+ const diskConvs = this.store.listConversations(this.cwd);
1150
+ const convMap = new Map();
1151
+ for (const c of diskConvs) {
1152
+ convMap.set(c.id, c);
1153
+ }
1154
+ for (const c of memoryConvs) {
1155
+ convMap.set(c.id, c);
1156
+ }
1157
+ const results = [];
1158
+ for (const conv of convMap.values()) {
1159
+ const titleMatches = conv.title.toLowerCase().includes(q);
1160
+ const anchors = [];
1161
+ let anyMessageMatches = false;
1162
+ for (const m of conv.messages) {
1163
+ let msgText = "";
1164
+ for (const b of m.content) {
1165
+ if (b.type === "text" && typeof b.text === "string") {
1166
+ msgText += b.text + "\n";
1167
+ }
1168
+ }
1169
+ if (msgText.toLowerCase().includes(q)) {
1170
+ anyMessageMatches = true;
1171
+ anchors.push({
1172
+ role: m.role,
1173
+ timestamp: m.timestamp ?? conv.updatedAt,
1174
+ });
1175
+ }
1176
+ }
1177
+ if (titleMatches || anyMessageMatches) {
1178
+ const firstUser = conv.messages.find((m) => m.role === "user");
1179
+ const firstText = firstUser?.content.find((b) => b.type === "text");
1180
+ const firstMsg = firstText && "text" in firstText && typeof firstText.text === "string"
1181
+ ? firstText.text
1182
+ : conv.title;
1183
+ results.push({
1184
+ path: conv.id,
1185
+ sessionId: conv.id,
1186
+ name: conv.title,
1187
+ firstMessage: firstMsg,
1188
+ messageCount: conv.messages.length,
1189
+ modified: conv.updatedAt,
1190
+ source: "web",
1191
+ anchors: anchors.slice(0, 10),
1192
+ });
1193
+ }
1194
+ }
1195
+ results.sort((a, b) => b.modified - a.modified);
1196
+ const payload = {
1197
+ type: "session_search_results",
1198
+ reqId,
1199
+ query,
1200
+ ok: true,
1201
+ results: results.slice(0, 50),
1202
+ };
1203
+ payload.hits = payload.results;
1204
+ this.send(payload);
1205
+ }
1206
+ catch {
1207
+ this.send({ type: "session_search_results", reqId, query, ok: false, results: [] });
1208
+ }
1209
+ }
1210
+ // ---------------------------------------------------------------------------
1211
+ // 文件、终端与 Git SCM 委托
1212
+ // ---------------------------------------------------------------------------
1213
+ async listFiles(path) {
1214
+ await this.files.listFiles(path);
1215
+ }
1216
+ async searchFiles(query, reqId) {
1217
+ await this.files.searchFiles(query, reqId);
1218
+ }
1219
+ async readFile(path) {
1220
+ await this.files.readFile(path);
1221
+ }
1222
+ async writeFile(path, text) {
1223
+ await this.files.writeFile(path, text);
1224
+ }
1225
+ async uploadFile(dirPath, name, data) {
1226
+ await this.files.uploadFile(dirPath, name, data);
1227
+ }
1228
+ async createEntry(dir, name, kind) {
1229
+ await this.files.createEntry(dir, name, kind);
1230
+ }
1231
+ async renameEntry(path, newName) {
1232
+ await this.files.renameEntry(path, newName);
1233
+ }
1234
+ async deleteEntry(path) {
1235
+ await this.files.deleteEntry(path);
1236
+ }
1237
+ async copyEntry(src, destDir, move) {
1238
+ await this.files.copyEntry(src, destDir, move);
1239
+ }
1240
+ async revealEntry(path) {
1241
+ await this.files.revealEntry(path);
1242
+ }
1243
+ async openDefaultEntry(path) {
1244
+ await this.files.openDefaultEntry(path);
1245
+ }
1246
+ async scmQuery(kind, reqId, opts) {
1247
+ await this.files.scmQuery(kind, reqId, opts);
1248
+ }
1249
+ getTerminalManager() {
1250
+ return this.terminals;
1251
+ }
1252
+ getTerminalCwd() {
1253
+ return this.cwd;
1254
+ }
1255
+ // ---------------------------------------------------------------------------
1256
+ // 后台服务生命周期委托
1257
+ // ---------------------------------------------------------------------------
1258
+ async killBackgroundServer(port, _taskId) {
1259
+ if (port === undefined)
1260
+ return false;
1261
+ const killed = await this.bg.killOne(port);
1262
+ if (killed)
1263
+ this.bg.push();
1264
+ return killed;
1265
+ }
1266
+ async killAllBackgroundServers() {
1267
+ const killed = await this.bg.killAll();
1268
+ this.bg.push();
1269
+ return killed;
1270
+ }
1271
+ async listBgServers() {
1272
+ this.bg.push();
1273
+ }
1274
+ setBackgroundKeep(port, keep) {
1275
+ return this.bg.setKeep(port, keep);
1276
+ }
1277
+ async cleanBackgroundLeftovers(minutesOverride) {
1278
+ const override = Number(minutesOverride);
1279
+ const minutes = Number.isFinite(override) && override > 0 ? override : 30;
1280
+ return this.bg.cleanStale(minutes * 60_000, { manual: true });
1281
+ }
1282
+ // ---------------------------------------------------------------------------
1283
+ // 模型与偏好控制
1284
+ // ---------------------------------------------------------------------------
1285
+ async listModels() {
1286
+ if (this.driver.listModels) {
1287
+ const models = await this.driver.listModels();
1288
+ const modelInfos = models.map((m) => {
1289
+ const hasSlash = m.id.includes("/");
1290
+ const provider = hasSlash ? m.id.split("/")[0] : this.driver.id;
1291
+ const bareId = hasSlash ? m.id.slice(m.id.indexOf("/") + 1) : m.id;
1292
+ const canonicalId = hasSlash ? m.id : `${this.driver.id}/${m.id}`;
1293
+ const entry = {
1294
+ id: bareId,
1295
+ name: m.name,
1296
+ provider,
1297
+ vision: true,
1298
+ };
1299
+ this.modelsMap.set(canonicalId, entry);
1300
+ this.modelsMap.set(bareId, entry);
1301
+ return {
1302
+ id: canonicalId,
1303
+ name: m.name,
1304
+ provider,
1305
+ reasoning: true,
1306
+ vision: true,
1307
+ };
1308
+ });
1309
+ this.send({
1310
+ type: "models",
1311
+ models: modelInfos,
1312
+ });
1313
+ this.flushSnapshot();
1314
+ }
1315
+ }
1316
+ async setModel(modelId) {
1317
+ this.currentModel = modelId;
1318
+ if (this.stateStore) {
1319
+ this.stateStore.saveProjectModel(this.clientId, this.cwd, modelId, this.engine);
1320
+ }
1321
+ if (this.driver.setModel) {
1322
+ await this.driver.setModel(modelId);
1323
+ }
1324
+ const info = this.resolveCurrentModelInfo();
1325
+ this.emitNotice("info", `已切换到模型:${info.name}`, `Switched to model: ${info.name}`);
1326
+ this.flushSnapshot();
1327
+ }
1328
+ async setDefaultModel(modelId) {
1329
+ if (this.stateStore) {
1330
+ this.stateStore.saveDefaultModel(modelId, this.engine);
1331
+ }
1332
+ this.send({ type: "default_model", modelId });
1333
+ this.emitNotice("info", `🌍 已设全局默认模型 ${modelId}(新项目自动使用,项目记忆优先)`, `🌍 Global default model set to ${modelId}`);
1334
+ this.flushSnapshot();
1335
+ }
1336
+ clearDefaultModel() {
1337
+ if (this.stateStore) {
1338
+ this.stateStore.saveDefaultModel("", this.engine);
1339
+ }
1340
+ this.send({ type: "default_model", modelId: null });
1341
+ this.emitNotice("info", "🌍 已清除全局默认模型", "🌍 Global default model cleared");
1342
+ this.flushSnapshot();
1343
+ }
1344
+ setThinking(level) {
1345
+ this.thinkingLevel = level;
1346
+ this.flushSnapshot();
1347
+ }
1348
+ async setCwd(path) {
1349
+ this.cwd = path;
1350
+ this.driver.setCwd(path);
1351
+ // 切换工作区 CWD:清空旧目录会话缓存与草稿,并加载属于新目录的会话
1352
+ this.conversations.clear();
1353
+ this.sessionDrafts.clear();
1354
+ const existing = this.store.listConversations(this.cwd);
1355
+ if (existing.length > 0) {
1356
+ for (const conv of existing) {
1357
+ this.conversations.set(conv.id, conv);
1358
+ }
1359
+ this.activeConvId = existing[0].id;
1360
+ }
1361
+ else {
1362
+ const initialConv = this.createEmptyConversation("新对话");
1363
+ this.activeConvId = initialConv.id;
1364
+ this.conversations.set(initialConv.id, initialConv);
1365
+ this.store.saveConversation(this.cwd, initialConv);
1366
+ }
1367
+ await this.refreshSessions();
1368
+ await this.refreshWorktreeInfo();
1369
+ // 切换目录后恢复该目录按引擎隔离的项目记忆模型
1370
+ const savedModel = this.stateStore?.getProjectModel(this.clientId, path, this.engine) ??
1371
+ this.stateStore?.getDefaultModel(this.engine);
1372
+ if (savedModel && savedModel !== this.currentModel) {
1373
+ void this.setModel(savedModel).catch(() => { });
1374
+ }
1375
+ this.flushSnapshot(true);
1376
+ }
1377
+ async setWorkspaceRoots(roots) {
1378
+ if (this.stateStore) {
1379
+ this.stateStore.saveWorkspaceRoots(this.clientId, this.cwd, roots ?? []);
1380
+ }
1381
+ this.flushSnapshot();
1382
+ }
1383
+ async refreshWorktreeInfo() {
1384
+ try {
1385
+ this.worktreeInfo = await getWorktreeContext(this.cwd);
1386
+ }
1387
+ catch {
1388
+ this.worktreeInfo = null;
1389
+ }
1390
+ }
1391
+ /** 获取通用底座持有的持久终端交互工具集 */
1392
+ getTerminalTools() {
1393
+ return makePersistentTerminalTools(this.terminals, this.cwd, () => this.lang);
1394
+ }
1395
+ /** 执行通用底座持久终端工具(供外部驱动或模型调用) */
1396
+ async execTerminalTool(name, args, signal) {
1397
+ const tools = this.getTerminalTools();
1398
+ const tool = tools.find((t) => t.name === name);
1399
+ if (!tool) {
1400
+ throw new Error(`Terminal tool "${name}" not found`);
1401
+ }
1402
+ const res = (await tool.execute(`call_${Date.now()}`, args, signal, undefined, undefined));
1403
+ const text = (res.content ?? []).map((c) => (c.type === "text" ? (c.text ?? "") : "")).join("\n");
1404
+ return { output: text, details: res.details };
1405
+ }
1406
+ getToolInfo(name) {
1407
+ if (name === "subagent") {
1408
+ const tools = makeSubagentTools(this.subagentHost);
1409
+ const target = tools.find((t) => t.name === "subagent") ?? tools[0];
1410
+ if (target) {
1411
+ this.send({
1412
+ type: "tool_info",
1413
+ name: target.name,
1414
+ found: true,
1415
+ description: target.description,
1416
+ promptSnippet: target.promptSnippet,
1417
+ parameters: target.parameters,
1418
+ });
1419
+ return;
1420
+ }
1421
+ }
1422
+ if (TERMINAL_TOOL_NAMES.includes(name)) {
1423
+ const tools = this.getTerminalTools();
1424
+ const target = tools.find((t) => t.name === name);
1425
+ if (target) {
1426
+ this.send({
1427
+ type: "tool_info",
1428
+ name: target.name,
1429
+ found: true,
1430
+ label: target.label,
1431
+ description: target.description,
1432
+ promptSnippet: target.promptSnippet,
1433
+ promptGuidelines: target.promptGuidelines,
1434
+ parameters: target.parameters,
1435
+ });
1436
+ return;
1437
+ }
1438
+ }
1439
+ this.send({ type: "tool_info", ...unsupportedToolInfo(name) });
1440
+ }
1441
+ getToolPrompt(name) {
1442
+ let targetTool;
1443
+ if (name === "subagent") {
1444
+ const tools = makeSubagentTools(this.subagentHost);
1445
+ targetTool = tools.find((t) => t.name === "subagent") ?? tools[0];
1446
+ }
1447
+ else if (TERMINAL_TOOL_NAMES.includes(name)) {
1448
+ const tools = this.getTerminalTools();
1449
+ targetTool = tools.find((t) => t.name === name);
1450
+ }
1451
+ if (targetTool) {
1452
+ this.send({
1453
+ type: "tool_prompt",
1454
+ name,
1455
+ found: true,
1456
+ defaultDescription: targetTool.description,
1457
+ defaultPromptSnippet: targetTool.promptSnippet,
1458
+ defaultPromptGuidelines: targetTool.promptGuidelines,
1459
+ });
1460
+ return;
1461
+ }
1462
+ this.send({
1463
+ type: "tool_prompt",
1464
+ name,
1465
+ found: false,
1466
+ unsupported: true,
1467
+ });
1468
+ }
1469
+ getCompactedMessages(compactionMessageId, conversationId) {
1470
+ const conv = conversationId ? this.conversations.get(conversationId) : this.activeConv;
1471
+ const msg = conv?.messages.find((m) => m.id === compactionMessageId);
1472
+ const compacted = msg?.details?.compactedMessages ?? [];
1473
+ this.send({
1474
+ type: "compacted_messages_result",
1475
+ compactionMessageId,
1476
+ conversationId: conv?.id ?? this.activeConvId,
1477
+ messages: compacted,
1478
+ });
1479
+ }
1480
+ async createSandbox(opts) {
1481
+ try {
1482
+ const { sandbox, copiedFiles } = await this.sandboxes.create(opts);
1483
+ await this.setCwd(sandbox.path);
1484
+ const modeZh = sandbox.sourcePath ? `已从源项目导入 ${copiedFiles} 个文件` : "空白隔离环境";
1485
+ const modeEn = sandbox.sourcePath ? `imported ${copiedFiles} files from source` : "blank isolated workspace";
1486
+ this.emitNotice("info", `🧪 沙盒「${sandbox.name}」已启动(${modeZh},一切修改与原项目完全隔离)`, `🧪 Sandbox "${sandbox.name}" started (${modeEn}; all changes are strictly isolated)`);
1487
+ }
1488
+ catch (err) {
1489
+ this.emitNotice("error", `创建沙盒失败:${err.message}`, `Failed to create sandbox: ${err.message}`);
1490
+ }
1491
+ }
1492
+ async resetSandbox(path) {
1493
+ const target = path?.trim() || this.cwd;
1494
+ try {
1495
+ const { sandbox, copiedFiles } = await this.sandboxes.reset(target);
1496
+ this.flushSnapshot();
1497
+ this.emitNotice("info", sandbox.sourcePath
1498
+ ? `🔄 已重置沙盒「${sandbox.name}」(重新从源项目同步 ${copiedFiles} 个文件)`
1499
+ : `🔄 已清空并重置沙盒「${sandbox.name}」`, sandbox.sourcePath
1500
+ ? `🔄 Reset sandbox "${sandbox.name}" (re-synced ${copiedFiles} files from source)`
1501
+ : `🔄 Cleared and reset sandbox "${sandbox.name}"`);
1502
+ }
1503
+ catch (err) {
1504
+ this.emitNotice("error", `重置沙盒失败:${err.message}`, `Failed to reset sandbox: ${err.message}`);
1505
+ }
1506
+ }
1507
+ async persistSandbox(path) {
1508
+ const target = path?.trim() || this.cwd;
1509
+ try {
1510
+ const sandbox = this.sandboxes.persist(target);
1511
+ this.flushSnapshot();
1512
+ this.emitNotice("info", `📌 沙盒「${sandbox.name}」已转为永久保留`, `📌 Sandbox "${sandbox.name}" is now saved permanently`);
1513
+ }
1514
+ catch (err) {
1515
+ this.emitNotice("error", `转换永久沙盒失败:${err.message}`, `Failed to persist sandbox: ${err.message}`);
1516
+ }
1517
+ }
1518
+ async promoteSandbox(targetPath, path, switchToTarget = true) {
1519
+ const sbxTarget = path?.trim() || this.cwd;
1520
+ try {
1521
+ const { sandbox, targetPath: resolvedTarget, copiedFiles } = await this.sandboxes.promote(sbxTarget, targetPath);
1522
+ if (switchToTarget) {
1523
+ await this.setCwd(resolvedTarget);
1524
+ }
1525
+ this.emitNotice("info", `📤 已将沙盒「${sandbox.name}」导出为正式项目:${resolvedTarget}(共 ${copiedFiles} 个文件)`, `📤 Exported sandbox "${sandbox.name}" to formal project: ${resolvedTarget} (${copiedFiles} files)`);
1526
+ }
1527
+ catch (err) {
1528
+ this.emitNotice("error", `导出沙盒失败:${err.message}`, `Failed to export sandbox: ${err.message}`);
1529
+ }
1530
+ }
1531
+ async diffSandbox(path) {
1532
+ const target = path?.trim() || this.cwd;
1533
+ try {
1534
+ const res = await this.sandboxes.diffWithSource(target);
1535
+ this.send({
1536
+ type: "sandbox_diff",
1537
+ diff: {
1538
+ sandboxId: res.sandbox.id,
1539
+ path: res.sandbox.path,
1540
+ sourcePath: res.sourcePath,
1541
+ added: res.added.slice(0, 200),
1542
+ modified: res.modified.slice(0, 200),
1543
+ deleted: res.deleted.slice(0, 200),
1544
+ unchangedCount: res.unchangedCount,
1545
+ },
1546
+ });
1547
+ }
1548
+ catch (err) {
1549
+ this.send({
1550
+ type: "sandbox_diff",
1551
+ diff: {
1552
+ sandboxId: "",
1553
+ path: target,
1554
+ added: [],
1555
+ modified: [],
1556
+ deleted: [],
1557
+ unchangedCount: 0,
1558
+ error: err.message,
1559
+ },
1560
+ });
1561
+ }
1562
+ }
1563
+ async applySandboxToSource(path) {
1564
+ const target = path?.trim() || this.cwd;
1565
+ try {
1566
+ const { sandbox, sourcePath, copiedFiles, deletedFiles } = await this.sandboxes.applyToSource(target);
1567
+ const delSuffixZh = deletedFiles ? `,清理 ${deletedFiles} 个已删除文件` : "";
1568
+ const delSuffixEn = deletedFiles ? `, pruned ${deletedFiles} deleted files` : "";
1569
+ this.emitNotice("info", `✅ 已将沙盒「${sandbox.name}」中的改动同步回源项目:${sourcePath}(同步 ${copiedFiles} 个文件${delSuffixZh})`, `✅ Applied changes from sandbox "${sandbox.name}" back to source project: ${sourcePath} (${copiedFiles} files synced${delSuffixEn})`);
1570
+ }
1571
+ catch (err) {
1572
+ this.emitNotice("error", `写回源项目失败:${err.message}`, `Failed to apply sandbox changes to source: ${err.message}`);
1573
+ }
1574
+ }
1575
+ async destroySandbox(path) {
1576
+ const target = path?.trim() || this.cwd;
1577
+ const sbx = this.sandboxes.get(target) ?? this.sandboxes.getByCwd(target);
1578
+ if (!sbx)
1579
+ return;
1580
+ try {
1581
+ if (this.cwd === sbx.path || this.cwd.startsWith(sbx.path + "/")) {
1582
+ const fallback = sbx.sourcePath && existsSync(sbx.sourcePath) ? sbx.sourcePath : homedir();
1583
+ await this.setCwd(fallback);
1584
+ }
1585
+ await this.sandboxes.destroy(sbx.path);
1586
+ this.emitNotice("info", `🗑️ 已销毁沙盒「${sbx.name}」`, `🗑️ Destroyed sandbox "${sbx.name}"`);
1587
+ }
1588
+ catch (err) {
1589
+ this.emitNotice("error", `销毁沙盒失败:${err.message}`, `Failed to destroy sandbox: ${err.message}`);
1590
+ }
1591
+ }
1592
+ async switchWorktree(targetPath) {
1593
+ await this.setCwd(targetPath);
1594
+ }
1595
+ async removeWorktree(targetPath, force = false) {
1596
+ try {
1597
+ await removeWorktree(this.cwd, targetPath, force, () => this.getLang());
1598
+ await this.refreshWorktreeInfo();
1599
+ this.emitNotice("info", `🗑️ 已移除 Git 工作树:${targetPath}`, `🗑️ Removed Git worktree: ${targetPath}`);
1600
+ }
1601
+ catch (err) {
1602
+ this.emitNotice("error", `移除工作树失败:${err.message}`, `Failed to remove worktree: ${err.message}`);
1603
+ }
1604
+ }
1605
+ async completePath(path) {
1606
+ await this.files.completePath(path);
1607
+ }
1608
+ async makeDir(path) {
1609
+ await this.files.makeDir(path);
1610
+ }
1611
+ // ---------------------------------------------------------------------------
1612
+ // 辅助方法与空实现
1613
+ // ---------------------------------------------------------------------------
1614
+ emitNotice(level, text, textEn) {
1615
+ this.send({ type: "notice", level, text, textEn });
1616
+ }
1617
+ getLang() {
1618
+ return this.lang;
1619
+ }
1620
+ async setLocale(locale) {
1621
+ this.lang = locale;
1622
+ }
1623
+ activeConversations() {
1624
+ return this.isStreaming ? 1 : 0;
1625
+ }
1626
+ pendingMessages() {
1627
+ return 0;
1628
+ }
1629
+ async pushSlashCommands() {
1630
+ await this.slash.push();
1631
+ }
1632
+ async listAvailableModelsForSlash() {
1633
+ const out = [];
1634
+ for (const m of this.modelsMap.values()) {
1635
+ if (!out.some((x) => x.id === m.id)) {
1636
+ out.push({ id: m.id, name: m.name, provider: m.provider });
1637
+ }
1638
+ }
1639
+ if (this.driver.listModels) {
1640
+ try {
1641
+ const driverModels = await this.driver.listModels();
1642
+ for (const dm of driverModels) {
1643
+ if (!out.some((x) => x.id === dm.id)) {
1644
+ out.push({ id: dm.id, name: dm.name, provider: this.driver.id });
1645
+ }
1646
+ }
1647
+ }
1648
+ catch {
1649
+ /* ignore driver model query error */
1650
+ }
1651
+ }
1652
+ return out;
1653
+ }
1654
+ async collectUniversalSkills() {
1655
+ const disk = discoverDiskSkills({ cwd: this.cwd, agentDir: this.agentDir });
1656
+ const out = [...disk];
1657
+ if (this.driver.getSkills) {
1658
+ try {
1659
+ const extra = await this.driver.getSkills();
1660
+ for (const es of extra) {
1661
+ if (!out.some((s) => s.name === es.name)) {
1662
+ out.push({
1663
+ name: es.name,
1664
+ description: es.description,
1665
+ filePath: es.filePath || "",
1666
+ dirPath: this.cwd,
1667
+ });
1668
+ }
1669
+ }
1670
+ }
1671
+ catch {
1672
+ /* ignore driver skills query error */
1673
+ }
1674
+ }
1675
+ this.skillsCache = out;
1676
+ return out;
1677
+ }
1678
+ async compactActiveConversation(instructions) {
1679
+ const conv = this.activeConv;
1680
+ if (conv.messages.length <= 4) {
1681
+ this.emitNotice("info", "当前对话上下文较短,无需压缩", "Conversation context is short, no compaction needed");
1682
+ return;
1683
+ }
1684
+ const first = conv.messages.slice(0, 2);
1685
+ const recent = conv.messages.slice(-4);
1686
+ const summaryMsg = {
1687
+ id: `compaction-${Date.now()}`,
1688
+ role: "compactionSummary",
1689
+ content: [
1690
+ {
1691
+ type: "text",
1692
+ text: instructions ? `上下文已根据说明压缩: ${instructions}` : "历史消息已由通用底座自动压缩归纳",
1693
+ },
1694
+ ],
1695
+ timestamp: Date.now(),
1696
+ };
1697
+ conv.messages = [...first, summaryMsg, ...recent];
1698
+ if (!conv.isEphemeral) {
1699
+ this.store.saveConversation(this.cwd, conv);
1700
+ }
1701
+ this.flushSnapshot();
1702
+ this.emitNotice("info", "已压缩当前会话上下文", "Current conversation context compacted");
1703
+ }
1704
+ async reloadSessionResources() {
1705
+ await this.collectUniversalSkills();
1706
+ if (this.modelAdmin) {
1707
+ await this.listModels();
1708
+ }
1709
+ await this.pushSlashCommands();
1710
+ }
1711
+ async listCommands() {
1712
+ this.send({ type: "commands", commands: [], path: "" });
1713
+ }
1714
+ async saveCommands(_commands) {
1715
+ /* no-op */
1716
+ }
1717
+ pushSettings() {
1718
+ const s = this.stateStore?.getSettings(this.clientId);
1719
+ const settings = {
1720
+ promptMode: s?.promptMode ?? "append",
1721
+ customSystemPrompt: s?.customSystemPrompt ?? "",
1722
+ disabledSkills: s?.disabledSkills ?? [],
1723
+ disabledExtensions: s?.disabledExtensions ?? [],
1724
+ disabledAgentTools: [],
1725
+ disabledPluginTools: [],
1726
+ terminalToolsEnabled: s?.terminalToolsEnabled ?? true,
1727
+ terminalBash: s?.terminalBash ?? true,
1728
+ terminalBashIdleMs: s?.terminalBashIdleMs ?? 3000,
1729
+ terminalBashMaxForegroundMs: s?.terminalBashMaxForegroundMs ?? 15000,
1730
+ toolWatchdogTimeoutMs: s?.toolWatchdogTimeoutMs ?? 1200000,
1731
+ readDirEnabled: true,
1732
+ bgAutoCleanupMin: s?.bgAutoCleanupMin ?? 0,
1733
+ toolLazyLoading: true,
1734
+ codemodeMode: "on",
1735
+ codemodeInlineBudget: 3000,
1736
+ editSoftEnabled: false,
1737
+ retryMaxAttempts: 0,
1738
+ softCapTokens: 0,
1739
+ softCapByModel: {},
1740
+ questionnaireEnabled: false,
1741
+ toolApprovalEnabled: true,
1742
+ approvalPolicy: { allowAll: false, categories: [] },
1743
+ approvalRules: [],
1744
+ goalModeEnabled: false,
1745
+ parallelReminderEnabled: false,
1746
+ thinkingWrap: s?.thinkingWrap ?? false,
1747
+ toolsWrap: s?.toolsWrap ?? false,
1748
+ toolImagesEnabled: s?.toolImagesEnabled ?? true,
1749
+ keepRecentMessages: s?.keepRecentMessages ?? 0,
1750
+ showForkedParentSessions: false,
1751
+ retainFinishedConversations: false,
1752
+ openRecentSessionOnProjectSwitch: true,
1753
+ skillsFullText: [],
1754
+ visionBridgeEnabled: false,
1755
+ visionBridgeModel: null,
1756
+ visionBridgePromptMode: "append",
1757
+ visionBridgePrompt: "",
1758
+ scmCommitMsgPromptMode: "append",
1759
+ scmCommitMsgPrompt: "",
1760
+ planModePromptMode: "append",
1761
+ planModePrompt: "",
1762
+ planModeDefaultPrompt: "",
1763
+ reviewPrompt: "",
1764
+ reviewDisabledSkills: [],
1765
+ disabledPlugins: s?.disabledPlugins ?? [],
1766
+ uiLayout: normalizeUiLayout(s?.uiLayout),
1767
+ promptTemplate: s?.promptTemplate ?? "",
1768
+ promptOverrides: s?.promptOverrides ?? {},
1769
+ toolPromptOverrides: {},
1770
+ effectiveSystemPrompt: "",
1771
+ promptSourceDefaults: {},
1772
+ toolsSchema: "",
1773
+ visionBridgeDefaultPrompt: "",
1774
+ scmCommitMsgDefaultPrompt: "",
1775
+ visionModels: [],
1776
+ skills: this.skillsCache.map((sk) => ({
1777
+ name: sk.name,
1778
+ description: sk.description,
1779
+ enabled: !(s?.disabledSkills ?? []).includes(sk.name),
1780
+ })),
1781
+ reviewSkills: [],
1782
+ extensions: [],
1783
+ presets: (this.stateStore?.getPresets(this.clientId) ?? []).map(settingsPresetToUi),
1784
+ markersEnabled: this.markerSvc.current.markersEnabled,
1785
+ disabledMarkers: [...this.markerSvc.current.disabledMarkers],
1786
+ markers: this.markerSvc.listForUi(),
1787
+ subagentTemplates: this.subagentTemplates.list(),
1788
+ subagentDefaultTemplates: DEFAULT_TEMPLATES.map((t) => t.name),
1789
+ subagentDefaultModel: null,
1790
+ subagentModels: [],
1791
+ quickPhrases: s?.quickPhrases ?? [],
1792
+ quickPhrasesEnabled: s?.quickPhrasesEnabled ?? true,
1793
+ minimalNewChat: s?.minimalNewChat ?? false,
1794
+ quickPhrasesSeeded: this.stateStore?.getQuickPhrasesSeeded() ?? true,
1795
+ };
1796
+ this.send({ type: "settings_state", settings });
1797
+ }
1798
+ async setSettings(partial) {
1799
+ if (this.stateStore) {
1800
+ this.stateStore.saveSettings(this.clientId, partial);
1801
+ }
1802
+ this.pushSettings();
1803
+ }
1804
+ async reloadExtensions() {
1805
+ /* no-op */
1806
+ }
1807
+ async checkUpdate() {
1808
+ /* no-op */
1809
+ }
1810
+ async checkUpdatesAll() {
1811
+ /* no-op */
1812
+ }
1813
+ resolveDialog(id, value) {
1814
+ this.webUi.resolveDialog(id, value);
1815
+ }
1816
+ handleTuiOverlayInput(id, data) {
1817
+ this.webUi.handleTuiOverlayInput(id, data);
1818
+ }
1819
+ handleTuiOverlayResize(id, cols, rows) {
1820
+ this.webUi.handleTuiOverlayResize(id, cols, rows);
1821
+ }
1822
+ handleTuiOverlayCancel(id) {
1823
+ this.webUi.handleTuiOverlayCancel(id);
1824
+ }
1825
+ installPiAgent() {
1826
+ /* no-op */
1827
+ return Promise.resolve();
1828
+ }
1829
+ setProviderApiKey(provider, apiKey) {
1830
+ return this.modelAdmin.setProviderApiKey(provider, apiKey);
1831
+ }
1832
+ clearProviderApiKey(provider) {
1833
+ return this.modelAdmin.clearProviderApiKey(provider);
1834
+ }
1835
+ startProviderOAuth(provider) {
1836
+ this.modelAdmin.startProviderOAuth(provider);
1837
+ }
1838
+ replyProviderOAuth(flowId, promptId, value) {
1839
+ this.modelAdmin.replyProviderOAuth(flowId, promptId, value);
1840
+ }
1841
+ cancelProviderOAuth(flowId) {
1842
+ this.modelAdmin.cancelProviderOAuth(flowId);
1843
+ }
1844
+ listProviderOAuthFlows() {
1845
+ this.modelAdmin.listProviderOAuthFlows();
1846
+ }
1847
+ logoutProviderOAuth(provider) {
1848
+ return this.modelAdmin.logoutProviderOAuth(provider);
1849
+ }
1850
+ listModelsConfig() {
1851
+ return this.modelAdmin.listModelsConfig();
1852
+ }
1853
+ reloadModelsConfig() {
1854
+ return this.modelAdmin.reloadModelsConfig();
1855
+ }
1856
+ saveModelConfig(providerId, config) {
1857
+ return this.modelAdmin.saveModelConfig(providerId, config);
1858
+ }
1859
+ deleteModelConfig(providerId) {
1860
+ return this.modelAdmin.deleteModelConfig(providerId);
1861
+ }
1862
+ listProviders() {
1863
+ return this.modelAdmin.listProviders();
1864
+ }
1865
+ listProviderKeys() {
1866
+ this.modelAdmin.listProviderKeys();
1867
+ }
1868
+ addProviderKey(provider, apiKey, name) {
1869
+ return this.modelAdmin.addProviderKey(provider, apiKey, name);
1870
+ }
1871
+ async activateProviderKey(provider, keyName) {
1872
+ await this.modelAdmin.activateProviderKey(provider, keyName);
1873
+ }
1874
+ removeProviderKey(provider, keyName) {
1875
+ return this.modelAdmin.removeProviderKey(provider, keyName);
1876
+ }
1877
+ fetchModelsList(reqId, baseUrl, apiKey, authHeader, api, providerId) {
1878
+ return this.modelAdmin.fetchModelsList(reqId, baseUrl, apiKey, authHeader, api, () => this.getLang(), providerId);
1879
+ }
1880
+ testModelConnection(reqId, baseUrl, apiKey, authHeader, api, providerId) {
1881
+ return this.modelAdmin.testConnection(reqId, baseUrl, apiKey, authHeader, api, () => this.getLang(), providerId);
1882
+ }
1883
+ refreshProviderModels(providerId, reqId) {
1884
+ return this.modelAdmin.refreshProviderModels(providerId, reqId, () => this.getLang());
1885
+ }
1886
+ refreshBuiltinModels(reqId) {
1887
+ return this.modelAdmin.refreshBuiltinModels(reqId);
1888
+ }
1889
+ appendBuiltinModel(providerId, model, reqId) {
1890
+ return this.modelAdmin.appendBuiltinModel(providerId, model, reqId);
1891
+ }
1892
+ cloneProvider(provider, reqId) {
1893
+ return this.modelAdmin.cloneProvider(provider, reqId);
1894
+ }
1895
+ enrichModels(reqId, ids, hints) {
1896
+ return this.modelAdmin.enrichModels(reqId, ids, hints);
1897
+ }
1898
+ abortEnrichModels(reqId) {
1899
+ this.modelAdmin.abortEnrichModels(reqId);
1900
+ }
1901
+ setGoal() {
1902
+ this.emitNotice("warning", "通用 Agent 模式暂不支持目标模式", "Goal mode not supported in universal agent");
1903
+ return Promise.resolve();
1904
+ }
1905
+ clearGoal() {
1906
+ /* no-op */
1907
+ return Promise.resolve();
1908
+ }
1909
+ startGoalWizard() {
1910
+ /* no-op */
1911
+ return Promise.resolve();
1912
+ }
1913
+ setGoalPrefs() {
1914
+ /* no-op */
1915
+ return Promise.resolve();
1916
+ }
1917
+ async savePreset(name) {
1918
+ if (!this.stateStore)
1919
+ return;
1920
+ const s = this.stateStore.getSettings(this.clientId);
1921
+ const currentPresets = this.stateStore.getPresets(this.clientId);
1922
+ const filtered = currentPresets.filter((p) => p.name !== name);
1923
+ filtered.push({
1924
+ name,
1925
+ promptMode: s.promptMode,
1926
+ customSystemPrompt: s.customSystemPrompt,
1927
+ promptTemplate: s.promptTemplate,
1928
+ promptOverrides: s.promptOverrides ? { ...s.promptOverrides } : {},
1929
+ disabledSkills: [...(s?.disabledSkills ?? [])],
1930
+ disabledExtensions: [...(s?.disabledExtensions ?? [])],
1931
+ reviewPrompt: s.reviewPrompt ?? "",
1932
+ reviewDisabledSkills: [...(s?.reviewDisabledSkills ?? [])],
1933
+ retryMaxAttempts: s.retryMaxAttempts,
1934
+ softCapTokens: s.softCapTokens,
1935
+ softCapByModel: s.softCapByModel,
1936
+ });
1937
+ this.stateStore.savePresets(this.clientId, filtered);
1938
+ this.pushSettings();
1939
+ this.emitNotice("info", `已保存设置预设「${name}」`, `Settings preset "${name}" saved`);
1940
+ }
1941
+ async applyPreset(name) {
1942
+ if (!this.stateStore)
1943
+ return;
1944
+ const currentPresets = this.stateStore.getPresets(this.clientId);
1945
+ const found = currentPresets.find((p) => p.name === name);
1946
+ if (!found) {
1947
+ this.emitNotice("error", `未找到名为「${name}」的设置预设`, `Settings preset "${name}" not found`);
1948
+ return;
1949
+ }
1950
+ this.stateStore.saveSettings(this.clientId, {
1951
+ promptMode: found.promptMode,
1952
+ customSystemPrompt: found.customSystemPrompt,
1953
+ disabledSkills: [...(found.disabledSkills ?? [])],
1954
+ disabledExtensions: [...(found.disabledExtensions ?? [])],
1955
+ reviewPrompt: found.reviewPrompt ?? "",
1956
+ reviewDisabledSkills: [...(found.reviewDisabledSkills ?? [])],
1957
+ retryMaxAttempts: found.retryMaxAttempts,
1958
+ softCapTokens: found.softCapTokens,
1959
+ softCapByModel: found.softCapByModel,
1960
+ });
1961
+ this.pushSettings();
1962
+ this.emitNotice("info", `已应用设置预设「${name}」`, `Settings preset "${name}" applied`);
1963
+ }
1964
+ async deletePreset(name) {
1965
+ if (!this.stateStore)
1966
+ return;
1967
+ const currentPresets = this.stateStore.getPresets(this.clientId);
1968
+ const filtered = currentPresets.filter((p) => p.name !== name);
1969
+ this.stateStore.savePresets(this.clientId, filtered);
1970
+ this.pushSettings();
1971
+ this.emitNotice("info", `已删除设置预设「${name}」`, `Settings preset "${name}" deleted`);
1972
+ }
1973
+ async scmGenCommitMessage(reqId) {
1974
+ const reply = (ok, extra) => {
1975
+ this.send({ type: "scm_data", reqId, kind: "commitmsg", ok, ...extra });
1976
+ };
1977
+ try {
1978
+ const ctx = await scmCommitContext(this.cwd, () => this.getLang());
1979
+ const input = buildCommitMsgInput(ctx, this.lang === "zh" ? "zh" : "en");
1980
+ if (!input) {
1981
+ reply(false, {
1982
+ error: this.lang === "zh" ? "没有可描述的更改(工作区干净)" : "Nothing to describe (working tree clean)",
1983
+ });
1984
+ return;
1985
+ }
1986
+ let commitText = "";
1987
+ const prompt = `Based on the following git changes, write a single-line conventional commit message (e.g. feat(...): ..., fix(...): ...):\n\n${input}`;
1988
+ let doneResolve;
1989
+ const p = new Promise((res) => {
1990
+ doneResolve = res;
1991
+ });
1992
+ const sink = {
1993
+ onThinkingDelta: () => { },
1994
+ onTextDelta: (d) => {
1995
+ commitText += d;
1996
+ },
1997
+ onToolStart: () => { },
1998
+ onToolEnd: () => { },
1999
+ onTurnComplete: () => doneResolve(),
2000
+ onError: () => doneResolve(),
2001
+ };
2002
+ await this.driver.sendPrompt(prompt, undefined, sink);
2003
+ await p;
2004
+ const clean = sanitizeCommitMessage(commitText.trim());
2005
+ if (clean) {
2006
+ reply(true, { text: clean });
2007
+ }
2008
+ else {
2009
+ reply(false, {
2010
+ error: this.lang === "zh" ? "未能生成提交信息" : "Failed to generate commit message",
2011
+ });
2012
+ }
2013
+ }
2014
+ catch (err) {
2015
+ reply(false, { error: err instanceof Error ? err.message : String(err) });
2016
+ }
2017
+ }
2018
+ sharePort() {
2019
+ return {
2020
+ lang: () => this.getLang(),
2021
+ appVersion: () => getAppVersion(),
2022
+ presets: () => this.stateStore?.getPresets(this.clientId) ?? [],
2023
+ currentSettings: () => this.stateStore?.getSettings(this.clientId) ?? {},
2024
+ upsertPreset: (preset) => {
2025
+ const presets = this.stateStore?.getPresets(this.clientId) ?? [];
2026
+ const filtered = presets.filter((p) => p.name !== preset.name);
2027
+ filtered.push(preset);
2028
+ this.stateStore?.savePresets(this.clientId, filtered);
2029
+ },
2030
+ applyPreset: async (name) => this.applyPreset(name),
2031
+ pushSettings: () => this.pushSettings(),
2032
+ emit: (msg) => this.send(msg),
2033
+ };
2034
+ }
2035
+ async exportPreset(msg) {
2036
+ exportPresetVia(this.sharePort(), msg);
2037
+ }
2038
+ async importPreset(msg) {
2039
+ await importPresetVia(this.sharePort(), msg);
2040
+ }
2041
+ async importPresetFromUrl(msg) {
2042
+ await importPresetFromUrlVia(this.sharePort(), msg);
2043
+ }
2044
+ async pushPresetCatalog(msg) {
2045
+ await pushPresetCatalogVia(this.sharePort(), msg);
2046
+ }
2047
+ async sharePreset(msg) {
2048
+ await sharePresetVia(this.sharePort(), msg);
2049
+ }
2050
+ async saveSubagentTemplate(template) {
2051
+ const err = this.subagentTemplates.upsert(template);
2052
+ if (err) {
2053
+ this.emitNotice("error", `子代理模板保存失败:${err}`, `Failed to save subagent template: ${err}`);
2054
+ return;
2055
+ }
2056
+ this.pushSettings();
2057
+ const n = template?.name?.trim() ?? "";
2058
+ this.emitNotice("info", `子代理模板已保存:${n}`, `Subagent template saved: ${n}`);
2059
+ }
2060
+ async deleteSubagentTemplate(name) {
2061
+ this.subagentTemplates.remove(name);
2062
+ this.pushSettings();
2063
+ this.emitNotice("info", `子代理模板已删除:${name}`, `Subagent template deleted: ${name}`);
2064
+ }
2065
+ async installSkill(name, scope, content) {
2066
+ const cleanName = name.trim();
2067
+ if (!cleanName || !/^[a-zA-Z0-9_-]+$/.test(cleanName)) {
2068
+ this.emitNotice("error", "技能名称非法,仅允许包含英文字母、数字、下划线及中划线", "Invalid skill name: only letters, numbers, underscores and hyphens are allowed");
2069
+ return;
2070
+ }
2071
+ const baseDir = scope === "global" ? join(this.agentDir, "skills") : join(this.cwd, ".pi", "skills");
2072
+ const targetDir = join(baseDir, cleanName);
2073
+ try {
2074
+ mkdirSync(targetDir, { recursive: true });
2075
+ writeFileSync(join(targetDir, "SKILL.md"), content.trim() + "\n", "utf8");
2076
+ await this.reloadSessionResources();
2077
+ this.pushSettings();
2078
+ this.emitNotice("info", `技能「${cleanName}」已成功安装至${scope === "global" ? "全局" : "当前项目"}`, `Skill "${cleanName}" installed successfully to ${scope === "global" ? "global" : "project"}`);
2079
+ }
2080
+ catch (err) {
2081
+ const msg = err instanceof Error ? err.message : String(err);
2082
+ this.emitNotice("error", `安装技能失败:${msg}`, `Failed to install skill: ${msg}`);
2083
+ }
2084
+ }
2085
+ async uninstallSkill(name, scope) {
2086
+ const cleanName = name.trim();
2087
+ const baseDir = scope === "global" ? join(this.agentDir, "skills") : join(this.cwd, ".pi", "skills");
2088
+ const targetDir = join(baseDir, cleanName);
2089
+ const singleFile = join(baseDir, `${cleanName}.md`);
2090
+ try {
2091
+ let deleted = false;
2092
+ if (existsSync(targetDir)) {
2093
+ rmSync(targetDir, { recursive: true, force: true });
2094
+ deleted = true;
2095
+ }
2096
+ if (existsSync(singleFile)) {
2097
+ rmSync(singleFile, { force: true });
2098
+ deleted = true;
2099
+ }
2100
+ if (!deleted) {
2101
+ this.emitNotice("warning", `未找到技能「${cleanName}」的安装文件`, `Skill "${cleanName}" installation file not found`);
2102
+ return;
2103
+ }
2104
+ await this.reloadSessionResources();
2105
+ this.pushSettings();
2106
+ this.emitNotice("info", `技能「${cleanName}」已从${scope === "global" ? "全局" : "当前项目"}卸载`, `Skill "${cleanName}" uninstalled from ${scope === "global" ? "global" : "project"}`);
2107
+ }
2108
+ catch (err) {
2109
+ const msg = err instanceof Error ? err.message : String(err);
2110
+ this.emitNotice("error", `卸载技能失败:${msg}`, `Failed to uninstall skill: ${msg}`);
2111
+ }
2112
+ }
2113
+ async fetchMcpMarket(source, query, page, refresh) {
2114
+ const res = await fetchRemoteMcpMarket({
2115
+ source,
2116
+ query,
2117
+ page,
2118
+ refresh,
2119
+ dataDir: this.dataDir,
2120
+ });
2121
+ this.send({
2122
+ type: "mcp_market_result",
2123
+ ok: res.ok,
2124
+ servers: res.servers,
2125
+ source: res.source,
2126
+ total: res.total,
2127
+ error: res.error,
2128
+ });
2129
+ }
2130
+ async fetchSkillMarket(repo, refresh) {
2131
+ const res = await fetchRemoteSkillMarket({
2132
+ repo,
2133
+ refresh,
2134
+ dataDir: this.dataDir,
2135
+ });
2136
+ this.send({
2137
+ type: "skill_market_result",
2138
+ ok: res.ok,
2139
+ skills: res.skills,
2140
+ repo: res.repo,
2141
+ error: res.error,
2142
+ });
2143
+ }
2144
+ async fetchSkillContent(repo, skillId) {
2145
+ const res = await fetchRemoteSkillContent({
2146
+ repo,
2147
+ skillId,
2148
+ dataDir: this.dataDir,
2149
+ });
2150
+ this.send({
2151
+ type: "skill_content_result",
2152
+ ok: res.ok,
2153
+ skillId: res.skillId,
2154
+ content: res.content,
2155
+ error: res.error,
2156
+ });
2157
+ }
2158
+ // ---------------------------------------------------------------------------
2159
+ // 通用底座第一方子代理(Subagent)生命周期与调度管理
2160
+ // ---------------------------------------------------------------------------
2161
+ /** 统计当前活跃(流式运行中)的子代理数量 */
2162
+ getLiveSubagentsCount() {
2163
+ let count = 0;
2164
+ for (const conv of this.conversations.values()) {
2165
+ if (conv.isSubagent && conv.subagentStreaming) {
2166
+ count++;
2167
+ }
2168
+ }
2169
+ return count;
2170
+ }
2171
+ /** 创建并启动一个子代理会话 */
2172
+ async spawnSubagent(prompt, type, cwd, templateName, model, parentId, persist = false, title) {
2173
+ const maxSubagents = Number(process.env.PI_WEB_MAX_SUBAGENTS) || 8;
2174
+ const liveCount = this.getLiveSubagentsCount();
2175
+ if (liveCount >= maxSubagents) {
2176
+ throw new Error(pick(this.lang, `同时运行的子代理数量已达上限(${maxSubagents} 个),请先用 wait 等一部分完成、或用 stop 停掉不需要的再派发`, `Active subagent limit reached (${maxSubagents} live). Wait for some with wait_all or stop unneeded ones with stop before spawning more`));
2177
+ }
2178
+ // 检查并解析模板
2179
+ let template;
2180
+ let effectivePrompt = prompt;
2181
+ if (templateName) {
2182
+ template = this.subagentTemplates.get(templateName);
2183
+ if (!template) {
2184
+ throw new Error(`Subagent template "${templateName}" not found`);
2185
+ }
2186
+ if (template.enabled === false) {
2187
+ throw new Error(`Subagent template "${templateName}" is disabled`);
2188
+ }
2189
+ const tplPrompt = pickTemplatePrompt(template, this.lang);
2190
+ if (tplPrompt?.trim()) {
2191
+ effectivePrompt = `${tplPrompt.trim()}\n\n${prompt}`;
2192
+ }
2193
+ }
2194
+ const now = Date.now();
2195
+ const convId = `subconv-${now}-${randomUUID().slice(0, 8)}`;
2196
+ const effectiveParentId = parentId || this.activeConvId;
2197
+ const effectiveType = type || "general";
2198
+ const effectiveTitle = title ?? subagentTitle(prompt);
2199
+ const effectiveModel = model ?? (template?.model?.trim() || null) ?? this.currentModel;
2200
+ const targetCwd = cwd || this.cwd;
2201
+ const subConv = {
2202
+ id: convId,
2203
+ title: effectiveTitle,
2204
+ createdAt: now,
2205
+ updatedAt: now,
2206
+ messages: [
2207
+ {
2208
+ id: `u-${now}-${randomUUID().slice(0, 6)}`,
2209
+ role: "user",
2210
+ content: [{ type: "text", text: prompt }],
2211
+ timestamp: now,
2212
+ },
2213
+ ],
2214
+ isEphemeral: !persist,
2215
+ isSubagent: true,
2216
+ subagentType: effectiveType,
2217
+ subagentPrompt: prompt,
2218
+ subagentParentId: effectiveParentId,
2219
+ subagentState: "running",
2220
+ subagentStreaming: true,
2221
+ subagentTemplate: template,
2222
+ subagentModel: effectiveModel,
2223
+ stats: {
2224
+ tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
2225
+ cost: 0,
2226
+ contextUsage: { tokens: null, contextWindow: this.resolveCurrentModelContextWindow(), percent: null },
2227
+ },
2228
+ };
2229
+ this.conversations.set(convId, subConv);
2230
+ if (persist) {
2231
+ this.store.saveConversation(targetCwd, subConv);
2232
+ }
2233
+ this.flushSnapshot();
2234
+ void this.refreshSessions();
2235
+ // 为该子代理创建独立的 Driver 实例
2236
+ let subDriver;
2237
+ if (this.driverFactory) {
2238
+ subDriver = this.driverFactory(targetCwd);
2239
+ }
2240
+ else if (this.driver.constructor && typeof this.driver.constructor === "function") {
2241
+ try {
2242
+ subDriver = new this.driver.constructor(targetCwd);
2243
+ }
2244
+ catch {
2245
+ subDriver = this.driver;
2246
+ }
2247
+ }
2248
+ else {
2249
+ subDriver = this.driver;
2250
+ }
2251
+ this.subagentDrivers.set(convId, subDriver);
2252
+ // 若驱动支持 setModel,应用子代理指定的模型
2253
+ if (effectiveModel && subDriver.setModel) {
2254
+ try {
2255
+ await subDriver.setModel(effectiveModel);
2256
+ }
2257
+ catch {
2258
+ // 驱动不支持或模型设置失败时平滑降级
2259
+ }
2260
+ }
2261
+ // 异步启动子代理执行流程
2262
+ void this.runSubagent(convId, subDriver, effectivePrompt, targetCwd);
2263
+ return { convId };
2264
+ }
2265
+ /** 后台异步执行子代理 Prompt */
2266
+ async runSubagent(convId, subDriver, prompt, cwd) {
2267
+ const conv = this.conversations.get(convId);
2268
+ if (!conv)
2269
+ return;
2270
+ const now = Date.now();
2271
+ const assistantMsgId = `a-${now}-${randomUUID().slice(0, 6)}`;
2272
+ let thinkingText = "";
2273
+ let assistantText = "";
2274
+ const assistantMsg = {
2275
+ id: assistantMsgId,
2276
+ role: "assistant",
2277
+ content: [],
2278
+ timestamp: now,
2279
+ model: conv.subagentModel,
2280
+ };
2281
+ conv.messages.push(assistantMsg);
2282
+ const sink = {
2283
+ onThinkingDelta: (delta) => {
2284
+ thinkingText += delta;
2285
+ let thinkBlock = assistantMsg.content.find((b) => b.type === "thinking");
2286
+ if (!thinkBlock) {
2287
+ thinkBlock = { type: "thinking", thinking: "" };
2288
+ assistantMsg.content.unshift(thinkBlock);
2289
+ }
2290
+ thinkBlock.thinking = thinkingText;
2291
+ if (this.activeConvId === convId) {
2292
+ this.emitDelta({ type: "thinking_delta", delta });
2293
+ this.scheduleThrottledSnapshot();
2294
+ }
2295
+ },
2296
+ onTextDelta: (delta) => {
2297
+ assistantText += delta;
2298
+ const lastBlock = assistantMsg.content[assistantMsg.content.length - 1];
2299
+ if (lastBlock && lastBlock.type === "text" && !lastBlock.truncated) {
2300
+ lastBlock.text += delta;
2301
+ }
2302
+ else {
2303
+ assistantMsg.content.push({ type: "text", text: delta });
2304
+ }
2305
+ if (this.activeConvId === convId) {
2306
+ this.emitDelta({ type: "text_delta", delta });
2307
+ this.scheduleThrottledSnapshot();
2308
+ }
2309
+ },
2310
+ onToolStart: (callId, toolName, args) => {
2311
+ const toolBlock = {
2312
+ type: "toolCall",
2313
+ id: callId,
2314
+ name: toolName,
2315
+ argumentsText: JSON.stringify(args, null, 2),
2316
+ };
2317
+ assistantMsg.content.push(toolBlock);
2318
+ if (this.activeConvId === convId) {
2319
+ this.scheduleThrottledSnapshot();
2320
+ }
2321
+ },
2322
+ onToolEnd: (callId, result) => {
2323
+ const toolMsg = {
2324
+ id: `t-${callId}`,
2325
+ role: "toolResult",
2326
+ toolCallId: callId,
2327
+ content: [{ type: "text", text: result.output ?? result.error ?? "" }],
2328
+ isError: Boolean(result.error),
2329
+ timestamp: Date.now(),
2330
+ };
2331
+ conv.messages.push(toolMsg);
2332
+ if (this.activeConvId === convId) {
2333
+ this.scheduleThrottledSnapshot();
2334
+ }
2335
+ },
2336
+ onTurnComplete: (meta) => {
2337
+ conv.subagentStreaming = false;
2338
+ conv.subagentState = conv.subagentCanceled ? "canceled" : "done";
2339
+ conv.updatedAt = Date.now();
2340
+ if (meta?.usage && conv.stats) {
2341
+ conv.stats.tokens.input += meta.usage.inputTokens ?? 0;
2342
+ conv.stats.tokens.output += meta.usage.outputTokens ?? 0;
2343
+ conv.stats.tokens.cacheRead += meta.usage.cacheReadTokens ?? 0;
2344
+ conv.stats.tokens.cacheWrite += meta.usage.cacheWriteTokens ?? 0;
2345
+ conv.stats.tokens.total = conv.stats.tokens.input + conv.stats.tokens.output;
2346
+ if (typeof meta.costUSD === "number") {
2347
+ conv.stats.cost += meta.costUSD;
2348
+ }
2349
+ }
2350
+ if (!conv.isEphemeral) {
2351
+ this.store.saveConversation(cwd, conv);
2352
+ }
2353
+ this.subagentDrivers.delete(convId);
2354
+ try {
2355
+ void subDriver.dispose();
2356
+ }
2357
+ catch {
2358
+ // 忽略 dispose 异常
2359
+ }
2360
+ this.notifySubagentWaitListeners();
2361
+ this.flushSnapshot();
2362
+ void this.refreshSessions();
2363
+ },
2364
+ onError: (err) => {
2365
+ const errMsg = typeof err === "string" ? err : err.message;
2366
+ conv.subagentError = errMsg;
2367
+ conv.subagentStreaming = false;
2368
+ conv.subagentState = "done";
2369
+ conv.updatedAt = Date.now();
2370
+ if (!conv.isEphemeral) {
2371
+ this.store.saveConversation(cwd, conv);
2372
+ }
2373
+ this.subagentDrivers.delete(convId);
2374
+ try {
2375
+ void subDriver.dispose();
2376
+ }
2377
+ catch {
2378
+ // 忽略 dispose 异常
2379
+ }
2380
+ this.notifySubagentWaitListeners();
2381
+ this.flushSnapshot();
2382
+ void this.refreshSessions();
2383
+ this.emitNotice("error", `子代理 ${conv.id.slice(0, 8)}(${conv.subagentType ?? "general"})运行失败:${errMsg}`, `Subagent ${conv.id.slice(0, 8)} (${conv.subagentType ?? "general"}) failed: ${errMsg}`);
2384
+ },
2385
+ };
2386
+ try {
2387
+ if (subDriver.createSession) {
2388
+ const sid = await subDriver.createSession();
2389
+ conv.driverSessionId = sid;
2390
+ }
2391
+ await subDriver.sendPrompt(prompt, undefined, sink);
2392
+ }
2393
+ catch (err) {
2394
+ const msg = err instanceof Error ? err.message : String(err);
2395
+ sink.onError(msg);
2396
+ }
2397
+ }
2398
+ /** 获取单个子代理运行态快照结果 */
2399
+ async getSubagentResult(convId) {
2400
+ const conv = this.conversations.get(convId);
2401
+ if (!conv || !conv.isSubagent) {
2402
+ throw new Error(`Subagent ${convId} not found`);
2403
+ }
2404
+ return this.subagentToSnapshot(conv);
2405
+ }
2406
+ /** 提取子代理会话的最终 assistant 正文输出 */
2407
+ extractSubagentOutput(conv) {
2408
+ const assistantMsgs = conv.messages.filter((m) => m.role === "assistant");
2409
+ const pieces = [];
2410
+ for (const m of assistantMsgs) {
2411
+ for (const b of m.content) {
2412
+ if (b.type === "text" && typeof b.text === "string") {
2413
+ pieces.push(b.text);
2414
+ }
2415
+ }
2416
+ }
2417
+ return pieces.join("\n").trim();
2418
+ }
2419
+ /** 将 UniversalConversation 转换成标准 SubagentSnapshot */
2420
+ subagentToSnapshot(conv) {
2421
+ const output = this.extractSubagentOutput(conv);
2422
+ const state = conv.subagentState ?? (conv.subagentStreaming ? "running" : conv.subagentCanceled ? "canceled" : "done");
2423
+ return {
2424
+ convId: conv.id,
2425
+ type: conv.subagentType ?? "general",
2426
+ title: conv.title,
2427
+ prompt: conv.subagentPrompt ?? "",
2428
+ state,
2429
+ streaming: Boolean(conv.subagentStreaming),
2430
+ error: conv.subagentError,
2431
+ canceled: conv.subagentCanceled,
2432
+ messageCount: conv.messages.length,
2433
+ model: conv.subagentModel,
2434
+ output,
2435
+ parentId: conv.subagentParentId,
2436
+ persisted: !conv.isEphemeral,
2437
+ handoffTo: conv.subagentHandoffTo ? [...conv.subagentHandoffTo] : undefined,
2438
+ handoffFrom: conv.subagentHandoffFrom ? [...conv.subagentHandoffFrom] : undefined,
2439
+ };
2440
+ }
2441
+ /** 停止指定的子代理运行 */
2442
+ async stopSubagent(convId) {
2443
+ const conv = this.conversations.get(convId);
2444
+ if (!conv)
2445
+ return;
2446
+ conv.subagentCanceled = true;
2447
+ conv.subagentStreaming = false;
2448
+ conv.subagentState = "canceled";
2449
+ conv.updatedAt = Date.now();
2450
+ const driver = this.subagentDrivers.get(convId);
2451
+ if (driver) {
2452
+ this.subagentDrivers.delete(convId);
2453
+ try {
2454
+ await driver.abort();
2455
+ void driver.dispose();
2456
+ }
2457
+ catch {
2458
+ // 忽略驱动中止失败
2459
+ }
2460
+ }
2461
+ this.notifySubagentWaitListeners();
2462
+ this.flushSnapshot();
2463
+ void this.refreshSessions();
2464
+ }
2465
+ /** 等待指定的子代理到达终态 */
2466
+ async waitSubagents(timeoutSeconds, runIds, callerId) {
2467
+ const waitCapMs = computeWaitCapMs();
2468
+ const requestedMs = typeof timeoutSeconds === "number" && timeoutSeconds > 0 ? Math.floor(timeoutSeconds * 1000) : waitCapMs;
2469
+ const effectiveTimeoutMs = Math.min(requestedMs, waitCapMs);
2470
+ const targetIds = runIds && runIds.length > 0
2471
+ ? new Set(runIds)
2472
+ : new Set(Array.from(this.conversations.values())
2473
+ .filter((c) => c.isSubagent && (!callerId || c.subagentParentId === callerId))
2474
+ .map((c) => c.id));
2475
+ const checkFinished = () => {
2476
+ const snapshots = [];
2477
+ let allDone = true;
2478
+ for (const id of targetIds) {
2479
+ const conv = this.conversations.get(id);
2480
+ if (!conv)
2481
+ continue;
2482
+ const snap = this.subagentToSnapshot(conv);
2483
+ snapshots.push(snap);
2484
+ if (!isSubagentTerminal(snap)) {
2485
+ allDone = false;
2486
+ }
2487
+ }
2488
+ return { finished: allDone, snapshots };
2489
+ };
2490
+ const initial = checkFinished();
2491
+ if (initial.finished) {
2492
+ return initial.snapshots;
2493
+ }
2494
+ return new Promise((resolve) => {
2495
+ let timer = null;
2496
+ const onUpdate = () => {
2497
+ const result = checkFinished();
2498
+ if (result.finished) {
2499
+ cleanup();
2500
+ resolve(result.snapshots);
2501
+ }
2502
+ };
2503
+ const cleanup = () => {
2504
+ if (timer) {
2505
+ clearTimeout(timer);
2506
+ timer = null;
2507
+ }
2508
+ this.subagentWaitListeners.delete(onUpdate);
2509
+ };
2510
+ timer = setTimeout(() => {
2511
+ cleanup();
2512
+ const result = checkFinished();
2513
+ resolve(result.snapshots);
2514
+ }, effectiveTimeoutMs);
2515
+ this.subagentWaitListeners.add(onUpdate);
2516
+ });
2517
+ }
2518
+ /** 唤醒所有等待中的子代理监听者 */
2519
+ notifySubagentWaitListeners() {
2520
+ for (const listener of this.subagentWaitListeners) {
2521
+ try {
2522
+ listener();
2523
+ }
2524
+ catch {
2525
+ // 忽略监听者异常
2526
+ }
2527
+ }
2528
+ }
2529
+ /** 列出子代理快照列表 */
2530
+ listSubagents(scope = "all") {
2531
+ const snaps = [];
2532
+ for (const conv of this.conversations.values()) {
2533
+ if (!conv.isSubagent)
2534
+ continue;
2535
+ if (scope === "persistent" && conv.isEphemeral)
2536
+ continue;
2537
+ if (scope === "subagent" && !conv.isEphemeral)
2538
+ continue;
2539
+ snaps.push(this.subagentToSnapshot(conv));
2540
+ }
2541
+ return snaps;
2542
+ }
2543
+ /** 向指定子代理发送引导/追加消息 */
2544
+ async steerSubagent(convId, message) {
2545
+ const conv = this.conversations.get(convId);
2546
+ if (!conv || !conv.isSubagent) {
2547
+ throw new Error(`Subagent ${convId} not found`);
2548
+ }
2549
+ conv.messages.push({
2550
+ id: `u-${Date.now()}-${randomUUID().slice(0, 6)}`,
2551
+ role: "user",
2552
+ content: [{ type: "text", text: message }],
2553
+ timestamp: Date.now(),
2554
+ });
2555
+ conv.updatedAt = Date.now();
2556
+ this.flushSnapshot();
2557
+ }
2558
+ /** 跨代理协作交接 */
2559
+ async handoffSubagent(fromRunId, toRunId, payload) {
2560
+ const fromConv = this.conversations.get(fromRunId);
2561
+ const toConv = this.conversations.get(toRunId);
2562
+ if (!toConv) {
2563
+ throw new Error(`Target subagent ${toRunId} not found`);
2564
+ }
2565
+ if (fromConv) {
2566
+ fromConv.subagentHandoffTo = fromConv.subagentHandoffTo ? [...fromConv.subagentHandoffTo, toRunId] : [toRunId];
2567
+ }
2568
+ toConv.subagentHandoffFrom = toConv.subagentHandoffFrom ? [...toConv.subagentHandoffFrom, fromRunId] : [fromRunId];
2569
+ const record = {
2570
+ fromRunId,
2571
+ toRunId,
2572
+ timestamp: Date.now(),
2573
+ };
2574
+ this.subagentHandoffs = recordSubagentHandoff(this.subagentHandoffs, record, 50);
2575
+ // 向目标子代理注入交接卡片消息
2576
+ const now = Date.now();
2577
+ const fromType = fromConv?.subagentType ?? "peer";
2578
+ toConv.messages.push({
2579
+ id: `handoff-${now}-${randomUUID().slice(0, 6)}`,
2580
+ role: "user",
2581
+ content: [{ type: "text", text: formatSubagentHandoffMessage(fromType, fromRunId, payload) }],
2582
+ timestamp: now,
2583
+ });
2584
+ toConv.updatedAt = now;
2585
+ this.flushSnapshot();
2586
+ }
2587
+ dispose() {
2588
+ this.disposed = true;
2589
+ if (this.snapshotTimer) {
2590
+ clearTimeout(this.snapshotTimer);
2591
+ this.snapshotTimer = null;
2592
+ }
2593
+ for (const driver of this.subagentDrivers.values()) {
2594
+ try {
2595
+ void driver.abort();
2596
+ void driver.dispose();
2597
+ }
2598
+ catch {
2599
+ // 忽略驱动释放异常
2600
+ }
2601
+ }
2602
+ this.subagentDrivers.clear();
2603
+ this.subagentWaitListeners.clear();
2604
+ this.files.unwatchDir();
2605
+ this.modelAdmin.dispose();
2606
+ this.webUi.dispose();
2607
+ this.terminals.killAll({ shutdown: true });
2608
+ this.driver.dispose();
2609
+ }
2610
+ }