@chroxy/server 0.10.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 (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  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 +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  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 +74 -9
  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 +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  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-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -2,29 +2,82 @@
2
2
  * Conversation, history, and cost summary handlers.
3
3
  *
4
4
  * Handles: list_conversations, search_conversations, resume_conversation,
5
- * request_full_history, request_session_context, request_cost_summary
5
+ * request_conversation_transcript, request_full_history,
6
+ * request_session_context, request_cost_summary
6
7
  */
8
+ import { realpathSync } from 'fs'
7
9
  import { scanConversations as defaultScanConversations } from '../conversation-scanner.js'
8
10
  import { searchConversations as defaultSearchConversations } from '../conversation-search.js'
11
+ import { readConversationTranscriptStrictAsync as defaultReadConversationTranscript, transcriptReadLimiter } from '../jsonl-reader.js'
12
+ import { resolveTranscriptSource } from '../transcript-sources.js'
13
+ import { projectSlug } from '../jsonl-reader.js'
9
14
  import { validateCwdAllowed, broadcastFocusChanged, resolveSession, autoSubscribeOtherClients, buildSessionTokenMismatchPayload, sendSessionError } from '../handler-utils.js'
10
- import { scopeConversationsToClient } from '../conversation-scope.js'
15
+ import { scopeConversationsToClient, boundConversationId } from '../conversation-scope.js'
16
+ import { isBoundClient, markConversationFrame } from '../environments/authority.js'
17
+ import { ReadLimitError, ReadCancelledError, admissionFor } from '../utils/read-limiter.js'
18
+ import { sendChunkedWithBackpressure, sendHistoryEntry } from '../ws-history.js'
11
19
  import { createLogger, loggerForSession } from '../logger.js'
12
20
 
13
21
  const log = createLogger('ws')
14
22
 
23
+ // Transcript reads are admitted through the one limiter that sits under every
24
+ // transcript reader (jsonl-reader.js `transcriptReadLimiter`).
25
+ const defaultTranscriptReadLimiter = transcriptReadLimiter
26
+
27
+ // An AbortSignal that fires when `ws` closes. `dispose` removes the listener.
28
+ function signalOnClose(ws) {
29
+ const ac = new AbortController()
30
+ if (ws?.readyState === 2 || ws?.readyState === 3) ac.abort()
31
+ const onClose = () => ac.abort()
32
+ if (typeof ws?.once === 'function') ws.once('close', onClose)
33
+ return {
34
+ signal: ac.signal,
35
+ dispose: () => { if (typeof ws?.removeListener === 'function') ws.removeListener('close', onClose) },
36
+ }
37
+ }
38
+
39
+ // UUID v4-ish shape guard shared by resume_conversation and the read-only
40
+ // transcript handler — rejects anything that isn't a canonical conversation id
41
+ // before it reaches the filesystem, closing path-traversal via the id segment.
42
+ const CONVERSATION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
43
+
44
+ // Prefer the provider-TAGGED sources (#7828) so every discovered conversation
45
+ // carries its provider; fall back to bare dirs (untagged), then the scanner
46
+ // default (~/.claude/projects).
47
+ function scanOptsFor(ctx) {
48
+ const tagged = ctx.runtime.transcriptSources
49
+ if (Array.isArray(tagged) && tagged.length > 0) return { projectsDirs: tagged }
50
+ return ctx.runtime.projectsDirs ? { projectsDirs: ctx.runtime.projectsDirs } : {}
51
+ }
52
+
15
53
  async function handleListConversations(ws, client, msg, ctx) {
16
54
  // ctx.scanConversations override allows tests to inject a stub and skip real fs.
17
55
  const scan = ctx.scanConversations || defaultScanConversations
18
56
  try {
19
- // Pass provider-driven projectsDirs when available (#2965); falls back to
20
- // the scanner's default (~/.claude/projects) when not set.
21
- const scanOpts = ctx.runtime.projectsDirs ? { projectsDirs: ctx.runtime.projectsDirs } : {}
22
- const all = await scan(scanOpts)
57
+ // Pass provider-driven sources when available (#2965, #7828).
58
+ const scanOpts = scanOptsFor(ctx)
59
+ // Scanning reads the head of every transcript in the store, so it is admitted
60
+ // through the same limiter as every other transcript read.
61
+ const closing = signalOnClose(ws)
62
+ let all
63
+ try {
64
+ all = await (ctx.transcriptReadLimiter || defaultTranscriptReadLimiter).submit(
65
+ { key: `scan\0${JSON.stringify(scanOpts)}`, ...admissionFor(client, isBoundClient), signal: closing.signal },
66
+ () => scan(scanOpts),
67
+ )
68
+ } finally {
69
+ closing.dispose()
70
+ }
23
71
  // Adversary A8: scope results so a bound pairing-issued client
24
72
  // cannot enumerate conversations outside its session cwd.
25
73
  const conversations = scopeConversationsToClient(all, client, ctx)
26
74
  ctx.transport.send(ws, { type: 'conversations_list', conversations })
27
75
  } catch (err) {
76
+ if (err instanceof ReadCancelledError) return
77
+ if (err instanceof ReadLimitError) {
78
+ sendSessionError(ws, ctx, `${err.message}. Try again shortly.`)
79
+ return
80
+ }
28
81
  log.warn(`Failed to scan conversations: ${err.message}`)
29
82
  ctx.transport.send(ws, { type: 'conversations_list', conversations: [] })
30
83
  }
@@ -33,16 +86,38 @@ async function handleListConversations(ws, client, msg, ctx) {
33
86
  async function handleSearchConversations(ws, client, msg, ctx) {
34
87
  const { query, maxResults } = msg
35
88
  const search = ctx.searchConversations || defaultSearchConversations
89
+ const closing = signalOnClose(ws)
36
90
  try {
37
- const all = await search(query, { maxResults })
38
- // Adversary A8: scope the search result set to the bound session's
39
- // cwd. Without this, a mobile client could substring-grep every
40
- // JSONL on disk for secrets-in-transcripts.
91
+ // A session-scoped connection searches only the conversation its own session
92
+ // is running: the source is chosen BEFORE anything is read, ranked or
93
+ // truncated, so what other conversations contain cannot change the answer.
94
+ const scoped = isBoundClient(client)
95
+ const own = scoped ? boundConversationId(client, ctx) : null
96
+ const ownCwd = scoped ? ctx.sessions.sessionManager?.getSession?.(client.boundSessionId)?.cwd : null
97
+ // Source selection needs BOTH the conversation association and the project
98
+ // that association lives in (the daemon's own derivation from the session's cwd).
99
+ const searchOpts = scoped
100
+ ? { maxResults, conversationId: own, projectDirName: typeof ownCwd === 'string' && ownCwd ? projectSlug(ownCwd) : null }
101
+ : { maxResults }
102
+ const all = scoped && (!own || !searchOpts.projectDirName)
103
+ ? []
104
+ : await (ctx.transcriptReadLimiter || defaultTranscriptReadLimiter).submit(
105
+ { key: `search\0${query}\0${maxResults ?? ''}\0${own ?? ''}`, ...admissionFor(client, isBoundClient), signal: closing.signal },
106
+ () => search(query, searchOpts),
107
+ )
108
+ // The cwd check still applies to what comes back.
41
109
  const results = scopeConversationsToClient(all, client, ctx)
42
110
  ctx.transport.send(ws, { type: 'search_results', query, results })
43
111
  } catch (err) {
112
+ if (err instanceof ReadCancelledError) return
113
+ if (err instanceof ReadLimitError) {
114
+ sendSessionError(ws, ctx, `${err.message}. Try again shortly.`)
115
+ return
116
+ }
44
117
  log.warn(`Failed to search conversations: ${err.message}`)
45
118
  ctx.transport.send(ws, { type: 'search_results', query, results: [] })
119
+ } finally {
120
+ closing.dispose()
46
121
  }
47
122
  }
48
123
 
@@ -76,7 +151,7 @@ async function handleResumeConversation(ws, client, msg, ctx) {
76
151
  return
77
152
  }
78
153
  // Validate conversationId is a UUID to prevent path traversal
79
- if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(conversationId)) {
154
+ if (!CONVERSATION_ID_RE.test(conversationId)) {
80
155
  sendSessionError(ws, ctx, 'Invalid conversationId format')
81
156
  return
82
157
  }
@@ -109,6 +184,283 @@ async function handleResumeConversation(ws, client, msg, ctx) {
109
184
  }
110
185
  }
111
186
 
187
+ /**
188
+ * Read-only transcript endpoint (#6860, epic #6765).
189
+ *
190
+ * Streams a CLOSED conversation's full history back to the requesting client
191
+ * straight off the persisted store (the Claude Code CLI JSONL layer under
192
+ * `~/.claude/projects/`) — WITHOUT calling `createSession` or spawning any
193
+ * provider process. Because it reads persisted bytes rather than driving a live
194
+ * process, it works uniformly for every provider, including those whose
195
+ * `capabilities.resume === false` (BYOK, Codex, Gemini, user-shell) for which
196
+ * `resume_conversation` is refused outright.
197
+ *
198
+ * Access follows the same scoping as `list_conversations`/`search_conversations`
199
+ * (`scopeConversationsToClient`): an UNBOUND client (primary token / dashboard)
200
+ * may read any conversation; a session-scoped client may read only the
201
+ * conversation its own session is running (conversation-scope.js) — anything
202
+ * else, or any case where the daemon does not know that association, is
203
+ * rejected. Reads go through a shared limiter (daemon-wide and per-connection
204
+ * caps, a bounded queue, coalescing of identical in-flight reads, and
205
+ * cancellation when the connection closes).
206
+ *
207
+ * The response reuses the existing `history_replay_start` / `message` /
208
+ * `history_replay_end` server→client frames (identical to `handleRequestFullHistory`,
209
+ * only sourced from disk) so clients render it with their existing renderers.
210
+ * The replay frames carry the `conversationId` in the `sessionId` field — there
211
+ * is no live session, and a resumed session always gets a fresh id distinct from
212
+ * the conversationId, so this cannot collide with or clobber a live session's
213
+ * transcript.
214
+ *
215
+ * `history_replay_start` carries `truncated` for the slice actually sent (#7501),
216
+ * from the same meta reader `getFullHistoryAsync` uses — this path is subject to
217
+ * jsonl-reader's `MAX_MESSAGES` / `MAX_TRANSCRIPT_BYTES` caps exactly as the
218
+ * full-history path is, and used to omit the field entirely.
219
+ */
220
+ async function handleRequestConversationTranscript(ws, client, msg, ctx) {
221
+ const { conversationId } = msg
222
+ if (!conversationId || typeof conversationId !== 'string') {
223
+ sendSessionError(ws, ctx, 'Missing conversationId')
224
+ return
225
+ }
226
+ // UUID guard — path-traversal protection (same gate as resume_conversation).
227
+ if (!CONVERSATION_ID_RE.test(conversationId)) {
228
+ sendSessionError(ws, ctx, 'Invalid conversationId format')
229
+ return
230
+ }
231
+
232
+ // Every failure from here on names the conversation it answers, with a
233
+ // stable code, so a viewer waiting on THIS conversation can settle on the
234
+ // reason instead of waiting out its inactivity timer.
235
+ const fail = (message) => ctx.transport.send(ws, {
236
+ type: 'session_error',
237
+ message,
238
+ code: 'TRANSCRIPT_UNAVAILABLE',
239
+ conversationId,
240
+ })
241
+
242
+ // A session-scoped connection may read only the conversation its own session
243
+ // is running. Decided from the daemon's association between the session and
244
+ // its conversation — before any scan or file access, and without consulting
245
+ // anything the client supplied. No known association means no access.
246
+ const scoped = isBoundClient(client)
247
+ if (scoped && conversationId !== boundConversationId(client, ctx)) {
248
+ fail('Not authorized to view this conversation')
249
+ return
250
+ }
251
+
252
+ // Resolve the conversation's recorded cwd authoritatively from the persisted
253
+ // store (the scanner reads the same JSONL layer list_conversations does). Only
254
+ // fall back to a client-provided cwd hint when the scan can't find it (e.g. a
255
+ // tiny conversation below the scanner's MIN_FILE_SIZE floor).
256
+ const scan = ctx.scanConversations || defaultScanConversations
257
+ //
258
+ // The same conversation id can exist under more than one provider's store.
259
+ // Collect EVERY match; the optional `provider` on the request selects one. An
260
+ // id that matches several providers with no selector is refused rather than
261
+ // resolved by whichever the scanner happened to list first (#7828).
262
+ let matches = []
263
+ try {
264
+ const all = await scan(scanOptsFor(ctx))
265
+ matches = Array.isArray(all) ? all.filter((c) => c?.conversationId === conversationId) : []
266
+ } catch (err) {
267
+ // Scan failure is non-fatal — fall through to the client-provided cwd hint.
268
+ log.warn(`Transcript scan failed for ${conversationId}: ${err.message}`)
269
+ }
270
+ const wantedProvider = typeof msg.provider === 'string' && msg.provider ? msg.provider : null
271
+ // Authorization comes BEFORE any answer that depends on how many records
272
+ // exist or which providers hold them: a bound client is shown only the
273
+ // records it may see, and when every record is outside its scope it gets the
274
+ // same response a single out-of-scope record always got.
275
+ if (matches.length > 0) {
276
+ matches = scopeConversationsToClient(matches, client, ctx)
277
+ if (matches.length === 0) {
278
+ fail('Not authorized to view this conversation')
279
+ return
280
+ }
281
+ }
282
+ if (wantedProvider) matches = matches.filter((c) => c?.provider === wantedProvider)
283
+ if (matches.length > 1) {
284
+ const providers = new Set(matches.map((c) => c?.provider))
285
+ fail(providers.size > 1
286
+ ? 'This conversation id exists under more than one provider and cannot be opened unambiguously from here. Open it from its provider\'s own session list.'
287
+ : 'Conversation id has more than one record for this provider, so it cannot be read unambiguously')
288
+ return
289
+ }
290
+ const conv = matches[0] || null
291
+
292
+ let cwd = conv?.cwd || null
293
+ if (!cwd && scoped) {
294
+ // The directory comes from the daemon's own record of the session, never
295
+ // from the request.
296
+ const ownCwd = ctx.sessions.sessionManager?.getSession?.(client.boundSessionId)?.cwd
297
+ cwd = typeof ownCwd === 'string' && ownCwd ? ownCwd : null
298
+ } else if (!cwd && typeof msg.cwd === 'string' && msg.cwd) {
299
+ // Client-supplied fallback: validate it against the same path hygiene the
300
+ // create/resume paths enforce before trusting it to resolve a filesystem path.
301
+ const cwdError = validateCwdAllowed(msg.cwd, ctx.services.config)
302
+ if (cwdError) {
303
+ fail(cwdError)
304
+ return
305
+ }
306
+ // Defense-in-depth: validateCwdAllowed already resolved + vetted the realpath
307
+ // but discarded it. Canonicalize ONCE here and reuse the resolved path for
308
+ // BOTH the scope check and the on-disk read, so a symlinked hint can't point
309
+ // the scope check at one directory and the file read at another.
310
+ try {
311
+ cwd = realpathSync(msg.cwd)
312
+ } catch {
313
+ fail(`Cannot resolve path: ${msg.cwd}`)
314
+ return
315
+ }
316
+ }
317
+
318
+ if (!cwd) {
319
+ fail(`Conversation not found: ${conversationId}`)
320
+ return
321
+ }
322
+
323
+ // Scope enforcement — reuse the guard list_conversations/search_conversations
324
+ // use. A bound client that can't see this cwd gets an empty set → reject.
325
+ const inScope = scopeConversationsToClient([{ conversationId, cwd }], client, ctx)
326
+ if (inScope.length === 0) {
327
+ fail('Not authorized to view this conversation')
328
+ return
329
+ }
330
+
331
+ // Read the transcript from disk. NO createSession, NO provider spawn. Reader is
332
+ // injectable for tests so the suite never touches the real ~/.claude/projects.
333
+ //
334
+ // #7501 — through the META reader, not the array-returning sibling one line
335
+ // away. This path is subject to jsonl-reader's OWN two caps (the 500
336
+ // most-recent `MAX_MESSAGES` window and the `MAX_TRANSCRIPT_BYTES` tail read),
337
+ // and the array alone cannot express either: 500 entries back is equally the
338
+ // shape of a complete 500-message conversation. This is the SAME reader
339
+ // `getFullHistoryAsync` uses for the full-history path (#7484) rather than a
340
+ // second meta implementation, so both replays report the same caps from one
341
+ // place and cannot drift apart.
342
+ //
343
+ // #7828 — the file is chosen by the conversation's OWN provider and locator,
344
+ // never by assuming Claude's layout. A refusal (unknown/unsupported provider,
345
+ // mismatched or escaping locator) is a session_error; nothing is retried
346
+ // against another provider's store.
347
+ const source = resolveTranscriptSource({
348
+ // A conversation the scan found carries its provider (absent => unknown).
349
+ // The cwd-hint path has no scan record and is Claude-only unless the
350
+ // request names another provider, which then reports its own refusal.
351
+ provider: conv ? conv.provider : (wantedProvider || 'claude'),
352
+ conversationId,
353
+ cwd,
354
+ sourceLocator: conv?.sourceLocator ?? null,
355
+ sources: ctx.runtime.transcriptSources,
356
+ })
357
+ if (!source.ok) {
358
+ fail(source.reason)
359
+ return
360
+ }
361
+ const readTranscript = ctx.readConversationTranscript || defaultReadConversationTranscript
362
+ let messages = []
363
+ let truncated = false
364
+ const limiter = ctx.transcriptReadLimiter || defaultTranscriptReadLimiter
365
+ const closing = signalOnClose(ws)
366
+ try {
367
+ // Duplicate in-flight requests for the same file share one read.
368
+ const readKey = `${source.path}\0${source.identity ? `${source.identity.dev}:${source.identity.ino}` : ''}`
369
+ const read = await limiter.submit(
370
+ { key: readKey, ...admissionFor(client, isBoundClient), signal: closing.signal },
371
+ (signal) => readTranscript(source.path, undefined, { expectedIdentity: source.identity, signal, admitted: true }),
372
+ )
373
+ if (Array.isArray(read)) {
374
+ // The pre-#7501 reader shape. `ctx.readConversationTranscript` is a
375
+ // TEST-ONLY injection seam — nothing in production injects it, so this
376
+ // branch is unreachable outside the suite — and a legacy fixture still
377
+ // supplies a bare array, accepted and reported as untruncated rather than
378
+ // throwing on a shape that used to work. `false` over omitting the field:
379
+ // omitting it puts the frame back into the exact absent-vs-false ambiguity
380
+ // #7501 removes, and gives the wire two shapes to pin instead of one. Same
381
+ // posture handleRequestFullHistory takes toward a descriptor-less legacy
382
+ // manager.
383
+ messages = read
384
+ } else if (read && Array.isArray(read.messages)) {
385
+ messages = read.messages
386
+ // Strict boolean, matching how both clients read this family of field.
387
+ truncated = read.truncated === true
388
+ }
389
+ } catch (err) {
390
+ // The connection went away while the read waited or ran: nobody to answer.
391
+ if (err instanceof ReadCancelledError || err?.code === 'cancelled') return
392
+ if (err instanceof ReadLimitError) {
393
+ fail(`${err.message}. Try again shortly.`)
394
+ return
395
+ }
396
+ // #7828 — a missing/unreadable file or a corrupt record is a DATA error, not
397
+ // an empty successful transcript: say so, and send no replay frames.
398
+ log.warn(`Failed to read transcript for ${conversationId}: ${err.message}`)
399
+ fail(err?.name === 'TranscriptDataError' ? err.message : 'Transcript could not be read. Try again.')
400
+ return
401
+ } finally {
402
+ closing.dispose()
403
+ }
404
+
405
+ // Stream back using the SAME wire shape as request_full_history so existing
406
+ // renderers light up. `sessionId` carries the conversationId (read-only; no
407
+ // live session exists for a closed conversation).
408
+ //
409
+ // Route through ctx.transport so a method-style sender keeps its receiver;
410
+ // the shared loop only ever needs a (ws, payload) callable.
411
+ // Frames of this replay name the conversation in `sessionId`; the conversation
412
+ // was authorised above, so they are marked as conversation frames (see
413
+ // markConversationFrame) and the delivery rule for other-session tags skips them.
414
+ const send = (target, payload) => ctx.transport.send(target, markConversationFrame(payload))
415
+
416
+ // #7501 — `truncated` describes the collection ACTUALLY SENT, and is emitted
417
+ // unconditionally: absence reads to a client exactly like `truncated: false`,
418
+ // which is what let this path hand the viewer the last 500 messages of a
419
+ // 5,000-message conversation with nothing on the wire saying so.
420
+ send(ws, { type: 'history_replay_start', sessionId: conversationId, truncated, fullHistory: true, conversationId })
421
+
422
+ // #7480 — the THIRD path through the #4833 chunk-and-drain loop, and the
423
+ // second one that had no `bufferedAmount` check at all: it pushed the whole
424
+ // transcript onto the socket in one turn of the event loop.
425
+ // `MAX_TRANSCRIPT_BYTES` caps the transcript, not how much of it is buffered
426
+ // on the socket at once, so a large transcript on a slow link could still
427
+ // sail past the 1MB EVICT_THRESHOLD in ws-client-sender.js — which CLOSES
428
+ // the client. Measured on the pre-fix code, a 30-entry fat transcript peaked
429
+ // at 6,148,308 bytes buffered: 5.9x the eviction line.
430
+ sendChunkedWithBackpressure(ws, messages, {
431
+ emit: (entry) => {
432
+ send(ws, {
433
+ type: 'message',
434
+ messageType: entry.type,
435
+ content: entry.content,
436
+ tool: entry.tool,
437
+ timestamp: entry.timestamp,
438
+ sessionId: conversationId,
439
+ })
440
+ },
441
+ onDone: () => {
442
+ send(ws, { type: 'history_replay_end', sessionId: conversationId })
443
+ // #7340: defence-in-depth. The dashboard normally DIVERTS this frame — it
444
+ // routes `history_replay_start`/`message`/`history_replay_end` for a pending
445
+ // transcript id into the transcript viewer, which never touches
446
+ // `sessionStates`, so no wipe happens — and the mobile app has no transcript
447
+ // surface at all. This covers the fail-safe branch where the diversion is not
448
+ // armed (a raw client, or a frame that arrives without a pending request), in
449
+ // which case the client wipes its ACTIVE session's badge list because
450
+ // `conversationId` is a closed transcript with no live session behind it.
451
+ // Idempotent either way: both clients dedupe `agent_spawned` by `toolUseId`.
452
+ //
453
+ // The re-seed is CONDITIONAL, so it stays inside onDone rather than being
454
+ // hoisted out of the now-asynchronous loop: hoisting it would fire it
455
+ // before the replay frames it repairs, which is exactly the ordering the
456
+ // #7340 fix exists to establish.
457
+ if (client?.activeSessionId) {
458
+ ctx.transport.reseedActiveAgents(ws, client.activeSessionId)
459
+ }
460
+ },
461
+ })
462
+ }
463
+
112
464
  async function handleRequestFullHistory(ws, client, msg, ctx) {
113
465
  const targetId = (typeof msg.sessionId === 'string' && msg.sessionId) || client.activeSessionId
114
466
  if (!targetId || !resolveSession(ctx, msg, client)) {
@@ -118,23 +470,208 @@ async function handleRequestFullHistory(ws, client, msg, ctx) {
118
470
  sendSessionError(ws, ctx, message)
119
471
  return
120
472
  }
121
- const fullHistory = await ctx.sessions.sessionManager.getFullHistoryAsync(targetId)
122
- ctx.transport.send(ws, { type: 'history_replay_start', sessionId: targetId, fullHistory: true })
473
+ const sessionManager = ctx.sessions.sessionManager
474
+ // Same admission as the strict transcript endpoint: the read is capped
475
+ // daemon-wide and per connection, and stops when the connection closes.
476
+ const closing = signalOnClose(ws)
477
+ let history
478
+ try {
479
+ history = await sessionManager.getFullHistoryAsync(targetId, { ...admissionFor(client, isBoundClient), signal: closing.signal })
480
+ } catch (err) {
481
+ if (err instanceof ReadLimitError) {
482
+ sendSessionError(ws, ctx, `${err.message}. Try again shortly.`)
483
+ return
484
+ }
485
+ throw err
486
+ } finally {
487
+ closing.dispose()
488
+ }
489
+ if (closing.signal.aborted) return
490
+ // #7484 — `getFullHistoryAsync` returns a descriptor: WHICH source it read
491
+ // (the on-disk JSONL transcript or the ring buffer) alongside the entries and
492
+ // that source's own truncation. Both decisions below turn on it, and neither
493
+ // can be recovered from the entries: a JSONL slice and a ring slice are the
494
+ // same shape of array.
495
+ //
496
+ // A bare array is the pre-#7484 shape. Accepted, and read as the ring buffer
497
+ // it always was, so a legacy ctx fixture keeps replaying rather than throwing
498
+ // — the same posture as the `typeof === 'function'` probes below. The REAL
499
+ // manager's shape is pinned at the producer
500
+ // (tests/session-manager-full-history-source.test.js), because every test on
501
+ // this side stubs the manager and so cannot witness it.
502
+ const hasDescriptor = !!history && !Array.isArray(history) && Array.isArray(history.entries)
503
+ const fullHistory = hasDescriptor ? history.entries : (Array.isArray(history) ? history : [])
504
+ const source = hasDescriptor && history.source === 'jsonl' ? 'jsonl' : 'ring'
505
+ // Route through ctx.transport so a method-style sender keeps its receiver;
506
+ // the shared loop only ever needs a (ws, payload) callable.
507
+ const send = (target, payload) => ctx.transport.send(target, payload)
508
+
509
+ // #7460 — frame parity with replayHistory. `truncated` is how a client learns
510
+ // history was dropped on this replay.
511
+ //
512
+ // #7484 — and it must describe the collection ACTUALLY SENT. `isHistoryTruncated`
513
+ // reports the RING BUFFER's overflow, while this handler usually sends the JSONL
514
+ // transcript, which has its own entirely separate caps (500 most-recent
515
+ // messages / a 25MB tail read, jsonl-reader.js). So `truncated: false` could
516
+ // accompany a slice that silently dropped everything before the last 500.
517
+ // Sourced from the descriptor it follows the slice; the probe survives only for
518
+ // the legacy array shape, where the ring IS the slice.
519
+ const truncated = hasDescriptor && typeof history.truncated === 'boolean'
520
+ ? history.truncated
521
+ : (typeof sessionManager.isHistoryTruncated === 'function'
522
+ ? sessionManager.isHistoryTruncated(targetId)
523
+ : false)
524
+ // `latestSeq` must describe what THIS replay actually DELIVERS, not what the
525
+ // ring buffer happens to hold. `getFullHistoryAsync` PREFERS the JSONL
526
+ // transcript whenever `resumeSessionId` is set, and jsonl-reader.js emits only
527
+ // user_input/response/tool_use — none of which carry `_seq`. Sourcing the
528
+ // counter from the buffer there advertises a cursor the client never received:
529
+ // `reconcileReplayEnd` hands it to `recordHistorySeq`, so the NEXT reconnect
530
+ // resolves as already-current and replays NOTHING, stranding the client on the
531
+ // lossy JSONL rebuild. Derived from the entries themselves this is unchanged on
532
+ // the ring-buffer path — that slice is the whole buffer, so its max `_seq` IS
533
+ // `getLatestHistorySeq()` — and correctly advertises nothing on the JSONL path.
534
+ let latestSeq
123
535
  for (const entry of fullHistory) {
124
- if (entry.type === 'user_input' || entry.type === 'response' || entry.type === 'tool_use') {
125
- ctx.transport.send(ws, {
126
- type: 'message',
127
- messageType: entry.type,
128
- content: entry.content,
129
- tool: entry.tool,
130
- timestamp: entry.timestamp,
131
- sessionId: targetId,
132
- })
133
- } else {
134
- ctx.transport.send(ws, { ...entry, sessionId: targetId })
536
+ if (entry && typeof entry._seq === 'number' && (latestSeq === undefined || entry._seq > latestSeq)) {
537
+ latestSeq = entry._seq
135
538
  }
136
539
  }
137
- ctx.transport.send(ws, { type: 'history_replay_end', sessionId: targetId })
540
+ // Omitted, never zeroed: absence means "this replay carried no cursor", while
541
+ // `latestSeq: 0` is a real seq the client would happily record.
542
+ const seqFrame = latestSeq === undefined ? {} : { latestSeq }
543
+
544
+ send(ws, { type: 'history_replay_start', sessionId: targetId, truncated, fullHistory: true, ...seqFrame })
545
+
546
+ // #7460 — the SAME chunk + bufferedAmount loop replayHistory uses, from the
547
+ // one implementation of it. Sending a 1000-entry ring buffer synchronously
548
+ // could push the socket past the 1MB EVICT_THRESHOLD in ws-client-sender.js
549
+ // and CLOSE the client: "Sync Full History" — the button a user presses
550
+ // BECAUSE the view looks wrong — was the action that could drop the
551
+ // connection.
552
+ // #8965: no synthesized agent_idle for a replayed result while the session runs.
553
+ const replayBusy = () => typeof sessionManager.isSessionBusy === 'function'
554
+ ? sessionManager.isSessionBusy(targetId)
555
+ : false
556
+ sendChunkedWithBackpressure(ws, fullHistory, {
557
+ emit: (entry) => {
558
+ if (entry.type === 'user_input' || entry.type === 'response' || entry.type === 'tool_use') {
559
+ send(ws, {
560
+ type: 'message',
561
+ messageType: entry.type,
562
+ content: entry.content,
563
+ tool: entry.tool,
564
+ timestamp: entry.timestamp,
565
+ sessionId: targetId,
566
+ })
567
+ } else {
568
+ // This is the SECOND replay path, and both per-entry duties — the
569
+ // `_seq` → `historySeq` map (#7454) and the `result` → `agent_idle`
570
+ // synthesis (#7459 / #4628) — come from ws-history.js's shared emitter
571
+ // rather than a copy that can drift away from it again.
572
+ sendHistoryEntry(send, ws, targetId, entry, client, replayBusy)
573
+ }
574
+ },
575
+ onDone: () => {
576
+ // #7484 — the JSONL path's heal. `sendHistoryEntry` synthesizes
577
+ // `agent_idle` from a replayed `result`, and a JSONL slice has none:
578
+ // jsonl-reader.js emits user_input/response/tool_use only. Since
579
+ // `getFullHistoryAsync` PREFERS that transcript for any session with a
580
+ // `resumeSessionId` — the normal state of a live claude-family session —
581
+ // the #4628 heal could not fire on the source almost every "Sync Full
582
+ // History" press actually reads.
583
+ //
584
+ // The stale chip is CLIENT-side state: a live `tool_start` whose
585
+ // `tool_result` never arrived (a dropped PostToolUse hook).
586
+ // `history_replay_start` deliberately PRESERVES that set (#4466) and
587
+ // nothing in a JSONL slice can clear it — those entries rebuild as
588
+ // `message` frames, which touch no tool state. `agent_idle` is the only
589
+ // frame that clears it and is not replay-gated.
590
+ //
591
+ // ONE heal, at the end, rather than a per-entry synthesis: JSONL rows
592
+ // carry no dependable turn boundary to hang one on, and landing after the
593
+ // last entry is what makes it unable to wipe an activeTools set
594
+ // MID-replay. Before `history_replay_end`, so it stays inside the window
595
+ // where the #4466 reasoning holds.
596
+ //
597
+ // NOT while `isSessionBusy` reports the session LIVE. `agent_idle` sets
598
+ // isIdle, clears streamingMessageId (hiding the stop button) and clears
599
+ // activeTools — all true after a finished turn, and no `agent_busy` is
600
+ // coming to undo it before the next turn starts.
601
+ //
602
+ // #7507 — "live" here is deliberately WIDER than mid-turn, and the comment
603
+ // this replaced described only the narrow half. `isSessionBusy` is
604
+ // `entry.session.isRunning`, which BaseSession defines as
605
+ // `_isBusy || _backgroundShellTracker.size > 0`: a session whose turn has
606
+ // ENDED but which still holds an un-polled `Bash(run_in_background: true)`
607
+ // shell reads busy (#4307; the 60s advisory sweep must not flip liveness,
608
+ // #5247, so release comes only from BashOutput / destroy / the 4h hard
609
+ // quiesce). Do NOT "simplify" this to `_isBusy`.
610
+ //
611
+ // The reason is CONSISTENCY WITH THE SERVER'S SINGLE BUSY AUTHORITY, not
612
+ // mid-turn correctness. `listSessions()` publishes that same `isRunning` as
613
+ // each entry's `isBusy`, and BOTH clients re-derive `isIdle` from it on
614
+ // every `session_list` and `session_activity` (#4639 for the dashboard;
615
+ // #7518 gave the mobile app the same two paths, via the shared store-core
616
+ // `isIdlePatches` derivation and the shared `session_activity` dispatch
617
+ // entry). A narrower `_isBusy` guard would emit an `agent_idle` that the
618
+ // very next broadcast reverts — a flicker, not a heal, on either client.
619
+ // Pinned by behaviour in
620
+ // tests/conversation-full-history-replay.test.js (a real SessionManager +
621
+ // BaseSession) and at the producer in
622
+ // tests/session-manager-full-history-source.test.js.
623
+ //
624
+ // Until #7518 that argument held for the dashboard ALONE: the app had
625
+ // neither path, so the suppression was a pure false negative there — this
626
+ // synthesized `agent_idle` was the only thing that could clear a stale
627
+ // chip (#7479 N2), and a session holding an un-polled background shell
628
+ // kept one. That is why the fix went to the CLIENT rather than forking
629
+ // this guard per client, and why the guard did not change: with both
630
+ // clients consuming the same authority, one rule is now right on both.
631
+ //
632
+ // One consequence still worth recording:
633
+ // - The LIVE path is LESS conservative than this. event-normalizer.js
634
+ // appends `agent_idle` to every `result` unconditionally, without
635
+ // consulting `isRunning`; the replay heal mirrors that fan-out
636
+ // (ws-history.js) everywhere except this state.
637
+ //
638
+ // A manager that cannot answer is treated as idle: "cannot tell" must not
639
+ // silently become "never heal", which is the defect this fixes.
640
+ const busy = typeof sessionManager.isSessionBusy === 'function'
641
+ ? sessionManager.isSessionBusy(targetId)
642
+ : false
643
+ if (source === 'jsonl' && !busy) {
644
+ send(ws, { type: 'agent_idle', sessionId: targetId })
645
+ }
646
+ send(ws, { type: 'history_replay_end', sessionId: targetId, ...seqFrame })
647
+ // #7340: same wipe, same repair — `request_full_history` targets a LIVE
648
+ // session, so its confirmed-backgrounded subagents must be re-asserted
649
+ // after the replay that cleared them.
650
+ ctx.transport.reseedActiveAgents(ws, targetId)
651
+ // #7457: same sweep, same repair. This end frame runs the client's
652
+ // unanswered-prompt sweep exactly as `replayHistory`'s does, so "Sync
653
+ // Full History" — the button a user presses BECAUSE the view looks
654
+ // wrong — would otherwise resolve the very question they are blocked on.
655
+ // The sibling `request_conversation_transcript` replay is exempt: its
656
+ // frames carry a conversationId in `sessionId`, which is never a live
657
+ // session id, so both clients' `updateSession` no-ops and the sweep
658
+ // touches nothing.
659
+ // #8357: PERMISSIONS FIRST, as `replayHistory`'s `finishReplay` does -- a
660
+ // question card is gated by its own permission, which the client must
661
+ // already hold when the question lands.
662
+ // #8340 / #8328: the permission card. `permission_request` is
663
+ // transient, so this full rebuild swaps the live Allow/Deny card away and
664
+ // the replay cannot restore it; `replayHistory` re-sends after its own end
665
+ // frame, and this path ends its own, so it must too. Same single
666
+ // implementation (ws-history's resendPendingPermissionsForSession), which
667
+ // keeps the #8342 session-bound-client guard.
668
+ try {
669
+ ctx.transport.resendPendingPermissions(ws, targetId)
670
+ } finally {
671
+ ctx.transport.resendPendingQuestions(ws, targetId)
672
+ }
673
+ },
674
+ })
138
675
  }
139
676
 
140
677
  async function handleRequestSessionContext(ws, client, msg, ctx) {
@@ -195,6 +732,7 @@ export const conversationHandlers = {
195
732
  list_conversations: handleListConversations,
196
733
  search_conversations: handleSearchConversations,
197
734
  resume_conversation: handleResumeConversation,
735
+ request_conversation_transcript: handleRequestConversationTranscript,
198
736
  request_full_history: handleRequestFullHistory,
199
737
  request_session_context: handleRequestSessionContext,
200
738
  request_cost_summary: handleRequestCostSummary,