pi-web-ui 0.118.0 → 0.120.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 (195) hide show
  1. package/CHANGELOG.md +143 -1
  2. package/bin/hub-upgrade.mjs +33 -15
  3. package/bin/lib/atomic-file.mjs +90 -0
  4. package/dist/server/agent-service-daemon.js +44 -10
  5. package/dist/server/agent-service.js +930 -166
  6. package/dist/server/approval-default-rules.js +4 -4
  7. package/dist/server/ask-user-question-tool.js +3 -40
  8. package/dist/server/atomic-file.js +130 -5
  9. package/dist/server/background-executors.js +235 -0
  10. package/dist/server/bash-timeout.js +47 -0
  11. package/dist/server/bash-tool.js +72 -5
  12. package/dist/server/bg-servers.js +19 -13
  13. package/dist/server/browser-page-tool.js +38 -29
  14. package/dist/server/browser-script-tool.js +119 -0
  15. package/dist/server/canvas/canvas-agent-tool.js +46 -35
  16. package/dist/server/canvas/canvas-dispatch.js +12 -1
  17. package/dist/server/claim-files-tool.js +6 -7
  18. package/dist/server/client-state.js +457 -41
  19. package/dist/server/communicate-tool.js +59 -77
  20. package/dist/server/compact-context-tool.js +4 -13
  21. package/dist/server/conversation-communication.js +23 -1
  22. package/dist/server/conversation-read-tool.js +14 -23
  23. package/dist/server/conversation-rows.js +17 -0
  24. package/dist/server/conversation-tool-names.js +2 -2
  25. package/dist/server/conversation-tool.js +23 -15
  26. package/dist/server/conversation-touches.js +1 -1
  27. package/dist/server/delegate-mode.js +0 -1
  28. package/dist/server/delegate-task.js +18 -39
  29. package/dist/server/device-center/approval-summary.js +0 -1
  30. package/dist/server/device-center/bot-execution.js +0 -1
  31. package/dist/server/device-center/group-router-runtime.js +2 -0
  32. package/dist/server/device-center/hub-upgrade.js +5 -10
  33. package/dist/server/device-center/task-progress.js +2 -2
  34. package/dist/server/dispatch-domain-handlers.js +97 -24
  35. package/dist/server/dispatch-plugin-handlers.js +10 -0
  36. package/dist/server/dsh/dsh-agent-service.js +21 -19
  37. package/dist/server/durable/durable-agent-service.js +1 -1
  38. package/dist/server/edit-tool.js +293 -0
  39. package/dist/server/engine-catalog.js +8 -2
  40. package/dist/server/engine-cli.js +29 -7
  41. package/dist/server/engine-probe.js +11 -6
  42. package/dist/server/eval-tool.js +5 -19
  43. package/dist/server/files-service.js +41 -19
  44. package/dist/server/fs-copy.js +93 -0
  45. package/dist/server/goal-review-gate.js +2 -3
  46. package/dist/server/index.js +92 -3
  47. package/dist/server/job-runner.js +345 -0
  48. package/dist/server/lsp-tool.js +10 -28
  49. package/dist/server/marker-service.js +42 -30
  50. package/dist/server/mcp-agent-tool.js +22 -47
  51. package/dist/server/model-session.js +16 -0
  52. package/dist/server/native-cli-session-hooks.js +3 -2
  53. package/dist/server/native-cli-session.js +27 -2
  54. package/dist/server/patch-tool.js +2 -8
  55. package/dist/server/phone-tool.js +167 -0
  56. package/dist/server/plan-mode.js +7 -4
  57. package/dist/server/plan-update-tool.js +5 -8
  58. package/dist/server/plugin-api-catalog.js +13 -1
  59. package/dist/server/plugin-bundled.js +35 -28
  60. package/dist/server/plugin-catalog.js +6 -0
  61. package/dist/server/plugin-delivery.js +358 -0
  62. package/dist/server/plugin-inbox.js +152 -0
  63. package/dist/server/plugin-installer.js +15 -0
  64. package/dist/server/plugin-ledger.js +183 -0
  65. package/dist/server/plugin-manifest-validate.js +19 -0
  66. package/dist/server/plugin-materialize.js +161 -0
  67. package/dist/server/plugin-paths.js +60 -0
  68. package/dist/server/plugin-removal.js +16 -3
  69. package/dist/server/plugin-schedule.js +8 -7
  70. package/dist/server/plugin-secrets.js +7 -3
  71. package/dist/server/plugin-updater.js +2 -4
  72. package/dist/server/plugins.js +205 -48
  73. package/dist/server/present-files-tool.js +7 -13
  74. package/dist/server/preset-fields.js +23 -12
  75. package/dist/server/preset-share.js +1 -1
  76. package/dist/server/process-utils.js +11 -0
  77. package/dist/server/project-scripts.js +38 -0
  78. package/dist/server/prompt-composer.js +40 -21
  79. package/dist/server/protocol-version.js +1 -1
  80. package/dist/server/question-params.js +98 -0
  81. package/dist/server/quick-ask-settings.js +0 -1
  82. package/dist/server/quick-ask.js +3 -0
  83. package/dist/server/read-tool.js +10 -17
  84. package/dist/server/remote-ssh-service.js +40 -1
  85. package/dist/server/sandbox-runtime-gate.js +1 -1
  86. package/dist/server/sandbox-service.js +0 -1
  87. package/dist/server/sandbox-tool.js +25 -34
  88. package/dist/server/schedule-agent-tool.js +9 -19
  89. package/dist/server/scm-commitmsg.js +2 -1
  90. package/dist/server/serialize.js +8 -0
  91. package/dist/server/session-list-index.js +246 -0
  92. package/dist/server/session-list-scan.js +5 -0
  93. package/dist/server/session-parser.js +16 -0
  94. package/dist/server/settings-service.js +49 -19
  95. package/dist/server/skill-tool.js +4 -6
  96. package/dist/server/subagent-budget.js +68 -0
  97. package/dist/server/subagent-evidence.js +297 -0
  98. package/dist/server/subagent-helpers.js +12 -0
  99. package/dist/server/subagent-ledger.js +401 -0
  100. package/dist/server/subagent-notify.js +6 -2
  101. package/dist/server/subagent-security-gate.js +2 -3
  102. package/dist/server/subagent-settle.js +71 -0
  103. package/dist/server/subagents.js +566 -211
  104. package/dist/server/tabs.js +8 -1
  105. package/dist/server/terminals.js +34 -28
  106. package/dist/server/tool-approval.js +15 -1
  107. package/dist/server/tool-guards.js +0 -91
  108. package/dist/server/tool-manager.js +127 -47
  109. package/dist/server/tool-overrides.js +8 -1
  110. package/dist/server/tool-prompt-overrides.js +3 -6
  111. package/dist/server/tool-prompts.js +60 -17
  112. package/dist/server/universal/driver-base.js +2 -0
  113. package/dist/server/universal/drivers/claude-code.js +210 -211
  114. package/dist/server/universal/drivers/codex.js +29 -24
  115. package/dist/server/universal/engine-mcp.js +107 -0
  116. package/dist/server/universal/universal-attachments.js +77 -1
  117. package/dist/server/universal/universal-service.js +1 -1
  118. package/dist/server/universal/universal-session.js +106 -69
  119. package/dist/server/vision-bridge.js +2 -0
  120. package/dist/server/workspace-handle.js +119 -17
  121. package/dist/server/workspace-queue.js +37 -0
  122. package/dist/server/worktree-tool.js +13 -20
  123. package/docs/README.md +40 -36
  124. package/docs/architecture-plugins.md +64 -35
  125. package/docs/device-center.md +1 -1
  126. package/package.json +16 -4
  127. package/plugin-sdk/index.d.ts +102 -0
  128. package/plugins/catalog.json +23 -51
  129. package/themes/bases/flow-base.css +8 -17
  130. package/themes/dark-teal.css +0 -3
  131. package/web/dist/.build-assets.json +1 -1
  132. package/web/dist/assets/BgTasksModal-BdOJ19Hj.js +1 -0
  133. package/web/dist/assets/BgTasksModal-SAH2XCkY.js +1 -0
  134. package/web/dist/assets/{CanvasStudio-CAWcs9tm.js → CanvasStudio-BB_Iq7pl.js} +3 -3
  135. package/web/dist/assets/CanvasStudio-DU6O3N4u.js +1579 -0
  136. package/web/dist/assets/DeviceCenter-By1zVTSY.js +3 -0
  137. package/web/dist/assets/DeviceCenter-Cnm0Tjrx.js +3 -0
  138. package/web/dist/assets/DeviceExecutionSettings-qJzbI0Cf.js +1 -0
  139. package/web/dist/assets/{DeviceGroups-C_fZMNeK.js → DeviceGroups-DPrQxW6B.js} +1 -1
  140. package/web/dist/assets/DeviceGroups-DoucyUjI.js +1 -0
  141. package/web/dist/assets/{Dropdown-CTgVLUbp.js → Dropdown-kj_NIj6e.js} +1 -1
  142. package/web/dist/assets/FilePreview-Bub8Y9uq.js +2 -0
  143. package/web/dist/assets/FilePreview-CC76Z6an.js +2 -0
  144. package/web/dist/assets/GlobalSearchModal-01nkgw4X.js +1 -0
  145. package/web/dist/assets/GlobalSearchModal-CiT6wBmR.js +1 -0
  146. package/web/dist/assets/GroupConversation-1-lsPO1f.js +61 -0
  147. package/web/dist/assets/GroupConversation-HeiyW_O_.js +61 -0
  148. package/web/dist/assets/{GroupWorkItems-BIvZtr10.js → GroupWorkItems-BYJv2XFj.js} +1 -1
  149. package/web/dist/assets/{HintTip-Da6qc566.js → HintTip-DFhoclDw.js} +1 -1
  150. package/web/dist/assets/ModelConfigModal-D2Ro-jUZ.js +2 -0
  151. package/web/dist/assets/ModelConfigModal-DPc9R1pq.js +2 -0
  152. package/web/dist/assets/{NativeCliPanel-CU1rZmyu.js → NativeCliPanel-B108d697.js} +3 -3
  153. package/web/dist/assets/NativeCliPanel-DupvGwQM.js +5 -0
  154. package/web/dist/assets/{PiSetupModal-DZKY5Wiw.js → PiSetupModal-D0HitBfd.js} +1 -1
  155. package/web/dist/assets/ProviderOAuthControls-BLKUEDde.js +1 -0
  156. package/web/dist/assets/SCMPanel-DDbWrUHR.js +2 -0
  157. package/web/dist/assets/SCMPanel-DluNcd2-.js +2 -0
  158. package/web/dist/assets/SettingsModal-Cy5lRC97.css +1 -0
  159. package/web/dist/assets/SettingsModal-DQu18366.js +33 -0
  160. package/web/dist/assets/SettingsModal-Dm_haPme.js +33 -0
  161. package/web/dist/assets/{TermXterm-Bt5WKAxP.js → TermXterm-SYc-MUk2.js} +2 -2
  162. package/web/dist/assets/TerminalPanel-CgA_lhVT.js +1 -0
  163. package/web/dist/assets/TerminalPanel-vdSIOPjD.js +1 -0
  164. package/web/dist/assets/TuiOverlayModal-Cy1jYYIw.js +1 -0
  165. package/web/dist/assets/TuiOverlayModal-kXY_4hV8.js +1 -0
  166. package/web/dist/assets/app-globals-CBEscsYP.js +129 -0
  167. package/web/dist/assets/{canvas-client-WkhM55mR.js → canvas-client-Clsypfs6.js} +1 -1
  168. package/web/dist/assets/{desktop-B8NZ3KW-.js → desktop-C6D9a8HZ.js} +1 -1
  169. package/web/dist/assets/index-BD29OL9L.js +404 -0
  170. package/web/dist/assets/index-BlCxbqqr.js +404 -0
  171. package/web/dist/assets/index-DB55rbKC.css +1 -0
  172. package/web/dist/assets/plugin-host-VWBcq-LQ.js +1 -0
  173. package/web/dist/assets/remote-ssh-client-C2eab5Kw.js +1 -0
  174. package/web/dist/assets/theme-CpQk_Agp.js +1 -0
  175. package/web/dist/index.html +10 -10
  176. package/web/dist/sw.js +1 -1
  177. package/dist/server/edit-soft-tool.js +0 -297
  178. package/web/dist/assets/BgTasksModal-D-x7kA63.js +0 -1
  179. package/web/dist/assets/DeviceCenter-Dc0whRcu.js +0 -3
  180. package/web/dist/assets/DeviceExecutionSettings-BoX7-0h7.js +0 -1
  181. package/web/dist/assets/FilePreview-C6W0PvaK.js +0 -2
  182. package/web/dist/assets/GlobalSearchModal-HR9LSspC.js +0 -1
  183. package/web/dist/assets/GroupConversation-C81YjF2C.js +0 -61
  184. package/web/dist/assets/ModelConfigModal-DhSyuIuV.js +0 -2
  185. package/web/dist/assets/ProviderOAuthControls-CIL85nA7.js +0 -1
  186. package/web/dist/assets/SCMPanel-CuEgzAlO.js +0 -2
  187. package/web/dist/assets/SettingsModal-Cdu5h29p.js +0 -33
  188. package/web/dist/assets/TerminalPanel-BCIBV8se.js +0 -1
  189. package/web/dist/assets/TuiOverlayModal-3NDd9T97.js +0 -1
  190. package/web/dist/assets/app-globals-CZjFtI4F.js +0 -129
  191. package/web/dist/assets/index-CQc3VrWa.css +0 -1
  192. package/web/dist/assets/index-D_AGu4Zv.js +0 -404
  193. package/web/dist/assets/plugin-host-uqZGpvCs.js +0 -1
  194. package/web/dist/assets/remote-ssh-client-Cdf-cTUe.js +0 -1
  195. package/web/dist/assets/theme-DGL7hLUs.js +0 -1
@@ -1,20 +1,73 @@
1
1
  import { spawn } from "node:child_process";
2
- import { existsSync, writeFileSync } from "node:fs";
2
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { createInterface } from "node:readline";
4
- import { homedir } from "node:os";
4
+ import { homedir, tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { probeEngineCliVersion, resolveEngineCliLaunch } from "../../engine-cli.js";
7
7
  import { BaseAgentDriver } from "../driver-base.js";
8
8
  import { resolveProviderCredential, listCustomModelsFromConfig, isModelProtocolSupportedByEngine, } from "../../model-resolver.js";
9
9
  import { discoverDiskSkills } from "../../skill-discovery.js";
10
- import { formatUnavailableCanvasReference } from "../universal-attachments.js";
10
+ import { decodeInlineImage, describeCliAttachment } from "../universal-attachments.js";
11
+ import { collectEnabledMcpServers, toClaudeMcpConfig } from "../engine-mcp.js";
12
+ /** `default` = no `--model`, so the CLI follows the user's own Claude Code configuration. */
13
+ export const CLAUDE_CODE_MODELS = [
14
+ { id: "default", name: "Default (Claude Code config)" },
15
+ { id: "opus", name: "Opus (latest)" },
16
+ { id: "sonnet", name: "Sonnet (latest)" },
17
+ { id: "haiku", name: "Haiku (latest)" },
18
+ ];
19
+ /** Older builds defaulted to retired Claude 3.x ids; those now fail every turn, so map them to `default`. */
20
+ export function normalizeClaudeModelId(modelId) {
21
+ const prefixed = modelId.startsWith("claude-code/");
22
+ const bare = prefixed ? modelId.slice("claude-code/".length) : modelId;
23
+ if (!bare.startsWith("claude-3-"))
24
+ return modelId;
25
+ return prefixed ? "claude-code/default" : "default";
26
+ }
27
+ /** pi-web-ui commands that drive UI state and must not be forwarded to the CLI. */
28
+ const PI_OWNED_SLASH = new Set([
29
+ "new",
30
+ "name",
31
+ "model",
32
+ "cwd",
33
+ "plan",
34
+ "thinking",
35
+ "resume",
36
+ "reload",
37
+ "help",
38
+ "copy",
39
+ "subagent",
40
+ "pi-web-ui:quit",
41
+ ]);
42
+ /** Claude API per-image limit; larger images are passed as files the CLI reads itself. */
43
+ const CLAUDE_MAX_INLINE_IMAGE_BYTES = 5 * 1024 * 1024;
11
44
  export async function probeClaudeCode(executablePath) {
12
45
  const { available, ...result } = await probeEngineCliVersion("claude", executablePath);
13
46
  return { installed: available, ...result };
14
47
  }
48
+ function toolResultText(content) {
49
+ if (typeof content === "string")
50
+ return content;
51
+ if (Array.isArray(content)) {
52
+ return content
53
+ .map((block) => {
54
+ if (block && typeof block === "object") {
55
+ const b = block;
56
+ if (b.type === "text" && typeof b.text === "string")
57
+ return b.text;
58
+ if (b.type === "image")
59
+ return "[image]";
60
+ }
61
+ return JSON.stringify(block);
62
+ })
63
+ .join("\n");
64
+ }
65
+ return JSON.stringify(content ?? "");
66
+ }
15
67
  export class ClaudeCodeDriver extends BaseAgentDriver {
16
68
  id = "claude-code";
17
69
  name = "Claude Code";
70
+ maxInlineImageBytes = CLAUDE_MAX_INLINE_IMAGE_BYTES;
18
71
  capabilities = {
19
72
  supportsTreeFork: false,
20
73
  supportsHistoryEdit: false,
@@ -26,6 +79,7 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
26
79
  executablePath;
27
80
  extraArgs;
28
81
  agentDir;
82
+ dataDir;
29
83
  currentModel;
30
84
  activeSessionId = null;
31
85
  activeProcess = null;
@@ -34,23 +88,29 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
34
88
  lastErrorHint = "";
35
89
  turnHadText = false;
36
90
  turnCompleteEmitted = false;
37
- lastTurnMeta;
91
+ resultFailed = false;
38
92
  currentThinkingLevel = "medium";
39
93
  seenToolStarts = new Set();
40
94
  seenToolEnds = new Set();
95
+ nativeSlashCommands = [];
96
+ nativeSkills = new Set();
97
+ slashCommandsChanged = false;
41
98
  constructor(cwd, opts) {
42
99
  super(cwd);
43
100
  this.executablePath = opts?.executablePath;
44
101
  this.extraArgs = opts?.extraArgs ?? ["--dangerously-skip-permissions"];
45
- this.currentModel = opts?.defaultModel ?? "claude-3-7-sonnet-20250219";
102
+ this.currentModel = normalizeClaudeModelId(opts?.defaultModel ?? "default");
46
103
  this.agentDir = opts?.agentDir || process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
104
+ this.dataDir = opts?.dataDir;
47
105
  }
48
106
  async createSession() {
107
+ // The real id is only known once the CLI reports it (system/init); never hand out a placeholder
108
+ // that a later `--resume` would reject.
49
109
  this.activeSessionId = null;
50
- return `claude-sess-${Date.now()}`;
110
+ return "";
51
111
  }
52
112
  async resumeSession(sessionId) {
53
- this.activeSessionId = sessionId;
113
+ this.activeSessionId = sessionId || null;
54
114
  }
55
115
  getActiveSessionId() {
56
116
  return this.activeSessionId;
@@ -61,59 +121,54 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
61
121
  getSupportedThinkingLevels() {
62
122
  return ["off", "low", "medium", "high", "xhigh", "max"];
63
123
  }
124
+ /** Builds the stream-json user message: inline images + text (attachment pointers, then the prompt). */
125
+ buildUserMessage(prompt, attachments) {
126
+ const content = [];
127
+ const notes = [];
128
+ for (const att of attachments ?? []) {
129
+ const image = decodeInlineImage(att);
130
+ if (image) {
131
+ content.push({ type: "image", source: { type: "base64", media_type: image.mimeType, data: image.data } });
132
+ continue;
133
+ }
134
+ const note = describeCliAttachment(att);
135
+ if (note)
136
+ notes.push(note);
137
+ }
138
+ content.push({ type: "text", text: notes.length ? `${notes.join("\n")}\n\n${prompt}` : prompt });
139
+ return { type: "user", message: { role: "user", content } };
140
+ }
64
141
  async sendPrompt(prompt, attachments, sink) {
65
142
  const mySeq = ++this.turnSeq;
66
143
  this.aborted = false;
67
144
  this.lastErrorHint = "";
68
145
  this.turnHadText = false;
69
146
  this.turnCompleteEmitted = false;
147
+ this.resultFailed = false;
70
148
  this.seenToolStarts.clear();
71
149
  this.seenToolEnds.clear();
72
- let finalPrompt = prompt;
73
- if (attachments && attachments.length > 0) {
74
- const notes = [];
75
- for (const att of attachments) {
76
- if (att.mode === "canvas") {
77
- notes.push(formatUnavailableCanvasReference(att));
78
- continue;
79
- }
80
- if (att.path) {
81
- const lineRange = att.lines ? ` (行 ${att.lines.start}-${att.lines.end})` : "";
82
- notes.push(`[文件引用: ${att.path}${lineRange}]`);
83
- }
84
- else if (att.uploadPath) {
85
- notes.push(`[上传文件: ${att.name || att.uploadPath}]`);
86
- }
87
- else if (att.imageData) {
88
- notes.push(`[包含图片附件: ${att.name || "图片"}]`);
89
- }
90
- else if (att.quote?.text) {
91
- notes.push(`[引用内容: "${att.quote.text.slice(0, 100)}..."]`);
92
- }
93
- }
94
- if (notes.length > 0) {
95
- finalPrompt = `${notes.join("\n")}\n\n${prompt}`;
96
- }
97
- }
98
- const args = ["-p", "--output-format", "stream-json", "--verbose", ...this.extraArgs];
150
+ const args = [
151
+ "-p",
152
+ "--input-format",
153
+ "stream-json",
154
+ "--output-format",
155
+ "stream-json",
156
+ "--verbose",
157
+ ...this.extraArgs,
158
+ ];
99
159
  let targetModel = this.currentModel;
100
160
  let targetProvider = null;
101
- let isOfficial = false;
161
+ let isOfficial = true;
102
162
  if (this.currentModel.includes("/")) {
103
- const parts = this.currentModel.split("/");
104
- if (parts[0] === "claude-code") {
105
- isOfficial = true;
106
- targetModel = parts.slice(1).join("/");
107
- }
108
- else {
109
- targetProvider = parts[0];
110
- targetModel = parts.slice(1).join("/");
163
+ const slash = this.currentModel.indexOf("/");
164
+ const provider = this.currentModel.slice(0, slash);
165
+ targetModel = this.currentModel.slice(slash + 1);
166
+ if (provider !== "claude-code") {
167
+ isOfficial = false;
168
+ targetProvider = provider;
111
169
  }
112
170
  }
113
- else {
114
- isOfficial = true;
115
- }
116
- if (targetModel) {
171
+ if (targetModel && targetModel !== "default") {
117
172
  args.push("--model", targetModel);
118
173
  }
119
174
  if (this.currentThinkingLevel && this.currentThinkingLevel !== "off") {
@@ -122,27 +177,42 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
122
177
  if (this.activeSessionId) {
123
178
  args.push("--resume", this.activeSessionId);
124
179
  }
125
- const spawnEnv = this.buildSpawnEnv(isOfficial, targetProvider);
180
+ let mcpDir;
181
+ const cleanup = () => {
182
+ if (mcpDir)
183
+ rmSync(mcpDir, { recursive: true, force: true });
184
+ mcpDir = undefined;
185
+ };
126
186
  let proc;
127
187
  try {
188
+ const servers = collectEnabledMcpServers({ cwd: this.cwd, agentDir: this.agentDir, dataDir: this.dataDir });
189
+ if (Object.keys(servers).length > 0) {
190
+ // File (not an inline JSON arg) so env/headers secrets don't show up in the process list.
191
+ mcpDir = mkdtempSync(join(tmpdir(), "pi-claude-mcp-"));
192
+ const mcpFile = join(mcpDir, "mcp.json");
193
+ writeFileSync(mcpFile, JSON.stringify(toClaudeMcpConfig(servers)), { mode: 0o600 });
194
+ args.push("--mcp-config", mcpFile);
195
+ }
196
+ const userMessage = this.buildUserMessage(prompt, attachments);
128
197
  const launch = resolveEngineCliLaunch("claude", { executablePath: this.executablePath, cwd: this.cwd });
129
198
  proc = spawn(launch.file, [...launch.args, ...args], {
130
199
  cwd: this.cwd,
131
- env: spawnEnv,
200
+ env: this.buildSpawnEnv(isOfficial, targetProvider),
132
201
  detached: process.platform !== "win32",
202
+ windowsHide: true,
133
203
  });
134
204
  if (proc.stdin) {
135
- proc.stdin.write(finalPrompt);
136
- proc.stdin.end();
205
+ proc.stdin.on("error", () => { });
206
+ proc.stdin.end(`${JSON.stringify(userMessage)}\n`);
137
207
  }
138
208
  }
139
209
  catch (err) {
210
+ cleanup();
140
211
  const msg = err instanceof Error ? err.message : String(err);
141
212
  sink.onError(`无法启动 Claude Code CLI: ${msg}。请确保已全局安装 npm i -g @anthropic-ai/claude-code 且已在终端运行 claude 完成登录。`);
142
213
  return;
143
214
  }
144
215
  this.activeProcess = proc;
145
- const activeToolJson = new Map();
146
216
  if (proc.stdout) {
147
217
  const rl = createInterface({ input: proc.stdout, terminal: false });
148
218
  rl.on("line", (line) => {
@@ -153,7 +223,7 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
153
223
  return;
154
224
  try {
155
225
  const event = JSON.parse(trimmed);
156
- this.handleClaudeEvent(event, sink, activeToolJson);
226
+ this.handleClaudeEvent(event, sink);
157
227
  }
158
228
  catch { }
159
229
  });
@@ -161,11 +231,12 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
161
231
  let stderrOutput = "";
162
232
  if (proc.stderr) {
163
233
  proc.stderr.on("data", (chunk) => {
164
- stderrOutput += chunk.toString("utf-8");
234
+ stderrOutput = (stderrOutput + chunk.toString("utf-8")).slice(-8000);
165
235
  });
166
236
  }
167
237
  return new Promise((resolve) => {
168
238
  proc.on("error", (err) => {
239
+ cleanup();
169
240
  if (mySeq !== this.turnSeq) {
170
241
  resolve();
171
242
  return;
@@ -178,6 +249,7 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
178
249
  resolve();
179
250
  });
180
251
  proc.on("close", (code) => {
252
+ cleanup();
181
253
  if (mySeq !== this.turnSeq) {
182
254
  resolve();
183
255
  return;
@@ -188,27 +260,45 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
188
260
  resolve();
189
261
  return;
190
262
  }
191
- if (code !== 0 && code !== null) {
263
+ if ((code !== 0 && code !== null) || this.resultFailed) {
192
264
  const errHint = this.lastErrorHint || stderrOutput.trim() || `Exit code ${code}`;
193
265
  sink.onError(`Claude Code 执行退出 (code ${code}): ${errHint}`);
194
266
  }
195
267
  else if (!this.turnCompleteEmitted) {
196
268
  const meta = { model: this.currentModel };
197
- this.lastTurnMeta = meta;
198
269
  sink.onTurnComplete(meta);
199
270
  }
200
271
  resolve();
201
272
  });
202
273
  });
203
274
  }
204
- handleClaudeEvent(event, sink, activeToolJson) {
275
+ noteSessionId(sessionId, sink) {
276
+ if (typeof sessionId !== "string" || !sessionId || sessionId === this.activeSessionId)
277
+ return;
278
+ this.activeSessionId = sessionId;
279
+ sink.onSessionStarted?.(sessionId);
280
+ }
281
+ noteNativeCommands(event) {
282
+ const names = Array.isArray(event.slash_commands)
283
+ ? event.slash_commands.filter((n) => typeof n === "string" && n.length > 0)
284
+ : [];
285
+ const skills = Array.isArray(event.skills) ? event.skills.filter((n) => typeof n === "string") : [];
286
+ if (names.join("\n") === this.nativeSlashCommands.join("\n"))
287
+ return;
288
+ this.nativeSlashCommands = names;
289
+ this.nativeSkills = new Set(skills);
290
+ this.slashCommandsChanged = true;
291
+ }
292
+ handleClaudeEvent(event, sink) {
205
293
  if (event.type === "stream_event" && event.event && typeof event.event === "object") {
206
- this.handleClaudeEvent(event.event, sink, activeToolJson);
294
+ this.handleClaudeEvent(event.event, sink);
207
295
  return;
208
296
  }
209
297
  const type = String(event.type ?? "");
210
- if (type === "system" && typeof event.session_id === "string") {
211
- this.activeSessionId = event.session_id;
298
+ if (type === "system") {
299
+ this.noteSessionId(event.session_id, sink);
300
+ if (event.subtype === "init")
301
+ this.noteNativeCommands(event);
212
302
  }
213
303
  if (type === "assistant") {
214
304
  const msg = event.message;
@@ -224,37 +314,21 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
224
314
  this.turnHadText = true;
225
315
  }
226
316
  else if (block.type === "tool_use") {
227
- const callId = String(block.id ?? `tool_${Date.now()}`);
228
- if (!this.seenToolStarts.has(callId)) {
229
- this.seenToolStarts.add(callId);
230
- const toolName = String(block.name ?? "tool");
231
- const input = block.input ?? {};
232
- sink.onToolStart(callId, toolName, input);
233
- }
317
+ this.startTool(block, sink);
234
318
  }
235
319
  }
236
320
  }
237
321
  }
238
322
  if (event.error) {
239
- const errMsg = typeof event.error === "string" ? event.error : JSON.stringify(event.error);
240
- this.lastErrorHint = errMsg;
323
+ this.lastErrorHint = typeof event.error === "string" ? event.error : JSON.stringify(event.error);
241
324
  }
242
325
  }
243
326
  if (type === "user") {
244
327
  const msg = event.message;
245
328
  if (msg && Array.isArray(msg.content)) {
246
329
  for (const item of msg.content) {
247
- if (item && typeof item === "object") {
248
- const block = item;
249
- if (block.type === "tool_result") {
250
- const toolId = String(block.tool_use_id ?? block.id ?? "");
251
- if (toolId && !this.seenToolEnds.has(toolId)) {
252
- this.seenToolEnds.add(toolId);
253
- const content = typeof block.content === "string" ? block.content : JSON.stringify(block.content ?? "");
254
- const isError = Boolean(block.is_error);
255
- sink.onToolEnd(toolId, isError ? { error: content } : { output: content });
256
- }
257
- }
330
+ if (item && typeof item === "object" && item.type === "tool_result") {
331
+ this.endTool(item, sink);
258
332
  }
259
333
  }
260
334
  }
@@ -270,45 +344,22 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
270
344
  else if (delta.type === "thinking_delta" && typeof delta.thinking === "string") {
271
345
  sink.onThinkingDelta(delta.thinking);
272
346
  }
273
- else if (delta.type === "input_json_delta" && typeof delta.partial_json === "string") {
274
- const index = String(event.index ?? 0);
275
- activeToolJson.set(index, (activeToolJson.get(index) ?? "") + delta.partial_json);
276
- }
277
347
  }
278
348
  if (type === "content_block_start") {
279
349
  const block = event.content_block;
280
- if (block && block.type === "tool_use") {
281
- const callId = String(block.id ?? `tool_${Date.now()}`);
282
- if (!this.seenToolStarts.has(callId)) {
283
- this.seenToolStarts.add(callId);
284
- const toolName = String(block.name ?? "tool");
285
- const input = block.input ?? {};
286
- sink.onToolStart(callId, toolName, input);
287
- }
288
- }
289
- }
290
- if (type === "tool_use") {
291
- const callId = String(event.id ?? `tool_${Date.now()}`);
292
- if (!this.seenToolStarts.has(callId)) {
293
- this.seenToolStarts.add(callId);
294
- const toolName = String(event.name ?? "tool");
295
- const input = event.input ?? {};
296
- sink.onToolStart(callId, toolName, input);
297
- }
298
- }
299
- if (type === "tool_result") {
300
- const toolId = String(event.tool_use_id ?? event.id ?? "");
301
- if (toolId && !this.seenToolEnds.has(toolId)) {
302
- this.seenToolEnds.add(toolId);
303
- const content = typeof event.content === "string" ? event.content : JSON.stringify(event.content ?? "");
304
- const isError = Boolean(event.is_error);
305
- sink.onToolEnd(toolId, isError ? { error: content } : { output: content });
306
- }
350
+ if (block && block.type === "tool_use")
351
+ this.startTool(block, sink);
307
352
  }
353
+ if (type === "tool_use")
354
+ this.startTool(event, sink);
355
+ if (type === "tool_result")
356
+ this.endTool(event, sink);
308
357
  if (type === "result") {
309
- if (event.is_error && event.result) {
310
- const resStr = typeof event.result === "string" ? event.result : JSON.stringify(event.result);
311
- this.lastErrorHint = resStr;
358
+ this.noteSessionId(event.session_id, sink);
359
+ if (event.is_error) {
360
+ const detail = event.result ?? (Array.isArray(event.errors) ? event.errors.join("; ") : event.subtype);
361
+ if (detail)
362
+ this.lastErrorHint = typeof detail === "string" ? detail : JSON.stringify(detail);
312
363
  }
313
364
  else if (!this.turnHadText && typeof event.result === "string" && event.result.trim()) {
314
365
  sink.onTextDelta(event.result.trim());
@@ -320,25 +371,34 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
320
371
  const outputTokens = usage?.output_tokens ?? 0;
321
372
  const cacheReadTokens = usage?.cache_read_input_tokens ?? 0;
322
373
  const cacheWriteTokens = usage?.cache_creation_input_tokens ?? 0;
374
+ if (event.is_error) {
375
+ this.resultFailed = true; // reported once on close, with lastErrorHint
376
+ return;
377
+ }
323
378
  this.turnCompleteEmitted = true;
324
- const turnMeta = {
325
- usage: usage
326
- ? {
327
- inputTokens,
328
- outputTokens,
329
- cacheReadTokens,
330
- cacheWriteTokens,
331
- costUSD,
332
- }
333
- : undefined,
379
+ sink.onTurnComplete({
380
+ usage: usage ? { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, costUSD } : undefined,
334
381
  costUSD,
335
382
  contextTokens: inputTokens > 0 ? inputTokens + outputTokens : undefined,
336
383
  model: typeof event.model === "string" ? event.model : this.currentModel,
337
- };
338
- this.lastTurnMeta = turnMeta;
339
- sink.onTurnComplete(turnMeta);
384
+ });
340
385
  }
341
386
  }
387
+ startTool(block, sink) {
388
+ const callId = String(block.id ?? `tool_${Date.now()}`);
389
+ if (this.seenToolStarts.has(callId))
390
+ return;
391
+ this.seenToolStarts.add(callId);
392
+ sink.onToolStart(callId, String(block.name ?? "tool"), block.input ?? {});
393
+ }
394
+ endTool(block, sink) {
395
+ const toolId = String(block.tool_use_id ?? block.id ?? "");
396
+ if (!toolId || this.seenToolEnds.has(toolId))
397
+ return;
398
+ this.seenToolEnds.add(toolId);
399
+ const content = toolResultText(block.content);
400
+ sink.onToolEnd(toolId, block.is_error ? { error: content } : { output: content });
401
+ }
342
402
  buildSpawnEnv(isOfficial, targetProvider) {
343
403
  const spawnEnv = {
344
404
  ...process.env,
@@ -370,7 +430,7 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
370
430
  if (this.activeProcess) {
371
431
  try {
372
432
  if (process.platform === "win32") {
373
- spawn("taskkill", ["/pid", String(this.activeProcess.pid), "/t", "/f"]);
433
+ spawn("taskkill", ["/pid", String(this.activeProcess.pid), "/t", "/f"], { windowsHide: true });
374
434
  }
375
435
  else {
376
436
  try {
@@ -386,12 +446,7 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
386
446
  }
387
447
  }
388
448
  async listModels() {
389
- const official = [
390
- { id: "claude-3-7-sonnet-20250219", name: "Claude 3.7 Sonnet" },
391
- { id: "claude-3-5-sonnet-20241022", name: "Claude 3.5 Sonnet" },
392
- { id: "claude-3-5-haiku-20241022", name: "Claude 3.5 Haiku" },
393
- { id: "claude-3-opus-20240229", name: "Claude 3 Opus" },
394
- ];
449
+ const official = [...CLAUDE_CODE_MODELS];
395
450
  if (!this.agentDir)
396
451
  return official;
397
452
  const custom = listCustomModelsFromConfig(this.agentDir, (entry) => isModelProtocolSupportedByEngine("claude", entry));
@@ -402,87 +457,31 @@ export class ClaudeCodeDriver extends BaseAgentDriver {
402
457
  return [...official, ...customRows];
403
458
  }
404
459
  async setModel(modelId) {
405
- this.currentModel = modelId;
460
+ this.currentModel = normalizeClaudeModelId(modelId);
406
461
  }
462
+ /** Native Claude Code commands and skills, as reported by the CLI's own init event. */
407
463
  async getSlashCommands() {
408
- return [
409
- {
410
- name: "cost",
411
- description: "查看 Claude Code 累计 Token 与成本消耗",
412
- descriptionEn: "Show Claude Code cumulative tokens & cost",
413
- source: "extension",
414
- },
415
- {
416
- name: "doctor",
417
- description: "运行 Claude Code 环境与凭据健康诊断",
418
- descriptionEn: "Run Claude Code environment & auth diagnostics",
419
- source: "extension",
420
- },
421
- {
422
- name: "init",
423
- description: "在当前工作区初始化 CLAUDE.md 指引文件",
424
- descriptionEn: "Initialize CLAUDE.md guidelines in workspace",
464
+ return this.nativeSlashCommands
465
+ .filter((name) => !PI_OWNED_SLASH.has(name))
466
+ .map((name) => {
467
+ const isSkill = this.nativeSkills.has(name);
468
+ return {
469
+ name,
470
+ description: isSkill ? "Claude Code 技能" : "Claude Code 原生命令",
471
+ descriptionEn: isSkill ? "Claude Code skill" : "Claude Code native command",
425
472
  source: "extension",
426
- },
427
- {
428
- name: "clear",
429
- description: "重置 Claude Code 会话上下文(相当于 /clear)",
430
- descriptionEn: "Reset Claude Code session context",
431
- source: "extension",
432
- },
433
- ];
473
+ };
474
+ });
434
475
  }
435
- async execSlashCommand(name, _args, context) {
436
- switch (name) {
437
- case "cost": {
438
- const meta = this.lastTurnMeta;
439
- const usage = meta?.usage;
440
- const cost = meta?.costUSD ?? usage?.costUSD ?? 0;
441
- const text = usage
442
- ? `Claude Code 用量:输入 ${usage.inputTokens ?? 0} tokens · 输出 ${usage.outputTokens ?? 0} tokens · 费用 $${cost.toFixed(4)}`
443
- : `Claude Code 当前未记录上一轮 token 用量`;
444
- const textEn = usage
445
- ? `Claude Code usage: in ${usage.inputTokens ?? 0} tok · out ${usage.outputTokens ?? 0} tok · cost $${cost.toFixed(4)}`
446
- : `No turn token usage recorded yet`;
447
- context?.emitNotice?.("info", text, textEn);
448
- return true;
449
- }
450
- case "doctor": {
451
- const probe = await probeClaudeCode(this.executablePath);
452
- const status = probe.installed
453
- ? `Claude Code CLI 正常 (版本: ${probe.version ?? "已安装"}) · Node ${process.version}`
454
- : `未检测到 Claude Code CLI: ${probe.error ?? "请运行 npm i -g @anthropic-ai/claude-code"}`;
455
- const statusEn = probe.installed
456
- ? `Claude Code CLI OK (v${probe.version ?? "installed"}) · Node ${process.version}`
457
- : `Claude Code CLI not found: ${probe.error ?? "run npm i -g @anthropic-ai/claude-code"}`;
458
- context?.emitNotice?.(probe.installed ? "info" : "warning", status, statusEn);
459
- return true;
460
- }
461
- case "init": {
462
- const target = join(this.cwd, "CLAUDE.md");
463
- if (existsSync(target)) {
464
- context?.emitNotice?.("info", "CLAUDE.md 已存在于当前工作区", "CLAUDE.md already exists in workspace");
465
- }
466
- else {
467
- try {
468
- 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`;
469
- writeFileSync(target, template, "utf8");
470
- context?.emitNotice?.("info", "已在当前工作区创建初始 CLAUDE.md", "Created initial CLAUDE.md in workspace");
471
- }
472
- catch (err) {
473
- context?.emitNotice?.("error", `创建 CLAUDE.md 失败: ${err.message}`, `Failed to create CLAUDE.md: ${err.message}`);
474
- }
475
- }
476
- return true;
477
- }
478
- case "clear": {
479
- this.activeSessionId = null;
480
- context?.emitNotice?.("info", "Claude Code 驱动会话上下文已重置", "Claude Code session context reset");
481
- return true;
482
- }
483
- default:
484
- return false;
485
- }
476
+ handlesNativeSlashCommand(name) {
477
+ if (PI_OWNED_SLASH.has(name))
478
+ return false;
479
+ return name === "compact" || this.nativeSlashCommands.includes(name);
480
+ }
481
+ consumeSlashCommandsChanged() {
482
+ const changed = this.slashCommandsChanged;
483
+ this.slashCommandsChanged = false;
484
+ return changed;
486
485
  }
487
486
  async getSkills() {
488
487
  const skills = discoverDiskSkills({ cwd: this.cwd, agentDir: this.agentDir });