@chroxy/server 0.11.0 → 0.11.10

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 (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +69 -5
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -23,6 +23,7 @@
23
23
  import { query } from '@anthropic-ai/claude-agent-sdk'
24
24
  import { extractSearchableText } from './conversation-search.js'
25
25
  import { createLogger } from './logger.js'
26
+ import { buildSpawnEnv } from './utils/spawn-env.js'
26
27
 
27
28
  const log = createLogger('summarize')
28
29
 
@@ -50,6 +51,9 @@ export function flattenHistory(history) {
50
51
  const lines = []
51
52
  for (const entry of history) {
52
53
  if (!entry || typeof entry !== 'object') continue
54
+ // #8348: a permission prompt's outcome is a transcript marker, not
55
+ // conversation; its `tool` field would otherwise flatten to a bare "[Bash]".
56
+ if (entry.type === 'permission_outcome') continue
53
57
  // extractSearchableText reads entry.message.content; chroxy history entries
54
58
  // store their text on `content`. Normalize so the shared flattener sees a
55
59
  // message-shaped object regardless of which source produced the entry.
@@ -178,14 +182,45 @@ export function buildSummaryPrompt({ transcript, truncated, sessionName }) {
178
182
  * user prompt, and the result text collected from assistant content blocks.
179
183
  * Used when the caller doesn't inject a `runOneShot` seam.
180
184
  *
185
+ * `queryFn` is an injectable seam (defaults to the real SDK `query`) so a test
186
+ * can assert on the built options — including `pathToClaudeCodeExecutable`
187
+ * (#7986) — without module-mocking `@anthropic-ai/claude-agent-sdk`.
188
+ *
189
+ * `resolveExecutable` has NO default (#8030) — it is a REQUIRED, verified
190
+ * binary-gate call, not a plain path resolve. Before #8030 this defaulted to
191
+ * `resolveClaudeBinary()`, which resolves a path but verifies nothing: a
192
+ * `block`-mode hash-mismatched `claude` that `createSession` would refuse
193
+ * could still be spawned by this one-shot path (the summarizer, the
194
+ * semantic-title generator) with no gate at all. Every caller now supplies a
195
+ * verified resolver — production wires `SessionManager.verifyOneShotExecutable`
196
+ * (see summarize-handlers.js / session-manager.js's `_generateSemanticTitle`),
197
+ * which re-runs the SAME preflight gate `createSession` runs.
198
+ *
181
199
  * @param {object} args
182
200
  * @param {string} args.prompt
183
201
  * @param {string} [args.model] - model id; omitted lets the SDK pick its default.
184
202
  * @param {string} [args.cwd]
185
203
  * @param {AbortSignal} [args.signal]
204
+ * @param {Function} [args.queryFn] - injected in tests; defaults to the SDK's `query`.
205
+ * @param {Function} args.resolveExecutable - REQUIRED (#8030): `() => string`,
206
+ * a verified binary-gate call. Throwing a `PROVIDER_BINARY_*`-coded error
207
+ * refuses the spawn before `queryFn` is ever invoked.
186
208
  * @returns {Promise<string>} the model's text reply.
209
+ * @throws {Error} when `resolveExecutable` is not a function, or when it throws.
187
210
  */
188
- export async function defaultRunOneShot({ prompt, model, cwd, signal }) {
211
+ export async function defaultRunOneShot({ prompt, model, cwd, signal, queryFn = query, resolveExecutable }) {
212
+ if (typeof resolveExecutable !== 'function') {
213
+ throw new Error('defaultRunOneShot (#8030): resolveExecutable is required — the caller must supply its verified spawn gate (e.g. SessionManager.verifyOneShotExecutable) instead of relying on an unverified default binary resolve.')
214
+ }
215
+ // Resolved BEFORE queryFn so a gate refusal never spawns anything. An empty
216
+ // result is refused too: with pathToClaudeCodeExecutable unset the SDK falls
217
+ // back to its own bundled binary, which nothing has verified.
218
+ const executable = resolveExecutable()
219
+ if (typeof executable !== 'string' || executable.length === 0) {
220
+ const err = new Error('defaultRunOneShot (#8030): the spawn gate returned no binary path — refusing rather than letting the SDK fall back to its bundled binary.')
221
+ err.code = 'PROVIDER_BINARY_UNVERIFIED'
222
+ throw err
223
+ }
189
224
  const options = {
190
225
  // No tools — a pure text summarization turn. The session must not be able
191
226
  // to read/write files or run commands during summarization.
@@ -194,13 +229,22 @@ export async function defaultRunOneShot({ prompt, model, cwd, signal }) {
194
229
  allowDangerouslySkipPermissions: true,
195
230
  includePartialMessages: false,
196
231
  maxTurns: 1,
232
+ // #7986 / #8030: the desktop bundle does not ship the Agent SDK's platform
233
+ // binary, and query() throws if pathToClaudeCodeExecutable is unset and
234
+ // that binary is absent — point it at the installed CLI, same as the
235
+ // chat-turn SDK provider, on every install.
236
+ pathToClaudeCodeExecutable: executable,
237
+ // #8262: without `env` the SDK copies process.env wholesale. Use the same
238
+ // builder the chat-turn SDK provider does, so a one-shot summary claude is a
239
+ // top-level session and no parent-session markers are inherited.
240
+ env: buildSpawnEnv('claude-sdk'),
197
241
  }
198
242
  if (typeof cwd === 'string' && cwd) options.cwd = cwd
199
243
  if (typeof model === 'string' && model) options.model = model
200
244
  if (signal) options.abortController = abortControllerFromSignal(signal)
201
245
 
202
246
  const parts = []
203
- const stream = query({ prompt, options })
247
+ const stream = queryFn({ prompt, options })
204
248
  for await (const msg of stream) {
205
249
  if (msg?.type === 'assistant' && Array.isArray(msg.message?.content)) {
206
250
  for (const block of msg.message.content) {
@@ -240,10 +284,13 @@ function abortControllerFromSignal(signal) {
240
284
  * @param {string} [args.sessionName] - human label for the brief header.
241
285
  * @param {Function} [args.runOneShot] - injected model runner.
242
286
  * @param {AbortSignal} [args.signal]
287
+ * @param {Function} [args.resolveExecutable] - #8030: forwarded to the runner
288
+ * (`defaultRunOneShot` requires it; an injected `runOneShot` test double may
289
+ * ignore it). Production wires `SessionManager.verifyOneShotExecutable`.
243
290
  * @returns {Promise<{ summary: string, truncated: boolean }>}
244
291
  * @throws {Error} when there is no history to summarize or the model returns empty.
245
292
  */
246
- export async function summarizeSession({ history, model, cwd, sessionName, runOneShot, signal } = {}) {
293
+ export async function summarizeSession({ history, model, cwd, sessionName, runOneShot, signal, resolveExecutable } = {}) {
247
294
  const transcript = flattenHistory(history)
248
295
  if (!transcript.trim()) {
249
296
  const err = new Error('Session has no readable history to summarize')
@@ -255,7 +302,7 @@ export async function summarizeSession({ history, model, cwd, sessionName, runOn
255
302
  const prompt = buildSummaryPrompt({ transcript: text, truncated, sessionName })
256
303
 
257
304
  const runner = typeof runOneShot === 'function' ? runOneShot : defaultRunOneShot
258
- const summary = await runner({ prompt, model, cwd, signal })
305
+ const summary = await runner({ prompt, model, cwd, signal, resolveExecutable })
259
306
 
260
307
  if (typeof summary !== 'string' || !summary.trim()) {
261
308
  const err = new Error('The summarizer returned no text')
package/src/supervisor.js CHANGED
@@ -5,7 +5,6 @@ import { dirname, resolve, join } from 'path'
5
5
  import { createInterface } from 'readline'
6
6
  import { fileURLToPath } from 'url'
7
7
  import { writeFileSync, readFileSync, unlinkSync, existsSync, mkdirSync } from 'fs'
8
- import { homedir } from 'os'
9
8
  import { EventEmitter } from 'events'
10
9
  import { createTunnel, parseTunnelArg } from './tunnel/index.js'
11
10
  import { QUICK_TUNNEL_DNS_SETTLE_MS, waitForTunnel } from './tunnel-check.js'
@@ -13,6 +12,8 @@ import { createLogger } from './logger.js'
13
12
  import QRCode from 'qrcode'
14
13
  import { writeConnectionInfo, removeConnectionInfo } from './connection-info.js'
15
14
  import { PushManager } from './push.js'
15
+ import { configPath } from './config-dir.js'
16
+ import { isGitShaRef } from './utils/argv-safety.js'
16
17
 
17
18
  function maskToken(token) {
18
19
  if (!token) return ''
@@ -34,7 +35,9 @@ const __filename = fileURLToPath(import.meta.url)
34
35
  const __dirname = dirname(__filename)
35
36
  const packageJson = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8'))
36
37
  const SUPERVISOR_VERSION = packageJson.version
37
- const DEFAULT_PID_FILE = join(homedir(), '.chroxy', 'supervisor.pid')
38
+ function defaultPidFile() {
39
+ return configPath('supervisor.pid')
40
+ }
38
41
 
39
42
  const DRAIN_TIMEOUT = 30000
40
43
  const RESTART_BACKOFFS = [2000, 2000, 3000, 3000, 5000, 5000, 8000, 8000, 10000, 10000]
@@ -62,8 +65,8 @@ export class Supervisor extends EventEmitter {
62
65
  this._port = config.port || parseInt(process.env.PORT || '8765', 10)
63
66
  this._apiToken = config.apiToken || process.env.API_TOKEN
64
67
  this._tunnelMode = config.tunnel || 'quick'
65
- this._pidFilePath = config.pidFilePath || DEFAULT_PID_FILE
66
- this._knownGoodFile = config.knownGoodFile || join(homedir(), '.chroxy', 'known-good-ref')
68
+ this._pidFilePath = config.pidFilePath || defaultPidFile()
69
+ this._knownGoodFile = config.knownGoodFile || configPath('known-good-ref')
67
70
  this._maxRestarts = (typeof config.maxRestarts === 'number' && config.maxRestarts >= 0)
68
71
  ? config.maxRestarts
69
72
  : 10
@@ -118,7 +121,7 @@ export class Supervisor extends EventEmitter {
118
121
  lastBackoffMs: 0,
119
122
  }
120
123
 
121
- this._pushStoragePath = config.pushStoragePath || join(homedir(), '.chroxy', 'push-tokens.json')
124
+ this._pushStoragePath = config.pushStoragePath || configPath('push-tokens.json')
122
125
  }
123
126
 
124
127
  /** Override point: fork a child process */
@@ -205,9 +208,9 @@ export class Supervisor extends EventEmitter {
205
208
  // picks up prefs the child persisted after startup, same as the tokens.
206
209
  const push = new PushManager({
207
210
  storagePath: this._pushStoragePath,
208
- prefsPath: join(homedir(), '.chroxy', 'notification-prefs.json'),
211
+ prefsPath: configPath('notification-prefs.json'),
209
212
  discord: {
210
- statePath: join(homedir(), '.chroxy', 'discord-webhook-state.json'),
213
+ statePath: configPath('discord-webhook-state.json'),
211
214
  ...(this.config.notifications?.discord || {}),
212
215
  },
213
216
  })
@@ -828,9 +831,13 @@ export class Supervisor extends EventEmitter {
828
831
  *
829
832
  * Two layers of defense now close this:
830
833
  *
831
- * 1. `~/.chroxy` is in FORBIDDEN_HOME_SUBDIRS, so sessions can no
832
- * longer create a cwd inside it — the attacker can't reach
833
- * `known-good-ref` via `write_file`.
834
+ * 1. `validateCwdAllowed` refuses a session cwd inside the config/state
835
+ * root, so the attacker can't reach `known-good-ref` via `write_file`.
836
+ * Two checks back that: `~/.chroxy` is in FORBIDDEN_HOME_SUBDIRS by
837
+ * name, AND the resolved `configDir()` is denied outright. The second
838
+ * is what keeps this true once CHROXY_CONFIG_DIR relocates the root
839
+ * (#7052) — the name-based set alone would then be guarding an empty
840
+ * directory while the real one sat open.
834
841
  *
835
842
  * 2. This function validates that the ref resolves to the SAME
836
843
  * commit as an existing `known-good-*` git tag. The tag is
@@ -854,7 +861,11 @@ export class Supervisor extends EventEmitter {
854
861
  // ≥ 7 chars to match historical behavior but require
855
862
  // hex-only content. Rejects arbitrary branch names, refspecs,
856
863
  // option flags (-rf, --help), etc.
857
- if (!/^[0-9a-f]{7,40}$/i.test(ref)) {
864
+ //
865
+ // #7296: `chroxy deploy` reads the SAME file into a `git diff` argv, so
866
+ // the predicate moved to utils/argv-safety.js and both call sites share
867
+ // it. A second transcription of this regex is the drift this prevents.
868
+ if (!isGitShaRef(ref)) {
858
869
  this._log.error(`Invalid known-good ref format: "${ref.slice(0, 64)}"`)
859
870
  return false
860
871
  }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Boot-time sweep of stale per-session provider dirs (#7374).
3
+ *
4
+ * Extracted from `server-cli.js` so the sweep is pinned BEHAVIOURALLY. It used
5
+ * to be an inline block in the boot path, guarded only by a test that grepped
6
+ * `server-cli.js` for `sweepStaleSinkDirs(log)` inside an anchored `import(...)`
7
+ * slice. Mutation testing during #7371's review showed two bypasses that kept
8
+ * that guard green:
9
+ *
10
+ * - wrapping the whole block in `if (process.env.__NEVER_SET__) { … }`
11
+ * - replacing the call with `.then(({CliSession}) => void CliSession)` and
12
+ * putting the expected string in a comment INSIDE the anchored window
13
+ *
14
+ * That is catalogue entry 1 ("the gate that never ran"): a source grep cannot
15
+ * tell a call reached at boot from the same characters behind a false
16
+ * condition. Extracting the body means the WORK is now covered by tests that
17
+ * actually run it — see `tests/sweep-stale-provider-dirs.test.js`.
18
+ *
19
+ * What remains source-level is only that `server-cli.js` calls this function at
20
+ * boot. That residual is recorded in `docs/false-safety-guards.md` rather than
21
+ * papered over in a comment here.
22
+ *
23
+ * All four sweeps (claude-tui, claude-cli, codex app-server, docker-byok —
24
+ * #8047 added the latter two) are safe and unconditional: only dirs whose
25
+ * owner pid is DEAD are removed, so a live daemon's dirs — including ours —
26
+ * are kept. Lazily imported so a boot that uses none of the four providers
27
+ * pays nothing, and every failure is warned rather than thrown so a sweep can
28
+ * never affect startup.
29
+ */
30
+
31
+ /**
32
+ * The real module loaders. Injectable so a test can drive this function with
33
+ * stubs instead of `mock.module`, which leaks across the parallel test files
34
+ * `node --test` runs.
35
+ */
36
+ export const DEFAULT_SWEEP_LOADERS = {
37
+ // #5323 (WP-5.1) — claude-tui hook-sink dirs left in /tmp by prior crashed
38
+ // processes (a leak on every crash).
39
+ 'claude-tui sink-dir': async () => {
40
+ const { ClaudeTuiSession } = await import('./claude-tui-session.js')
41
+ return (log) => ClaudeTuiSession.sweepStaleSinkDirs(log)
42
+ },
43
+ // #7337 — same sweep for claude-cli's per-session permission-mode sidecar
44
+ // dirs, which leak on a crash for exactly the same reason.
45
+ 'claude-cli sidecar-dir': async () => {
46
+ const { CliSession } = await import('./cli-session.js')
47
+ return (log) => CliSession.sweepStaleSidecarDirs(log)
48
+ },
49
+ // #7373 — codex app-server's per-session materialized-attachment dirs,
50
+ // same crash-leak shape as the two sweeps above.
51
+ 'codex attach-dir': async () => {
52
+ const { CodexAppServerSession } = await import('./codex-app-server-session.js')
53
+ return (log) => CodexAppServerSession.sweepStaleAttachDirs(log)
54
+ },
55
+ // #7373 — docker-byok's per-session compose env-file dirs. This one is
56
+ // materially worse than a plain directory leak: the file holds
57
+ // ANTHROPIC_API_KEY, so an unswept orphan is a credential left in /tmp.
58
+ 'docker-byok env-file-dir': async () => {
59
+ const { DockerByokSession } = await import('./docker-byok-session.js')
60
+ return (log) => DockerByokSession.sweepStaleEnvDirs(log)
61
+ },
62
+ }
63
+
64
+ /**
65
+ * Run every provider's stale-dir sweep. Never rejects: a loader or sweep that
66
+ * throws is warned and the others still run.
67
+ *
68
+ * @param {{ info: Function, warn: Function }} log
69
+ * @param {Record<string, () => Promise<Function>>} [loaders]
70
+ * @returns {Promise<void>}
71
+ */
72
+ export async function sweepStaleProviderDirs(log, loaders = DEFAULT_SWEEP_LOADERS) {
73
+ await Promise.all(
74
+ Object.entries(loaders).map(async ([label, load]) => {
75
+ try {
76
+ const sweep = await load()
77
+ await sweep(log)
78
+ } catch (err) {
79
+ // The logger is the one call left outside the try, and a throwing
80
+ // `log.warn` would reject `Promise.all` — which nothing awaits, so it
81
+ // surfaces as an unhandledRejection, and server-orchestrator treats
82
+ // that as fatal. The OLD inline form had the identical hole (a throw
83
+ // inside `.catch()` rejects the chain just the same), so this is not a
84
+ // regression being fixed — it is the "never rejects" claim being made
85
+ // true rather than nearly true.
86
+ try {
87
+ log.warn(`${label} sweep failed: ${(err && err.message) || err}`)
88
+ } catch {
89
+ // Nothing left to report it with. Swallowing is correct: a
90
+ // best-effort reaper must never be able to take down boot.
91
+ }
92
+ }
93
+ }),
94
+ )
95
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The ONE builder of the wire `thinking_level_changed` frame (#8700).
3
+ *
4
+ * Four senders put this frame on the wire: ws-history's `sendSessionInfo`
5
+ * replay (reconnect / tab switch), the event normalizer's `ready` burst, the
6
+ * `set_thinking_level` handler after an accepted change, and the normalizer's
7
+ * own `thinking_level_changed` entry for a level the SESSION changed or learned
8
+ * (a model switch that dropped an unoffered level, the effort Claude Code
9
+ * reported at the start of a turn). Each used to spell `{ level }` by hand, so a
10
+ * field added to one sender was missing from the rest — a replay would then
11
+ * erase what the live frame had said. They all build it here instead.
12
+ *
13
+ * `level` is what the operator asked for (`default` when nothing was asked).
14
+ * `effective` is what the provider REPORTS it applied, and it is sent only by a
15
+ * provider that declares `capabilities.thinkingLevelEffective`: there `null`
16
+ * means "not reported yet", while an absent key (every other provider) means
17
+ * "this provider makes no such report". Clients render the two differently, so
18
+ * the builder never collapses one into the other.
19
+ *
20
+ * Returns null for a session with no thinking-level concept (`thinkingLevel`
21
+ * getter `undefined`, BaseSession's default), so no sender invents a `default`
22
+ * that would stomp a client's state for a provider that never had one.
23
+ */
24
+ import { LEGACY_DEFAULT_THINKING_LEVEL } from '@chroxy/protocol'
25
+
26
+ /**
27
+ * @param {object|null|undefined} session
28
+ * @returns {{ type: 'thinking_level_changed', level: string, effective?: string|null } | null}
29
+ */
30
+ export function buildThinkingLevelChanged(session) {
31
+ const level = session?.thinkingLevel
32
+ if (level === undefined) return null
33
+ const msg = { type: 'thinking_level_changed', level: level || LEGACY_DEFAULT_THINKING_LEVEL }
34
+ if (session.constructor?.capabilities?.thinkingLevelEffective === true) {
35
+ const effective = session.effectiveThinkingLevel
36
+ msg.effective = typeof effective === 'string' && effective.length > 0 ? effective : null
37
+ }
38
+ return msg
39
+ }
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Producer for `thinking: true` stream frames (#7393).
3
+ *
4
+ * The wire contract is the one sdk-session and byok-session already emit
5
+ * (packages/protocol/src/schemas/server/stream.ts): a reasoning stream is a
6
+ * stream_start / stream_delta / stream_end triple tagged `thinking: true`, on a
7
+ * DISTINCT messageId `<turnId>-thinking-<n>` so it can never land in the
8
+ * response slot. The client renders it as a `type: 'thinking'` bubble, and the
9
+ * message history records it (`kind: 'thinking'`) from the very same frames, so
10
+ * a producer that emits these gets live display AND replay with nothing else.
11
+ *
12
+ * sdk-session and byok-session each carry an inline copy of this because they
13
+ * stream token by token off the API. The two providers that were never
14
+ * connected, claude-tui and claude-cli, get one shared implementation here
15
+ * instead of a third and fourth copy:
16
+ *
17
+ * - `emitBlock()` a block that is already complete (claude-tui reads it from
18
+ * the session transcript once claude has written it).
19
+ * - `open()` / `append()` / `close()` a block that arrives as stream events
20
+ * (claude-cli's `content_block_*`).
21
+ *
22
+ * Redaction. Thinking quotes what the model just read (an env file, a tool
23
+ * result) far more often than the reply does, so its text is pattern-redacted
24
+ * (redaction.js, the same value-shape patterns the logger and the tool-input
25
+ * broadcast use) before it leaves the process. A secret can straddle two
26
+ * chunks, which no per-chunk redactor can see (#8135 made the same point about
27
+ * tool input), so the streaming API holds a block's text and redacts the WHOLE
28
+ * of it at `close()`. `open()` still emits `stream_start` at once, which is the
29
+ * "it is thinking" signal; only the text waits for the block to finish.
30
+ */
31
+
32
+ import { redactBounded } from './redaction.js'
33
+ import { boundedThinkingPrecedes } from './message-wire.js'
34
+
35
+ /** What stands in for an Anthropic `redacted_thinking` block, whose payload is encrypted and never readable. */
36
+ export const REDACTED_THINKING_PLACEHOLDER = '[redacted thinking]'
37
+
38
+ /**
39
+ * Upper bound on the text kept for one block. The client bubble is capped at
40
+ * the same size (store-core MAX_THINKING_CONTENT_LEN), so anything past it
41
+ * would be dropped on arrival anyway.
42
+ */
43
+ export const THINKING_TEXT_MAX = 1024 * 1024
44
+
45
+ /**
46
+ * The messageId of the `n`th reasoning stream of a turn. The `-thinking-<n>`
47
+ * suffix is also how session-message-history classifies a legacy entry that
48
+ * predates the `kind` field, so it is part of the contract, not a style choice.
49
+ */
50
+ export function thinkingMessageId(turnId, n) {
51
+ return `${turnId}-thinking-${n}`
52
+ }
53
+
54
+ function cleanDuration(ms) {
55
+ return typeof ms === 'number' && Number.isFinite(ms) && ms >= 0 ? Math.round(ms) : undefined
56
+ }
57
+
58
+ function clip(text) {
59
+ const s = typeof text === 'string' ? text : ''
60
+ return s.length > THINKING_TEXT_MAX ? s.slice(0, THINKING_TEXT_MAX) : s
61
+ }
62
+
63
+ export class ThinkingStreams {
64
+ /**
65
+ * @param {(event: string, data: object) => void} emit - the session's emit
66
+ * @param {string} turnId - the turn's response messageId; ids derive from it
67
+ * @param {object} [opts]
68
+ * @param {() => number} [opts.now] - monotonic ms clock (injectable for tests)
69
+ */
70
+ constructor(emit, turnId, { now = () => performance.now() } = {}) {
71
+ this._emit = emit
72
+ this._turnId = turnId
73
+ this._now = now
74
+ this._seq = 0
75
+ /** @type {Map<unknown, {id: string, text: string, startMs: number}>} */
76
+ this._open = new Map()
77
+ }
78
+
79
+ get openCount() {
80
+ return this._open.size
81
+ }
82
+
83
+ _nextId() {
84
+ return thinkingMessageId(this._turnId, this._seq++)
85
+ }
86
+
87
+ _body(text, redacted) {
88
+ if (redacted) return REDACTED_THINKING_PLACEHOLDER
89
+ return redactBounded(clip(text))
90
+ }
91
+
92
+ /**
93
+ * Emit a reasoning block that is already complete as start, delta, end.
94
+ * Empty text (a block that carries only its signature, which is what the API
95
+ * returns when summaries are not requested) emits no delta: the client shows
96
+ * "Thought for Xs" with an empty body, and the history keeps that entry.
97
+ *
98
+ * `late: true` marks a block shown after its turn was already answered (the
99
+ * transcript is written late). It is an INTERNAL tag on the session event, not a
100
+ * wire field: the forwarder reads it to keep a finished session idle (a thinking
101
+ * `stream_start` otherwise pings the sidebar "busy", and nothing pings idle again
102
+ * until the next `result`), and it never reaches a client.
103
+ *
104
+ * `precedes` (#8518) is the transcript's own order, so a client can put a block that
105
+ * arrives late where it belongs: `{ kind: 'tool_use', toolUseId }` above that tool
106
+ * row, `{ kind: 'response' }` above the turn's answer. It rides the `stream_start`
107
+ * as `thinkingPrecedes` (the frame that creates the bubble). A response hint is
108
+ * sent only for a `late` block: before the answer exists its slot is empty and
109
+ * sits above the tool rows, so "above the response" would put the bubble in the
110
+ * wrong place; the block is simply appended, which is right for a block that
111
+ * arrives in order.
112
+ *
113
+ * @param {{ text?: string, redacted?: boolean, durationMs?: number, late?: boolean,
114
+ * precedes?: ({kind: 'tool_use', toolUseId: string}|{kind: 'response'}) }} block
115
+ * @returns {string} the messageId used
116
+ */
117
+ emitBlock({ text = '', redacted = false, durationMs, late = false, precedes } = {}) {
118
+ const messageId = this._nextId()
119
+ const tag = late ? { late: true } : {}
120
+ const hint = this._hint(precedes, late)
121
+ this._emit('stream_start', { messageId, thinking: true, ...tag, ...(hint ? { thinkingPrecedes: hint } : {}) })
122
+ const body = this._body(text, redacted)
123
+ if (body) this._emit('stream_delta', { messageId, delta: body, thinking: true, ...tag })
124
+ this._emit('stream_end', { ...this._endFrame(messageId, cleanDuration(durationMs)), ...tag })
125
+ return messageId
126
+ }
127
+
128
+ _hint(precedes, late) {
129
+ if (precedes?.kind === 'response') {
130
+ return late ? boundedThinkingPrecedes({ kind: 'response', messageId: this._turnId }) : undefined
131
+ }
132
+ return boundedThinkingPrecedes(precedes)
133
+ }
134
+
135
+ /** Open a streaming block under `key` (idempotent per key). Emits `stream_start`. */
136
+ open(key) {
137
+ const existing = this._open.get(key)
138
+ if (existing) return existing.id
139
+ const id = this._nextId()
140
+ this._open.set(key, { id, text: '', startMs: this._now() })
141
+ this._emit('stream_start', { messageId: id, thinking: true })
142
+ return id
143
+ }
144
+
145
+ /** Hold more text for the block under `key`. Nothing is emitted until `close()`. */
146
+ append(key, text) {
147
+ const block = this._open.get(key)
148
+ if (!block || typeof text !== 'string' || !text) return
149
+ if (block.text.length >= THINKING_TEXT_MAX) return
150
+ block.text += text
151
+ }
152
+
153
+ /**
154
+ * Finish the block under `key`: one redacted delta (when there is text), then
155
+ * `stream_end` carrying the wall time since `open()`. No-op for an unknown key.
156
+ *
157
+ * @param {unknown} key
158
+ * @param {{ redacted?: boolean }} [opts]
159
+ */
160
+ close(key, { redacted = false } = {}) {
161
+ const block = this._open.get(key)
162
+ if (!block) return
163
+ this._open.delete(key)
164
+ const body = this._body(block.text, redacted)
165
+ if (body) this._emit('stream_delta', { messageId: block.id, delta: body, thinking: true })
166
+ this._emit('stream_end', this._endFrame(block.id, cleanDuration(this._now() - block.startMs)))
167
+ }
168
+
169
+ /** Finalise every open block (a turn ending under them must not strand "Thinking…"). */
170
+ closeAll() {
171
+ for (const key of [...this._open.keys()]) this.close(key)
172
+ }
173
+
174
+ _endFrame(messageId, durationMs) {
175
+ const frame = { messageId, thinking: true }
176
+ if (durationMs !== undefined) frame.thinkingDurationMs = durationMs
177
+ return frame
178
+ }
179
+ }
@@ -1,3 +1,5 @@
1
+ import { isTurnTerminationReason, describeTurnTermination } from '@chroxy/protocol'
2
+
1
3
  // Max size for tool result text forwarded to mobile (10KB)
2
4
  export const MAX_TOOL_RESULT_SIZE = 10240
3
5
 
@@ -70,10 +72,69 @@ export function emitToolResults(content, emitter, maxSize = MAX_TOOL_RESULT_SIZE
70
72
  truncated,
71
73
  }
72
74
 
75
+ // #8300: carry the block's own error flag to the wire (the schema already
76
+ // declares `isError`; the turn-end orphan sweep sets it on its synthetic
77
+ // results), so a client can tell a failed tool call from a result that
78
+ // merely reads like one. Only ever added, never defaulted to false.
79
+ if (block.is_error === true) {
80
+ event.isError = true
81
+ }
82
+
73
83
  if (images.length > 0) {
74
84
  event.images = images
75
85
  }
76
86
 
87
+ // #8936: the provider's own refusal boilerplate ("The user doesn't want to
88
+ // proceed ... STOP what you are doing and wait ...") is an instruction aimed
89
+ // at the MODEL. The session swaps it for the short sentence the decision
90
+ // itself carried (what byok/claude-tui show), here, before the event is
91
+ // broadcast and journalled, so live and replay read the same. The text
92
+ // already sent to the provider is untouched. A no-op for any emitter
93
+ // without the hook.
94
+ if (typeof emitter._deniedTextForToolResult === 'function') {
95
+ const denied = emitter._deniedTextForToolResult(block.tool_use_id, block)
96
+ if (typeof denied === 'string') {
97
+ event.truncated = denied.length > maxSize
98
+ event.result = event.truncated ? denied.slice(0, maxSize) : denied
99
+ event.isError = true
100
+ delete event.images
101
+ }
102
+ }
103
+
104
+ // #8363: the provider wrote this result itself because Stop cancelled the
105
+ // tool's pending permission prompt -- its text says the USER declined, which
106
+ // is false. The session names the real cause; the result then says so (the
107
+ // clients render the shared wording and hide this text for a terminated tool)
108
+ // and carries the same `terminatedReason` the turn-end sweep stamps (#7376).
109
+ // Only a BaseSession-derived emitter that overrides the hook can ask; for
110
+ // anything else this is a no-op.
111
+ if (typeof emitter._terminatedReasonForToolResult === 'function') {
112
+ const reason = emitter._terminatedReasonForToolResult(block.tool_use_id, block)
113
+ if (isTurnTerminationReason(reason)) {
114
+ event.terminatedReason = reason
115
+ event.result = describeTurnTermination(reason).summary
116
+ event.truncated = false
117
+ event.isError = true
118
+ delete event.images
119
+ }
120
+ }
121
+
122
+ // #7346: backfill the finalized tool input recorded via
123
+ // `_recordToolInput` (base-session.js) — at `content_block_stop` for
124
+ // CliSession, or from the full assistant-message `block.input` for
125
+ // SdkSession — onto this tool_result. session-message-history.js's
126
+ // `tool_result` case uses it to correct the matching `tool_start`
127
+ // history entry (which was `input: null` when first emitted, since
128
+ // neither provider's `content_block_start` carries the real input),
129
+ // and the client backfills `toolInput` from it too. `undefined` when
130
+ // nothing was recorded (BYOK never calls `_trackToolStart`, so
131
+ // `_getTrackedToolInput` isn't even present there) — this stays a
132
+ // no-op and BYOK's `tool_result` shape is unchanged.
133
+ if (typeof emitter._getTrackedToolInput === 'function') {
134
+ const input = emitter._getTrackedToolInput(block.tool_use_id)
135
+ if (input !== undefined) event.input = input
136
+ }
137
+
77
138
  emitter.emit('tool_result', event)
78
139
  // #4628: drop the in-flight tracker entry so _emitResult's sweep
79
140
  // (BaseSession) doesn't double-emit a synthetic for an already-