@chroxy/server 0.11.0 → 0.11.11

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 (386) hide show
  1. package/CONFIG.md +206 -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 +958 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +304 -0
  14. package/src/agent-control/client.js +1645 -0
  15. package/src/agent-control/events.js +551 -0
  16. package/src/agent-control/local-connection.js +293 -0
  17. package/src/agent-control/mcp-server.js +547 -0
  18. package/src/anthropic-compatible-config.js +30 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-gemini-shim.js +444 -0
  21. package/src/anthropic-gemini-translate.js +1030 -0
  22. package/src/anthropic-openai-shim.js +0 -1
  23. package/src/archive-continuation.js +164 -0
  24. package/src/assistant-response.js +24 -0
  25. package/src/auth-probes.js +120 -13
  26. package/src/background-shell-tracker.js +27 -0
  27. package/src/base-session.js +1520 -36
  28. package/src/bearer-recheck.js +49 -0
  29. package/src/billing-budget.js +19 -0
  30. package/src/billing-class.js +40 -7
  31. package/src/binary-provenance-trust.js +11 -5
  32. package/src/bound-client-policy.js +291 -0
  33. package/src/built-in-tools/bash-exec.js +46 -7
  34. package/src/built-in-tools/file-ops.js +69 -5
  35. package/src/built-in-tools/tool-transforms.js +1113 -13
  36. package/src/byok-compose-state.js +6 -9
  37. package/src/byok-credentials.js +2 -3
  38. package/src/byok-mcp-client.js +92 -7
  39. package/src/byok-mcp-config.js +633 -122
  40. package/src/byok-mcp-fleet.js +49 -7
  41. package/src/byok-mcp-oauth-store.js +18 -16
  42. package/src/byok-mcp-trust.js +37 -23
  43. package/src/byok-session.js +707 -179
  44. package/src/byok-tool-executor.js +2742 -26
  45. package/src/byok-tools.js +9 -2
  46. package/src/channels/chroxy-channel-server.js +2 -3
  47. package/src/checkpoint-manager.js +64 -46
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-setting-sources.js +74 -0
  53. package/src/claude-stream-parser.js +53 -3
  54. package/src/claude-tui/diagnostic-tail.js +83 -0
  55. package/src/claude-tui/form-driver.js +44 -7
  56. package/src/claude-tui/model-error.js +41 -0
  57. package/src/claude-tui/pty-driver.js +215 -88
  58. package/src/claude-tui/sanitize-question-payload.js +109 -0
  59. package/src/claude-tui/usage-limit.js +239 -0
  60. package/src/claude-tui-session.js +3563 -284
  61. package/src/claude-tui-tool-response.js +300 -0
  62. package/src/cli/agent-cmd.js +236 -0
  63. package/src/cli/agent-control-cmd.js +65 -0
  64. package/src/cli/config-cmd.js +4 -4
  65. package/src/cli/config-dir-cmd.js +234 -0
  66. package/src/cli/connection-state.js +54 -0
  67. package/src/cli/deploy-cmd.js +45 -10
  68. package/src/cli/doctor-cmd.js +7 -3
  69. package/src/cli/freshness-cmd.js +53 -0
  70. package/src/cli/init-cmd.js +15 -16
  71. package/src/cli/pages-cmd.js +6 -4
  72. package/src/cli/pair-code-cmd.js +7 -6
  73. package/src/cli/pair-discord-cmd.js +7 -6
  74. package/src/cli/providers-cmd.js +3 -3
  75. package/src/cli/schedule-cmd.js +91 -40
  76. package/src/cli/server-cmd.js +54 -1
  77. package/src/cli/service-cmd.js +33 -10
  78. package/src/cli/session-cmd.js +227 -74
  79. package/src/cli/shared.js +162 -11
  80. package/src/cli/shell-cmd.js +7 -4
  81. package/src/cli/status-cmd.js +19 -5
  82. package/src/cli/tokens-cmd.js +4 -5
  83. package/src/cli/tunnel-cmd.js +255 -24
  84. package/src/cli/worktree-gc-cmd.js +2 -2
  85. package/src/cli-session.js +1250 -126
  86. package/src/cli.js +8 -0
  87. package/src/codex-app-server-client.js +36 -3
  88. package/src/codex-app-server-session.js +1517 -81
  89. package/src/codex-bundled-client.js +66 -0
  90. package/src/codex-error-text.js +114 -0
  91. package/src/codex-model-catalog.js +548 -0
  92. package/src/codex-model-rejections.js +87 -0
  93. package/src/codex-native-resume.js +104 -0
  94. package/src/codex-protocol-capabilities.js +188 -0
  95. package/src/codex-session.js +450 -27
  96. package/src/config-dir-migration.js +449 -0
  97. package/src/config-dir.js +108 -0
  98. package/src/config.js +306 -26
  99. package/src/connection-authority.js +48 -0
  100. package/src/connection-info.js +78 -23
  101. package/src/connection-locality.js +60 -0
  102. package/src/container-liveness-monitor.js +189 -0
  103. package/src/continuation-metadata-worker.js +17 -0
  104. package/src/continuations.js +227 -0
  105. package/src/control-room/host-prune.js +5 -0
  106. package/src/control-room/integrations.js +7 -20
  107. package/src/control-room/skills-inventory.js +2 -2
  108. package/src/conversation-scanner.js +42 -39
  109. package/src/conversation-scope.js +59 -39
  110. package/src/conversation-search.js +28 -39
  111. package/src/credential-store.js +23 -19
  112. package/src/daemon-commit.js +92 -0
  113. package/src/daemon-idle-state.js +171 -0
  114. package/src/daemon-update-status.js +314 -0
  115. package/src/dashboard-build.js +70 -0
  116. package/src/declared-status.js +90 -0
  117. package/src/deepseek-credentials.js +2 -3
  118. package/src/dev-preview.js +170 -182
  119. package/src/device-preferences.js +2 -2
  120. package/src/diff-parser.js +87 -0
  121. package/src/discord-credentials.js +2 -3
  122. package/src/docker-byok-pool.js +3 -1
  123. package/src/docker-byok-session.js +678 -78
  124. package/src/docker-image-allowlist.js +23 -1
  125. package/src/docker-sdk-session.js +172 -3
  126. package/src/docker-session.js +294 -11
  127. package/src/doctor.js +781 -64
  128. package/src/durable-write.js +35 -0
  129. package/src/edited-input.js +264 -0
  130. package/src/environment-manager.js +175 -36
  131. package/src/environments/authority.js +101 -0
  132. package/src/environments/backends/container-claude-spawn.js +94 -0
  133. package/src/environments/backends/docker.js +31 -10
  134. package/src/environments/backends/k8s.js +49 -24
  135. package/src/environments/destroy-with-sessions.js +142 -0
  136. package/src/event-ingest.js +118 -13
  137. package/src/event-normalizer.js +186 -235
  138. package/src/folder-trust-wire.js +137 -0
  139. package/src/folder-trust-worker.js +17 -0
  140. package/src/folder-trust.js +1572 -0
  141. package/src/freshness/activity-meter.js +101 -0
  142. package/src/freshness/adapter.js +199 -0
  143. package/src/freshness/checks.js +239 -0
  144. package/src/freshness/config.js +98 -0
  145. package/src/freshness/core.js +185 -0
  146. package/src/freshness/derive.js +680 -0
  147. package/src/freshness/exchange.js +305 -0
  148. package/src/freshness/file-ledger.js +400 -0
  149. package/src/freshness/grade.js +81 -0
  150. package/src/freshness/hash.js +45 -0
  151. package/src/freshness/inbox.js +163 -0
  152. package/src/freshness/index.js +20 -0
  153. package/src/freshness/investigation.js +474 -0
  154. package/src/freshness/keys.js +177 -0
  155. package/src/freshness/ledger.js +122 -0
  156. package/src/freshness/outbox.js +131 -0
  157. package/src/freshness/policy.js +599 -0
  158. package/src/freshness/queue.js +843 -0
  159. package/src/freshness/read-errors.js +23 -0
  160. package/src/freshness/render.js +153 -0
  161. package/src/freshness/runtime.js +113 -0
  162. package/src/freshness/session-registry-adapter.js +161 -0
  163. package/src/freshness/state-file-adapter.js +167 -0
  164. package/src/freshness-runner/build-info.js +139 -0
  165. package/src/freshness-runner/cli.js +105 -0
  166. package/src/freshness-runner/run-tick.js +109 -0
  167. package/src/freshness-runner/stamp.js +57 -0
  168. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  169. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  170. package/src/freshness-sources/index.js +8 -0
  171. package/src/gemini-byok-session.js +292 -0
  172. package/src/gemini-credentials.js +67 -0
  173. package/src/gemini-key-safety.js +246 -0
  174. package/src/gemini-models.js +386 -0
  175. package/src/gemini-session.js +81 -5
  176. package/src/handler-utils.js +540 -80
  177. package/src/handlers/checkpoint-handlers.js +47 -4
  178. package/src/handlers/control-room-handlers.js +51 -11
  179. package/src/handlers/conversation-handlers.js +469 -56
  180. package/src/handlers/daemon-update-handlers.js +81 -0
  181. package/src/handlers/evaluator-handlers.js +14 -1
  182. package/src/handlers/feature-handlers.js +186 -69
  183. package/src/handlers/file-handlers.js +57 -13
  184. package/src/handlers/folder-trust-handlers.js +90 -0
  185. package/src/handlers/input-handlers.js +714 -48
  186. package/src/handlers/orchestration-handlers.js +3 -3
  187. package/src/handlers/principal-admin-handlers.js +229 -0
  188. package/src/handlers/principal-handlers.js +262 -0
  189. package/src/handlers/scheduler-handlers.js +92 -18
  190. package/src/handlers/session-handlers.js +551 -20
  191. package/src/handlers/session-pr-status-handlers.js +283 -0
  192. package/src/handlers/session-pr-threads-handlers.js +247 -0
  193. package/src/handlers/settings-handlers.js +372 -50
  194. package/src/handlers/skills-handlers.js +20 -4
  195. package/src/handlers/summarize-handlers.js +32 -1
  196. package/src/handlers/survey-throttle.js +380 -0
  197. package/src/health-proof.js +40 -0
  198. package/src/history-page.js +112 -0
  199. package/src/http-routes.js +127 -8
  200. package/src/ide/search.js +24 -6
  201. package/src/ide/symbols.js +20 -6
  202. package/src/input-context.js +117 -0
  203. package/src/instruction-policy-compiler.js +229 -0
  204. package/src/instruction-policy.js +250 -0
  205. package/src/jsonl-reader.js +378 -91
  206. package/src/jsonl-subprocess-session.js +96 -9
  207. package/src/keychain.js +1 -1
  208. package/src/logger.js +166 -30
  209. package/src/mailbox-route.js +113 -22
  210. package/src/message-wire.js +386 -0
  211. package/src/model-discovery.js +43 -3
  212. package/src/models.js +1276 -174
  213. package/src/notification-prefs.js +27 -4
  214. package/src/notifications/discord-billing-sink.js +22 -5
  215. package/src/notifications/discord-ci-sink.js +243 -0
  216. package/src/notifications/discord-webhook-client.js +71 -0
  217. package/src/notifications/discord-webhook-sink.js +64 -23
  218. package/src/notifications/expo-push-sink.js +85 -6
  219. package/src/notifications/ready-body.js +16 -5
  220. package/src/ollama-session.js +34 -2
  221. package/src/orchestration/build-manager.js +9 -2
  222. package/src/orchestration/git-ops.js +41 -7
  223. package/src/orchestration/orchestration-manager.js +112 -36
  224. package/src/orchestration/permission-gate.js +17 -2
  225. package/src/orchestration/run-model.js +2 -1
  226. package/src/orchestration/run-record.js +11 -0
  227. package/src/orchestration/turn-driver.js +185 -43
  228. package/src/orphan-reaper.js +470 -0
  229. package/src/outgoing-policy.js +189 -0
  230. package/src/pairing.js +92 -13
  231. package/src/path-hash-trust-ledger.js +642 -25
  232. package/src/permission-deadlines.js +82 -0
  233. package/src/permission-floor.js +1410 -43
  234. package/src/permission-hook.js +180 -69
  235. package/src/permission-manager.js +737 -89
  236. package/src/permission-mode-support.js +35 -0
  237. package/src/permission-resolved-by.js +89 -0
  238. package/src/permission-resolver.js +126 -8
  239. package/src/permission-scope.js +43 -0
  240. package/src/platform.js +315 -47
  241. package/src/preview-ingress.js +54 -0
  242. package/src/preview-target.js +213 -0
  243. package/src/principal-audit.js +189 -0
  244. package/src/principal-binding.js +25 -0
  245. package/src/principal-brakes.js +21 -0
  246. package/src/principal-effect.js +101 -0
  247. package/src/principal-journal.js +905 -0
  248. package/src/principal-kill-switch.js +183 -0
  249. package/src/principal-label.js +5 -0
  250. package/src/principal-pending-permissions.js +177 -0
  251. package/src/principal-policy.js +1094 -0
  252. package/src/principal-sessions-snapshot.js +208 -0
  253. package/src/principal-store.js +488 -0
  254. package/src/principal-subscriptions.js +283 -0
  255. package/src/prompt-evaluator.js +34 -4
  256. package/src/provider-customization.js +180 -0
  257. package/src/providers.js +209 -4
  258. package/src/push.js +30 -4
  259. package/src/question-route-map.js +130 -0
  260. package/src/redaction.js +531 -20
  261. package/src/roster-broadcast.js +186 -0
  262. package/src/scheduled-task-store.js +330 -26
  263. package/src/scheduler.js +368 -11
  264. package/src/sdk-session.js +2114 -188
  265. package/src/server-cli/preview-shutdown.js +22 -0
  266. package/src/server-cli/push-notification-handler.js +17 -3
  267. package/src/server-cli/server-orchestrator.js +28 -5
  268. package/src/server-cli-child.js +33 -18
  269. package/src/server-cli.js +553 -38
  270. package/src/server-identity.js +15 -11
  271. package/src/service.js +396 -25
  272. package/src/session-archive-limits.js +15 -0
  273. package/src/session-archive.js +1029 -0
  274. package/src/session-busy-state.js +72 -0
  275. package/src/session-ci-watcher.js +1099 -0
  276. package/src/session-context.js +7 -2
  277. package/src/session-manager.js +4062 -312
  278. package/src/session-message-history.js +841 -16
  279. package/src/session-name-allocator.js +685 -0
  280. package/src/session-pr-status.js +654 -0
  281. package/src/session-pr-threads.js +271 -0
  282. package/src/session-preset-trust.js +3 -3
  283. package/src/session-preset.js +10 -5
  284. package/src/session-state-persistence.js +94 -17
  285. package/src/session-timeout-manager.js +20 -0
  286. package/src/session-token-store.js +17 -8
  287. package/src/session-wake.js +240 -0
  288. package/src/shell-approval-info.js +2 -2
  289. package/src/shell-approval-store.js +3 -1
  290. package/src/skills-loader.js +7 -4
  291. package/src/skills-manager.js +2 -2
  292. package/src/skills-trust.js +95 -13
  293. package/src/skills-usage.js +2 -3
  294. package/src/snapshots-store.js +2 -3
  295. package/src/statusline.js +100 -29
  296. package/src/summarize-session.js +53 -4
  297. package/src/supervisor.js +22 -11
  298. package/src/sweep-stale-provider-dirs.js +95 -0
  299. package/src/thinking-level-wire.js +39 -0
  300. package/src/thinking-stream.js +179 -0
  301. package/src/tool-result.js +61 -0
  302. package/src/transcript-sources.js +109 -0
  303. package/src/transcript-tasks.js +372 -25
  304. package/src/trusted-file-read.js +302 -0
  305. package/src/tunnel/base.js +0 -8
  306. package/src/tunnel/cloudflare.js +34 -31
  307. package/src/tunnel/index.js +9 -0
  308. package/src/tunnel/preview.js +64 -0
  309. package/src/turn-outcome.js +140 -0
  310. package/src/usage-normalize.js +9 -5
  311. package/src/user-shell-session.js +59 -5
  312. package/src/utils/agent-sdk-version.js +107 -0
  313. package/src/utils/argv-safety.js +770 -0
  314. package/src/utils/auth-cause.js +60 -0
  315. package/src/utils/binary-package-manifest.js +639 -0
  316. package/src/utils/binary-version.js +224 -0
  317. package/src/utils/bounded-regex-worker.js +29 -0
  318. package/src/utils/bounded-regex.js +162 -0
  319. package/src/utils/claude-binary.js +43 -0
  320. package/src/utils/claude-config-dir.js +245 -0
  321. package/src/utils/claude-login-command.js +16 -0
  322. package/src/utils/claude-native-route.js +81 -0
  323. package/src/utils/componentwise-resolver.js +133 -37
  324. package/src/utils/deploy-control-files.js +87 -0
  325. package/src/utils/exec-failure-reason.js +21 -0
  326. package/src/utils/git-repo.js +42 -0
  327. package/src/utils/is-entry-point.js +137 -0
  328. package/src/utils/node-pty-probe.js +95 -0
  329. package/src/utils/node-pty-support.js +118 -0
  330. package/src/utils/opened-file-path.js +167 -0
  331. package/src/utils/path-containment.js +165 -0
  332. package/src/utils/permission-mode-sidecar.js +51 -0
  333. package/src/utils/pid-liveness.js +47 -0
  334. package/src/utils/preflight.js +360 -16
  335. package/src/utils/read-limiter.js +217 -0
  336. package/src/utils/regular-file.js +375 -0
  337. package/src/utils/safe-regex.js +113 -0
  338. package/src/utils/small-file.js +129 -0
  339. package/src/utils/spawn-env.js +189 -4
  340. package/src/utils/stale-session-dirs.js +182 -0
  341. package/src/utils/stat-identity.js +43 -0
  342. package/src/utils/verify-provenance.js +406 -13
  343. package/src/web-task-manager.js +297 -16
  344. package/src/worktree-gc.js +202 -6
  345. package/src/ws-auth.js +163 -31
  346. package/src/ws-broadcaster.js +49 -5
  347. package/src/ws-client-manager.js +24 -1
  348. package/src/ws-client-sender.js +7 -0
  349. package/src/ws-file-ops/browser.js +363 -58
  350. package/src/ws-file-ops/common.js +320 -14
  351. package/src/ws-file-ops/git.js +395 -42
  352. package/src/ws-file-ops/index.js +2 -0
  353. package/src/ws-file-ops/memory.js +137 -35
  354. package/src/ws-file-ops/open-nofollow.js +354 -0
  355. package/src/ws-file-ops/reader.js +571 -113
  356. package/src/ws-forwarding.js +349 -39
  357. package/src/ws-handler-context.js +88 -2
  358. package/src/ws-history.js +1010 -175
  359. package/src/ws-message-handlers.js +25 -1
  360. package/src/ws-permissions.js +307 -37
  361. package/src/ws-schemas.js +5 -0
  362. package/src/ws-server.js +885 -98
  363. package/sidecar/node_modules/.package-lock.json +0 -29
  364. package/sidecar/node_modules/ws/LICENSE +0 -20
  365. package/sidecar/node_modules/ws/README.md +0 -548
  366. package/sidecar/node_modules/ws/browser.js +0 -8
  367. package/sidecar/node_modules/ws/index.js +0 -22
  368. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  369. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  370. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  371. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  372. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  373. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  374. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  375. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  376. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  377. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  378. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  379. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  380. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  381. package/sidecar/node_modules/ws/package.json +0 -70
  382. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  383. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  384. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  385. package/src/dashboard-next/dist/index.html +0 -13
  386. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -1,10 +1,169 @@
1
1
  import { EventEmitter } from 'events'
2
2
  import { createLogger } from './logger.js'
3
3
  import { truncateTitle } from './session-title.js'
4
+ import { redactBounded, sanitizeToolInput, isSanitizedToolInput, MAX_INPUT_CHARS, RECORD_DESCRIPTION_MAX } from './redaction.js'
5
+ import { MAX_SANE_DURATION_MS } from '@chroxy/protocol'
6
+ import { boundedNonNegInt, boundedThinkingPrecedes, buildMessageWire, buildErrorWire } from './message-wire.js'
7
+ import { turnOutcomeField } from './turn-outcome.js'
8
+
9
+ /**
10
+ * #8259: how far past the seq being issued a persisted reservation reaches. See
11
+ * `_nextSeq`: it bounds how often the state file is rewritten for reservations
12
+ * (once per this many entries per session), not how far a cursor can run ahead.
13
+ */
14
+ export const SEQ_RESERVATION_STEP = 1000
15
+
16
+ /**
17
+ * #8259: fallback only. A state file written before reservations existed has no
18
+ * persisted high-water mark, so the marker is numbered this far past the last
19
+ * persisted seq (best effort, NOT a guarantee). Files written by this build
20
+ * always carry the reservation.
21
+ */
22
+ export const RESTART_SEQ_GAP = 100000
4
23
 
5
24
  const log = createLogger('session-message-history')
6
25
  const MAX_PENDING_STREAM_SIZE = 100 * 1024 * 1024 // 100MB
7
26
 
27
+ /**
28
+ * #8348 -- the outcomes a permission prompt can end in, as recorded in history.
29
+ * `expired` covers every way a prompt ended with NO decision: it timed out, the
30
+ * turn behind it ended, or the session cleared it. `stopped` (#8374) is the one
31
+ * of those with its own name: the user pressed Stop while the prompt was open.
32
+ */
33
+ export const PERMISSION_OUTCOMES = Object.freeze(['allowed', 'denied', 'expired', 'stopped'])
34
+ // Bounds on the two free-text fields of a `permission_outcome` entry. The
35
+ // description already went to clients capped and redacted; these bound what the
36
+ // ring buffer and the state file keep, so a long hook-path description (the hook
37
+ // route broadcasts it uncapped) cannot bloat either.
38
+ export const PERMISSION_OUTCOME_TOOL_MAX = 100
39
+
40
+ /**
41
+ * #8503: the decision tokens an `allowed` outcome may name. `allowAlways` writes a
42
+ * persistent rule and `allowSession` a session one, so a record of either must stay
43
+ * distinguishable from a one-time `allow` after a rebuild (a replayed group of
44
+ * "allowed x N" must not fold them together). `deny` is not here: a denial needs no
45
+ * token, and an outcome with no decision at all (expired, stopped) has none to name.
46
+ */
47
+ export const PERMISSION_ALLOW_DECISIONS = Object.freeze(['allow', 'allowSession', 'allowAlways'])
48
+
49
+ /**
50
+ * The decision token an outcome may keep, or `undefined`: only an `allowed` outcome,
51
+ * only one of {@link PERMISSION_ALLOW_DECISIONS}. One rule for the recorder and the
52
+ * replay, so a damaged restored entry cannot send what the recorder would not keep.
53
+ *
54
+ * @param {unknown} outcome
55
+ * @param {unknown} decision
56
+ * @returns {'allow'|'allowSession'|'allowAlways'|undefined}
57
+ */
58
+ export function permissionOutcomeDecision(outcome, decision) {
59
+ return outcome === 'allowed' && PERMISSION_ALLOW_DECISIONS.includes(decision) ? decision : undefined
60
+ }
61
+ export const PERMISSION_OUTCOME_DESCRIPTION_MAX = RECORD_DESCRIPTION_MAX
62
+
63
+ /**
64
+ * #8503: the most the journaled tool input of a `permission_outcome` may weigh,
65
+ * SERIALIZED, whatever its shape. `sanitizeToolInput` returns at most
66
+ * `MAX_INPUT_CHARS` serialized characters, or, past that, a `{ _truncated, summary }`
67
+ * wrapper whose summary is the first `MAX_INPUT_CHARS` characters of the input's JSON
68
+ * plus a marker. That summary is itself JSON text, so serializing the wrapper escapes
69
+ * its quotes and backslashes again: at most twice the summary, plus the wrapper's own
70
+ * keys. This is that figure, so every value the broadcast ever sends fits and nothing
71
+ * larger is kept. On disk this is the weight of one entry's `input`; `truncateEntry`
72
+ * caps it at 50 KB regardless and the ring buffer holds 1000 entries per session, the
73
+ * bound a `tool_start` entry's input already has.
74
+ */
75
+ const TRUNCATION_MARKER = '... [truncated]'
76
+ export const PERMISSION_OUTCOME_INPUT_MAX = 2 * (MAX_INPUT_CHARS + TRUNCATION_MARKER.length) + 64
77
+
78
+ function isPlainObject(value) {
79
+ return !!value && typeof value === 'object' && !Array.isArray(value)
80
+ }
81
+
82
+ /**
83
+ * #8503: the tool input a `permission_outcome` may keep, or `undefined` for none.
84
+ *
85
+ * The journal is what the clients were SHOWN: the value `sanitizeToolInput` produced
86
+ * for the live `permission_request`, handed over by the caller. That value is kept
87
+ * EXACTLY, never re-shaped, never re-redacted. A wrapper stays the sanitizer's
88
+ * wrapper, and an input an agent wrote with a `_truncated` or `summary` key stays the
89
+ * agent's input: nothing here reads the VALUE's content to decide what it is, because
90
+ * an agent controls every key in it.
91
+ *
92
+ * What tells "already broadcast" from "raw" is identity, not content:
93
+ * `isSanitizedToolInput` is true only for an object `sanitizeToolInput` returned. An
94
+ * input that is not one (a raw input by a future caller's mistake, a copy that lost
95
+ * its identity) is sanitized first, so what is journaled is what the broadcast would
96
+ * have sent for it. The journal is persisted and replayed to every client of the
97
+ * session, so it does not trust its caller to have done that.
98
+ *
99
+ * Not a plain object (a string, an array, a number, null) or absent: no input is kept
100
+ * and the entry reads like one from before the field. A value heavier than
101
+ * {@link PERMISSION_OUTCOME_INPUT_MAX} is dropped, not cut: the pull path's larger
102
+ * sanitized inputs are the one such source, and cutting would re-shape them.
103
+ *
104
+ * @param {unknown} input
105
+ * @returns {object|undefined}
106
+ */
107
+ export function boundPermissionOutcomeInput(input) {
108
+ if (!isPlainObject(input)) return undefined
109
+ try {
110
+ const kept = isSanitizedToolInput(input) ? input : sanitizeToolInput(input)
111
+ if (!isPlainObject(kept)) return undefined
112
+ return JSON.stringify(kept).length <= PERMISSION_OUTCOME_INPUT_MAX ? kept : undefined
113
+ } catch {
114
+ return undefined
115
+ }
116
+ }
117
+
118
+ // `<turnId>-thinking-<n>` (sdk, byok) and `<turnId>-thinking` (acp).
119
+ const LEGACY_THINKING_ID = /-thinking(?:-\d+)?$/
120
+
121
+ /**
122
+ * #6630 / #8282: which kind of stream a recorded `response` entry was. Today
123
+ * only `'thinking'` (extended-thinking reasoning) is distinguished; anything
124
+ * else is a reply and returns `undefined`.
125
+ *
126
+ * The recorder stamps `kind: 'thinking'` on new entries. An entry written
127
+ * before that field existed (a state file from an older run) is classified by
128
+ * the message id the providers give a reasoning stream: `<turnId>-thinking-<n>`
129
+ * (sdk-session, byok-session) and ACP's `<turnId>-thinking` (acp-session), so
130
+ * those still replay as reasoning instead of as an answer. ONE classifier, used by the replay emitter -- a client reads the
131
+ * `kind` on the frame and never re-derives it from an id.
132
+ *
133
+ * @param {object} entry - a ring-buffer entry
134
+ * @returns {'thinking'|undefined}
135
+ */
136
+ export function streamKindOf(entry) {
137
+ if (!entry || entry.type !== 'message' || entry.messageType !== 'response') return undefined
138
+ if (entry.kind === 'thinking') return 'thinking'
139
+ if (typeof entry.messageId === 'string' && LEGACY_THINKING_ID.test(entry.messageId)) return 'thinking'
140
+ return undefined
141
+ }
142
+
143
+ /** #9024: the most tool-call split points one reply entry records, and the longest tool id one may name (the protocol's `splits` schema mirrors both). */
144
+ export const MAX_REPLY_SPLITS = 64
145
+ export const MAX_SPLIT_TOOL_ID_LENGTH = 256
146
+
147
+ /** `{ input }` when there is one, else nothing: an absent input is an absent key. */
148
+ function inputField(input) {
149
+ return input === undefined ? {} : { input }
150
+ }
151
+
152
+ /** `{ decision }` when there is one, else nothing. */
153
+ function decisionField(decision) {
154
+ return decision === undefined ? {} : { decision }
155
+ }
156
+
157
+ function clipText(value, max) {
158
+ const text = typeof value === 'string' ? value : ''
159
+ return text.length > max ? text.slice(0, max - 1) + '\u2026' : text
160
+ }
161
+
162
+ /** Pattern-redact (never cutting a token in half), THEN clip: clipping first could leave a partial secret the patterns miss. */
163
+ function clipRedacted(value, max) {
164
+ return clipText(redactBounded(typeof value === 'string' ? value : ''), max)
165
+ }
166
+
8
167
  /**
9
168
  * Manages per-session message history ring buffers, stream delta accumulation,
10
169
  * truncation tracking, and auto-labeling from first user input.
@@ -30,12 +189,37 @@ export class SessionMessageHistory extends EventEmitter {
30
189
  this._maxToolInput = maxToolInput || null
31
190
  this._maxPendingStreamSize = maxPendingStreamSize || MAX_PENDING_STREAM_SIZE
32
191
  this._messageHistory = new Map() // sessionId -> Array<{ type, _seq, ...data }>
192
+ // #8415 -- entry object -> the last seq issued when its tool input was filled in
193
+ // after the entry was recorded (`backfillToolInput`). A WeakMap on purpose: the
194
+ // marker is no field of the entry, so it is never persisted, never copied by
195
+ // `truncateEntry`, and needs no seq of its own. A daemon restart (or `setHistory`)
196
+ // forgets it; that limitation is accepted.
197
+ this._toolInputFillSeqs = new WeakMap()
33
198
  this._pendingStreams = new Map() // sessionId:messageId -> accumulated delta text
34
199
  // #6431 — messageIds whose pending stream has already been truncated, so the
35
200
  // truncation is signalled to the client ONCE per stream (every subsequent
36
201
  // over-size delta for the same message also exceeds the cap and would
37
202
  // otherwise re-fire the error). Cleared on stream_end / session clear.
38
203
  this._truncatedStreams = new Set() // sessionId:messageId
204
+ // #6630 / #8282 -- sessionId:messageId -> stream kind, for the streams that
205
+ // are not ordinary replies (reasoning). Kept beside `_pendingStreams` rather
206
+ // than inside its value because that map is read as plain strings elsewhere.
207
+ this._streamKinds = new Map()
208
+ // #8518 -- sessionId:messageId -> the ordering hint a reasoning stream_start
209
+ // carried (what it precedes). The entry is written at stream_end, so the
210
+ // start's hint is held here until then.
211
+ this._streamPrecedes = new Map()
212
+ // #9022 -- sessionId:messageId -> the seq the NEXT history entry would take when
213
+ // the stream's first text arrived. A reply is recorded only at stream_end, so while it is open
214
+ // a replay has no entry for it; this is where that text belongs in the replay
215
+ // (before every entry recorded after the stream began). Cleared with the stream.
216
+ this._streamStartSeqs = new Map()
217
+ // #9024 -- sessionId:messageId -> [{ at, toolUseId }]: where tool calls interrupted an
218
+ // open reply stream. `at` is how much of the stream's text existed when the call
219
+ // started. A reply is recorded as ONE entry at stream_end (after the tool cards), so
220
+ // a replay lost where each tool call fell in the text; the entry carries these as
221
+ // `splits` and the client lays the text out around the cards again. Cleared with the stream.
222
+ this._streamSplits = new Map()
39
223
  this._historyTruncated = new Map() // sessionId -> boolean
40
224
  // #5555.3 (lastSeq delta replay) — per-session monotonic history sequence.
41
225
  // Every entry pushed into the ring buffer is stamped with a strictly
@@ -46,6 +230,10 @@ export class SessionMessageHistory extends EventEmitter {
46
230
  // seq is server-internal bookkeeping; the wire only exposes it as
47
231
  // `historySeq` on replayed entries (see ws-history.js).
48
232
  this._seqCounters = new Map() // sessionId -> next seq to assign (>= 1)
233
+ // #8259: sessionId -> highest seq this process may issue, already handed to the
234
+ // reservation handler (the SessionManager persists it synchronously).
235
+ this._seqReserved = new Map()
236
+ this._onSeqReservation = null
49
237
  }
50
238
 
51
239
  /**
@@ -55,10 +243,47 @@ export class SessionMessageHistory extends EventEmitter {
55
243
  */
56
244
  _nextSeq(sessionId) {
57
245
  const next = this._seqCounters.get(sessionId) || 1
246
+ // #8259 RESERVATION INVARIANT: no seq above `_seqReserved` is ever issued
247
+ // before the reservation covering it has been handed to the handler, which
248
+ // persists it synchronously. So the persisted `seqReservedThrough` is >= every
249
+ // seq this process ever gave a client, whatever the lazy state-file debounce
250
+ // has or has not written. A restart numbers new entries above it, so a cursor
251
+ // a client took from the previous process can never equal or exceed them.
252
+ // The persist runs here (once per SEQ_RESERVATION_STEP entries), before the
253
+ // counter moves.
254
+ if (next > (this._seqReserved.get(sessionId) || 0)) {
255
+ this._seqReserved.set(sessionId, next + SEQ_RESERVATION_STEP)
256
+ if (this._onSeqReservation) {
257
+ try { this._onSeqReservation(sessionId) } catch (err) { log.warn(`seq reservation handler failed for ${sessionId}: ${err?.message || err}`) }
258
+ }
259
+ }
58
260
  this._seqCounters.set(sessionId, next + 1)
59
261
  return next
60
262
  }
61
263
 
264
+ /** #8259: install the callback that persists a seq reservation synchronously. */
265
+ setSeqReservationHandler(fn) {
266
+ this._onSeqReservation = typeof fn === 'function' ? fn : null
267
+ }
268
+
269
+ /** #8259: the persisted-or-persisting high-water mark for a session, or 0 when none. */
270
+ getSeqReservedThrough(sessionId) {
271
+ return this._seqReserved.get(sessionId) || 0
272
+ }
273
+
274
+ /**
275
+ * #8259: adopt the previous process's reservation on restore and move the
276
+ * counter above it, so nothing this process issues can reuse a seq a client
277
+ * holds. Returns false (and changes nothing) for a state file without a usable
278
+ * value, which then falls back to the best-effort gap.
279
+ */
280
+ restoreSeqReservation(sessionId, reservedThrough) {
281
+ if (!Number.isSafeInteger(reservedThrough) || reservedThrough < 1) return false
282
+ this._seqReserved.set(sessionId, reservedThrough)
283
+ this._seqCounters.set(sessionId, Math.max(this._seqCounters.get(sessionId) || 1, reservedThrough + 1))
284
+ return true
285
+ }
286
+
62
287
  /**
63
288
  * #5555.3 — seq of the oldest entry still retained in the ring buffer, or
64
289
  * null when the session has no history. Used by the cursor-replay path to
@@ -127,11 +352,49 @@ export class SessionMessageHistory extends EventEmitter {
127
352
  closedMessageIds.push(messageId)
128
353
  this._pendingStreams.delete(key)
129
354
  this._truncatedStreams.delete(key) // #6431 — release the truncation guard
355
+ this._streamKinds.delete(key)
356
+ this._streamPrecedes.delete(key)
357
+ this._streamStartSeqs.delete(key)
358
+ this._streamSplits.delete(key)
130
359
  }
131
360
  }
132
361
  return closedMessageIds
133
362
  }
134
363
 
364
+ /**
365
+ * #9022 -- the reply text a session has streamed so far but not yet closed.
366
+ *
367
+ * History only ever holds a COMPLETED reply (the entry is pushed at
368
+ * `stream_end`), so a turn paused mid-stream -- on a permission prompt, say --
369
+ * has its text in no replay, and a client that reloads shows the tool card and
370
+ * the prompt but none of what the model already said. This is that text, for
371
+ * the replay to splice in at its place in the transcript.
372
+ *
373
+ * Reasoning streams are left out (they replay as their own kind, on a
374
+ * capability), as is a stream that has produced no text yet.
375
+ *
376
+ * @param {string} sessionId
377
+ * @returns {Array<{ messageId: string, content: string, startSeq: number, splits: Array<{ at: number, toolUseId: string }> }>}
378
+ * `startSeq` is the seq the next recorded entry had when its first text arrived:
379
+ * the reply belongs before every entry with `_seq >= startSeq`. `splits` are the
380
+ * tool calls that interrupted it so far (#9024), as the closing entry will carry.
381
+ */
382
+ getPendingResponseStreams(sessionId) {
383
+ const prefix = sessionId + ':'
384
+ const out = []
385
+ for (const [key, content] of this._pendingStreams) {
386
+ if (!key.startsWith(prefix) || !content) continue
387
+ if (this._streamKinds.get(key) === 'thinking') continue
388
+ out.push({
389
+ messageId: key.slice(prefix.length),
390
+ content,
391
+ startSeq: this._streamStartSeqs.get(key) ?? Infinity,
392
+ splits: (this._streamSplits.get(key) ?? []).map((split) => ({ ...split })),
393
+ })
394
+ }
395
+ return out
396
+ }
397
+
135
398
  /**
136
399
  * Get message history for a session.
137
400
  * @param {string} sessionId
@@ -159,28 +422,142 @@ export class SessionMessageHistory extends EventEmitter {
159
422
  return this._historyTruncated.get(sessionId) || false
160
423
  }
161
424
 
425
+ /**
426
+ * #8336 — the highest seq this session has handed out (0 when none). It is
427
+ * what a state file records so the NEXT run can keep numbering past it; the
428
+ * newest retained entry carries it, but the counter is the authority because
429
+ * it survives a front-trim of the whole buffer.
430
+ * @param {string} sessionId
431
+ * @returns {number}
432
+ */
433
+ getLastIssuedSeq(sessionId) {
434
+ return (this._seqCounters.get(sessionId) || 1) - 1
435
+ }
436
+
162
437
  /**
163
438
  * Set pre-existing history for a session (used during state restore).
439
+ *
440
+ * #8336 -- SEQUENCE CONTINUITY. Entries are stamped `firstSeq, firstSeq + 1, ...`
441
+ * and the counter is left just past the last one. The caller passes the first
442
+ * seq so that the entries the previous run persisted keep (roughly) the
443
+ * numbers that run served them under: a reconnecting client's cursor
444
+ * (`lastSeq`) then still means what it meant, and every entry added after the
445
+ * restore (a tail correction, the next turn) is numbered PAST every cursor the
446
+ * previous run issued. Restarting from 1 broke that: with the ring buffer
447
+ * already full, the restore's own additions plus the post-restart traffic could
448
+ * climb through the old cursor's value, and `resolveReplayPlan` then honoured a
449
+ * cursor that no longer pointed at what the client had seen.
450
+ *
451
+ * Without `firstSeq` (a state file from before this field, or a malformed one)
452
+ * numbering starts at 1: the pre-#8336 behaviour, where a cursor from the prior
453
+ * run is honoured only by accident and falls back to a full replay otherwise.
454
+ *
455
+ * The history is also trimmed to the ring-buffer cap, oldest first. A restore
456
+ * can add entries (synthetic tool results, a marked question copy) to a buffer
457
+ * that was already full, and `_pushHistory` only ever evicts one entry per push,
458
+ * so without this the buffer grew by the restore's additions on EVERY restart.
459
+ * The trimmed front is what falls off, so a cursor older than the new oldest
460
+ * entry takes the "trimmed past" full-replay fallback, as designed.
461
+ *
164
462
  * @param {string} sessionId
165
463
  * @param {Array} history
464
+ * @param {object} [opts]
465
+ * @param {number} [opts.firstSeq] - seq to give the first entry (integer >= 1)
166
466
  */
167
- setHistory(sessionId, history) {
168
- // #5555.3 — restored entries predate the seq scheme (it is server-internal
169
- // and not persisted), so stamp them with a fresh 1..N sequence and advance
170
- // the counter past the end. A reconnecting client's cursor from a PRIOR
171
- // server process can't be honoured across a restart (seqs reset to 1), so
172
- // it will simply fall through to a full replay — the safe default.
467
+ setHistory(sessionId, history, { firstSeq } = {}) {
173
468
  if (Array.isArray(history)) {
174
- let seq = 1
469
+ const start = Number.isSafeInteger(firstSeq) && firstSeq >= 1 ? firstSeq : 1
470
+ let seq = start
175
471
  for (const entry of history) {
176
472
  if (entry && typeof entry === 'object') entry._seq = seq
177
473
  seq++
178
474
  }
179
475
  this._seqCounters.set(sessionId, seq)
476
+ const excess = history.length - this._maxHistory
477
+ if (excess > 0) {
478
+ history = history.slice(excess)
479
+ this._historyTruncated.set(sessionId, true)
480
+ }
180
481
  }
181
482
  this._messageHistory.set(sessionId, history)
182
483
  }
183
484
 
485
+ /**
486
+ * #8362 -- record that the server ACCEPTED an answer to a `user_question`.
487
+ *
488
+ * The restore-time sweep (`sweepUnresolvedToolStarts`) calls a question
489
+ * interrupted when its AskUserQuestion tool has no `tool_result`. For
490
+ * claude-cli and claude-tui the answer is delivered to the provider BEFORE the
491
+ * tool's result event arrives, so a restart in that window cut off a question
492
+ * that had in fact been answered, and a client rebuilding from scratch showed
493
+ * "Interrupted -- chroxy restarted before this was answered". This is the
494
+ * record the sweep consults.
495
+ *
496
+ * A flag only: the answer text is not stored (it is not already in the entry,
497
+ * and the history would otherwise start persisting user answers). Idempotent.
498
+ * Mutates the entry in place, like `tool_result`'s input backfill: nothing a
499
+ * client could hold is changed on the live wire, and `sendHistoryEntry` keeps
500
+ * the field off replay frames.
501
+ *
502
+ * @param {string} sessionId
503
+ * @param {string} [toolUseId] - The question's id (the one its route and wire
504
+ * frame carry). Without one, the newest question not yet marked answered:
505
+ * only clients that send no id reach that, and they have one question in
506
+ * flight.
507
+ * @returns {boolean} true when an entry was newly marked (the caller persists)
508
+ */
509
+ markQuestionAnswered(sessionId, toolUseId) {
510
+ const history = this._messageHistory.get(sessionId)
511
+ if (!Array.isArray(history)) return false
512
+ for (let i = history.length - 1; i >= 0; i--) {
513
+ const entry = history[i]
514
+ if (!entry || entry.type !== 'user_question') continue
515
+ if (typeof toolUseId === 'string') {
516
+ if (entry.toolUseId !== toolUseId) continue
517
+ } else if (entry.answered === true) {
518
+ continue
519
+ }
520
+ if (entry.answered === true) return false
521
+ entry.answered = true
522
+ return true
523
+ }
524
+ return false
525
+ }
526
+
527
+ /**
528
+ * #8470 -- record that a newer question REPLACED this one, so nobody answered it
529
+ * and nobody will. `permission_resolved` is transient, so without this a client
530
+ * that was not watching live (a fresh dashboard, a full rebuild, a reconnect)
531
+ * replays the question as unanswered and stamps it "(resolved)", which reads as
532
+ * answered.
533
+ *
534
+ * Two writes, for the same reason the restore-time sweep makes two (#8336): the
535
+ * entry is flagged IN PLACE (a full rebuild receives the question where it was
536
+ * asked, already marked), and a marked COPY is appended at the tail with a fresh
537
+ * seq (a client whose cursor is already past the question would otherwise never
538
+ * hear; the client collapses the copy onto the card it holds by `toolUseId`).
539
+ * The flag also stops the restore-time sweep calling the question interrupted
540
+ * when a restart lands before the denial's `tool_result`.
541
+ *
542
+ * @param {string} sessionId
543
+ * @param {string} toolUseId - the question's id (the `ask-...` id on its frame)
544
+ * @returns {boolean} true when an entry was newly marked (the caller persists)
545
+ */
546
+ markQuestionSuperseded(sessionId, toolUseId) {
547
+ const history = this._messageHistory.get(sessionId)
548
+ if (!Array.isArray(history) || typeof toolUseId !== 'string') return false
549
+ for (let i = history.length - 1; i >= 0; i--) {
550
+ const entry = history[i]
551
+ if (!entry || entry.type !== 'user_question' || entry.toolUseId !== toolUseId) continue
552
+ if (entry.superseded === true || entry.answered === true) return false
553
+ entry.superseded = true
554
+ const { _seq: _dropped, ...copy } = entry
555
+ this._pushHistory(history, copy, sessionId)
556
+ return true
557
+ }
558
+ return false
559
+ }
560
+
184
561
  /**
185
562
  * Sweep an in-memory history array for `tool_start` entries that lack a
186
563
  * matching `tool_result` and splice in a synthetic `tool_result` right
@@ -196,6 +573,17 @@ export class SessionMessageHistory extends EventEmitter {
196
573
  * downstream consumers that sort by timestamp stay monotonic without
197
574
  * pretending the tool completed "now".
198
575
  *
576
+ * #8336: a `user_question` entry for one of the swept `tool_start`s (matched
577
+ * on its `sourceToolUseId` when it has one, else its `toolUseId`) is returned
578
+ * as a COPY carrying `interrupted: true` (the question was cut off, not
579
+ * answered), so a replaying client can say so instead of stamping it
580
+ * "(resolved)". A second marked copy is appended at the END of the history so
581
+ * that a delta replay for a client whose cursor is already past the question
582
+ * still delivers the mark. Other entries are passed through. A question carrying
583
+ * `answered: true` (#8362: the server accepted an answer before the restart) is
584
+ * passed through unmarked, as is one carrying `superseded: true` (#8470: a newer
585
+ * question replaced it, which is its own verdict).
586
+ *
199
587
  * Safe to call on:
200
588
  * - empty / non-array input (returns the input unchanged)
201
589
  * - history with no tool_start entries (returns a shallow copy)
@@ -213,7 +601,41 @@ export class SessionMessageHistory extends EventEmitter {
213
601
  }
214
602
  }
215
603
  const out = []
604
+ // #8336: the toolUseIds this sweep cuts off. A `user_question` entry for
605
+ // one of them was never answered (an answer would have produced the
606
+ // tool_result), so it is marked `interrupted` below rather than left
607
+ // looking like every other replayed question, which the client's
608
+ // history_replay_end sweep stamps "(resolved)".
609
+ const interruptedIds = new Set()
216
610
  for (const entry of history) {
611
+ if (
612
+ entry
613
+ && entry.type === 'tool_start'
614
+ && typeof entry.toolUseId === 'string'
615
+ && !resolved.has(entry.toolUseId)
616
+ ) {
617
+ interruptedIds.add(entry.toolUseId)
618
+ }
619
+ }
620
+ // #8336: the marked copies to re-append at the tail, see below.
621
+ const redelivered = []
622
+ for (const rawEntry of history) {
623
+ // `user_question` is copied, never mutated: the input array is the
624
+ // caller's, and the contract above says it is not modified. The set was
625
+ // collected up front, so the question is marked whichever side of its
626
+ // tool_start it was recorded on. A question names its tool by
627
+ // `sourceToolUseId` when it has one (SDK, BYOK: `toolUseId` is chroxy's
628
+ // own `ask-...` id there), else by `toolUseId` itself (CLI, TUI).
629
+ const questionToolId = rawEntry && rawEntry.type === 'user_question'
630
+ ? (typeof rawEntry.sourceToolUseId === 'string' ? rawEntry.sourceToolUseId : rawEntry.toolUseId)
631
+ : undefined
632
+ // #8362: a question the server accepted an answer for is not cut off even
633
+ // though its tool_result has not arrived yet (cli/tui deliver the answer
634
+ // first). The tool_start is still swept below -- the TOOL was in flight.
635
+ const entry = (typeof questionToolId === 'string' && interruptedIds.has(questionToolId) && rawEntry.answered !== true && rawEntry.superseded !== true)
636
+ ? { ...rawEntry, interrupted: true }
637
+ : rawEntry
638
+ if (entry !== rawEntry) redelivered.push({ ...entry })
217
639
  out.push(entry)
218
640
  if (
219
641
  entry
@@ -242,6 +664,9 @@ export class SessionMessageHistory extends EventEmitter {
242
664
  isError: true,
243
665
  synthetic: true,
244
666
  reason: 'session_restored',
667
+ // #7376: the restore-time sweep is the one termination whose OUTCOME is
668
+ // unknown (the daemon went down mid-tool) -- say so distinctly.
669
+ terminatedReason: 'daemon_restart',
245
670
  timestamp: baseTs + 1,
246
671
  })
247
672
  // Mark this toolUseId resolved so a malformed history with two
@@ -249,9 +674,76 @@ export class SessionMessageHistory extends EventEmitter {
249
674
  resolved.add(entry.toolUseId)
250
675
  }
251
676
  }
677
+ // #8336: the marked question is ALSO appended as a fresh entry at the tail.
678
+ // Marking it in place changes an entry a client may already be past: a
679
+ // reconnecting client's cursor is honoured when it falls inside the restored
680
+ // range, and the delta replay then sends only what lies past it. A client
681
+ // whose cursor sits beyond the question's position would never hear that it
682
+ // was cut off, and its replay-end sweep would stamp the card "(resolved)".
683
+ // A tail entry is numbered past every cursor the previous run could have
684
+ // issued -- `setHistory` continues the previous run's numbering rather than
685
+ // restarting at 1, and the tail is beyond its last entry by construction --
686
+ // so it always arrives. The client collapses it onto the card it holds (same
687
+ // `toolUseId`, same questions), so nobody sees two; a client rebuilding from
688
+ // scratch gets the question in place from the marked entry above and the copy
689
+ // merges onto it. If the ring-buffer cap later evicts the in-place original
690
+ // first (oldest-first), the copy is what remains: a full replay then shows the
691
+ // question after newer messages rather than where it was asked, which is the
692
+ // price of never losing the verdict.
693
+ for (const copy of redelivered) out.push(copy)
252
694
  return out
253
695
  }
254
696
 
697
+ /**
698
+ * #8259: close a turn the daemon went down under. Called by the SessionManager's
699
+ * restore ONLY for a session whose persisted state says a turn was in flight
700
+ * (dispatched to the provider and not yet ended). The partial reply only ever
701
+ * lived in memory, so without this no client could be told how that turn
702
+ * ended. Appends a `result` carrying the `interrupted` turn outcome, the SAME
703
+ * marker path (`turnOutcome` on a `result`) a stopped or truncated turn uses.
704
+ *
705
+ * DELIVERY. A client's cursor comes from the previous process, and the state
706
+ * file's `historyLastSeq` can lag it without bound (the write is debounced and
707
+ * the debounce restarts on every append). What does not lag is the seq
708
+ * RESERVATION (see `_nextSeq`): it is persisted before any seq under it is
709
+ * issued, so `seqReservedThrough` is >= every seq the previous process gave a
710
+ * client. Restore moves the counter above it, so the marker is numbered strictly
711
+ * past every possible cursor: the delta replay (strictly newer than the cursor)
712
+ * honours the cursor and sends it. A state file without a reservation (written
713
+ * before this existed) falls back to `RESTART_SEQ_GAP`, best effort.
714
+ *
715
+ * The timestamp is clamped to one past the newest entry, like the synthetic
716
+ * tool_result of `sweepUnresolvedToolStarts`, so the marker never sorts before
717
+ * the entries it follows.
718
+ *
719
+ * PROVIDER RESUME. No provider continues a half-run turn after a restart: a
720
+ * restored session is a fresh idle provider that resumes the CONVERSATION
721
+ * (context), not the turn, so nothing completes the interrupted turn later.
722
+ * If one ever did, its completed result would simply follow this chip (a
723
+ * completed outcome adds no marker and does not remove one), which stays an
724
+ * honest record that the turn was cut off once.
725
+ *
726
+ * @param {string} sessionId
727
+ * @param {number} [now] - injectable for tests
728
+ * @returns {object} the appended entry
729
+ */
730
+ recordInterruptedTurn(sessionId, now = Date.now()) {
731
+ if (!this._messageHistory.has(sessionId)) this._messageHistory.set(sessionId, [])
732
+ const history = this._messageHistory.get(sessionId)
733
+ let lastTs = 0
734
+ for (const e of history) {
735
+ if (e && Number.isFinite(e.timestamp) && e.timestamp > lastTs) lastTs = e.timestamp
736
+ }
737
+ // With a restored reservation the counter is already above it (restoreSeqReservation);
738
+ // only a pre-reservation state file needs the best-effort gap.
739
+ if (!this._seqReserved.has(sessionId)) {
740
+ this._seqCounters.set(sessionId, (this._seqCounters.get(sessionId) || 1) + RESTART_SEQ_GAP)
741
+ }
742
+ const marker = { type: 'result', turnOutcome: 'interrupted', timestamp: Math.max(now, lastTs + 1) }
743
+ this._pushHistory(history, marker, sessionId)
744
+ return marker
745
+ }
746
+
255
747
  /**
256
748
  * Record a user input message in the session's history ring buffer.
257
749
  * On the first non-empty input, emits auto_label if the session qualifies.
@@ -265,8 +757,9 @@ export class SessionMessageHistory extends EventEmitter {
265
757
  * `handlers/input-handlers.js::resolveUserInputId`) always resolves one
266
758
  * before calling in, so replayed entries always carry an id in practice.
267
759
  * See issue #2902.
760
+ * @param {'daemon'} [source] - #8301: marks a daemon-authored turn (the CI wake).
268
761
  */
269
- recordUserInput(sessionId, text, sessionEntry, messageId) {
762
+ recordUserInput(sessionId, text, sessionEntry, messageId, source) {
270
763
  if (sessionEntry) {
271
764
  this._autoLabelSession(sessionId, text, sessionEntry)
272
765
  }
@@ -278,6 +771,10 @@ export class SessionMessageHistory extends EventEmitter {
278
771
  if (typeof messageId === 'string' && messageId.length > 0) {
279
772
  entry.messageId = messageId
280
773
  }
774
+ // #8301: `source: 'daemon'` marks a turn the daemon wrote (the CI wake), so a
775
+ // replaying client can tell it from something a person typed. Absent for
776
+ // typed input — an older client ignores the field either way.
777
+ if (source === 'daemon') entry.source = 'daemon'
281
778
  this.recordHistory(sessionId, 'message', entry)
282
779
  }
283
780
 
@@ -294,11 +791,20 @@ export class SessionMessageHistory extends EventEmitter {
294
791
  }
295
792
  const history = this._messageHistory.get(sessionId)
296
793
  let persistNeeded = false
794
+ let completedAssistant
795
+ let assistantCompleted = false
297
796
 
298
797
  switch (event) {
299
798
  case 'stream_start': {
300
799
  const key = `${sessionId}:${data.messageId}`
301
800
  this._pendingStreams.set(key, '')
801
+ this._streamSplits.delete(key)
802
+ // #6630 / #8282: a reasoning stream must not be recorded as a reply.
803
+ if (data.thinking === true) {
804
+ this._streamKinds.set(key, 'thinking')
805
+ const thinkingPrecedes = boundedThinkingPrecedes(data.thinkingPrecedes)
806
+ if (thinkingPrecedes) this._streamPrecedes.set(key, thinkingPrecedes)
807
+ }
302
808
  break
303
809
  }
304
810
 
@@ -319,6 +825,13 @@ export class SessionMessageHistory extends EventEmitter {
319
825
  }
320
826
  return { persistNeeded: false, truncated: firstDrop }
321
827
  }
828
+ // #9022: where the reply BEGINS is where its first text arrived, not where
829
+ // the stream opened. claude-tui and byok open the stream inside sendMessage,
830
+ // before the input is accepted and `user_input` recorded, so a start-time
831
+ // seq would put the reply above the prompt it answers.
832
+ if (data.delta.length > 0 && !this._streamStartSeqs.has(key)) {
833
+ this._streamStartSeqs.set(key, this._seqCounters.get(sessionId) || 1)
834
+ }
322
835
  this._pendingStreams.set(key, existing + data.delta)
323
836
  }
324
837
  break
@@ -327,14 +840,52 @@ export class SessionMessageHistory extends EventEmitter {
327
840
  case 'stream_end': {
328
841
  const key = `${sessionId}:${data.messageId}`
329
842
  const content = this._pendingStreams.get(key) || ''
843
+ const hadStream = this._pendingStreams.has(key)
844
+ const kind = this._streamKinds.get(key) || (data.thinking === true ? 'thinking' : undefined)
845
+ const thinkingPrecedes = kind === 'thinking' ? this._streamPrecedes.get(key) : undefined
330
846
  this._pendingStreams.delete(key)
847
+ this._streamKinds.delete(key)
848
+ this._streamPrecedes.delete(key)
849
+ const wasTruncated = this._truncatedStreams.has(key)
850
+ this._streamStartSeqs.delete(key)
851
+ const splits = this._streamSplits.get(key)
852
+ this._streamSplits.delete(key)
331
853
  this._truncatedStreams.delete(key) // #6431 — release the once-per-stream guard
332
- if (content) {
854
+ // A reasoning stream is recorded even with no text: current Claude models
855
+ // return the block with its signature only, so the SDK opens and closes a
856
+ // thinking stream that never carries a delta. Live, that is a "thought for
857
+ // Xs" bubble with an empty body; skipping it for want of text made the whole
858
+ // bubble vanish on replay. A reply with no text is still no entry, and so is
859
+ // a stream_end whose start this history never saw.
860
+ assistantCompleted = hadStream && kind !== 'thinking'
861
+ if (assistantCompleted && !wasTruncated && data.interrupted !== true) completedAssistant = content
862
+ if (content || (kind === 'thinking' && hadStream)) {
863
+ // #6630: a reasoning stream keeps what the live bubble shows -- that it
864
+ // IS reasoning (`kind`) and how long it took (`thinkingDurationMs`, the
865
+ // same bounded value the live `stream_end` frame carries). Without them
866
+ // a replay rebuilt it as a plain answer.
867
+ const thinkingDurationMs = kind === 'thinking'
868
+ ? boundedNonNegInt(data.thinkingDurationMs, { max: MAX_SANE_DURATION_MS })
869
+ : undefined
870
+ // The live stream_end carries a token count when a provider separates one
871
+ // out (` · N tokens` in the footer); record it so a replay says the same.
872
+ const thinkingTokens = kind === 'thinking' ? boundedNonNegInt(data.thinkingTokens) : undefined
333
873
  this._pushHistory(history, {
334
874
  type: 'message',
335
875
  messageType: 'response',
336
876
  content,
337
877
  messageId: data.messageId,
878
+ ...(kind ? { kind } : {}),
879
+ ...(thinkingDurationMs !== undefined ? { thinkingDurationMs } : {}),
880
+ ...(thinkingTokens !== undefined ? { thinkingTokens } : {}),
881
+ // #8518: a block that reached the wire after the tool row / answer it
882
+ // belongs above keeps saying so, so a reload orders it the way the live
883
+ // client did. Absent for a block that arrived in order.
884
+ ...(thinkingPrecedes ? { thinkingPrecedes } : {}),
885
+ // #9024: where tool calls interrupted this reply's text, so a reload lays it
886
+ // out around the tool cards as the live client did. Additive: a client that
887
+ // does not read it shows the one entry as before.
888
+ ...(kind !== 'thinking' && splits?.length ? { splits } : {}),
338
889
  timestamp: Date.now(),
339
890
  }, sessionId)
340
891
  }
@@ -343,38 +894,85 @@ export class SessionMessageHistory extends EventEmitter {
343
894
  }
344
895
 
345
896
  case 'message':
897
+ assistantCompleted = data.type === 'response' && data.kind !== 'thinking' && data.thinking !== true
898
+ if (assistantCompleted) completedAssistant = data.content
346
899
  this._pushHistory(history, {
347
- type: 'message',
348
- messageType: data.type,
349
- content: data.content,
350
- tool: data.tool,
351
- options: data.options,
900
+ // #6630: the SAME envelope the live frame is built from, so a field the
901
+ // live message carries (the compact_boundary / MCP-prompt-expansion
902
+ // markers) reaches the replay too.
903
+ ...buildMessageWire(data),
352
904
  // Carry through the stable messageId for user_input entries so
353
905
  // clients can dedup rehydrated prompts against their own
354
906
  // optimistic/live-echo copies (issue #2902).
355
907
  ...(data.messageId ? { messageId: data.messageId } : {}),
356
- timestamp: data.timestamp,
908
+ ...(data.source === 'daemon' ? { source: 'daemon' } : {}),
357
909
  }, sessionId)
358
910
  persistNeeded = true
359
911
  break
360
912
 
913
+ case 'error':
914
+ // #6630: an error is a chat bubble live (an error card, or a code-specific
915
+ // chip: stream stall, resume failure, auth required), so it is part of the
916
+ // transcript. It was not recorded at all, and so vanished on the first
917
+ // session switch or reload. Built by the live frame's own builder, so the
918
+ // `code` and the fields that select a chip travel with it. A malformed
919
+ // event with no message text is not a bubble live either.
920
+ if (!data || typeof data.message !== 'string') break
921
+ this._pushHistory(history, buildErrorWire(data), sessionId)
922
+ persistNeeded = true
923
+ break
924
+
361
925
  case 'tool_start':
926
+ this._noteReplySplit(sessionId, data.toolUseId)
362
927
  this._pushHistory(history, {
363
928
  type: 'tool_start',
364
929
  messageId: data.messageId,
365
930
  toolUseId: data.toolUseId,
366
931
  tool: data.tool,
367
932
  input: data.input,
933
+ // #6630: the MCP server a tool belongs to labels its card; the live
934
+ // frame carries it, so the replay must.
935
+ ...(typeof data.serverName === 'string' && data.serverName ? { serverName: data.serverName } : {}),
368
936
  timestamp: Date.now(),
369
937
  }, sessionId)
370
938
  break
371
939
 
372
940
  case 'tool_result':
941
+ // #7346: backfill the matching tool_start entry's `input` when the
942
+ // caller (tool-result.js's emitToolResults, via
943
+ // base-session.js's `_getTrackedToolInput`) attached the
944
+ // finalized input it captured at content_block_stop (CliSession)
945
+ // / from the full assistant block (SdkSession). tool_start is
946
+ // write-once (`_pushHistory` only ever appends), so without this
947
+ // the persisted entry stays `input: null` forever — the exact
948
+ // root cause of the "(no input)" placeholder surviving a session
949
+ // switch: a forceFull replay faithfully rebuilds from history,
950
+ // and history never had the input to rebuild WITH. Search
951
+ // backward (most turns have only a handful of recent entries,
952
+ // and the match is almost always near the end) rather than
953
+ // indexing by toolUseId, since tool_start entries are rare
954
+ // enough that a second Map isn't worth the bookkeeping.
955
+ //
956
+ // BYOK never sets `data.input` (its `_getTrackedToolInput` is
957
+ // never even reached — see tool-result.js), so this loop is a
958
+ // no-op for it and its tool_start entries are unchanged.
959
+ this.backfillToolInput(sessionId, data.toolUseId, data.input)
373
960
  this._pushHistory(history, {
374
961
  type: 'tool_result',
375
962
  toolUseId: data.toolUseId,
376
963
  result: data.result,
377
964
  truncated: data.truncated,
965
+ // #7376: persist the failed / terminated markers, not just the text.
966
+ // This entry is what a reconnect or session switch replays raw.
967
+ // (Sync Full History PREFERS the native JSONL, whose parser keeps no
968
+ // tool results, so that path carries neither marker; the ring-buffer
969
+ // fallback still replays this entry.) Without them the live "turn
970
+ // terminated" (or "failed") state silently reverted to a plain green
971
+ // result on replay. Only the
972
+ // meaningful values are stored (`isError: true`, a string reason), so
973
+ // entries for ordinary successful results are byte-for-byte unchanged.
974
+ ...(data.isError === true ? { isError: true } : {}),
975
+ ...(typeof data.terminatedReason === 'string' ? { terminatedReason: data.terminatedReason } : {}),
378
976
  timestamp: Date.now(),
379
977
  }, sessionId)
380
978
  break
@@ -385,22 +983,114 @@ export class SessionMessageHistory extends EventEmitter {
385
983
  cost: data.cost,
386
984
  duration: data.duration,
387
985
  usage: data.usage,
986
+ // #7326: durable, so a session switch or reload re-shows the marker.
987
+ // Omitted when unknown, so ordinary entries are unchanged.
988
+ ...turnOutcomeField(data.turnOutcome),
989
+ // #7326: a result that was stamped at emit keeps that stamp, so the
990
+ // replayed entry and the live frame share the marker's identity.
991
+ timestamp: Number.isFinite(data.timestamp) ? data.timestamp : Date.now(),
992
+ }, sessionId)
993
+ persistNeeded = true
994
+ break
995
+
996
+ case 'permission_outcome': {
997
+ // #8348 -- the durable record of how a permission prompt ended. The live
998
+ // `permission_request` / `permission_resolved` / `permission_expired`
999
+ // frames are transient (never in the ring buffer), so a full-rebuild
1000
+ // replay (session switch, reload) cannot show a prompt that already
1001
+ // expired or was answered; this entry is what it replays instead.
1002
+ //
1003
+ // ONE entry per requestId. SessionManager's request registry already
1004
+ // makes a second call a no-op, but the entry must not depend on its
1005
+ // caller for that: a duplicate here would put two records in the
1006
+ // transcript, and the ring buffer is the only place both are visible.
1007
+ if (!data || typeof data.requestId !== 'string' || data.requestId.length === 0) break
1008
+ if (!PERMISSION_OUTCOMES.includes(data.outcome)) break
1009
+ for (let i = history.length - 1; i >= 0; i--) {
1010
+ const prior = history[i]
1011
+ if (prior && prior.type === 'permission_outcome' && prior.requestId === data.requestId) {
1012
+ return { persistNeeded: false }
1013
+ }
1014
+ }
1015
+ this._pushHistory(history, {
1016
+ type: 'permission_outcome',
1017
+ requestId: data.requestId,
1018
+ tool: clipRedacted(data.tool, PERMISSION_OUTCOME_TOOL_MAX),
1019
+ description: clipRedacted(data.description, PERMISSION_OUTCOME_DESCRIPTION_MAX),
1020
+ outcome: data.outcome,
1021
+ // #8503: the tool input the clients were shown, so a replayed record
1022
+ // and group read the same as a live one. Omitted when there is none,
1023
+ // which is also every entry from before this field.
1024
+ ...inputField(boundPermissionOutcomeInput(data.input)),
1025
+ // #8503: which allow it was (see PERMISSION_ALLOW_DECISIONS). Omitted for
1026
+ // any other outcome and for an entry from before the field.
1027
+ ...decisionField(permissionOutcomeDecision(data.outcome, data.decision)),
1028
+ // #8357: the tool-use id the prompt carried, so a replayed record still
1029
+ // pairs with its AskUserQuestion card. Omitted when there is none.
1030
+ ...(typeof data.toolUseId === 'string' && data.toolUseId.length > 0 && data.toolUseId.length <= 200
1031
+ ? { toolUseId: data.toolUseId }
1032
+ : {}),
388
1033
  timestamp: Date.now(),
389
1034
  }, sessionId)
390
1035
  persistNeeded = true
391
1036
  break
1037
+ }
392
1038
 
393
1039
  case 'user_question':
394
1040
  this._pushHistory(history, {
395
1041
  type: 'user_question',
396
1042
  toolUseId: data.toolUseId,
397
1043
  questions: data.questions,
1044
+ // #8336: the provider's id for the AskUserQuestion tool call, when it
1045
+ // differs from `toolUseId` (the SDK and BYOK route the answer on a
1046
+ // chroxy-minted `ask-...` id). It is how the restore-time sweep finds
1047
+ // the `tool_start` this question belongs to.
1048
+ ...(typeof data.sourceToolUseId === 'string' && data.sourceToolUseId.length > 0
1049
+ ? { sourceToolUseId: data.sourceToolUseId }
1050
+ : {}),
398
1051
  timestamp: Date.now(),
399
1052
  }, sessionId)
400
1053
  break
401
1054
  }
402
1055
 
403
- return { persistNeeded }
1056
+ return { persistNeeded, ...(assistantCompleted ? { assistantCompleted, completedAssistant } : {}) }
1057
+ }
1058
+
1059
+ /**
1060
+ * #9024 -- note where a tool call interrupted each open reply stream of the session.
1061
+ *
1062
+ * A `tool_start` carries no stream id, so it applies to EVERY open non-thinking reply
1063
+ * stream of the session (there is normally one). A reply that is not the tool's owner
1064
+ * then carries a split naming a tool row that is not its own, which is harmless: the
1065
+ * client lays a reply out only around tool rows it holds, in transcript order.
1066
+ *
1067
+ * A split is kept only when the stream has text since the previous one, so a run of
1068
+ * tool calls in a row keeps the first (the text sits above it, and no text sits
1069
+ * between them). The list is bounded in count and in the length of the id, and a
1070
+ * call with no usable id splits nothing: an unusable split must never become a
1071
+ * position on a client.
1072
+ *
1073
+ * @param {string} sessionId
1074
+ * @param {unknown} toolUseId
1075
+ */
1076
+ _noteReplySplit(sessionId, toolUseId) {
1077
+ if (typeof toolUseId !== 'string' || toolUseId.length === 0 || toolUseId.length > MAX_SPLIT_TOOL_ID_LENGTH) return
1078
+ const prefix = sessionId + ':'
1079
+ for (const [key, content] of this._pendingStreams) {
1080
+ if (!key.startsWith(prefix) || !content) continue
1081
+ if (this._streamKinds.get(key) === 'thinking') continue
1082
+ const splits = this._streamSplits.get(key) ?? []
1083
+ if (splits.length >= MAX_REPLY_SPLITS) continue
1084
+ if (content.length <= (splits.at(-1)?.at ?? 0)) continue
1085
+ // Never between the two halves of a surrogate pair: the next delta carries the low
1086
+ // half, and a piece must not start with half a character.
1087
+ let at = content.length
1088
+ const lastUnit = content.charCodeAt(at - 1)
1089
+ if (lastUnit >= 0xd800 && lastUnit <= 0xdbff) at -= 1
1090
+ if (at <= (splits.at(-1)?.at ?? 0)) continue
1091
+ splits.push({ at, toolUseId })
1092
+ this._streamSplits.set(key, splits)
1093
+ }
404
1094
  }
405
1095
 
406
1096
  /**
@@ -423,9 +1113,101 @@ export class SessionMessageHistory extends EventEmitter {
423
1113
  }
424
1114
  }
425
1115
 
1116
+ /**
1117
+ * #7346 / #8371: set the finalized `input` on the matching `tool_start`
1118
+ * entry. `tool_start` is write-once (`_pushHistory` only appends) and every
1119
+ * claude provider emits it with `input: null`, so without this a replay
1120
+ * rebuilds from history that never had the input to rebuild WITH.
1121
+ *
1122
+ * Two callers, one rule: `tool_result` (#7346, the input rode the result)
1123
+ * and `BaseSession._recordToolInput` via the session manager (#8371, the
1124
+ * moment the provider knows the input, which is BEFORE the tool runs -- a
1125
+ * replay during a still-running tool otherwise shows no INPUT). Both pass an
1126
+ * already-sanitised, size-capped value (`sanitizeToolInput`); this method
1127
+ * stores nothing else and applies no second copy of the redaction.
1128
+ *
1129
+ * Does not schedule a persist and returns no flag for one: `tool_start` and
1130
+ * `tool_result` themselves never set `persistNeeded` (the next message or
1131
+ * result persists the whole history, `truncateEntry` bounding the input).
1132
+ * Searches backward, so a repeated toolUseId backfills the most recent.
1133
+ *
1134
+ * @param {string} sessionId
1135
+ * @param {string} toolUseId
1136
+ * @param {unknown} input - sanitised input; `undefined` is ignored
1137
+ * @returns {boolean} true when a tool_start entry was updated
1138
+ */
1139
+ backfillToolInput(sessionId, toolUseId, input) {
1140
+ if (input === undefined) return false
1141
+ const history = this._messageHistory.get(sessionId)
1142
+ if (!Array.isArray(history)) return false
1143
+ for (let i = history.length - 1; i >= 0; i--) {
1144
+ const entry = history[i]
1145
+ if (entry && entry.type === 'tool_start' && entry.toolUseId === toolUseId) {
1146
+ // #8415: a client whose cursor already covers this entry holds the card
1147
+ // without its input, and the fill takes no seq of its own. Record when it
1148
+ // happened so a delta replay can tell that client. Only a fill of an input
1149
+ // the entry did not have counts: an entry recorded with its input (the
1150
+ // claude-tui shape) was sent with it.
1151
+ if (!isPlainObject(entry.input) && isPlainObject(input)) {
1152
+ this._toolInputFillSeqs.set(entry, this.getLastIssuedSeq(sessionId))
1153
+ }
1154
+ entry.input = input
1155
+ return true
1156
+ }
1157
+ }
1158
+ return false
1159
+ }
1160
+
1161
+ /**
1162
+ * #8415 -- the tool inputs a client at `cursor` holds a card for but not the input
1163
+ * of: retained `tool_start` entries at or before the cursor whose input was filled
1164
+ * in at or after it. An entry past the cursor is in the delta slice already, with
1165
+ * its input. Stored values are returned as they are (already sanitised): the frame
1166
+ * inherits the `sanitizeToolInput` cap.
1167
+ *
1168
+ * With cursor == fillSeq the frame repeats on every reconnect until a newer entry is
1169
+ * recorded. That is idempotent (a client never overwrites a held input) and bounded
1170
+ * by the history ring.
1171
+ *
1172
+ * @param {string} sessionId
1173
+ * @param {number} cursor - the client's history cursor
1174
+ * @returns {Array<{messageId: string, toolUseId?: string, input: object}>}
1175
+ */
1176
+ getToolInputBackfills(sessionId, cursor) {
1177
+ const history = this._messageHistory.get(sessionId)
1178
+ if (!Array.isArray(history)) return []
1179
+ const out = []
1180
+ for (const entry of history) {
1181
+ if (!entry || entry.type !== 'tool_start') continue
1182
+ const fillSeq = this._toolInputFillSeqs.get(entry)
1183
+ if (fillSeq === undefined) continue
1184
+ if (typeof entry._seq !== 'number' || !isPlainObject(entry.input)) continue
1185
+ if (typeof entry.messageId !== 'string' || !entry.messageId) continue
1186
+ if (!(entry._seq <= cursor && cursor <= fillSeq)) continue
1187
+ out.push({
1188
+ messageId: entry.messageId,
1189
+ ...(typeof entry.toolUseId === 'string' ? { toolUseId: entry.toolUseId } : {}),
1190
+ input: entry.input,
1191
+ })
1192
+ }
1193
+ return out
1194
+ }
1195
+
426
1196
  /**
427
1197
  * Shallow-clone and truncate a history entry for serialization.
428
1198
  * Content/input fields >50KB are truncated to avoid bloated state files.
1199
+ *
1200
+ * #8136 (review on #7346): `input` on a `tool_start` entry used to be
1201
+ * `null` for every provider, so the string-only check below was dead
1202
+ * code for it. Since #7346's backfill, `input` is a PARSED OBJECT (the
1203
+ * tool's structured arguments, e.g. `{ file_path, content }` for
1204
+ * `Write`) — measured here by its SERIALIZED size, matching the string
1205
+ * branch's semantics rather than leaving objects uncapped entirely.
1206
+ * (In practice `base-session.js`'s `_recordToolInput` already runs
1207
+ * every captured input through `sanitizeToolInput`'s ~10KB broadcast
1208
+ * cap before it ever reaches history, so this branch is defense in
1209
+ * depth — a second, independent bound at the persistence boundary — not
1210
+ * the only thing standing between a huge input and the state file.)
429
1211
  * @param {object} entry
430
1212
  * @returns {object}
431
1213
  */
@@ -437,9 +1219,34 @@ export class SessionMessageHistory extends EventEmitter {
437
1219
  delete clone._seq
438
1220
  if (typeof clone.content === 'string' && clone.content.length > MAX) {
439
1221
  clone.content = clone.content.slice(0, MAX) + '[truncated]'
1222
+ // #9024: a split past the clipped text points into text that is gone (or into the
1223
+ // marker). One out-of-range point makes a client drop the whole list, so keep only
1224
+ // those strictly inside what was kept (one AT the clip would leave the marker alone as a tail).
1225
+ if (Array.isArray(clone.splits)) {
1226
+ const kept = clone.splits.filter((split) => split && typeof split.at === 'number' && split.at < MAX)
1227
+ if (kept.length > 0) clone.splits = kept
1228
+ else delete clone.splits
1229
+ }
440
1230
  }
441
1231
  if (typeof clone.input === 'string' && clone.input.length > MAX) {
442
1232
  clone.input = clone.input.slice(0, MAX) + '[truncated]'
1233
+ } else if (clone.input && typeof clone.input === 'object') {
1234
+ // #8136: object-shaped input (tool_start, since #7346's backfill) —
1235
+ // the string branch above never fires for it. Serialize to measure
1236
+ // its real on-disk size; a cyclic/unserializable value (shouldn't
1237
+ // happen for a JSON-sourced tool input, but defensive) falls back
1238
+ // to a safe marker rather than throwing out of a persist path.
1239
+ let serialized
1240
+ try {
1241
+ serialized = JSON.stringify(clone.input)
1242
+ } catch {
1243
+ serialized = null
1244
+ }
1245
+ if (typeof serialized !== 'string') {
1246
+ clone.input = { _truncated: true, summary: '[unserializable]' }
1247
+ } else if (serialized.length > MAX) {
1248
+ clone.input = { _truncated: true, summary: serialized.slice(0, MAX) + '... [truncated]' }
1249
+ }
443
1250
  }
444
1251
  return clone
445
1252
  }
@@ -491,6 +1298,7 @@ export class SessionMessageHistory extends EventEmitter {
491
1298
  this._messageHistory.delete(sessionId)
492
1299
  this._historyTruncated.delete(sessionId)
493
1300
  this._seqCounters.delete(sessionId)
1301
+ this._seqReserved.delete(sessionId)
494
1302
 
495
1303
  // Clean up pending stream state (composite keys: `${sessionId}:messageId`)
496
1304
  const prefix = sessionId + ':'
@@ -503,6 +1311,18 @@ export class SessionMessageHistory extends EventEmitter {
503
1311
  for (const key of this._truncatedStreams) {
504
1312
  if (key.startsWith(prefix)) this._truncatedStreams.delete(key)
505
1313
  }
1314
+ for (const key of this._streamKinds.keys()) {
1315
+ if (key.startsWith(prefix)) this._streamKinds.delete(key)
1316
+ }
1317
+ for (const key of this._streamPrecedes.keys()) {
1318
+ if (key.startsWith(prefix)) this._streamPrecedes.delete(key)
1319
+ }
1320
+ for (const key of this._streamStartSeqs.keys()) {
1321
+ if (key.startsWith(prefix)) this._streamStartSeqs.delete(key)
1322
+ }
1323
+ for (const key of this._streamSplits.keys()) {
1324
+ if (key.startsWith(prefix)) this._streamSplits.delete(key)
1325
+ }
506
1326
  }
507
1327
 
508
1328
  /**
@@ -512,6 +1332,11 @@ export class SessionMessageHistory extends EventEmitter {
512
1332
  this._messageHistory.clear()
513
1333
  this._historyTruncated.clear()
514
1334
  this._pendingStreams.clear()
1335
+ this._streamKinds.clear()
1336
+ this._streamPrecedes.clear()
1337
+ this._streamStartSeqs.clear()
1338
+ this._streamSplits.clear()
515
1339
  this._seqCounters.clear()
1340
+ this._seqReserved.clear()
516
1341
  }
517
1342
  }