@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
@@ -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
@@ -285,12 +628,39 @@ export class TranscriptTaskScanner {
285
628
  if (name === 'ScheduleWakeup') {
286
629
  const delaySeconds = Number(input.delaySeconds)
287
630
  if (Number.isFinite(delaySeconds) && delaySeconds >= 0) {
288
- // A newer ScheduleWakeup supersedes any earlier pending one — the
289
- // harness keeps at most one timer armed.
290
- this._wakeup = {
291
- at: startedAt + delaySeconds * 1000,
292
- reason: typeof input.reason === 'string' ? input.reason : '',
293
- prompt: typeof input.prompt === 'string' ? input.prompt : '',
631
+ const at = startedAt + delaySeconds * 1000
632
+ // #7084: the computed instant must be a SAFE integer, not merely finite.
633
+ // `delaySeconds` is model-authored tool input, so it is arbitrary JSON, and the
634
+ // wire schema is `z.number().int().nonnegative().finite()` — where Zod's
635
+ // `.int()` enforces the SAFE-integer range, not just integrality. Two reachable
636
+ // shapes fail it:
637
+ // delaySeconds: 0.0001 -> a fractional `at` (invalid_type)
638
+ // delaySeconds: 1e15 -> an `at` past 2^53 (too_big)
639
+ // Measured against the built schema; 9e12 still fits, so the ceiling is real
640
+ // rather than theoretical.
641
+ //
642
+ // DROP the wakeup rather than clamp it. The field is optional, and any clamp
643
+ // renders a precise-looking lie about when the agent will wake — clamping to
644
+ // MAX_SAFE_INTEGER actually yields an Invalid Date, and to Date's own ceiling
645
+ // (8.64e15) yields "13 Sep 275760". Neither is a time. A nonsense delay means
646
+ // the tool call is garbage, so having no scheduled wakeup is the honest state.
647
+ //
648
+ // Ignoring (rather than clearing an existing wakeup) matches what this guard
649
+ // already did for a NaN `delaySeconds`: invalid input leaves any previously
650
+ // armed wakeup alone instead of destroying it.
651
+ // `at >= 0` is DEFENCE-IN-DEPTH, not load-bearing: measured, no input reaches
652
+ // the snapshot with a negative `at`, because the consumption path already treats
653
+ // a wakeup whose instant has passed as spent and every negative instant is past.
654
+ // Kept because it is free and states the wire contract at the point of
655
+ // construction — but do not read it as a guard with test coverage.
656
+ if (Number.isSafeInteger(at) && at >= 0) {
657
+ // A newer ScheduleWakeup supersedes any earlier pending one — the
658
+ // harness keeps at most one timer armed.
659
+ this._wakeup = {
660
+ at,
661
+ reason: typeof input.reason === 'string' ? input.reason : '',
662
+ prompt: typeof input.prompt === 'string' ? input.prompt : '',
663
+ }
294
664
  }
295
665
  }
296
666
  return
@@ -310,6 +680,14 @@ export class TranscriptTaskScanner {
310
680
  : typeof input.prompt === 'string'
311
681
  ? input.prompt.slice(0, PROMPT_DESCRIPTION_MAX)
312
682
  : ''
683
+ // #7084: `startedAt` carries the byte-identical wire constraint to
684
+ // scheduledWakeup.at — BackgroundTaskSchema.startedAt is
685
+ // `z.number().int().nonnegative().finite()` — and had no guard at all. It comes
686
+ // from Date.parse of a transcript timestamp, so a pre-epoch entry yields a negative
687
+ // instant (verified: 1960-01-01 -> -315619200000, which the schema refuses as
688
+ // too_small). Drop the task rather than emit an unrepresentable one; the snapshot
689
+ // is a list, so one bad entry would otherwise fail the whole claude_ready frame.
690
+ if (!Number.isSafeInteger(startedAt) || startedAt < 0) return
313
691
  this._tasks.set(block.id, { toolUseId: block.id, kind, description, startedAt })
314
692
  }
315
693
 
@@ -329,6 +707,10 @@ export class TranscriptTaskScanner {
329
707
  return {
330
708
  backgroundTasks: [...this._tasks.values()].map((t) => ({ ...t })),
331
709
  scheduledWakeup,
710
+ observedModel: this._observedModel,
711
+ authFailureCount: this._authFailureCount,
712
+ usageLimitCount: this._usageLimitCount,
713
+ lastUsageLimit: this._lastUsageLimit,
332
714
  }
333
715
  }
334
716
  }