pi-web-ui 0.105.1 → 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 +43 -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 +136 -30
  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-Mk4laCAL.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-BDLVjBeK.js +0 -690
  74. package/web/dist/assets/index-BQC6lADz.css +0 -1
@@ -95,6 +95,10 @@ export const SUBAGENT_ACTIONS = [
95
95
  * 普通对话 id 即可(不在子代理列表里,delete 是 no-op)。
96
96
  */
97
97
  export function makeSubagentTool(host, lang, selfConvId) {
98
+ // B20:过户会把对话改名(撞 id 时 remap),自省 id 必须在调用时刻解析
99
+ // (按 runtime 身份查当前持有方),不能死用建时的旧 id —— 否则 wait_all
100
+ // 排除自省/展开后代时拿错锚点。传函数形式由建时点按 findConversationHome 解析。
101
+ const selfIdOf = () => (typeof selfConvId === "function" ? selfConvId() : selfConvId);
98
102
  const getLang = lang ?? host.lang ?? (() => "en");
99
103
  const text = (t, details = {}) => ({
100
104
  content: [{ type: "text", text: t }],
@@ -205,6 +209,9 @@ export function makeSubagentTool(host, lang, selfConvId) {
205
209
  templateLineEn,
206
210
  modelLineZh,
207
211
  modelLineEn,
212
+ kindLabel: kindLabelEn,
213
+ kindLabelEn,
214
+ kindLabelZh,
208
215
  }), { convId, template: p.template, model: p.model, persisted: !!p.persist });
209
216
  }
210
217
  case "get_result": {
@@ -242,7 +249,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
242
249
  return text(pick(getLang(), `已向子代理 ${steerId} 注入消息。`, `Message injected into subagent ${steerId}.`, "subagents.steer.injected", { steerId }));
243
250
  }
244
251
  case "list": {
245
- const list = host.listSubagents(p.kind);
252
+ const list = host.listSubagents(p.kind, selfIdOf());
246
253
  if (list.length === 0)
247
254
  return text(pick(getLang(), "当前没有运行中的对话/子代理。", "No managed conversations or subagents running.", "subagents.list.empty"));
248
255
  const tLang = getLang();
@@ -272,6 +279,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
272
279
  return text(pick(getLang(), `已请求停止子代理 ${stopId}。`, `Stop requested for subagent ${stopId}.`, "subagents.stop.requested", { stopId }));
273
280
  }
274
281
  case "wait_all": {
282
+ const selfId = selfIdOf();
275
283
  const ancestorIdsOf = (selfId) => {
276
284
  const out = new Set();
277
285
  const seen = new Set([selfId]);
@@ -287,7 +295,9 @@ export function makeSubagentTool(host, lang, selfConvId) {
287
295
  if (roots instanceof Set ? roots.size === 0 : roots.length === 0)
288
296
  return [];
289
297
  const rootSet = roots instanceof Set ? roots : new Set(roots);
290
- const all = host.listSubagents();
298
+ // B20:带 forSelfId(本会话的族)展开 —— 过户把整族搬到别的会话后,
299
+ // 只列本会话自己的列表会展不开后代,wait_all 会误报「没有需要等待的子代理」。
300
+ const all = host.listSubagents(undefined, selfId);
291
301
  const out = [];
292
302
  for (const s of all) {
293
303
  if (rootSet.has(s.convId))
@@ -309,11 +319,11 @@ export function makeSubagentTool(host, lang, selfConvId) {
309
319
  };
310
320
  const explicit = p.runIds && p.runIds.length > 0;
311
321
  const wanted = new Set();
312
- const selfAncestorIds = selfConvId ? ancestorIdsOf(selfConvId) : new Set();
322
+ const selfAncestorIds = selfId ? ancestorIdsOf(selfId) : new Set();
313
323
  if (explicit) {
314
324
  const seedRoots = [];
315
325
  for (const id of p.runIds) {
316
- if (selfConvId && id === selfConvId)
326
+ if (selfId && id === selfId)
317
327
  continue;
318
328
  if (selfAncestorIds.has(id))
319
329
  continue;
@@ -321,16 +331,16 @@ export function makeSubagentTool(host, lang, selfConvId) {
321
331
  seedRoots.push(id);
322
332
  }
323
333
  for (const descId of expandDescendants(seedRoots)) {
324
- if (selfConvId && descId === selfConvId)
334
+ if (selfId && descId === selfId)
325
335
  continue;
326
336
  if (selfAncestorIds.has(descId))
327
337
  continue;
328
338
  wanted.add(descId);
329
339
  }
330
340
  }
331
- else if (selfConvId) {
332
- for (const descId of expandDescendants(new Set([selfConvId]))) {
333
- if (descId === selfConvId)
341
+ else if (selfId) {
342
+ for (const descId of expandDescendants(new Set([selfId]))) {
343
+ if (descId === selfId)
334
344
  continue;
335
345
  if (selfAncestorIds.has(descId))
336
346
  continue;
@@ -342,8 +352,8 @@ export function makeSubagentTool(host, lang, selfConvId) {
342
352
  wanted.add(r.convId);
343
353
  }
344
354
  }
345
- if (selfConvId)
346
- wanted.delete(selfConvId);
355
+ if (selfId)
356
+ wanted.delete(selfId);
347
357
  for (const ancId of selfAncestorIds)
348
358
  wanted.delete(ancId);
349
359
  if (wanted.size === 0) {
@@ -354,7 +364,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
354
364
  const POLL_INTERVAL_MS = 250;
355
365
  while (!signal?.aborted && Date.now() - startedAt < timeoutMs) {
356
366
  for (const descId of expandDescendants(wanted)) {
357
- if (selfConvId && descId === selfConvId)
367
+ if (selfId && descId === selfId)
358
368
  continue;
359
369
  if (selfAncestorIds.has(descId))
360
370
  continue;
@@ -428,7 +438,7 @@ export function makeSubagentTool(host, lang, selfConvId) {
428
438
  return text(pick(getLang(), `可用的子代理模板(subagent 的 template 参数传名字,如 subagent(action="spawn", template="${firstTemplateName}")):\n${templateLines}`, `Available subagent templates (pass the name as subagent's template param, e.g. subagent(action="spawn", template="${firstTemplateName}")):\n${templateLines}`, "subagents.templates.list", { firstTemplateName, templateLines }));
429
439
  }
430
440
  case "handoff": {
431
- const fromId = p.fromRunId || selfConvId || "unknown";
441
+ const fromId = p.fromRunId || selfIdOf() || "unknown";
432
442
  if (!p.toRunId || typeof p.toRunId !== "string" || !p.toRunId.trim()) {
433
443
  return text(pick(getLang(), 'subagent(action="handoff") 缺少 toRunId 参数。', 'subagent(action="handoff") requires toRunId parameter.', "subagents.handoff.missing.toRunId"));
434
444
  }
@@ -1982,7 +1982,7 @@ export function makeTerminalBashTool(terminals, opts) {
1982
1982
  : incomplete === "unclosed_block"
1983
1983
  ? "has an unclosed if/for/case block"
1984
1984
  : "has an unclosed { } / ( ) group";
1985
- throw new Error(pick(lang, `命令语法不完整(${reasonZh}),未执行。终端接管 bash 无法为它注入退出码哨兵,残句还会让 shell 停在续行提示符、零执行。请补全引号 / 续行符 / 括号后重试。`, `Command is syntactically incomplete (${reasonEn}); nothing was executed. The terminal bash path cannot inject an exit-code sentinel here, and the leftover fragment would leave the shell waiting at a continuation prompt. Complete the quote / continuation / bracket and retry.`, "terminals.bash.incomplete"));
1985
+ throw new Error(pick(lang, `命令语法不完整(${reasonZh}),未执行。终端接管 bash 无法为它注入退出码哨兵,残句还会让 shell 停在续行提示符、零执行。请补全引号 / 续行符 / 括号后重试。`, `Command is syntactically incomplete (${reasonEn}); nothing was executed. The terminal bash path cannot inject an exit-code sentinel here, and the leftover fragment would leave the shell waiting at a continuation prompt. Complete the quote / continuation / bracket and retry.`, "terminals.bash.incomplete", { reason: reasonEn, reasonEn, reasonZh }));
1986
1986
  }
1987
1987
  const persist = p.persist ?? opts.defaultPersist();
1988
1988
  // create() 对已存活的同名终端原样返回、对已退出的原地重启。
@@ -2088,7 +2088,7 @@ export function makeTerminalBashTool(terminals, opts) {
2088
2088
  terminals.inputChecked(termId, "\x03");
2089
2089
  closeOneShot();
2090
2090
  const timeoutPartial = truncateMiddle(stripAnsi(collected), 4000);
2091
- throw new Error(pick(lang, `Command timed out after ${p.timeout}s(已发 Ctrl+C;已有输出:${timeoutPartial})`, `Command timed out after ${p.timeout}s (sent Ctrl+C; partial output: ${timeoutPartial})`, "terminals.bash.timeout", { "p.timeout": p.timeout, timeoutPartial }));
2091
+ throw new Error(pick(lang, `Command timed out after ${p.timeout}s(已发 Ctrl+C;已有输出:${timeoutPartial})`, `Command timed out after ${p.timeout}s (sent Ctrl+C; partial output: ${timeoutPartial})`, "terminals.bash.timeout", { "p.timeout": p.timeout, timeout: p.timeout, timeoutPartial, sentinelNote: "" }));
2092
2092
  }
2093
2093
  // 静默解阻(仅持久终端):转后台 + 注册完成观察器,立即把控制权还给模型。
2094
2094
  if (persist && idleMs > 0 && Date.now() - lastDataAt >= idleMs) {
@@ -441,6 +441,9 @@ export function applyAgentToolsGating(session, disabled, preset, options) {
441
441
  else if (allNames.includes(core))
442
442
  names.add(core);
443
443
  }
444
+ // load_tools 是延迟加载模式下的脚手架工具:非延迟加载模式下绝不暴露给模型。
445
+ // 默认从候选集中剔除;仅当延迟加载开启且由 options.forceActive 显式指定时才加回。
446
+ names.delete(LOAD_TOOLS_TOOL_NAME);
444
447
  const filtered = filterToolsByPreset(names, preset);
445
448
  const active = new Set(filtered);
446
449
  const baseline = new Set(allNames);
@@ -0,0 +1,56 @@
1
+ /**
2
+ * driver-base.ts — 通用 Agent 适配底座基础驱动契约与能力定义。
3
+ *
4
+ * 任何第三方 Agent(Claude Code、Aider、Codex、ACP 等)只要实现 BaseAgentDriver,
5
+ * 并向 AgentEventSink 发射标准事件,即可通过 UniversalAgentHost 自动获得:
6
+ * - Web 聊天界面渲染(文本、流式 Thinking 气泡、折叠工具调用卡片、Token 统计)
7
+ * - 完整工作区文件树(代码查看、高亮、文件上传、图片音视频预览)
8
+ * - 底部/侧边多终端(xterm.js + node-pty)
9
+ * - Git SCM(代码差异、状态、提交历史)
10
+ * - 后台服务检测与一键释放
11
+ * - 60ms 增量快照广播与刷新后状态恢复
12
+ */
13
+ import { DEFAULT_UNIVERSAL_CAPABILITIES } from "../engine-capabilities.js";
14
+ /**
15
+ * 通用 Agent 驱动抽象基类。
16
+ */
17
+ export class BaseAgentDriver {
18
+ cwd;
19
+ constructor(cwd) {
20
+ this.cwd = cwd;
21
+ }
22
+ /** 更新驱动运行的工作目录 */
23
+ setCwd(cwd) {
24
+ this.cwd = cwd;
25
+ }
26
+ /** 列出可用的模型列表(若不支持返回空数组) */
27
+ async listModels() {
28
+ return [];
29
+ }
30
+ /** 切换当前模型(可选) */
31
+ async setModel(_modelId) {
32
+ /* 可由子类覆盖 */
33
+ }
34
+ /** 转换为标准底座能力声明(AgentEngineCapabilities)供前端与快照使用 */
35
+ getEngineCapabilities() {
36
+ return {
37
+ ...DEFAULT_UNIVERSAL_CAPABILITIES,
38
+ treeFork: this.capabilities.supportsTreeFork ?? false,
39
+ messageEdit: this.capabilities.supportsHistoryEdit ?? false,
40
+ toolPromptOverride: this.capabilities.supportsToolPromptOverride ?? false,
41
+ subagents: this.capabilities.supportsSubagents ?? DEFAULT_UNIVERSAL_CAPABILITIES.subagents,
42
+ };
43
+ }
44
+ /** 驱动支持的自定义斜杠命令列表(供输入框 / 补全展示) */
45
+ async getSlashCommands() {
46
+ return [];
47
+ }
48
+ /** 驱动执行自定义斜杠命令(返回 true 表示已拦截处理,无需作为普通 prompt 投递) */
49
+ async execSlashCommand(_name, _args, _context) {
50
+ return false;
51
+ }
52
+ /** 驱动特定的额外技能列表 */
53
+ async getSkills() {
54
+ return [];
55
+ }
56
+ }
@@ -0,0 +1,462 @@
1
+ /**
2
+ * claude-code.ts — Anthropic Claude Code CLI 驱动实现。
3
+ *
4
+ * 通过子进程拉起官方 `claude` CLI(--output-format stream-json),
5
+ * 实时将 Claude Code 输出的 NDJSON 事件流映射为 Universal 底座的 AgentEventSink 事件。
6
+ *
7
+ * 特性:
8
+ * 1. 原生支持流式正文输出与 Thinking 思考过程;
9
+ * 2. 自动捕获 Bash / View / Edit / Glob / Grep 等工具调用并折叠展示;
10
+ * 3. 会话自动维护:每次对话通过 --resume <sessionId> 保持上下文连续;
11
+ * 4. 支持用户中断(abort)时向进程发送中断信号;
12
+ * 5. 环境容错:未安装 claude 时输出清晰友好的中英文引导提示。
13
+ */
14
+ import { execFile, spawn } from "node:child_process";
15
+ import { existsSync, writeFileSync } from "node:fs";
16
+ import { createInterface } from "node:readline";
17
+ import { homedir } from "node:os";
18
+ import { join } from "node:path";
19
+ import { BaseAgentDriver } from "../driver-base.js";
20
+ import { resolveProviderCredential, listCustomModelsFromConfig } from "../../model-resolver.js";
21
+ import { discoverDiskSkills } from "../../skill-discovery.js";
22
+ /**
23
+ * 快速异步探测系统中是否安装了可用的 Claude Code CLI。
24
+ */
25
+ export async function probeClaudeCode(executablePath = "claude") {
26
+ return new Promise((resolve) => {
27
+ try {
28
+ execFile(executablePath, ["--version"], {
29
+ timeout: 4000,
30
+ shell: process.platform === "win32",
31
+ }, (err, stdout) => {
32
+ if (err) {
33
+ resolve({ installed: false, error: err.message });
34
+ }
35
+ else {
36
+ const v = stdout.trim();
37
+ resolve({ installed: true, version: v || undefined });
38
+ }
39
+ });
40
+ }
41
+ catch (err) {
42
+ const msg = err instanceof Error ? err.message : String(err);
43
+ resolve({ installed: false, error: msg });
44
+ }
45
+ });
46
+ }
47
+ export class ClaudeCodeDriver extends BaseAgentDriver {
48
+ id = "claude-code";
49
+ name = "Claude Code";
50
+ capabilities = {
51
+ supportsTreeFork: false,
52
+ supportsHistoryEdit: false,
53
+ supportsToolPromptOverride: false,
54
+ supportsModelSwitch: true,
55
+ supportsThinkingLevels: true,
56
+ supportsAskUser: false,
57
+ };
58
+ executablePath;
59
+ extraArgs;
60
+ agentDir;
61
+ currentModel;
62
+ activeSessionId = null;
63
+ activeProcess = null;
64
+ aborted = false;
65
+ lastErrorHint = "";
66
+ turnHadText = false;
67
+ turnCompleteEmitted = false;
68
+ lastTurnMeta;
69
+ constructor(cwd, opts) {
70
+ super(cwd);
71
+ this.executablePath = opts?.executablePath ?? "claude";
72
+ // 默认添加 --dangerously-skip-permissions,防止无头模式下因等待交互式 y/n 确认导致整个生成假死
73
+ this.extraArgs = opts?.extraArgs ?? ["--dangerously-skip-permissions"];
74
+ this.currentModel = opts?.defaultModel ?? "claude-3-7-sonnet-20250219";
75
+ this.agentDir = opts?.agentDir || process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
76
+ }
77
+ async createSession() {
78
+ this.activeSessionId = null;
79
+ return `claude-sess-${Date.now()}`;
80
+ }
81
+ async resumeSession(sessionId) {
82
+ this.activeSessionId = sessionId;
83
+ }
84
+ getActiveSessionId() {
85
+ return this.activeSessionId;
86
+ }
87
+ async sendPrompt(prompt, attachments, sink) {
88
+ this.aborted = false;
89
+ this.lastErrorHint = "";
90
+ this.turnHadText = false;
91
+ this.turnCompleteEmitted = false;
92
+ // 格式化用户附件上下文
93
+ let finalPrompt = prompt;
94
+ if (attachments && attachments.length > 0) {
95
+ const notes = [];
96
+ for (const att of attachments) {
97
+ if (att.path) {
98
+ const lineRange = att.lines ? ` (行 ${att.lines.start}-${att.lines.end})` : "";
99
+ notes.push(`[文件引用: ${att.path}${lineRange}]`);
100
+ }
101
+ else if (att.uploadPath) {
102
+ notes.push(`[上传文件: ${att.name || att.uploadPath}]`);
103
+ }
104
+ else if (att.imageData) {
105
+ notes.push(`[包含图片附件: ${att.name || "图片"}]`);
106
+ }
107
+ else if (att.quote?.text) {
108
+ notes.push(`[引用内容: "${att.quote.text.slice(0, 100)}..."]`);
109
+ }
110
+ }
111
+ if (notes.length > 0) {
112
+ finalPrompt = `${notes.join("\n")}\n\n${prompt}`;
113
+ }
114
+ }
115
+ const args = ["-p", finalPrompt, "--output-format", "stream-json", "--verbose", ...this.extraArgs];
116
+ // 解析目标模型与对应服务商凭据
117
+ let targetModel = this.currentModel;
118
+ let targetProvider = "anthropic";
119
+ if (this.currentModel.includes("/")) {
120
+ const parts = this.currentModel.split("/");
121
+ if (parts[0] === "claude-code") {
122
+ targetProvider = "anthropic";
123
+ targetModel = parts.slice(1).join("/");
124
+ }
125
+ else {
126
+ targetProvider = parts[0];
127
+ targetModel = parts.slice(1).join("/");
128
+ }
129
+ }
130
+ if (targetModel) {
131
+ args.push("--model", targetModel);
132
+ }
133
+ if (this.activeSessionId) {
134
+ args.push("--resume", this.activeSessionId);
135
+ }
136
+ // 动态从模型配置基础层解析凭据与 BaseURL,实现类似 cc-switch 的零侵入环境注入
137
+ const cred = this.agentDir
138
+ ? resolveProviderCredential(this.agentDir, targetProvider)
139
+ : { providerId: targetProvider };
140
+ const spawnEnv = {
141
+ ...process.env,
142
+ NO_COLOR: "1",
143
+ CI: "1",
144
+ };
145
+ if (cred.baseUrl) {
146
+ spawnEnv.ANTHROPIC_BASE_URL = cred.baseUrl;
147
+ }
148
+ if (cred.apiKey) {
149
+ spawnEnv.ANTHROPIC_API_KEY = cred.apiKey;
150
+ }
151
+ if (cred.headers) {
152
+ for (const [hk, hv] of Object.entries(cred.headers)) {
153
+ if (hk.toLowerCase() === "authorization" && hv) {
154
+ spawnEnv.ANTHROPIC_AUTH_TOKEN = hv.replace(/^Bearer\s+/i, "");
155
+ }
156
+ }
157
+ }
158
+ let proc;
159
+ try {
160
+ proc = spawn(this.executablePath, args, {
161
+ cwd: this.cwd,
162
+ env: spawnEnv,
163
+ // Windows 下处理 .cmd 包装脚本;Unix 下 detached 方便向进程组发送 SIGINT
164
+ shell: process.platform === "win32",
165
+ detached: process.platform !== "win32",
166
+ });
167
+ // 立即关闭 stdin,防止 CLI 因等待流式输入而挂死
168
+ proc.stdin?.end();
169
+ }
170
+ catch (err) {
171
+ const msg = err instanceof Error ? err.message : String(err);
172
+ sink.onError(`无法启动 Claude Code CLI: ${msg}。请确保已全局安装 npm i -g @anthropic-ai/claude-code 且已在终端运行 claude 完成登录。`);
173
+ return;
174
+ }
175
+ this.activeProcess = proc;
176
+ const activeToolJson = new Map();
177
+ if (proc.stdout) {
178
+ const rl = createInterface({ input: proc.stdout, terminal: false });
179
+ rl.on("line", (line) => {
180
+ const trimmed = line.trim();
181
+ if (!trimmed || !trimmed.startsWith("{"))
182
+ return;
183
+ try {
184
+ const event = JSON.parse(trimmed);
185
+ this.handleClaudeEvent(event, sink, activeToolJson);
186
+ }
187
+ catch {
188
+ // 忽略非 JSON 行日志
189
+ }
190
+ });
191
+ }
192
+ let stderrOutput = "";
193
+ if (proc.stderr) {
194
+ proc.stderr.on("data", (chunk) => {
195
+ stderrOutput += chunk.toString("utf-8");
196
+ });
197
+ }
198
+ return new Promise((resolve) => {
199
+ proc.on("error", (err) => {
200
+ this.activeProcess = null;
201
+ if (!this.aborted) {
202
+ sink.onError(`Claude Code 进程启动失败: ${err.message}`);
203
+ }
204
+ resolve();
205
+ });
206
+ proc.on("close", (code) => {
207
+ this.activeProcess = null;
208
+ if (this.aborted) {
209
+ resolve();
210
+ return;
211
+ }
212
+ if (code !== 0 && code !== null) {
213
+ const errHint = this.lastErrorHint || stderrOutput.trim() || `Exit code ${code}`;
214
+ sink.onError(`Claude Code 执行退出 (code ${code}): ${errHint}`);
215
+ }
216
+ else if (!this.turnCompleteEmitted) {
217
+ const meta = { model: this.currentModel };
218
+ this.lastTurnMeta = meta;
219
+ sink.onTurnComplete(meta);
220
+ }
221
+ resolve();
222
+ });
223
+ });
224
+ }
225
+ handleClaudeEvent(event, sink, activeToolJson) {
226
+ const type = String(event.type ?? "");
227
+ // 1. 会话建立或恢复事件
228
+ if (type === "system" && typeof event.session_id === "string") {
229
+ this.activeSessionId = event.session_id;
230
+ }
231
+ // 1.1 assistant 完整消息(含思考、正文、错误或合成响应)
232
+ if (type === "assistant") {
233
+ const msg = event.message;
234
+ if (msg && Array.isArray(msg.content)) {
235
+ for (const item of msg.content) {
236
+ if (item && typeof item === "object") {
237
+ const block = item;
238
+ if (block.type === "thinking" && typeof block.thinking === "string" && block.thinking.trim()) {
239
+ sink.onThinkingDelta(block.thinking);
240
+ }
241
+ else if (block.type === "text" && typeof block.text === "string" && block.text.trim()) {
242
+ sink.onTextDelta(block.text);
243
+ this.turnHadText = true;
244
+ }
245
+ }
246
+ }
247
+ }
248
+ if (event.error) {
249
+ const errMsg = typeof event.error === "string" ? event.error : JSON.stringify(event.error);
250
+ this.lastErrorHint = errMsg;
251
+ }
252
+ }
253
+ // 2. 流式 Content Block 增量
254
+ if (type === "content_block_delta") {
255
+ const delta = event.delta;
256
+ if (!delta)
257
+ return;
258
+ if (delta.type === "text_delta" && typeof delta.text === "string") {
259
+ sink.onTextDelta(delta.text);
260
+ this.turnHadText = true;
261
+ }
262
+ else if (delta.type === "thinking_delta" && typeof delta.thinking === "string") {
263
+ sink.onThinkingDelta(delta.thinking);
264
+ }
265
+ else if (delta.type === "input_json_delta" && typeof delta.partial_json === "string") {
266
+ const index = String(event.index ?? 0);
267
+ activeToolJson.set(index, (activeToolJson.get(index) ?? "") + delta.partial_json);
268
+ }
269
+ }
270
+ // 3. 工具调用开始 (content_block_start)
271
+ if (type === "content_block_start") {
272
+ const block = event.content_block;
273
+ if (block && block.type === "tool_use") {
274
+ const callId = String(block.id ?? `tool_${Date.now()}`);
275
+ const toolName = String(block.name ?? "tool");
276
+ const input = block.input ?? {};
277
+ sink.onToolStart(callId, toolName, input);
278
+ }
279
+ }
280
+ // 4. 工具调用直接触发 (完整块)
281
+ if (type === "tool_use") {
282
+ const callId = String(event.id ?? `tool_${Date.now()}`);
283
+ const toolName = String(event.name ?? "tool");
284
+ const input = event.input ?? {};
285
+ sink.onToolStart(callId, toolName, input);
286
+ }
287
+ // 5. 工具执行结果
288
+ if (type === "tool_result") {
289
+ const toolId = String(event.tool_use_id ?? event.id ?? "");
290
+ const content = typeof event.content === "string" ? event.content : JSON.stringify(event.content ?? "");
291
+ const isError = Boolean(event.is_error);
292
+ sink.onToolEnd(toolId, isError ? { error: content } : { output: content });
293
+ }
294
+ // 6. 最终完成统计
295
+ if (type === "result") {
296
+ if (event.is_error && event.result) {
297
+ const resStr = typeof event.result === "string" ? event.result : JSON.stringify(event.result);
298
+ this.lastErrorHint = resStr;
299
+ }
300
+ else if (!this.turnHadText && typeof event.result === "string" && event.result.trim()) {
301
+ sink.onTextDelta(event.result.trim());
302
+ this.turnHadText = true;
303
+ }
304
+ const usage = event.usage;
305
+ const costUSD = typeof event.total_cost_usd === "number" ? event.total_cost_usd : undefined;
306
+ const inputTokens = usage?.input_tokens ?? 0;
307
+ const outputTokens = usage?.output_tokens ?? 0;
308
+ const cacheReadTokens = usage?.cache_read_input_tokens ?? 0;
309
+ const cacheWriteTokens = usage?.cache_creation_input_tokens ?? 0;
310
+ this.turnCompleteEmitted = true;
311
+ const turnMeta = {
312
+ usage: usage
313
+ ? {
314
+ inputTokens,
315
+ outputTokens,
316
+ cacheReadTokens,
317
+ cacheWriteTokens,
318
+ costUSD,
319
+ }
320
+ : undefined,
321
+ costUSD,
322
+ contextTokens: inputTokens > 0 ? inputTokens + outputTokens : undefined,
323
+ model: typeof event.model === "string" ? event.model : this.currentModel,
324
+ };
325
+ this.lastTurnMeta = turnMeta;
326
+ sink.onTurnComplete(turnMeta);
327
+ }
328
+ }
329
+ async abort() {
330
+ this.aborted = true;
331
+ if (this.activeProcess) {
332
+ try {
333
+ if (process.platform === "win32") {
334
+ // Windows 上 spawn 带有 shell 时通过 taskkill /t /f 终止整棵进程树
335
+ spawn("taskkill", ["/pid", String(this.activeProcess.pid), "/t", "/f"]);
336
+ }
337
+ else {
338
+ try {
339
+ process.kill(-this.activeProcess.pid, "SIGINT");
340
+ }
341
+ catch {
342
+ this.activeProcess.kill("SIGINT");
343
+ }
344
+ }
345
+ }
346
+ catch {
347
+ /* best effort */
348
+ }
349
+ this.activeProcess = null;
350
+ }
351
+ }
352
+ async listModels() {
353
+ const official = [
354
+ { id: "claude-3-7-sonnet-20250219", name: "Claude 3.7 Sonnet" },
355
+ { id: "claude-3-5-sonnet-20241022", name: "Claude 3.5 Sonnet" },
356
+ { id: "claude-3-5-haiku-20241022", name: "Claude 3.5 Haiku" },
357
+ { id: "claude-3-opus-20240229", name: "Claude 3 Opus" },
358
+ ];
359
+ if (!this.agentDir)
360
+ return official;
361
+ const custom = listCustomModelsFromConfig(this.agentDir);
362
+ const customRows = custom.map((c) => ({
363
+ id: `${c.providerId}/${c.modelId}`,
364
+ name: c.name,
365
+ }));
366
+ return [...official, ...customRows];
367
+ }
368
+ async setModel(modelId) {
369
+ this.currentModel = modelId;
370
+ }
371
+ async getSlashCommands() {
372
+ return [
373
+ {
374
+ name: "cost",
375
+ description: "查看 Claude Code 累计 Token 与成本消耗",
376
+ descriptionEn: "Show Claude Code cumulative tokens & cost",
377
+ source: "extension",
378
+ },
379
+ {
380
+ name: "doctor",
381
+ description: "运行 Claude Code 环境与凭据健康诊断",
382
+ descriptionEn: "Run Claude Code environment & auth diagnostics",
383
+ source: "extension",
384
+ },
385
+ {
386
+ name: "init",
387
+ description: "在当前工作区初始化 CLAUDE.md 指引文件",
388
+ descriptionEn: "Initialize CLAUDE.md guidelines in workspace",
389
+ source: "extension",
390
+ },
391
+ {
392
+ name: "clear",
393
+ description: "重置 Claude Code 会话上下文(相当于 /clear)",
394
+ descriptionEn: "Reset Claude Code session context",
395
+ source: "extension",
396
+ },
397
+ ];
398
+ }
399
+ async execSlashCommand(name, _args, context) {
400
+ switch (name) {
401
+ case "cost": {
402
+ const meta = this.lastTurnMeta;
403
+ const usage = meta?.usage;
404
+ const cost = meta?.costUSD ?? usage?.costUSD ?? 0;
405
+ const text = usage
406
+ ? `Claude Code 用量:输入 ${usage.inputTokens ?? 0} tokens · 输出 ${usage.outputTokens ?? 0} tokens · 费用 $${cost.toFixed(4)}`
407
+ : `Claude Code 当前未记录上一轮 token 用量`;
408
+ const textEn = usage
409
+ ? `Claude Code usage: in ${usage.inputTokens ?? 0} tok · out ${usage.outputTokens ?? 0} tok · cost $${cost.toFixed(4)}`
410
+ : `No turn token usage recorded yet`;
411
+ context?.emitNotice?.("info", text, textEn);
412
+ return true;
413
+ }
414
+ case "doctor": {
415
+ const probe = await probeClaudeCode(this.executablePath);
416
+ const status = probe.installed
417
+ ? `Claude Code CLI 正常 (版本: ${probe.version ?? "已安装"}) · Node ${process.version}`
418
+ : `未检测到 Claude Code CLI: ${probe.error ?? "请运行 npm i -g @anthropic-ai/claude-code"}`;
419
+ const statusEn = probe.installed
420
+ ? `Claude Code CLI OK (v${probe.version ?? "installed"}) · Node ${process.version}`
421
+ : `Claude Code CLI not found: ${probe.error ?? "run npm i -g @anthropic-ai/claude-code"}`;
422
+ context?.emitNotice?.(probe.installed ? "info" : "warning", status, statusEn);
423
+ return true;
424
+ }
425
+ case "init": {
426
+ const target = join(this.cwd, "CLAUDE.md");
427
+ if (existsSync(target)) {
428
+ context?.emitNotice?.("info", "CLAUDE.md 已存在于当前工作区", "CLAUDE.md already exists in workspace");
429
+ }
430
+ else {
431
+ try {
432
+ const template = `# CLAUDE.md\n\n> Project guidelines for Claude Code\n\n## Build & Test\n- Build: npm run build\n- Test: npm test\n`;
433
+ writeFileSync(target, template, "utf8");
434
+ context?.emitNotice?.("info", "已在当前工作区创建初始 CLAUDE.md", "Created initial CLAUDE.md in workspace");
435
+ }
436
+ catch (err) {
437
+ context?.emitNotice?.("error", `创建 CLAUDE.md 失败: ${err.message}`, `Failed to create CLAUDE.md: ${err.message}`);
438
+ }
439
+ }
440
+ return true;
441
+ }
442
+ case "clear": {
443
+ this.activeSessionId = null;
444
+ context?.emitNotice?.("info", "Claude Code 驱动会话上下文已重置", "Claude Code session context reset");
445
+ return true;
446
+ }
447
+ default:
448
+ return false;
449
+ }
450
+ }
451
+ async getSkills() {
452
+ const skills = discoverDiskSkills({ cwd: this.cwd, agentDir: this.agentDir });
453
+ return skills.map((s) => ({
454
+ name: s.name,
455
+ description: s.description,
456
+ filePath: s.filePath,
457
+ }));
458
+ }
459
+ dispose() {
460
+ void this.abort();
461
+ }
462
+ }