@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
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Provider-aware transcript source resolution for the read-only closed-
3
+ * conversation endpoint (#7828, part of #7818).
4
+ *
5
+ * The scanner tags every discovered conversation with the provider whose store
6
+ * it was found in plus an opaque locator. This module is the ONE place that
7
+ * turns (provider, locator, conversationId) into a file to read, and it never
8
+ * guesses: an unknown provider, a provider with no adapter, a locator that does
9
+ * not name this conversation, or a path that escapes the provider's projects
10
+ * root is a refusal. No refusal falls back to another provider's source, and a
11
+ * same-id file under a different provider is never consulted.
12
+ */
13
+ import { realpathSync, statSync } from 'fs'
14
+ import { join, isAbsolute, parse } from 'path'
15
+ import { isPathWithin } from './utils/path-containment.js'
16
+ import { projectSlug } from './jsonl-reader.js'
17
+ import { claudeProjectsDir } from './utils/claude-config-dir.js'
18
+
19
+ const UNSUPPORTED_CODEX =
20
+ 'Codex keeps its sessions in ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl in its own record format, ' +
21
+ 'which Chroxy cannot replay as a transcript yet'
22
+
23
+ /**
24
+ * Providers whose store Chroxy can replay. Everything else known is listed with
25
+ * the reason it cannot be; anything not listed is an unknown provider.
26
+ */
27
+ const ADAPTERS = {
28
+ claude: { format: 'claude-jsonl' },
29
+ codex: { unsupported: UNSUPPORTED_CODEX },
30
+ gemini: { unsupported: 'Gemini transcripts are not stored in a format Chroxy can replay' },
31
+ }
32
+
33
+ // `<encoded project dir>/<conversationId>.jsonl` — exactly two segments, the
34
+ // second being this conversation's own file. Anything else is not a locator the
35
+ // scanner produced.
36
+ function locatorMatches(locator, conversationId) {
37
+ if (typeof locator !== 'string') return false
38
+ const parts = locator.split('/')
39
+ if (parts.length !== 2) return false
40
+ const [dir, file] = parts
41
+ if (!dir || dir === '.' || dir === '..' || dir.includes('\\') || dir.includes('\0')) return false
42
+ return file === `${conversationId}.jsonl`
43
+ }
44
+
45
+ /**
46
+ * @param {object} p
47
+ * @param {string|null|undefined} p.provider
48
+ * @param {string} p.conversationId
49
+ * @param {string|null} [p.cwd] - recorded cwd; used only to place a Claude file when no locator exists (cwd-hint path)
50
+ * @param {string|null} [p.sourceLocator]
51
+ * @param {Array<{provider: string, projectsDir: string}>} [p.sources] - the provider-tagged roots
52
+ * @returns {{ ok: true, provider: string, path: string } |
53
+ * { ok: false, code: 'unknown_provider'|'unsupported'|'invalid_source'|'source_unavailable', reason: string }}
54
+ */
55
+ export function resolveTranscriptSource({ provider, conversationId, cwd = null, sourceLocator = null, sources = null }) {
56
+ if (typeof provider !== 'string' || !Object.hasOwn(ADAPTERS, provider)) {
57
+ return { ok: false, code: 'unknown_provider', reason: typeof provider === 'string' ? `Unknown transcript provider: ${provider}` : 'This conversation has no recorded provider, so its transcript cannot be located' }
58
+ }
59
+ const adapter = ADAPTERS[provider]
60
+ if (adapter.unsupported) {
61
+ return { ok: false, code: 'unsupported', reason: `Transcript view is not supported for ${provider}: ${adapter.unsupported}` }
62
+ }
63
+
64
+ // claude-jsonl. With a locator, the file is the one the scanner found. Without
65
+ // one (the client-hint path, or a scan source that predates tagging) the cwd
66
+ // names the file — but that derivation is only a STORAGE KEY: every
67
+ // non-alphanumeric character encodes to the same `-`, so it can name a
68
+ // colliding project's directory, and nothing about it has been checked against
69
+ // the store. It therefore goes through the same containment and identity
70
+ // checks as a scanner-found file, below.
71
+ if (sourceLocator == null) {
72
+ if (typeof cwd !== 'string' || !cwd) {
73
+ return { ok: false, code: 'invalid_source', reason: 'No source recorded for this conversation' }
74
+ }
75
+ } else if (!locatorMatches(sourceLocator, conversationId)) {
76
+ return { ok: false, code: 'invalid_source', reason: 'Transcript source does not match the conversation' }
77
+ }
78
+ const registeredRoot = (sources || []).find((s) => s?.provider === provider)?.projectsDir
79
+ // With no registered store the hint path falls back to the default Claude
80
+ // store; a locator always needs the store it was found in.
81
+ const root = sourceLocator == null && registeredRoot == null ? claudeProjectsDir() : registeredRoot
82
+ if (typeof root !== 'string' || !isAbsolute(root)) {
83
+ return { ok: false, code: 'source_unavailable', reason: `No ${provider} transcript store is registered` }
84
+ }
85
+ const candidate = sourceLocator == null
86
+ ? join(root, projectSlug(cwd), `${conversationId}.jsonl`)
87
+ : join(root, sourceLocator)
88
+ // Containment on the REAL paths, so a symlinked project dir or file cannot
89
+ // point the read outside the provider's root (shared helper, #7287).
90
+ try {
91
+ const realRoot = realpathSync(root)
92
+ if (parse(realRoot).root === realRoot) {
93
+ return { ok: false, code: 'source_unavailable', reason: `No ${provider} transcript store is registered` }
94
+ }
95
+ const realFile = realpathSync(candidate)
96
+ if (!isPathWithin(realFile, realRoot)) {
97
+ return { ok: false, code: 'invalid_source', reason: 'Transcript source is outside the provider store' }
98
+ }
99
+ // The identity of the contained file; the reader refuses an opened file
100
+ // that is not this exact object.
101
+ const st = statSync(realFile, { bigint: true })
102
+ return { ok: true, provider, path: realFile, identity: { dev: st.dev, ino: st.ino } }
103
+ } catch (err) {
104
+ if (err?.code === 'ENOENT' || err?.code === 'ENOTDIR') {
105
+ return { ok: false, code: 'source_unavailable', reason: 'Transcript file not found' }
106
+ }
107
+ return { ok: false, code: 'invalid_source', reason: 'Transcript source could not be resolved' }
108
+ }
109
+ }
@@ -1,7 +1,13 @@
1
1
  // TranscriptTaskScanner (#5431) — incremental session-transcript scanner that
2
2
  // derives OUTSTANDING background work (run_in_background Bash/Agent calls,
3
- // Monitor streams) and a pending ScheduleWakeup from a Claude Code session
4
- // transcript (`~/.claude/projects/<slug>/<sessionId>.jsonl`).
3
+ // Monitor streams), a pending ScheduleWakeup, and (#7327) the most recently
4
+ // OBSERVED model from a Claude Code session transcript
5
+ // (`~/.claude/projects/<slug>/<sessionId>.jsonl`). The model field exists
6
+ // because claude-tui — the default provider — is a PTY-driven interactive
7
+ // TUI with no structured init event of its own (unlike cli-session/sdk-
8
+ // session, which learn their booted model from the CLI/SDK's own init
9
+ // payload); the transcript's `message.model` on assistant entries is the
10
+ // only place that information appears at all.
5
11
  //
6
12
  // Why a transcript scan: the per-PID session file (`~/.claude/sessions/
7
13
  // <pid>.json`) that drives the readiness probe carries only `status` — no
@@ -36,6 +42,49 @@
36
42
  // (the harness re-invoked the agent), a later user entry carries its prompt,
37
43
  // or a newer ScheduleWakeup supersedes it.
38
44
  //
45
+ // #8223 — authentication failures. claude writes an API call that failed
46
+ // authentication to the transcript as a STRUCTURED entry, regardless of the
47
+ // PTY's width (at a narrow PTY it never paints the "Please run /login" banner
48
+ // at all), with the same `error` enum the Agent SDK types as
49
+ // `SDKAssistantMessageError`:
50
+ // { "type": "assistant", "isApiErrorMessage": true,
51
+ // "error": "authentication_failed",
52
+ // "message": { "role": "assistant", "content": [ { "type": "text",
53
+ // "text": "Please run /login · API Error: 401 OAuth access token is invalid." } ] } }
54
+ // The scanner COUNTS those entries (`authFailureCount`, cumulative since the
55
+ // scanner was last reset) and nothing else about them; a consumer compares the
56
+ // count with a baseline it captured earlier. Only the two structured fields
57
+ // count — never the entry's TEXT, because a model discussing `/login` in a
58
+ // normal reply carries the same words.
59
+ //
60
+ // #8400 — usage / rate limits. The SAME structured marker carries them:
61
+ // { "type": "assistant", "isApiErrorMessage": true, "error": "rate_limit",
62
+ // "apiErrorStatus": 429, "message": { ..., "content": [ { "type": "text",
63
+ // "text": "You've hit your session limit · resets 11:30pm (America/Los_Angeles)" } ] } }
64
+ // and a 529 overload (`error: "server_error"`, `apiErrorStatus: 529`). The
65
+ // scanner counts them (`usageLimitCount`, cumulative like `authFailureCount`) and
66
+ // keeps the latest classification (`lastUsageLimit`, see claude-tui/usage-limit.js)
67
+ // so a consumer that saw the count rise can say what the limit was. A sidechain
68
+ // (subagent) entry is not counted: the main conversation has not stopped.
69
+ //
70
+ // #7393 — thinking blocks. Claude Code writes ONE JSONL entry per content block
71
+ // (a message with thinking, text and tool_use blocks is three `assistant`
72
+ // entries sharing `message.id` / `requestId`, told apart by `apiBlockIndex`),
73
+ // and a thinking entry looks like:
74
+ // { "type": "assistant", "isSidechain": false, "uuid": "…",
75
+ // "timestamp": "2026-10-08T12:00:05.000Z", "thinkingDurationMs": 1236,
76
+ // "apiBlockIndex": 0,
77
+ // "message": { "role": "assistant", "content": [ { "type": "thinking",
78
+ // "thinking": "…", "signature": "…" } ], … } }
79
+ // `thinking` is the empty string unless the API was asked for summaries (the
80
+ // TUI asks only when `showThinkingSummaries` is set), and `thinkingDurationMs`
81
+ // is on the ENTRY. claude-tui is deliver-on-complete and has no stream to read
82
+ // reasoning from, so the transcript is the only source. Capture is opt-in per
83
+ // turn (`startThinkingCapture`) and bounded: a scan that is only rebuilding
84
+ // state from history queues nothing, so a long resumed transcript costs no
85
+ // memory. Sidechain (subagent) entries are skipped, the same as for the
86
+ // observed model.
87
+ //
39
88
  // Robustness contract (#5431 success criterion — degrade silently):
40
89
  // - The transcript format is the harness's INTERNAL representation, not a
41
90
  // stable API. Every parse is defensive; an unparseable line is skipped.
@@ -45,10 +94,12 @@
45
94
  // each scan reads only the new tail. A shrunken file (rotation /
46
95
  // truncation) resets the scanner and re-reads from byte 0.
47
96
 
48
- import { closeSync, fstatSync, openSync, readFileSync, readSync } from 'fs'
49
- import { homedir } from 'os'
97
+ import { closeSync, constants, fstatSync, openSync, readFileSync, readSync } from 'fs'
98
+ import { claudeProjectsDir } from './utils/claude-config-dir.js'
50
99
  import { join } from 'path'
51
100
  import { createLogger } from './logger.js'
101
+ import { encodeProjectPath } from './jsonl-reader.js'
102
+ import { classifyApiErrorEntry } from './claude-tui/usage-limit.js'
52
103
 
53
104
  const log = createLogger('transcript-tasks')
54
105
 
@@ -56,8 +107,23 @@ const log = createLogger('transcript-tasks')
56
107
  export const EMPTY_TASK_SNAPSHOT = Object.freeze({
57
108
  backgroundTasks: Object.freeze([]),
58
109
  scheduledWakeup: null,
110
+ observedModel: null,
111
+ // #8223: `null` = unknown (the transcript could not be read), as opposed to a
112
+ // known count of 0 — see `TranscriptTaskScanner.scan()`.
113
+ authFailureCount: null,
114
+ // #8400: same convention -- `null` = unknown, `0` = known none.
115
+ usageLimitCount: null,
116
+ lastUsageLimit: null,
59
117
  })
60
118
 
119
+ // #7327: the harness writes this literal `message.model` on synthetic
120
+ // assistant entries it injects itself (an API-error stand-in, a retry
121
+ // placeholder, …) — verified against live transcripts: every `<synthetic>`
122
+ // entry carries `usage.output_tokens: 0` and is not something the model
123
+ // actually booted with. Reporting it as the observed model would show a
124
+ // fake value instead of an honest "not yet observed" null.
125
+ const SYNTHETIC_MODEL = '<synthetic>'
126
+
61
127
  // Cap a single incremental read so a pathological transcript (or a first
62
128
  // scan against an existing multi-MB file) can't balloon memory. 16 MiB is
63
129
  // >3x the largest transcript observed in the wild (~5 MB); when the unread
@@ -66,24 +132,25 @@ export const EMPTY_TASK_SNAPSHOT = Object.freeze({
66
132
  // readiness path stays fast.
67
133
  export const MAX_SCAN_BYTES = 16 * 1024 * 1024
68
134
 
135
+ // #7396: how many task-notification tool-use ids the scanner remembers. The set
136
+ // answers "has this launch been reported finished", which a session asks about
137
+ // the handful of subagents it is tracking right now -- so only recent ids
138
+ // matter -- but a long session can see thousands of notifications, and an
139
+ // unbounded set is a leak with no consumer. Insertion order is age, so eviction
140
+ // drops the oldest first.
141
+ export const NOTIFIED_TOOL_USE_IDS_MAX = 512
142
+
69
143
  // Truncate `description` fallbacks derived from an Agent `prompt` — prompts
70
144
  // are unbounded; 80 chars matches the issue's payload sketch.
71
145
  const PROMPT_DESCRIPTION_MAX = 80
72
146
 
73
- /**
74
- * Slugify a cwd into the directory name Claude Code uses under
75
- * `~/.claude/projects/`. Verified against real project dirs on disk:
76
- * every non-alphanumeric character (slashes, dots, spaces, …) becomes `-`,
77
- * e.g. `/Users/blamechris/Projects/repo-relay` →
78
- * `-Users-blamechris-Projects-repo-relay` and
79
- * `/Users/x/Downloads/Mom Hospitalization Files` →
80
- * `-Users-x-Downloads-Mom-Hospitalization-Files`.
81
- * @param {string} cwd
82
- * @returns {string}
83
- */
84
- export function slugifyCwd(cwd) {
85
- return String(cwd).replace(/[^a-zA-Z0-9]/g, '-')
86
- }
147
+ // #7393: the most thinking blocks held between two drains, and the most text
148
+ // kept per block. A turn is drained every poll pass, so the cap is a backstop
149
+ // against a runaway file, not a working limit; the newest blocks survive. The
150
+ // per-block bound matches the client bubble's own cap (store-core
151
+ // MAX_THINKING_CONTENT_LEN), past which it drops text on arrival anyway.
152
+ export const MAX_PENDING_THINKING_BLOCKS = 256
153
+ export const MAX_THINKING_BLOCK_CHARS = 1024 * 1024
87
154
 
88
155
  /**
89
156
  * Derive the transcript path for a per-PID session file
@@ -91,9 +158,10 @@ export function slugifyCwd(cwd) {
91
158
  * Returns null on any failure (missing file, bad JSON, missing fields) —
92
159
  * callers treat null as "no transcript available, degrade to plain ready".
93
160
  * @param {string} sessionFilePath
161
+ * @param {Record<string, string|undefined>} [env] - env claude runs with (picks the projects root)
94
162
  * @returns {string|null}
95
163
  */
96
- export function transcriptPathForSessionFile(sessionFilePath) {
164
+ export function transcriptPathForSessionFile(sessionFilePath, env = process.env) {
97
165
  try {
98
166
  const data = JSON.parse(readFileSync(sessionFilePath, 'utf8'))
99
167
  const sessionId = typeof data?.sessionId === 'string' ? data.sessionId : null
@@ -102,7 +170,7 @@ export function transcriptPathForSessionFile(sessionFilePath) {
102
170
  // Defence-in-depth: the sessionId becomes a path segment. Real ids are
103
171
  // UUIDs; reject anything that could traverse out of the projects dir.
104
172
  if (!/^[A-Za-z0-9-]+$/.test(sessionId)) return null
105
- return join(homedir(), '.claude', 'projects', slugifyCwd(cwd), `${sessionId}.jsonl`)
173
+ return join(claudeProjectsDir(env), encodeProjectPath(cwd), `${sessionId}.jsonl`)
106
174
  } catch (err) {
107
175
  log.debug?.(`transcriptPathForSessionFile failed for ${sessionFilePath}: ${err.message}`)
108
176
  return null
@@ -120,7 +188,24 @@ const TOOL_USE_ID_TAG = /<tool-use-id>\s*([^<\s]+)\s*<\/tool-use-id>/g
120
188
  * call and returns the current outstanding-work snapshot:
121
189
  *
122
190
  * { backgroundTasks: [{ toolUseId, kind, description, startedAt }],
123
- * scheduledWakeup: { at, reason } | null }
191
+ * scheduledWakeup: { at, reason } | null,
192
+ * observedModel: string | null,
193
+ * authFailureCount: number | null,
194
+ * usageLimitCount: number | null, // #8400, same null/0 convention
195
+ * lastUsageLimit: UsageLimit | null }
196
+ *
197
+ * `authFailureCount` (#8223) is the cumulative number of structured
198
+ * `authentication_failed` API-error assistant entries seen, `0` for a
199
+ * transcript that does not exist yet or holds none, and `null` ONLY when the
200
+ * transcript could not be read for some other reason — so a consumer that
201
+ * needs a baseline can tell "known: none" from "unknown" and wait for a
202
+ * successful read rather than baseline against a guess.
203
+ *
204
+ * `observedModel` (#7327) is the most recent real `message.model` seen on an
205
+ * `assistant` transcript entry — an OBSERVATION of what the session is
206
+ * actually running, never the configured/requested model. `null` until the
207
+ * first assistant entry lands (or when every entry seen so far carries only
208
+ * the synthetic placeholder — see `SYNTHETIC_MODEL`).
124
209
  *
125
210
  * `scan()` NEVER throws. A missing transcript yields the empty snapshot
126
211
  * (the file may simply not exist yet); any other failure logs at debug and
@@ -134,6 +219,14 @@ export class TranscriptTaskScanner {
134
219
  constructor(transcriptPath, logger = log) {
135
220
  this.path = transcriptPath
136
221
  this._log = logger
222
+ // #7396 (review): health of the scanner itself, deliberately OUTSIDE
223
+ // `_reset()` -- a rotation or a skipped tail is exactly when these must
224
+ // survive the reset, because they are how a consumer learns the state it is
225
+ // holding no longer reflects the file.
226
+ this._readable = null
227
+ this._discardCount = 0
228
+ /** @type {{ has(id: string): boolean } | null} */
229
+ this.pinnedToolUseIds = null
137
230
  this._reset()
138
231
  }
139
232
 
@@ -145,35 +238,160 @@ export class TranscriptTaskScanner {
145
238
  this._discardFirstPartialLine = false
146
239
  /** @type {Map<string, {toolUseId:string,kind:string,description:string,startedAt:number}>} */
147
240
  this._tasks = new Map()
241
+ // #7396: every tool-use id a task-notification has named, in arrival order.
242
+ // Reset with the rest of the state, so a rotated or truncated transcript is
243
+ // re-derived from its start. See `notifiedToolUseIds`.
244
+ /** @type {Set<string>} */
245
+ this._notified = new Set()
148
246
  /** @type {{at:number,reason:string,prompt:string}|null} */
149
247
  this._wakeup = null
150
248
  // Latest user/assistant entry timestamp seen (epoch ms) — used to decide
151
249
  // whether a scheduled wakeup has already fired (activity after its time).
152
250
  this._lastActivityTs = 0
251
+ // #7327: most recent real (non-synthetic) `message.model` seen on an
252
+ // assistant entry. Only ever moves forward to a newly-observed value —
253
+ // never reset to null except by `_reset()` itself (a rotated/truncated
254
+ // transcript), so a transient parse miss can't blank out an already-
255
+ // known model.
256
+ this._observedModel = null
257
+ // #8223: cumulative count of `isApiErrorMessage` / `authentication_failed`
258
+ // assistant entries (see the header). Reset with the rest of the state, so a
259
+ // rotated or truncated transcript is recounted from its start.
260
+ this._authFailureCount = 0
261
+ // #8400: cumulative count of structured usage-limit / rate-limit / overload
262
+ // entries, and the classification of the most recent one.
263
+ this._usageLimitCount = 0
264
+ this._lastUsageLimit = null
265
+ // #7393: thinking capture. `_thinkingSinceMs === null` means OFF: blocks seen
266
+ // while rebuilding state are never queued. It is deliberately not cleared by
267
+ // a rotation reset (a reset re-reads the file; the timestamp cutoff and the
268
+ // consumer's uuid de-duplication keep the re-read from replaying old blocks).
269
+ this._thinking ??= []
270
+ this._thinkingSinceMs ??= null
271
+ }
272
+
273
+ /**
274
+ * #7393 — start queueing the thinking blocks of the current turn: those on
275
+ * main-conversation assistant entries stamped at or after `sinceMs`. Idempotent
276
+ * while active, so a consumer can call it on every pass without moving the
277
+ * cutoff or dropping what is queued.
278
+ * @param {number} sinceMs epoch ms of the turn start
279
+ */
280
+ startThinkingCapture(sinceMs) {
281
+ if (this._thinkingSinceMs !== null) return
282
+ this._thinking = []
283
+ this._thinkingSinceMs = Number.isFinite(sinceMs) ? sinceMs : Date.now()
284
+ }
285
+
286
+ /** #7393 — stop queueing and drop whatever is queued. */
287
+ stopThinkingCapture() {
288
+ this._thinkingSinceMs = null
289
+ this._thinking = []
290
+ }
291
+
292
+ /**
293
+ * #7393 — take (and clear) the queued thinking blocks, oldest first.
294
+ * `precedes` (#8518) is the ordering hint read off the transcript: the tool call the
295
+ * block comes before, or the response, or undefined when the scan cannot say.
296
+ * @returns {Array<{uuid: string, ts: number, text: string, redacted: boolean, durationMs: number|undefined,
297
+ * precedes: ({kind: 'tool_use', toolUseId: string}|{kind: 'response'}|undefined)}>}
298
+ */
299
+ drainThinking() {
300
+ const out = this._thinking
301
+ this._thinking = []
302
+ return out
303
+ }
304
+
305
+ /**
306
+ * #7396: the tool-use ids of every `<task-notification>` seen so far, whatever
307
+ * launched them and whatever their status.
308
+ *
309
+ * Deliberately NOT part of the `scan()` snapshot: the snapshot is what rides
310
+ * the `claude_ready` wire and what the idle poll dedups on, and neither wants
311
+ * this. And deliberately not derived from `backgroundTasks`: that list only
312
+ * knows launches that REQUESTED `run_in_background`, while Claude Code also
313
+ * backgrounds an Agent call that never asked (observed on a live transcript:
314
+ * `toolUseResult.isAsync` on an Agent whose input has no `run_in_background`).
315
+ * A caller tracking such an agent has to ask "was this id reported finished",
316
+ * and this is the one place that answers it.
317
+ *
318
+ * Read-only view: callers must not mutate it.
319
+ * @returns {ReadonlySet<string>}
320
+ */
321
+ get notifiedToolUseIds() {
322
+ return this._notified
323
+ }
324
+
325
+ /**
326
+ * #7396 (review): did the LAST `scan()` manage to read the transcript?
327
+ * `null` before any scan. `scan()` itself degrades every failure to an empty
328
+ * snapshot (its contract), which is indistinguishable from "nothing new" -- a
329
+ * consumer that waits on a notification forever needs to tell the two apart.
330
+ * A transcript that does not exist is `false` here, not an empty one.
331
+ * @returns {boolean|null}
332
+ */
333
+ get readable() {
334
+ return this._readable
335
+ }
336
+
337
+ /**
338
+ * #7396 (review): how many times an over-cap unread tail made the scanner skip
339
+ * ahead and drop the prefix it never parsed. A notification in that prefix is
340
+ * gone for good, so a consumer waiting on one compares this with the value it
341
+ * saw when it started waiting. Never reset.
342
+ * @returns {number}
343
+ */
344
+ get discardCount() {
345
+ return this._discardCount
153
346
  }
154
347
 
155
348
  /**
156
349
  * Read any new transcript bytes, fold them into the tracked state, and
157
350
  * return the outstanding-work snapshot. Never throws.
158
- * @returns {{backgroundTasks: Array<{toolUseId:string,kind:string,description:string,startedAt:number}>, scheduledWakeup: {at:number,reason:string}|null}}
351
+ * @returns {{backgroundTasks: Array<{toolUseId:string,kind:string,description:string,startedAt:number}>, scheduledWakeup: {at:number,reason:string}|null, observedModel: string|null, authFailureCount: number|null, usageLimitCount: number|null, lastUsageLimit: object|null}}
159
352
  */
160
353
  scan() {
161
354
  try {
162
355
  this._readNewBytes()
356
+ this._readable = true
163
357
  return this._snapshot()
164
358
  } catch (err) {
359
+ this._readable = false
165
360
  // ENOENT is the common benign case (transcript not written yet) —
166
361
  // still debug-logged, but state is preserved so a later scan picks
167
362
  // up where it left off if the file appears.
168
363
  this._log.debug?.(`transcript scan failed for ${this.path}: ${err.message} — degrading to empty snapshot`)
169
- return { backgroundTasks: [], scheduledWakeup: null }
364
+ // #8223: a transcript that does not exist holds no auth failures — a KNOWN
365
+ // zero (or whatever was counted before the file went away). Any other
366
+ // failure is "could not look", reported as null so a consumer never
367
+ // baselines against it.
368
+ return {
369
+ backgroundTasks: [],
370
+ scheduledWakeup: null,
371
+ observedModel: null,
372
+ authFailureCount: err?.code === 'ENOENT' ? this._authFailureCount : null,
373
+ usageLimitCount: err?.code === 'ENOENT' ? this._usageLimitCount : null,
374
+ lastUsageLimit: err?.code === 'ENOENT' ? this._lastUsageLimit : null,
375
+ }
170
376
  }
171
377
  }
172
378
 
173
379
  _readNewBytes() {
174
- const fd = openSync(this.path, 'r')
380
+ // Non-blocking: a FIFO planted at the transcript path must be refused by the
381
+ // fstat below, not waited on by the open (and the daemon with it).
382
+ const fd = openSync(this.path, constants.O_RDONLY | (constants.O_NONBLOCK || 0))
175
383
  try {
176
- const size = fstatSync(fd).size
384
+ const stat = fstatSync(fd)
385
+ // #8223: something other than a regular file at the transcript path is
386
+ // "could not look", not an empty transcript. POSIX refuses to read a
387
+ // directory (EISDIR); Windows opens it and reports size 0, which would
388
+ // otherwise read as a KNOWN zero auth-failure count.
389
+ if (!stat.isFile()) {
390
+ const err = new Error(`transcript path is not a regular file: ${this.path}`)
391
+ err.code = 'EISDIR'
392
+ throw err
393
+ }
394
+ const size = stat.size
177
395
  if (size < this._offset) {
178
396
  // Truncated / rotated — drop everything and re-read from the start.
179
397
  this._log.debug?.(`transcript ${this.path} shrank (${size} < ${this._offset}) — resetting scanner`)
@@ -187,6 +405,7 @@ export class TranscriptTaskScanner {
187
405
  // degradation for a pathological file; note it at debug level.
188
406
  this._log.debug?.(`transcript ${this.path} unread tail ${size - start}B exceeds cap — scanning final ${MAX_SCAN_BYTES}B only`)
189
407
  this._reset()
408
+ this._discardCount++
190
409
  start = size - MAX_SCAN_BYTES
191
410
  // Discard the (almost certainly partial) first line of the window.
192
411
  this._discardFirstPartialLine = true
@@ -229,6 +448,7 @@ export class TranscriptTaskScanner {
229
448
  // raw match is exact. Any status (completed/failed/…) means the
230
449
  // task is no longer running.
231
450
  this._tasks.delete(m[1])
451
+ this._noteNotified(m[1])
232
452
  }
233
453
  }
234
454
 
@@ -248,11 +468,46 @@ export class TranscriptTaskScanner {
248
468
  }
249
469
 
250
470
  if (entry.type === 'assistant') {
471
+ // #8223: both structured markers, never the text (see the header).
472
+ if (entry.isApiErrorMessage === true && entry.error === 'authentication_failed') {
473
+ this._authFailureCount++
474
+ }
475
+ // #8400: the same two structured markers, never free text on its own.
476
+ if (entry.isApiErrorMessage === true && entry.isSidechain !== true) {
477
+ const blocks = entry?.message?.content
478
+ const text = Array.isArray(blocks)
479
+ ? blocks.map((b) => (b && typeof b.text === 'string' ? b.text : '')).join(' ')
480
+ : ''
481
+ const limit = classifyApiErrorEntry({ error: entry.error, apiErrorStatus: entry.apiErrorStatus, text })
482
+ if (limit) {
483
+ this._usageLimitCount++
484
+ this._lastUsageLimit = limit
485
+ }
486
+ }
487
+ // #7327: an OBSERVATION of the model this turn actually ran on — never
488
+ // a stand-in for the requested/configured model. Excludes the
489
+ // synthetic placeholder (see SYNTHETIC_MODEL), any non-string/empty
490
+ // value, and a sidechain entry (review N2) — a subagent turn can run a
491
+ // DIFFERENT model than the main conversation, and this scanner reports
492
+ // the main session's own model. A later real observation always
493
+ // supersedes an earlier one.
494
+ const observedModel = entry?.message?.model
495
+ if (
496
+ entry.isSidechain !== true &&
497
+ typeof observedModel === 'string' && observedModel && observedModel !== SYNTHETIC_MODEL
498
+ ) {
499
+ this._observedModel = observedModel
500
+ }
251
501
  const blocks = entry?.message?.content
252
502
  if (Array.isArray(blocks)) {
503
+ // #8532: queue this entry's thinking BEFORE its tool_use claims one, so an
504
+ // entry that carries both (Claude Code writes one block per entry today)
505
+ // still hints its own thinking.
506
+ this._ingestThinking(entry, blocks, entryTs)
253
507
  for (const block of blocks) {
254
508
  if (!block || block.type !== 'tool_use' || typeof block.id !== 'string') continue
255
509
  this._ingestToolUse(block, entryTs ?? Date.now())
510
+ this._claimThinkingForToolUse(entry, block.id)
256
511
  }
257
512
  }
258
513
  return
@@ -274,6 +529,94 @@ export class TranscriptTaskScanner {
274
529
  }
275
530
  }
276
531
 
532
+ /** @param {string} toolUseId */
533
+ _noteNotified(toolUseId) {
534
+ // Re-insert so a repeat notification (the same task-id notifies again each
535
+ // time the agent stops) refreshes the id's age rather than leaving it to be
536
+ // evicted ahead of newer ones.
537
+ this._notified.delete(toolUseId)
538
+ this._notified.add(toolUseId)
539
+ if (this._notified.size > NOTIFIED_TOOL_USE_IDS_MAX) {
540
+ // Oldest first, but never an id a caller has pinned (the subagents a
541
+ // session is still waiting on): more than the cap of later notifications
542
+ // in one scan window would otherwise evict a tracked agent's id before the
543
+ // caller ever looked. Bounded by the number of pinned ids.
544
+ for (const id of this._notified) {
545
+ if (this.pinnedToolUseIds?.has(id)) continue
546
+ this._notified.delete(id)
547
+ break
548
+ }
549
+ }
550
+ }
551
+
552
+ /**
553
+ * #7393 — queue the thinking blocks of one assistant entry while capture is on.
554
+ * An entry with no usable timestamp is skipped: without it there is no telling
555
+ * whether it belongs to this turn, and showing another turn's reasoning is worse
556
+ * than showing none.
557
+ */
558
+ _ingestThinking(entry, blocks, entryTs) {
559
+ if (this._thinkingSinceMs === null) return
560
+ if (entry.isSidechain === true) return
561
+ if (entryTs === null || entryTs < this._thinkingSinceMs) return
562
+ const thinkingBlocks = blocks.filter((b) => b && (b.type === 'thinking' || b.type === 'redacted_thinking'))
563
+ if (thinkingBlocks.length === 0) return
564
+ // `thinkingDurationMs` is per ENTRY, and Claude Code writes one block per
565
+ // entry. If an entry ever held several, the duration cannot be attributed to
566
+ // any one of them, so none gets it.
567
+ const duration = thinkingBlocks.length === 1 && Number.isFinite(entry.thinkingDurationMs) && entry.thinkingDurationMs >= 0
568
+ ? entry.thinkingDurationMs
569
+ : undefined
570
+ const uuid = typeof entry.uuid === 'string' ? entry.uuid : ''
571
+ // #8518: what this block precedes, from the transcript's own order. The
572
+ // entries of one API message share `message.id`, and that message's
573
+ // `stop_reason` says how it ended: in a tool call (the block precedes that
574
+ // message's first tool_use, which a LATER entry names: see
575
+ // `_claimThinkingForToolUse`) or in the answer (it precedes the response).
576
+ // A message that ended in a tool call, or one with no stop reason yet, can only
577
+ // be told once its tool_use is read; anything the scan has not reached by the
578
+ // time the block is drained is simply left without a hint.
579
+ const apiMessageId = typeof entry.message?.id === 'string' ? entry.message.id : ''
580
+ const stopReason = entry.message?.stop_reason
581
+ const endedInAnswer = typeof stopReason === 'string' && stopReason !== 'tool_use' && stopReason !== 'pause_turn'
582
+ for (const block of thinkingBlocks) {
583
+ const redacted = block.type === 'redacted_thinking'
584
+ let text = ''
585
+ if (!redacted && typeof block.thinking === 'string') {
586
+ text = block.thinking.length > MAX_THINKING_BLOCK_CHARS ? block.thinking.slice(0, MAX_THINKING_BLOCK_CHARS) : block.thinking
587
+ }
588
+ this._thinking.push({
589
+ uuid: thinkingBlocks.length > 1 ? `${uuid}#${this._thinking.length}` : uuid,
590
+ ts: entryTs,
591
+ text,
592
+ redacted,
593
+ durationMs: duration,
594
+ apiMessageId,
595
+ precedes: endedInAnswer ? { kind: 'response' } : undefined,
596
+ })
597
+ if (this._thinking.length > MAX_PENDING_THINKING_BLOCKS) this._thinking.shift()
598
+ }
599
+ }
600
+
601
+ /**
602
+ * #8518 — a tool_use was read: every queued thinking block of the same API
603
+ * message that is still waiting for its follower precedes THIS tool call. The
604
+ * first tool_use of a message claims the block; a later one finds it settled.
605
+ * Only blocks still in the queue can be claimed, so one already drained is never
606
+ * amended after the fact.
607
+ */
608
+ _claimThinkingForToolUse(entry, toolUseId) {
609
+ if (this._thinkingSinceMs === null || this._thinking.length === 0) return
610
+ if (entry.isSidechain === true) return
611
+ const apiMessageId = typeof entry.message?.id === 'string' ? entry.message.id : ''
612
+ if (!apiMessageId) return
613
+ for (const queued of this._thinking) {
614
+ if (queued.apiMessageId === apiMessageId && queued.precedes === undefined) {
615
+ queued.precedes = { kind: 'tool_use', toolUseId }
616
+ }
617
+ }
618
+ }
619
+
277
620
  /**
278
621
  * @param {{id:string,name?:string,input?:object}} block
279
622
  * @param {number} startedAt epoch ms
@@ -364,6 +707,10 @@ export class TranscriptTaskScanner {
364
707
  return {
365
708
  backgroundTasks: [...this._tasks.values()].map((t) => ({ ...t })),
366
709
  scheduledWakeup,
710
+ observedModel: this._observedModel,
711
+ authFailureCount: this._authFailureCount,
712
+ usageLimitCount: this._usageLimitCount,
713
+ lastUsageLimit: this._lastUsageLimit,
367
714
  }
368
715
  }
369
716
  }