@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
@@ -1,10 +1,165 @@
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
+ /** `{ input }` when there is one, else nothing: an absent input is an absent key. */
144
+ function inputField(input) {
145
+ return input === undefined ? {} : { input }
146
+ }
147
+
148
+ /** `{ decision }` when there is one, else nothing. */
149
+ function decisionField(decision) {
150
+ return decision === undefined ? {} : { decision }
151
+ }
152
+
153
+ function clipText(value, max) {
154
+ const text = typeof value === 'string' ? value : ''
155
+ return text.length > max ? text.slice(0, max - 1) + '\u2026' : text
156
+ }
157
+
158
+ /** Pattern-redact (never cutting a token in half), THEN clip: clipping first could leave a partial secret the patterns miss. */
159
+ function clipRedacted(value, max) {
160
+ return clipText(redactBounded(typeof value === 'string' ? value : ''), max)
161
+ }
162
+
8
163
  /**
9
164
  * Manages per-session message history ring buffers, stream delta accumulation,
10
165
  * truncation tracking, and auto-labeling from first user input.
@@ -36,6 +191,19 @@ export class SessionMessageHistory extends EventEmitter {
36
191
  // over-size delta for the same message also exceeds the cap and would
37
192
  // otherwise re-fire the error). Cleared on stream_end / session clear.
38
193
  this._truncatedStreams = new Set() // sessionId:messageId
194
+ // #6630 / #8282 -- sessionId:messageId -> stream kind, for the streams that
195
+ // are not ordinary replies (reasoning). Kept beside `_pendingStreams` rather
196
+ // than inside its value because that map is read as plain strings elsewhere.
197
+ this._streamKinds = new Map()
198
+ // #8518 -- sessionId:messageId -> the ordering hint a reasoning stream_start
199
+ // carried (what it precedes). The entry is written at stream_end, so the
200
+ // start's hint is held here until then.
201
+ this._streamPrecedes = new Map()
202
+ // #9022 -- sessionId:messageId -> the seq the NEXT history entry would take when
203
+ // the stream's first text arrived. A reply is recorded only at stream_end, so while it is open
204
+ // a replay has no entry for it; this is where that text belongs in the replay
205
+ // (before every entry recorded after the stream began). Cleared with the stream.
206
+ this._streamStartSeqs = new Map()
39
207
  this._historyTruncated = new Map() // sessionId -> boolean
40
208
  // #5555.3 (lastSeq delta replay) — per-session monotonic history sequence.
41
209
  // Every entry pushed into the ring buffer is stamped with a strictly
@@ -46,6 +214,10 @@ export class SessionMessageHistory extends EventEmitter {
46
214
  // seq is server-internal bookkeeping; the wire only exposes it as
47
215
  // `historySeq` on replayed entries (see ws-history.js).
48
216
  this._seqCounters = new Map() // sessionId -> next seq to assign (>= 1)
217
+ // #8259: sessionId -> highest seq this process may issue, already handed to the
218
+ // reservation handler (the SessionManager persists it synchronously).
219
+ this._seqReserved = new Map()
220
+ this._onSeqReservation = null
49
221
  }
50
222
 
51
223
  /**
@@ -55,10 +227,47 @@ export class SessionMessageHistory extends EventEmitter {
55
227
  */
56
228
  _nextSeq(sessionId) {
57
229
  const next = this._seqCounters.get(sessionId) || 1
230
+ // #8259 RESERVATION INVARIANT: no seq above `_seqReserved` is ever issued
231
+ // before the reservation covering it has been handed to the handler, which
232
+ // persists it synchronously. So the persisted `seqReservedThrough` is >= every
233
+ // seq this process ever gave a client, whatever the lazy state-file debounce
234
+ // has or has not written. A restart numbers new entries above it, so a cursor
235
+ // a client took from the previous process can never equal or exceed them.
236
+ // The persist runs here (once per SEQ_RESERVATION_STEP entries), before the
237
+ // counter moves.
238
+ if (next > (this._seqReserved.get(sessionId) || 0)) {
239
+ this._seqReserved.set(sessionId, next + SEQ_RESERVATION_STEP)
240
+ if (this._onSeqReservation) {
241
+ try { this._onSeqReservation(sessionId) } catch (err) { log.warn(`seq reservation handler failed for ${sessionId}: ${err?.message || err}`) }
242
+ }
243
+ }
58
244
  this._seqCounters.set(sessionId, next + 1)
59
245
  return next
60
246
  }
61
247
 
248
+ /** #8259: install the callback that persists a seq reservation synchronously. */
249
+ setSeqReservationHandler(fn) {
250
+ this._onSeqReservation = typeof fn === 'function' ? fn : null
251
+ }
252
+
253
+ /** #8259: the persisted-or-persisting high-water mark for a session, or 0 when none. */
254
+ getSeqReservedThrough(sessionId) {
255
+ return this._seqReserved.get(sessionId) || 0
256
+ }
257
+
258
+ /**
259
+ * #8259: adopt the previous process's reservation on restore and move the
260
+ * counter above it, so nothing this process issues can reuse a seq a client
261
+ * holds. Returns false (and changes nothing) for a state file without a usable
262
+ * value, which then falls back to the best-effort gap.
263
+ */
264
+ restoreSeqReservation(sessionId, reservedThrough) {
265
+ if (!Number.isSafeInteger(reservedThrough) || reservedThrough < 1) return false
266
+ this._seqReserved.set(sessionId, reservedThrough)
267
+ this._seqCounters.set(sessionId, Math.max(this._seqCounters.get(sessionId) || 1, reservedThrough + 1))
268
+ return true
269
+ }
270
+
62
271
  /**
63
272
  * #5555.3 — seq of the oldest entry still retained in the ring buffer, or
64
273
  * null when the session has no history. Used by the cursor-replay path to
@@ -127,11 +336,46 @@ export class SessionMessageHistory extends EventEmitter {
127
336
  closedMessageIds.push(messageId)
128
337
  this._pendingStreams.delete(key)
129
338
  this._truncatedStreams.delete(key) // #6431 — release the truncation guard
339
+ this._streamKinds.delete(key)
340
+ this._streamPrecedes.delete(key)
341
+ this._streamStartSeqs.delete(key)
130
342
  }
131
343
  }
132
344
  return closedMessageIds
133
345
  }
134
346
 
347
+ /**
348
+ * #9022 -- the reply text a session has streamed so far but not yet closed.
349
+ *
350
+ * History only ever holds a COMPLETED reply (the entry is pushed at
351
+ * `stream_end`), so a turn paused mid-stream -- on a permission prompt, say --
352
+ * has its text in no replay, and a client that reloads shows the tool card and
353
+ * the prompt but none of what the model already said. This is that text, for
354
+ * the replay to splice in at its place in the transcript.
355
+ *
356
+ * Reasoning streams are left out (they replay as their own kind, on a
357
+ * capability), as is a stream that has produced no text yet.
358
+ *
359
+ * @param {string} sessionId
360
+ * @returns {Array<{ messageId: string, content: string, startSeq: number }>}
361
+ * `startSeq` is the seq the next recorded entry had when its first text arrived:
362
+ * the reply belongs before every entry with `_seq >= startSeq`.
363
+ */
364
+ getPendingResponseStreams(sessionId) {
365
+ const prefix = sessionId + ':'
366
+ const out = []
367
+ for (const [key, content] of this._pendingStreams) {
368
+ if (!key.startsWith(prefix) || !content) continue
369
+ if (this._streamKinds.get(key) === 'thinking') continue
370
+ out.push({
371
+ messageId: key.slice(prefix.length),
372
+ content,
373
+ startSeq: this._streamStartSeqs.get(key) ?? Infinity,
374
+ })
375
+ }
376
+ return out
377
+ }
378
+
135
379
  /**
136
380
  * Get message history for a session.
137
381
  * @param {string} sessionId
@@ -159,28 +403,142 @@ export class SessionMessageHistory extends EventEmitter {
159
403
  return this._historyTruncated.get(sessionId) || false
160
404
  }
161
405
 
406
+ /**
407
+ * #8336 — the highest seq this session has handed out (0 when none). It is
408
+ * what a state file records so the NEXT run can keep numbering past it; the
409
+ * newest retained entry carries it, but the counter is the authority because
410
+ * it survives a front-trim of the whole buffer.
411
+ * @param {string} sessionId
412
+ * @returns {number}
413
+ */
414
+ getLastIssuedSeq(sessionId) {
415
+ return (this._seqCounters.get(sessionId) || 1) - 1
416
+ }
417
+
162
418
  /**
163
419
  * Set pre-existing history for a session (used during state restore).
420
+ *
421
+ * #8336 -- SEQUENCE CONTINUITY. Entries are stamped `firstSeq, firstSeq + 1, ...`
422
+ * and the counter is left just past the last one. The caller passes the first
423
+ * seq so that the entries the previous run persisted keep (roughly) the
424
+ * numbers that run served them under: a reconnecting client's cursor
425
+ * (`lastSeq`) then still means what it meant, and every entry added after the
426
+ * restore (a tail correction, the next turn) is numbered PAST every cursor the
427
+ * previous run issued. Restarting from 1 broke that: with the ring buffer
428
+ * already full, the restore's own additions plus the post-restart traffic could
429
+ * climb through the old cursor's value, and `resolveReplayPlan` then honoured a
430
+ * cursor that no longer pointed at what the client had seen.
431
+ *
432
+ * Without `firstSeq` (a state file from before this field, or a malformed one)
433
+ * numbering starts at 1: the pre-#8336 behaviour, where a cursor from the prior
434
+ * run is honoured only by accident and falls back to a full replay otherwise.
435
+ *
436
+ * The history is also trimmed to the ring-buffer cap, oldest first. A restore
437
+ * can add entries (synthetic tool results, a marked question copy) to a buffer
438
+ * that was already full, and `_pushHistory` only ever evicts one entry per push,
439
+ * so without this the buffer grew by the restore's additions on EVERY restart.
440
+ * The trimmed front is what falls off, so a cursor older than the new oldest
441
+ * entry takes the "trimmed past" full-replay fallback, as designed.
442
+ *
164
443
  * @param {string} sessionId
165
444
  * @param {Array} history
445
+ * @param {object} [opts]
446
+ * @param {number} [opts.firstSeq] - seq to give the first entry (integer >= 1)
166
447
  */
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.
448
+ setHistory(sessionId, history, { firstSeq } = {}) {
173
449
  if (Array.isArray(history)) {
174
- let seq = 1
450
+ const start = Number.isSafeInteger(firstSeq) && firstSeq >= 1 ? firstSeq : 1
451
+ let seq = start
175
452
  for (const entry of history) {
176
453
  if (entry && typeof entry === 'object') entry._seq = seq
177
454
  seq++
178
455
  }
179
456
  this._seqCounters.set(sessionId, seq)
457
+ const excess = history.length - this._maxHistory
458
+ if (excess > 0) {
459
+ history = history.slice(excess)
460
+ this._historyTruncated.set(sessionId, true)
461
+ }
180
462
  }
181
463
  this._messageHistory.set(sessionId, history)
182
464
  }
183
465
 
466
+ /**
467
+ * #8362 -- record that the server ACCEPTED an answer to a `user_question`.
468
+ *
469
+ * The restore-time sweep (`sweepUnresolvedToolStarts`) calls a question
470
+ * interrupted when its AskUserQuestion tool has no `tool_result`. For
471
+ * claude-cli and claude-tui the answer is delivered to the provider BEFORE the
472
+ * tool's result event arrives, so a restart in that window cut off a question
473
+ * that had in fact been answered, and a client rebuilding from scratch showed
474
+ * "Interrupted -- chroxy restarted before this was answered". This is the
475
+ * record the sweep consults.
476
+ *
477
+ * A flag only: the answer text is not stored (it is not already in the entry,
478
+ * and the history would otherwise start persisting user answers). Idempotent.
479
+ * Mutates the entry in place, like `tool_result`'s input backfill: nothing a
480
+ * client could hold is changed on the live wire, and `sendHistoryEntry` keeps
481
+ * the field off replay frames.
482
+ *
483
+ * @param {string} sessionId
484
+ * @param {string} [toolUseId] - The question's id (the one its route and wire
485
+ * frame carry). Without one, the newest question not yet marked answered:
486
+ * only clients that send no id reach that, and they have one question in
487
+ * flight.
488
+ * @returns {boolean} true when an entry was newly marked (the caller persists)
489
+ */
490
+ markQuestionAnswered(sessionId, toolUseId) {
491
+ const history = this._messageHistory.get(sessionId)
492
+ if (!Array.isArray(history)) return false
493
+ for (let i = history.length - 1; i >= 0; i--) {
494
+ const entry = history[i]
495
+ if (!entry || entry.type !== 'user_question') continue
496
+ if (typeof toolUseId === 'string') {
497
+ if (entry.toolUseId !== toolUseId) continue
498
+ } else if (entry.answered === true) {
499
+ continue
500
+ }
501
+ if (entry.answered === true) return false
502
+ entry.answered = true
503
+ return true
504
+ }
505
+ return false
506
+ }
507
+
508
+ /**
509
+ * #8470 -- record that a newer question REPLACED this one, so nobody answered it
510
+ * and nobody will. `permission_resolved` is transient, so without this a client
511
+ * that was not watching live (a fresh dashboard, a full rebuild, a reconnect)
512
+ * replays the question as unanswered and stamps it "(resolved)", which reads as
513
+ * answered.
514
+ *
515
+ * Two writes, for the same reason the restore-time sweep makes two (#8336): the
516
+ * entry is flagged IN PLACE (a full rebuild receives the question where it was
517
+ * asked, already marked), and a marked COPY is appended at the tail with a fresh
518
+ * seq (a client whose cursor is already past the question would otherwise never
519
+ * hear; the client collapses the copy onto the card it holds by `toolUseId`).
520
+ * The flag also stops the restore-time sweep calling the question interrupted
521
+ * when a restart lands before the denial's `tool_result`.
522
+ *
523
+ * @param {string} sessionId
524
+ * @param {string} toolUseId - the question's id (the `ask-...` id on its frame)
525
+ * @returns {boolean} true when an entry was newly marked (the caller persists)
526
+ */
527
+ markQuestionSuperseded(sessionId, toolUseId) {
528
+ const history = this._messageHistory.get(sessionId)
529
+ if (!Array.isArray(history) || typeof toolUseId !== 'string') return false
530
+ for (let i = history.length - 1; i >= 0; i--) {
531
+ const entry = history[i]
532
+ if (!entry || entry.type !== 'user_question' || entry.toolUseId !== toolUseId) continue
533
+ if (entry.superseded === true || entry.answered === true) return false
534
+ entry.superseded = true
535
+ const { _seq: _dropped, ...copy } = entry
536
+ this._pushHistory(history, copy, sessionId)
537
+ return true
538
+ }
539
+ return false
540
+ }
541
+
184
542
  /**
185
543
  * Sweep an in-memory history array for `tool_start` entries that lack a
186
544
  * matching `tool_result` and splice in a synthetic `tool_result` right
@@ -196,6 +554,17 @@ export class SessionMessageHistory extends EventEmitter {
196
554
  * downstream consumers that sort by timestamp stay monotonic without
197
555
  * pretending the tool completed "now".
198
556
  *
557
+ * #8336: a `user_question` entry for one of the swept `tool_start`s (matched
558
+ * on its `sourceToolUseId` when it has one, else its `toolUseId`) is returned
559
+ * as a COPY carrying `interrupted: true` (the question was cut off, not
560
+ * answered), so a replaying client can say so instead of stamping it
561
+ * "(resolved)". A second marked copy is appended at the END of the history so
562
+ * that a delta replay for a client whose cursor is already past the question
563
+ * still delivers the mark. Other entries are passed through. A question carrying
564
+ * `answered: true` (#8362: the server accepted an answer before the restart) is
565
+ * passed through unmarked, as is one carrying `superseded: true` (#8470: a newer
566
+ * question replaced it, which is its own verdict).
567
+ *
199
568
  * Safe to call on:
200
569
  * - empty / non-array input (returns the input unchanged)
201
570
  * - history with no tool_start entries (returns a shallow copy)
@@ -213,7 +582,41 @@ export class SessionMessageHistory extends EventEmitter {
213
582
  }
214
583
  }
215
584
  const out = []
585
+ // #8336: the toolUseIds this sweep cuts off. A `user_question` entry for
586
+ // one of them was never answered (an answer would have produced the
587
+ // tool_result), so it is marked `interrupted` below rather than left
588
+ // looking like every other replayed question, which the client's
589
+ // history_replay_end sweep stamps "(resolved)".
590
+ const interruptedIds = new Set()
216
591
  for (const entry of history) {
592
+ if (
593
+ entry
594
+ && entry.type === 'tool_start'
595
+ && typeof entry.toolUseId === 'string'
596
+ && !resolved.has(entry.toolUseId)
597
+ ) {
598
+ interruptedIds.add(entry.toolUseId)
599
+ }
600
+ }
601
+ // #8336: the marked copies to re-append at the tail, see below.
602
+ const redelivered = []
603
+ for (const rawEntry of history) {
604
+ // `user_question` is copied, never mutated: the input array is the
605
+ // caller's, and the contract above says it is not modified. The set was
606
+ // collected up front, so the question is marked whichever side of its
607
+ // tool_start it was recorded on. A question names its tool by
608
+ // `sourceToolUseId` when it has one (SDK, BYOK: `toolUseId` is chroxy's
609
+ // own `ask-...` id there), else by `toolUseId` itself (CLI, TUI).
610
+ const questionToolId = rawEntry && rawEntry.type === 'user_question'
611
+ ? (typeof rawEntry.sourceToolUseId === 'string' ? rawEntry.sourceToolUseId : rawEntry.toolUseId)
612
+ : undefined
613
+ // #8362: a question the server accepted an answer for is not cut off even
614
+ // though its tool_result has not arrived yet (cli/tui deliver the answer
615
+ // first). The tool_start is still swept below -- the TOOL was in flight.
616
+ const entry = (typeof questionToolId === 'string' && interruptedIds.has(questionToolId) && rawEntry.answered !== true && rawEntry.superseded !== true)
617
+ ? { ...rawEntry, interrupted: true }
618
+ : rawEntry
619
+ if (entry !== rawEntry) redelivered.push({ ...entry })
217
620
  out.push(entry)
218
621
  if (
219
622
  entry
@@ -242,6 +645,9 @@ export class SessionMessageHistory extends EventEmitter {
242
645
  isError: true,
243
646
  synthetic: true,
244
647
  reason: 'session_restored',
648
+ // #7376: the restore-time sweep is the one termination whose OUTCOME is
649
+ // unknown (the daemon went down mid-tool) -- say so distinctly.
650
+ terminatedReason: 'daemon_restart',
245
651
  timestamp: baseTs + 1,
246
652
  })
247
653
  // Mark this toolUseId resolved so a malformed history with two
@@ -249,9 +655,76 @@ export class SessionMessageHistory extends EventEmitter {
249
655
  resolved.add(entry.toolUseId)
250
656
  }
251
657
  }
658
+ // #8336: the marked question is ALSO appended as a fresh entry at the tail.
659
+ // Marking it in place changes an entry a client may already be past: a
660
+ // reconnecting client's cursor is honoured when it falls inside the restored
661
+ // range, and the delta replay then sends only what lies past it. A client
662
+ // whose cursor sits beyond the question's position would never hear that it
663
+ // was cut off, and its replay-end sweep would stamp the card "(resolved)".
664
+ // A tail entry is numbered past every cursor the previous run could have
665
+ // issued -- `setHistory` continues the previous run's numbering rather than
666
+ // restarting at 1, and the tail is beyond its last entry by construction --
667
+ // so it always arrives. The client collapses it onto the card it holds (same
668
+ // `toolUseId`, same questions), so nobody sees two; a client rebuilding from
669
+ // scratch gets the question in place from the marked entry above and the copy
670
+ // merges onto it. If the ring-buffer cap later evicts the in-place original
671
+ // first (oldest-first), the copy is what remains: a full replay then shows the
672
+ // question after newer messages rather than where it was asked, which is the
673
+ // price of never losing the verdict.
674
+ for (const copy of redelivered) out.push(copy)
252
675
  return out
253
676
  }
254
677
 
678
+ /**
679
+ * #8259: close a turn the daemon went down under. Called by the SessionManager's
680
+ * restore ONLY for a session whose persisted state says a turn was in flight
681
+ * (dispatched to the provider and not yet ended). The partial reply only ever
682
+ * lived in memory, so without this no client could be told how that turn
683
+ * ended. Appends a `result` carrying the `interrupted` turn outcome, the SAME
684
+ * marker path (`turnOutcome` on a `result`) a stopped or truncated turn uses.
685
+ *
686
+ * DELIVERY. A client's cursor comes from the previous process, and the state
687
+ * file's `historyLastSeq` can lag it without bound (the write is debounced and
688
+ * the debounce restarts on every append). What does not lag is the seq
689
+ * RESERVATION (see `_nextSeq`): it is persisted before any seq under it is
690
+ * issued, so `seqReservedThrough` is >= every seq the previous process gave a
691
+ * client. Restore moves the counter above it, so the marker is numbered strictly
692
+ * past every possible cursor: the delta replay (strictly newer than the cursor)
693
+ * honours the cursor and sends it. A state file without a reservation (written
694
+ * before this existed) falls back to `RESTART_SEQ_GAP`, best effort.
695
+ *
696
+ * The timestamp is clamped to one past the newest entry, like the synthetic
697
+ * tool_result of `sweepUnresolvedToolStarts`, so the marker never sorts before
698
+ * the entries it follows.
699
+ *
700
+ * PROVIDER RESUME. No provider continues a half-run turn after a restart: a
701
+ * restored session is a fresh idle provider that resumes the CONVERSATION
702
+ * (context), not the turn, so nothing completes the interrupted turn later.
703
+ * If one ever did, its completed result would simply follow this chip (a
704
+ * completed outcome adds no marker and does not remove one), which stays an
705
+ * honest record that the turn was cut off once.
706
+ *
707
+ * @param {string} sessionId
708
+ * @param {number} [now] - injectable for tests
709
+ * @returns {object} the appended entry
710
+ */
711
+ recordInterruptedTurn(sessionId, now = Date.now()) {
712
+ if (!this._messageHistory.has(sessionId)) this._messageHistory.set(sessionId, [])
713
+ const history = this._messageHistory.get(sessionId)
714
+ let lastTs = 0
715
+ for (const e of history) {
716
+ if (e && Number.isFinite(e.timestamp) && e.timestamp > lastTs) lastTs = e.timestamp
717
+ }
718
+ // With a restored reservation the counter is already above it (restoreSeqReservation);
719
+ // only a pre-reservation state file needs the best-effort gap.
720
+ if (!this._seqReserved.has(sessionId)) {
721
+ this._seqCounters.set(sessionId, (this._seqCounters.get(sessionId) || 1) + RESTART_SEQ_GAP)
722
+ }
723
+ const marker = { type: 'result', turnOutcome: 'interrupted', timestamp: Math.max(now, lastTs + 1) }
724
+ this._pushHistory(history, marker, sessionId)
725
+ return marker
726
+ }
727
+
255
728
  /**
256
729
  * Record a user input message in the session's history ring buffer.
257
730
  * On the first non-empty input, emits auto_label if the session qualifies.
@@ -265,8 +738,9 @@ export class SessionMessageHistory extends EventEmitter {
265
738
  * `handlers/input-handlers.js::resolveUserInputId`) always resolves one
266
739
  * before calling in, so replayed entries always carry an id in practice.
267
740
  * See issue #2902.
741
+ * @param {'daemon'} [source] - #8301: marks a daemon-authored turn (the CI wake).
268
742
  */
269
- recordUserInput(sessionId, text, sessionEntry, messageId) {
743
+ recordUserInput(sessionId, text, sessionEntry, messageId, source) {
270
744
  if (sessionEntry) {
271
745
  this._autoLabelSession(sessionId, text, sessionEntry)
272
746
  }
@@ -278,6 +752,10 @@ export class SessionMessageHistory extends EventEmitter {
278
752
  if (typeof messageId === 'string' && messageId.length > 0) {
279
753
  entry.messageId = messageId
280
754
  }
755
+ // #8301: `source: 'daemon'` marks a turn the daemon wrote (the CI wake), so a
756
+ // replaying client can tell it from something a person typed. Absent for
757
+ // typed input — an older client ignores the field either way.
758
+ if (source === 'daemon') entry.source = 'daemon'
281
759
  this.recordHistory(sessionId, 'message', entry)
282
760
  }
283
761
 
@@ -294,11 +772,19 @@ export class SessionMessageHistory extends EventEmitter {
294
772
  }
295
773
  const history = this._messageHistory.get(sessionId)
296
774
  let persistNeeded = false
775
+ let completedAssistant
776
+ let assistantCompleted = false
297
777
 
298
778
  switch (event) {
299
779
  case 'stream_start': {
300
780
  const key = `${sessionId}:${data.messageId}`
301
781
  this._pendingStreams.set(key, '')
782
+ // #6630 / #8282: a reasoning stream must not be recorded as a reply.
783
+ if (data.thinking === true) {
784
+ this._streamKinds.set(key, 'thinking')
785
+ const thinkingPrecedes = boundedThinkingPrecedes(data.thinkingPrecedes)
786
+ if (thinkingPrecedes) this._streamPrecedes.set(key, thinkingPrecedes)
787
+ }
302
788
  break
303
789
  }
304
790
 
@@ -319,6 +805,13 @@ export class SessionMessageHistory extends EventEmitter {
319
805
  }
320
806
  return { persistNeeded: false, truncated: firstDrop }
321
807
  }
808
+ // #9022: where the reply BEGINS is where its first text arrived, not where
809
+ // the stream opened. claude-tui and byok open the stream inside sendMessage,
810
+ // before the input is accepted and `user_input` recorded, so a start-time
811
+ // seq would put the reply above the prompt it answers.
812
+ if (data.delta.length > 0 && !this._streamStartSeqs.has(key)) {
813
+ this._streamStartSeqs.set(key, this._seqCounters.get(sessionId) || 1)
814
+ }
322
815
  this._pendingStreams.set(key, existing + data.delta)
323
816
  }
324
817
  break
@@ -327,14 +820,46 @@ export class SessionMessageHistory extends EventEmitter {
327
820
  case 'stream_end': {
328
821
  const key = `${sessionId}:${data.messageId}`
329
822
  const content = this._pendingStreams.get(key) || ''
823
+ const hadStream = this._pendingStreams.has(key)
824
+ const kind = this._streamKinds.get(key) || (data.thinking === true ? 'thinking' : undefined)
825
+ const thinkingPrecedes = kind === 'thinking' ? this._streamPrecedes.get(key) : undefined
330
826
  this._pendingStreams.delete(key)
827
+ this._streamKinds.delete(key)
828
+ this._streamPrecedes.delete(key)
829
+ const wasTruncated = this._truncatedStreams.has(key)
830
+ this._streamStartSeqs.delete(key)
331
831
  this._truncatedStreams.delete(key) // #6431 — release the once-per-stream guard
332
- if (content) {
832
+ // A reasoning stream is recorded even with no text: current Claude models
833
+ // return the block with its signature only, so the SDK opens and closes a
834
+ // thinking stream that never carries a delta. Live, that is a "thought for
835
+ // Xs" bubble with an empty body; skipping it for want of text made the whole
836
+ // bubble vanish on replay. A reply with no text is still no entry, and so is
837
+ // a stream_end whose start this history never saw.
838
+ assistantCompleted = hadStream && kind !== 'thinking'
839
+ if (assistantCompleted && !wasTruncated && data.interrupted !== true) completedAssistant = content
840
+ if (content || (kind === 'thinking' && hadStream)) {
841
+ // #6630: a reasoning stream keeps what the live bubble shows -- that it
842
+ // IS reasoning (`kind`) and how long it took (`thinkingDurationMs`, the
843
+ // same bounded value the live `stream_end` frame carries). Without them
844
+ // a replay rebuilt it as a plain answer.
845
+ const thinkingDurationMs = kind === 'thinking'
846
+ ? boundedNonNegInt(data.thinkingDurationMs, { max: MAX_SANE_DURATION_MS })
847
+ : undefined
848
+ // The live stream_end carries a token count when a provider separates one
849
+ // out (` · N tokens` in the footer); record it so a replay says the same.
850
+ const thinkingTokens = kind === 'thinking' ? boundedNonNegInt(data.thinkingTokens) : undefined
333
851
  this._pushHistory(history, {
334
852
  type: 'message',
335
853
  messageType: 'response',
336
854
  content,
337
855
  messageId: data.messageId,
856
+ ...(kind ? { kind } : {}),
857
+ ...(thinkingDurationMs !== undefined ? { thinkingDurationMs } : {}),
858
+ ...(thinkingTokens !== undefined ? { thinkingTokens } : {}),
859
+ // #8518: a block that reached the wire after the tool row / answer it
860
+ // belongs above keeps saying so, so a reload orders it the way the live
861
+ // client did. Absent for a block that arrived in order.
862
+ ...(thinkingPrecedes ? { thinkingPrecedes } : {}),
338
863
  timestamp: Date.now(),
339
864
  }, sessionId)
340
865
  }
@@ -343,21 +868,34 @@ export class SessionMessageHistory extends EventEmitter {
343
868
  }
344
869
 
345
870
  case 'message':
871
+ assistantCompleted = data.type === 'response' && data.kind !== 'thinking' && data.thinking !== true
872
+ if (assistantCompleted) completedAssistant = data.content
346
873
  this._pushHistory(history, {
347
- type: 'message',
348
- messageType: data.type,
349
- content: data.content,
350
- tool: data.tool,
351
- options: data.options,
874
+ // #6630: the SAME envelope the live frame is built from, so a field the
875
+ // live message carries (the compact_boundary / MCP-prompt-expansion
876
+ // markers) reaches the replay too.
877
+ ...buildMessageWire(data),
352
878
  // Carry through the stable messageId for user_input entries so
353
879
  // clients can dedup rehydrated prompts against their own
354
880
  // optimistic/live-echo copies (issue #2902).
355
881
  ...(data.messageId ? { messageId: data.messageId } : {}),
356
- timestamp: data.timestamp,
882
+ ...(data.source === 'daemon' ? { source: 'daemon' } : {}),
357
883
  }, sessionId)
358
884
  persistNeeded = true
359
885
  break
360
886
 
887
+ case 'error':
888
+ // #6630: an error is a chat bubble live (an error card, or a code-specific
889
+ // chip: stream stall, resume failure, auth required), so it is part of the
890
+ // transcript. It was not recorded at all, and so vanished on the first
891
+ // session switch or reload. Built by the live frame's own builder, so the
892
+ // `code` and the fields that select a chip travel with it. A malformed
893
+ // event with no message text is not a bubble live either.
894
+ if (!data || typeof data.message !== 'string') break
895
+ this._pushHistory(history, buildErrorWire(data), sessionId)
896
+ persistNeeded = true
897
+ break
898
+
361
899
  case 'tool_start':
362
900
  this._pushHistory(history, {
363
901
  type: 'tool_start',
@@ -365,16 +903,49 @@ export class SessionMessageHistory extends EventEmitter {
365
903
  toolUseId: data.toolUseId,
366
904
  tool: data.tool,
367
905
  input: data.input,
906
+ // #6630: the MCP server a tool belongs to labels its card; the live
907
+ // frame carries it, so the replay must.
908
+ ...(typeof data.serverName === 'string' && data.serverName ? { serverName: data.serverName } : {}),
368
909
  timestamp: Date.now(),
369
910
  }, sessionId)
370
911
  break
371
912
 
372
913
  case 'tool_result':
914
+ // #7346: backfill the matching tool_start entry's `input` when the
915
+ // caller (tool-result.js's emitToolResults, via
916
+ // base-session.js's `_getTrackedToolInput`) attached the
917
+ // finalized input it captured at content_block_stop (CliSession)
918
+ // / from the full assistant block (SdkSession). tool_start is
919
+ // write-once (`_pushHistory` only ever appends), so without this
920
+ // the persisted entry stays `input: null` forever — the exact
921
+ // root cause of the "(no input)" placeholder surviving a session
922
+ // switch: a forceFull replay faithfully rebuilds from history,
923
+ // and history never had the input to rebuild WITH. Search
924
+ // backward (most turns have only a handful of recent entries,
925
+ // and the match is almost always near the end) rather than
926
+ // indexing by toolUseId, since tool_start entries are rare
927
+ // enough that a second Map isn't worth the bookkeeping.
928
+ //
929
+ // BYOK never sets `data.input` (its `_getTrackedToolInput` is
930
+ // never even reached — see tool-result.js), so this loop is a
931
+ // no-op for it and its tool_start entries are unchanged.
932
+ this.backfillToolInput(sessionId, data.toolUseId, data.input)
373
933
  this._pushHistory(history, {
374
934
  type: 'tool_result',
375
935
  toolUseId: data.toolUseId,
376
936
  result: data.result,
377
937
  truncated: data.truncated,
938
+ // #7376: persist the failed / terminated markers, not just the text.
939
+ // This entry is what a reconnect or session switch replays raw.
940
+ // (Sync Full History PREFERS the native JSONL, whose parser keeps no
941
+ // tool results, so that path carries neither marker; the ring-buffer
942
+ // fallback still replays this entry.) Without them the live "turn
943
+ // terminated" (or "failed") state silently reverted to a plain green
944
+ // result on replay. Only the
945
+ // meaningful values are stored (`isError: true`, a string reason), so
946
+ // entries for ordinary successful results are byte-for-byte unchanged.
947
+ ...(data.isError === true ? { isError: true } : {}),
948
+ ...(typeof data.terminatedReason === 'string' ? { terminatedReason: data.terminatedReason } : {}),
378
949
  timestamp: Date.now(),
379
950
  }, sessionId)
380
951
  break
@@ -385,22 +956,77 @@ export class SessionMessageHistory extends EventEmitter {
385
956
  cost: data.cost,
386
957
  duration: data.duration,
387
958
  usage: data.usage,
959
+ // #7326: durable, so a session switch or reload re-shows the marker.
960
+ // Omitted when unknown, so ordinary entries are unchanged.
961
+ ...turnOutcomeField(data.turnOutcome),
962
+ // #7326: a result that was stamped at emit keeps that stamp, so the
963
+ // replayed entry and the live frame share the marker's identity.
964
+ timestamp: Number.isFinite(data.timestamp) ? data.timestamp : Date.now(),
965
+ }, sessionId)
966
+ persistNeeded = true
967
+ break
968
+
969
+ case 'permission_outcome': {
970
+ // #8348 -- the durable record of how a permission prompt ended. The live
971
+ // `permission_request` / `permission_resolved` / `permission_expired`
972
+ // frames are transient (never in the ring buffer), so a full-rebuild
973
+ // replay (session switch, reload) cannot show a prompt that already
974
+ // expired or was answered; this entry is what it replays instead.
975
+ //
976
+ // ONE entry per requestId. SessionManager's request registry already
977
+ // makes a second call a no-op, but the entry must not depend on its
978
+ // caller for that: a duplicate here would put two records in the
979
+ // transcript, and the ring buffer is the only place both are visible.
980
+ if (!data || typeof data.requestId !== 'string' || data.requestId.length === 0) break
981
+ if (!PERMISSION_OUTCOMES.includes(data.outcome)) break
982
+ for (let i = history.length - 1; i >= 0; i--) {
983
+ const prior = history[i]
984
+ if (prior && prior.type === 'permission_outcome' && prior.requestId === data.requestId) {
985
+ return { persistNeeded: false }
986
+ }
987
+ }
988
+ this._pushHistory(history, {
989
+ type: 'permission_outcome',
990
+ requestId: data.requestId,
991
+ tool: clipRedacted(data.tool, PERMISSION_OUTCOME_TOOL_MAX),
992
+ description: clipRedacted(data.description, PERMISSION_OUTCOME_DESCRIPTION_MAX),
993
+ outcome: data.outcome,
994
+ // #8503: the tool input the clients were shown, so a replayed record
995
+ // and group read the same as a live one. Omitted when there is none,
996
+ // which is also every entry from before this field.
997
+ ...inputField(boundPermissionOutcomeInput(data.input)),
998
+ // #8503: which allow it was (see PERMISSION_ALLOW_DECISIONS). Omitted for
999
+ // any other outcome and for an entry from before the field.
1000
+ ...decisionField(permissionOutcomeDecision(data.outcome, data.decision)),
1001
+ // #8357: the tool-use id the prompt carried, so a replayed record still
1002
+ // pairs with its AskUserQuestion card. Omitted when there is none.
1003
+ ...(typeof data.toolUseId === 'string' && data.toolUseId.length > 0 && data.toolUseId.length <= 200
1004
+ ? { toolUseId: data.toolUseId }
1005
+ : {}),
388
1006
  timestamp: Date.now(),
389
1007
  }, sessionId)
390
1008
  persistNeeded = true
391
1009
  break
1010
+ }
392
1011
 
393
1012
  case 'user_question':
394
1013
  this._pushHistory(history, {
395
1014
  type: 'user_question',
396
1015
  toolUseId: data.toolUseId,
397
1016
  questions: data.questions,
1017
+ // #8336: the provider's id for the AskUserQuestion tool call, when it
1018
+ // differs from `toolUseId` (the SDK and BYOK route the answer on a
1019
+ // chroxy-minted `ask-...` id). It is how the restore-time sweep finds
1020
+ // the `tool_start` this question belongs to.
1021
+ ...(typeof data.sourceToolUseId === 'string' && data.sourceToolUseId.length > 0
1022
+ ? { sourceToolUseId: data.sourceToolUseId }
1023
+ : {}),
398
1024
  timestamp: Date.now(),
399
1025
  }, sessionId)
400
1026
  break
401
1027
  }
402
1028
 
403
- return { persistNeeded }
1029
+ return { persistNeeded, ...(assistantCompleted ? { assistantCompleted, completedAssistant } : {}) }
404
1030
  }
405
1031
 
406
1032
  /**
@@ -423,9 +1049,58 @@ export class SessionMessageHistory extends EventEmitter {
423
1049
  }
424
1050
  }
425
1051
 
1052
+ /**
1053
+ * #7346 / #8371: set the finalized `input` on the matching `tool_start`
1054
+ * entry. `tool_start` is write-once (`_pushHistory` only appends) and every
1055
+ * claude provider emits it with `input: null`, so without this a replay
1056
+ * rebuilds from history that never had the input to rebuild WITH.
1057
+ *
1058
+ * Two callers, one rule: `tool_result` (#7346, the input rode the result)
1059
+ * and `BaseSession._recordToolInput` via the session manager (#8371, the
1060
+ * moment the provider knows the input, which is BEFORE the tool runs -- a
1061
+ * replay during a still-running tool otherwise shows no INPUT). Both pass an
1062
+ * already-sanitised, size-capped value (`sanitizeToolInput`); this method
1063
+ * stores nothing else and applies no second copy of the redaction.
1064
+ *
1065
+ * Does not schedule a persist and returns no flag for one: `tool_start` and
1066
+ * `tool_result` themselves never set `persistNeeded` (the next message or
1067
+ * result persists the whole history, `truncateEntry` bounding the input).
1068
+ * Searches backward, so a repeated toolUseId backfills the most recent.
1069
+ *
1070
+ * @param {string} sessionId
1071
+ * @param {string} toolUseId
1072
+ * @param {unknown} input - sanitised input; `undefined` is ignored
1073
+ * @returns {boolean} true when a tool_start entry was updated
1074
+ */
1075
+ backfillToolInput(sessionId, toolUseId, input) {
1076
+ if (input === undefined) return false
1077
+ const history = this._messageHistory.get(sessionId)
1078
+ if (!Array.isArray(history)) return false
1079
+ for (let i = history.length - 1; i >= 0; i--) {
1080
+ const entry = history[i]
1081
+ if (entry && entry.type === 'tool_start' && entry.toolUseId === toolUseId) {
1082
+ entry.input = input
1083
+ return true
1084
+ }
1085
+ }
1086
+ return false
1087
+ }
1088
+
426
1089
  /**
427
1090
  * Shallow-clone and truncate a history entry for serialization.
428
1091
  * Content/input fields >50KB are truncated to avoid bloated state files.
1092
+ *
1093
+ * #8136 (review on #7346): `input` on a `tool_start` entry used to be
1094
+ * `null` for every provider, so the string-only check below was dead
1095
+ * code for it. Since #7346's backfill, `input` is a PARSED OBJECT (the
1096
+ * tool's structured arguments, e.g. `{ file_path, content }` for
1097
+ * `Write`) — measured here by its SERIALIZED size, matching the string
1098
+ * branch's semantics rather than leaving objects uncapped entirely.
1099
+ * (In practice `base-session.js`'s `_recordToolInput` already runs
1100
+ * every captured input through `sanitizeToolInput`'s ~10KB broadcast
1101
+ * cap before it ever reaches history, so this branch is defense in
1102
+ * depth — a second, independent bound at the persistence boundary — not
1103
+ * the only thing standing between a huge input and the state file.)
429
1104
  * @param {object} entry
430
1105
  * @returns {object}
431
1106
  */
@@ -440,6 +1115,23 @@ export class SessionMessageHistory extends EventEmitter {
440
1115
  }
441
1116
  if (typeof clone.input === 'string' && clone.input.length > MAX) {
442
1117
  clone.input = clone.input.slice(0, MAX) + '[truncated]'
1118
+ } else if (clone.input && typeof clone.input === 'object') {
1119
+ // #8136: object-shaped input (tool_start, since #7346's backfill) —
1120
+ // the string branch above never fires for it. Serialize to measure
1121
+ // its real on-disk size; a cyclic/unserializable value (shouldn't
1122
+ // happen for a JSON-sourced tool input, but defensive) falls back
1123
+ // to a safe marker rather than throwing out of a persist path.
1124
+ let serialized
1125
+ try {
1126
+ serialized = JSON.stringify(clone.input)
1127
+ } catch {
1128
+ serialized = null
1129
+ }
1130
+ if (typeof serialized !== 'string') {
1131
+ clone.input = { _truncated: true, summary: '[unserializable]' }
1132
+ } else if (serialized.length > MAX) {
1133
+ clone.input = { _truncated: true, summary: serialized.slice(0, MAX) + '... [truncated]' }
1134
+ }
443
1135
  }
444
1136
  return clone
445
1137
  }
@@ -491,6 +1183,7 @@ export class SessionMessageHistory extends EventEmitter {
491
1183
  this._messageHistory.delete(sessionId)
492
1184
  this._historyTruncated.delete(sessionId)
493
1185
  this._seqCounters.delete(sessionId)
1186
+ this._seqReserved.delete(sessionId)
494
1187
 
495
1188
  // Clean up pending stream state (composite keys: `${sessionId}:messageId`)
496
1189
  const prefix = sessionId + ':'
@@ -503,6 +1196,15 @@ export class SessionMessageHistory extends EventEmitter {
503
1196
  for (const key of this._truncatedStreams) {
504
1197
  if (key.startsWith(prefix)) this._truncatedStreams.delete(key)
505
1198
  }
1199
+ for (const key of this._streamKinds.keys()) {
1200
+ if (key.startsWith(prefix)) this._streamKinds.delete(key)
1201
+ }
1202
+ for (const key of this._streamPrecedes.keys()) {
1203
+ if (key.startsWith(prefix)) this._streamPrecedes.delete(key)
1204
+ }
1205
+ for (const key of this._streamStartSeqs.keys()) {
1206
+ if (key.startsWith(prefix)) this._streamStartSeqs.delete(key)
1207
+ }
506
1208
  }
507
1209
 
508
1210
  /**
@@ -512,6 +1214,10 @@ export class SessionMessageHistory extends EventEmitter {
512
1214
  this._messageHistory.clear()
513
1215
  this._historyTruncated.clear()
514
1216
  this._pendingStreams.clear()
1217
+ this._streamKinds.clear()
1218
+ this._streamPrecedes.clear()
1219
+ this._streamStartSeqs.clear()
515
1220
  this._seqCounters.clear()
1221
+ this._seqReserved.clear()
516
1222
  }
517
1223
  }