@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
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Session ↔ pull-request / CI status handler (#7344, display slice).
3
+ *
4
+ * One request type, one reply type:
5
+ *
6
+ * session_pr_status_request → session_pr_status
7
+ *
8
+ * ## Why this is not a Control Room survey
9
+ *
10
+ * The Control Room surveys answer *"what is happening in this repo"* and are
11
+ * host-authority gated — a pairing-bound (share-a-session) token is refused
12
+ * outright. This one answers *"what is the state of the thing THIS session
13
+ * produced"*, which is a question the bound client legitimately has about its
14
+ * own session. So the gate is the SESSION-scoped one used by the other
15
+ * per-session handlers: a bound client may ask about the session it is bound to
16
+ * and about nothing else.
17
+ *
18
+ * ## Always a snapshot, never a spinner
19
+ *
20
+ * Every path — unauthorised, unknown session, survey failure, a survey already
21
+ * running for this client — replies with a schema-valid `session_pr_status`
22
+ * carrying a `reason`. A client that only ever receives one reply type cannot
23
+ * be left waiting on a reply that never comes, and "cannot determine" renders
24
+ * as cannot-determine rather than as an implied green (see the field contracts
25
+ * on `ServerSessionPrStatusSchema`).
26
+ *
27
+ * The authority check runs BEFORE the session lookup, so a bound client cannot
28
+ * use the difference between "not authorised" and "not found" to probe which
29
+ * session ids exist.
30
+ *
31
+ * ## The reply also ARMS the CI watcher (#7427)
32
+ *
33
+ * `SessionCiWatcher` (#7426) fires only on a pending→settled transition it
34
+ * observed, and its own sweep only surveys an unarmed session every five
35
+ * minutes — so a run that starts and finishes between two of those passes was
36
+ * never noticed. This handler surveys the same thing on demand, at the moment
37
+ * someone is actually looking, so the snapshot is handed to `observe()` on the
38
+ * way out: opening the dashboard arms the watch.
39
+ *
40
+ * Note this endpoint is therefore no longer read-only — it MUTATES daemon watch
41
+ * state. `isInFlight` below bars CONCURRENT surveys per client; the #7436
42
+ * per-session throttle (`SURVEY_MIN_INTERVAL_MS`) bounds back-to-back ones
43
+ * across clients — answering throttled requests by REPLAYING the last cached
44
+ * reading (never a degraded reply after the first reading exists, so a
45
+ * Refresh inside the window cannot blank the chip). The throttle is the
46
+ * bound on the caller; `observe()`'s own safety under an un-throttled caller
47
+ * (see its doc) is the belt behind it.
48
+ *
49
+ * `observe()` arms and never fires, so nothing a client does can produce a
50
+ * completion event. Note the order and the isolation below — the reply goes out
51
+ * FIRST, and the hand-off is wrapped separately, because an exception raised
52
+ * after `send()` would fall into the survey's catch and emit a SECOND reply,
53
+ * breaking the one-reply-per-request property this whole handler is built on.
54
+ *
55
+ * NOTE the binding check below duplicates the one in `handler-utils.js`'s
56
+ * `resolveSession`. That is deliberate — `resolveSession` collapses "not
57
+ * authorised" and "not found" into a single `null`, and this handler must keep
58
+ * them apart AND check authority first — but it means a change to the binding
59
+ * rule there will not reach here. `resolveSession` carries the matching
60
+ * back-reference. See docs/security/bearer-token-authority.md §4.
61
+ */
62
+ import { surveySessionPrStatus } from '../session-pr-status.js'
63
+ import { authorizedFor, stillAuthorized } from '../connection-authority.js'
64
+ import { createSurveyThrottle } from './survey-throttle.js'
65
+ import { createLogger } from '../logger.js'
66
+ import { getErrorMessage } from '../utils/error-message.js'
67
+
68
+ const log = createLogger('ws')
69
+
70
+ /** Reason when a bound client asks about a session it is not bound to. */
71
+ export const NOT_AUTHORIZED_REASON = 'not authorized to view this session\'s pull-request status'
72
+
73
+ /** Reason when the requested (or active) session id resolves to nothing. */
74
+ export const NO_SESSION_REASON = 'no such session'
75
+
76
+ /** Reason when this client already has a survey running. */
77
+ export const IN_PROGRESS_REASON = 'a pull-request status survey is already running for this client'
78
+
79
+ /**
80
+ * Reason when a throttled request arrives before ANY reading has been cached
81
+ * for the session (#7436) — the one unreplayable case: some other client's
82
+ * very first survey is still in flight. Every later throttled request is
83
+ * answered by replaying the cached snapshot instead (review on #7445: a
84
+ * degraded reply here blanks the chip the user is looking at, with nothing
85
+ * scheduled to repair it — the throttle bounds subprocesses, it must not
86
+ * punish the click).
87
+ */
88
+ export const RATE_LIMITED_REASON = 'pull-request status was surveyed moments ago — retry in a few seconds'
89
+
90
+ /**
91
+ * #7436: minimum interval between surveys of ONE session, across all clients.
92
+ *
93
+ * The in-flight guard below only bars CONCURRENT surveys; back-to-back ones
94
+ * were unrestricted, and since #7427 each survey also MUTATES daemon watch
95
+ * state via `observe()`. `observe()` is written to be safe under an
96
+ * un-throttled caller, but "the callee is careful" is a weaker guarantee than
97
+ * a bound on the caller. Five seconds keeps the Refresh button useful for a
98
+ * user actually waiting on CI (the armed sweep itself only re-reads once a
99
+ * minute) while bounding the git+gh subprocess fan-out.
100
+ *
101
+ * Per SESSION, not per (client, session), deliberately: a pairing-bound token
102
+ * is authoritative for its own session (bearer-token-authority.md), so there
103
+ * are no token classes to keep apart — and a per-client stamp would let N
104
+ * clients multiply the subprocess cost N-fold.
105
+ *
106
+ * The magnitude is pinned by test: it must stay UNDER the dashboard's 30s
107
+ * auto-pull freshness window, or manual Refresh becomes the slower path.
108
+ * (Tests drive the clock through the `ctx._nowMs` seam — the one flat
109
+ * test-injection field this handler reads; production takes `Date.now()`.)
110
+ */
111
+ export const SURVEY_MIN_INTERVAL_MS = 5_000
112
+
113
+ /**
114
+ * This handler's own throttle instance, keyed on the session MANAGER and then
115
+ * the session id. The window semantics, the replay-don't-degrade refusal shape
116
+ * and the compare-and-restore rollback all live in `survey-throttle.js` — the
117
+ * threads handler (#7430) opens its own instance of the same gate rather than
118
+ * carrying a second copy of that logic.
119
+ */
120
+ const surveyThrottle = createSurveyThrottle()
121
+
122
+ /**
123
+ * One survey per (client, session) at a time. `gh` + git spawn subprocesses, so
124
+ * an un-guarded client could fan out a subprocess per click.
125
+ *
126
+ * Keyed on the SESSION as well as the client, deliberately. A client-global
127
+ * guard conflated "this client is spamming Refresh" with "this client switched
128
+ * tabs while a survey was running" — and the second is not abuse. It produced a
129
+ * real defect: switching from session A to B mid-survey had B's request refused
130
+ * on account of A's, and because every reply is stored under its own session id,
131
+ * B's chip was left reading "CI unavailable" with nothing scheduled to retry it.
132
+ *
133
+ * A WeakMap keyed on the client keeps the disconnected-client collection
134
+ * property the WeakSet had; the inner Set is bounded by the client's session
135
+ * count, and entries are removed in the `finally` below.
136
+ */
137
+ const inFlight = new WeakMap()
138
+
139
+ /** True when this client already has a survey running for `sessionId`. */
140
+ function isInFlight(client, sessionId) {
141
+ return inFlight.get(client)?.has(sessionId) === true
142
+ }
143
+
144
+ /** Mark `sessionId` in flight for this client. */
145
+ function markInFlight(client, sessionId) {
146
+ const set = inFlight.get(client)
147
+ if (set) set.add(sessionId)
148
+ else inFlight.set(client, new Set([sessionId]))
149
+ }
150
+
151
+ /** Release `sessionId` for this client, dropping the bag when it empties. */
152
+ function clearInFlight(client, sessionId) {
153
+ const set = inFlight.get(client)
154
+ if (!set) return
155
+ set.delete(sessionId)
156
+ if (set.size === 0) inFlight.delete(client)
157
+ }
158
+
159
+ /** Build the degraded reply used by every non-survey path. */
160
+ function degraded({ requestId, sessionId, reason, now = new Date() }) {
161
+ return {
162
+ type: 'session_pr_status',
163
+ requestId,
164
+ sessionId: sessionId ?? null,
165
+ generatedAt: now.toISOString(),
166
+ branch: null,
167
+ repo: null,
168
+ pr: null,
169
+ checks: null,
170
+ merge: null,
171
+ reason,
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Handle `session_pr_status_request`.
177
+ *
178
+ * @param {WebSocket} ws
179
+ * @param {object} client
180
+ * @param {object} msg
181
+ * @param {object} ctx
182
+ */
183
+ export async function handleSessionPrStatusRequest(ws, client, msg, ctx) {
184
+ const requestId = typeof msg?.requestId === 'string' ? msg.requestId : null
185
+ const targetSessionId = (typeof msg?.sessionId === 'string' && msg.sessionId.length > 0)
186
+ ? msg.sessionId
187
+ : (client?.activeSessionId ?? null)
188
+
189
+ // Authority first — before any lookup, so the reply cannot reveal existence.
190
+ if (client?.boundSessionId && client.boundSessionId !== targetSessionId) {
191
+ ctx.transport.send(ws, degraded({ requestId, sessionId: targetSessionId, reason: NOT_AUTHORIZED_REASON }))
192
+ return
193
+ }
194
+
195
+ const entry = ctx.sessions?.sessionManager?.getSession?.(targetSessionId) ?? null
196
+ if (!entry) {
197
+ ctx.transport.send(ws, degraded({ requestId, sessionId: targetSessionId, reason: NO_SESSION_REASON }))
198
+ return
199
+ }
200
+
201
+ if (isInFlight(client, targetSessionId)) {
202
+ ctx.transport.send(ws, degraded({ requestId, sessionId: targetSessionId, reason: IN_PROGRESS_REASON }))
203
+ return
204
+ }
205
+
206
+ // #7436: per-session minimum interval. Checked AFTER the in-flight guard so
207
+ // a concurrent duplicate keeps its more specific reason, and the record is
208
+ // only written when a survey actually starts — a replayed or refused request
209
+ // must not extend the window. `entry` resolved through this same manager
210
+ // above, so it exists; the optional chain mirrors the lookup's.
211
+ const manager = ctx.sessions?.sessionManager
212
+ const nowMs = typeof ctx._nowMs === 'function' ? ctx._nowMs() : Date.now()
213
+ const sendSnapshot = (snap) => {
214
+ // #7435 / #7442: `indeterminate` is server-side state for the CI watcher,
215
+ // not a wire field. It no longer needs an explicit strip here — it is
216
+ // defined non-enumerable in `baseSnapshot()` (session-pr-status.js), so
217
+ // this plain spread structurally cannot carry it, for a fresh reply or a
218
+ // cached replay alike (the cache keeps the RAW snapshot; observe() below
219
+ // also receives it raw, unaffected by this spread).
220
+ ctx.transport.send(ws, { type: 'session_pr_status', requestId, ...snap })
221
+ }
222
+ const gate = surveyThrottle.open(manager, targetSessionId, nowMs, SURVEY_MIN_INTERVAL_MS)
223
+ if (!gate.admitted) {
224
+ // Same display posture as #7422: never downgrade a usable answer. The
225
+ // cached reading goes out under THIS request's id, with its original
226
+ // generatedAt — honest about when it was taken. Only before the first
227
+ // completed reading is there nothing to replay.
228
+ if (gate.cached) sendSnapshot(gate.cached)
229
+ else ctx.transport.send(ws, degraded({ requestId, sessionId: targetSessionId, reason: RATE_LIMITED_REASON }))
230
+ return
231
+ }
232
+
233
+ // Tests can inject `ctx.surveySessionPrStatus` to stub the survey, matching the
234
+ // `ctx.surveyRepos` seam the Control Room handlers use — so a handler test
235
+ // never shells out to real git/gh.
236
+ const surveyFn = typeof ctx?.surveySessionPrStatus === 'function' ? ctx.surveySessionPrStatus : surveySessionPrStatus
237
+
238
+ markInFlight(client, targetSessionId)
239
+ try {
240
+ const snapshot = await surveyFn({ sessionId: targetSessionId, cwd: entry.cwd })
241
+ // #7469: only a reading worth replaying is cached. `reason` is the whole
242
+ // test here — deliberately NOT a check on `pr`, because an `indeterminate`
243
+ // fork bail-out (#7435) carries `reason: null` and is byte-identical on the
244
+ // wire to an authoritative "no open PR". Replaying it shows a client
245
+ // exactly what a fresh survey would have shown, so suppressing it would
246
+ // degrade a usable display for nothing. A reason-bearing snapshot is the
247
+ // opposite: caching it hands one transient failure to every client of this
248
+ // session for the rest of the window, and `replayable: false` keeps the
249
+ // last good reading in place instead of blanking it.
250
+ gate.commit(snapshot, { replayable: !snapshot?.reason })
251
+ sendSnapshot(snapshot)
252
+ // #7427: arm the CI watcher off the reading we just paid for. Absent
253
+ // whenever `sessionCi.watch` is off, and in ctx mocks that do not wire it.
254
+ try {
255
+ if (stillAuthorized(authorizedFor(ctx, client))) ctx.services?.sessionCiWatcher?.observe?.(targetSessionId, snapshot)
256
+ } catch (err) {
257
+ log.warn(`session_pr_status_request: ci-watch observe failed: ${getErrorMessage(err, 'unknown error')}`)
258
+ }
259
+ } catch (err) {
260
+ // #7436: a thrown survey did not spend the subprocess budget the throttle
261
+ // protects, and the retry a user reaches for next must not be refused for
262
+ // it — roll OUR record back. Compare-and-restore, not a bare delete:
263
+ // inFlight is per-CLIENT, so client A's slow survey and client B's later
264
+ // admitted one CAN overlap, and an unconditional delete here would destroy
265
+ // B's newer stamp and cache when A fails late (#7445 review, reproduced).
266
+ gate.rollback()
267
+ // surveySessionPrStatus degrades environmental failures itself, so reaching
268
+ // here means a genuine defect — log it, and still answer.
269
+ const message = getErrorMessage(err, 'unknown error')
270
+ log.warn(`session_pr_status_request failed: ${message}`)
271
+ ctx.transport.send(ws, degraded({
272
+ requestId,
273
+ sessionId: targetSessionId,
274
+ reason: `pull-request status survey failed: ${message}`,
275
+ }))
276
+ } finally {
277
+ clearInFlight(client, targetSessionId)
278
+ }
279
+ }
280
+
281
+ export const sessionPrStatusHandlers = {
282
+ session_pr_status_request: handleSessionPrStatusRequest,
283
+ }
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Session PR → unresolved review-thread count handler (#7430).
3
+ *
4
+ * One request type, one reply type:
5
+ *
6
+ * session_pr_threads_request → session_pr_threads
7
+ *
8
+ * A deliberate SECOND pair beside `session_pr_status_request`, rather than a
9
+ * flag on it. Since #7426 the status survey runs on a daemon-side sweep across
10
+ * every session; the count needs a GraphQL read that survey cannot serve, so
11
+ * folding it in would put an extra `gh` subprocess on every tick of a
12
+ * background poll to enrich a string only a click builds. This pair is sent by
13
+ * the click and never by the sweep. (See session-pr-threads.js for the full
14
+ * rationale, and the schema comment for the field contracts.)
15
+ *
16
+ * ## Same authority shape as its sibling
17
+ *
18
+ * SESSION-scoped, exactly like `session_pr_status_request`: this answers a
19
+ * question the bound client legitimately has about its OWN session, so a
20
+ * pairing-bound token may ask about the session it is bound to and nothing
21
+ * else. The authority check runs BEFORE the session lookup, so a bound client
22
+ * cannot use the difference between "not authorised" and "not found" to probe
23
+ * which session ids exist (docs/security/bearer-token-authority.md §4).
24
+ *
25
+ * NOTE the binding check below duplicates the one in `handler-utils.js`'s
26
+ * `resolveSession` for the same reason its sibling does: `resolveSession`
27
+ * collapses "not authorised" and "not found" into a single `null`, and this
28
+ * handler must keep them apart AND check authority first.
29
+ *
30
+ * ## Always a count-shaped answer, never a spinner and never a zero
31
+ *
32
+ * Every path — unauthorised, unknown session, throttled, already running,
33
+ * survey failure — replies with a schema-valid `session_pr_threads` carrying a
34
+ * `reason` and a NULL count. Both halves matter: a path that replied with
35
+ * nothing leaves a caller unable to tell "still counting" from "never
36
+ * answered", and a refusal that came back as `unresolvedCount: 0` would be
37
+ * indistinguishable from a real zero — the false green the issue was filed
38
+ * against.
39
+ *
40
+ * ## Throttled, because a click costs subprocesses
41
+ *
42
+ * The read spawns `git` + `gh pr list` (resolution, delegated) + `gh api
43
+ * graphql` (the count). `isInFlight` bars CONCURRENT counts per client;
44
+ * `COUNT_MIN_INTERVAL_MS` bounds back-to-back ones across clients, answering a
45
+ * throttled request by REPLAYING the last completed count rather than
46
+ * degrading — a degraded reply would blank a count the user is looking at, with
47
+ * nothing scheduled to repair it. The window/replay/rollback machinery is
48
+ * shared with the status handler via `survey-throttle.js`; it is not a second
49
+ * copy of it.
50
+ *
51
+ * Unlike its sibling this endpoint is READ-ONLY — nothing here arms a watcher
52
+ * or mutates daemon state.
53
+ */
54
+ import { surveySessionPrThreads } from '../session-pr-threads.js'
55
+ import { createSurveyThrottle } from './survey-throttle.js'
56
+ import { createLogger } from '../logger.js'
57
+ import { getErrorMessage } from '../utils/error-message.js'
58
+
59
+ const log = createLogger('ws')
60
+
61
+ /** Reason when a bound client asks about a session it is not bound to. */
62
+ export const NOT_AUTHORIZED_REASON = 'not authorized to view this session\'s review threads'
63
+
64
+ /** Reason when the requested (or active) session id resolves to nothing. */
65
+ export const NO_SESSION_REASON = 'no such session'
66
+
67
+ /** Reason when this client already has a count running for this session. */
68
+ export const IN_PROGRESS_REASON = 'a review-thread count is already running for this client'
69
+
70
+ /**
71
+ * Reason when a throttled request arrives before ANY count has been cached for
72
+ * the session — the one unreplayable case: some other client's very first count
73
+ * is still in flight. Every later throttled request replays the cached count
74
+ * instead, because the throttle exists to bound subprocesses, not to punish the
75
+ * click (#7445's review of the sibling handler).
76
+ */
77
+ export const RATE_LIMITED_REASON = 'review threads were counted moments ago — retry in a few seconds'
78
+
79
+ /**
80
+ * Minimum interval between counts of ONE session, across all clients.
81
+ *
82
+ * Matched to the sibling survey's five seconds deliberately: the two are
83
+ * triggered by the same clicks (Refresh fires both), so a different window
84
+ * would make one of them silently the slower path and the pair would disagree
85
+ * about how fresh "just now" is. Five seconds keeps a Refresh useful to someone
86
+ * actually waiting on a review while bounding the `gh` fan-out.
87
+ *
88
+ * Per SESSION, not per (client, session): a pairing-bound token is
89
+ * authoritative for its own session, so there are no token classes to keep
90
+ * apart, and a per-client stamp would let N clients multiply the cost N-fold.
91
+ *
92
+ * Tests drive the clock through the `ctx._nowMs` seam — the one flat
93
+ * test-injection field this handler reads; production takes `Date.now()`.
94
+ */
95
+ export const COUNT_MIN_INTERVAL_MS = 5_000
96
+
97
+ /** This handler's own throttle instance (see survey-throttle.js). */
98
+ const countThrottle = createSurveyThrottle()
99
+
100
+ /**
101
+ * One count per (client, session) at a time.
102
+ *
103
+ * Keyed on the SESSION as well as the client for the reason #7445 established
104
+ * on the sibling: a client-global guard conflates "spamming Refresh" with
105
+ * "switched tabs mid-count", and the second is not abuse — it left the new
106
+ * tab's chip refused on account of the old one's, with nothing to retry it.
107
+ */
108
+ const inFlight = new WeakMap()
109
+
110
+ /** True when this client already has a count running for `sessionId`. */
111
+ function isInFlight(client, sessionId) {
112
+ return inFlight.get(client)?.has(sessionId) === true
113
+ }
114
+
115
+ /** Mark `sessionId` in flight for this client. */
116
+ function markInFlight(client, sessionId) {
117
+ const set = inFlight.get(client)
118
+ if (set) set.add(sessionId)
119
+ else inFlight.set(client, new Set([sessionId]))
120
+ }
121
+
122
+ /** Release `sessionId` for this client, dropping the bag when it empties. */
123
+ function clearInFlight(client, sessionId) {
124
+ const set = inFlight.get(client)
125
+ if (!set) return
126
+ set.delete(sessionId)
127
+ if (set.size === 0) inFlight.delete(client)
128
+ }
129
+
130
+ /**
131
+ * Build the degraded reply used by every non-count path.
132
+ *
133
+ * The three count fields are pinned NULL/false here rather than defaulted,
134
+ * which is the whole safety property: there is no code path in this file that
135
+ * can emit a zero it did not count.
136
+ */
137
+ function degraded({ requestId, sessionId, reason, now = new Date() }) {
138
+ return {
139
+ type: 'session_pr_threads',
140
+ requestId,
141
+ sessionId: sessionId ?? null,
142
+ countedAt: now.toISOString(),
143
+ prNumber: null,
144
+ unresolvedCount: null,
145
+ totalCount: null,
146
+ truncated: false,
147
+ reason,
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Handle `session_pr_threads_request`.
153
+ *
154
+ * @param {WebSocket} ws
155
+ * @param {object} client
156
+ * @param {object} msg
157
+ * @param {object} ctx
158
+ */
159
+ export async function handleSessionPrThreadsRequest(ws, client, msg, ctx) {
160
+ const requestId = typeof msg?.requestId === 'string' ? msg.requestId : null
161
+ const targetSessionId = (typeof msg?.sessionId === 'string' && msg.sessionId.length > 0)
162
+ ? msg.sessionId
163
+ : (client?.activeSessionId ?? null)
164
+
165
+ // Authority first — before any lookup, so the reply cannot reveal existence.
166
+ if (client?.boundSessionId && client.boundSessionId !== targetSessionId) {
167
+ ctx.transport.send(ws, degraded({ requestId, sessionId: targetSessionId, reason: NOT_AUTHORIZED_REASON }))
168
+ return
169
+ }
170
+
171
+ const entry = ctx.sessions?.sessionManager?.getSession?.(targetSessionId) ?? null
172
+ if (!entry) {
173
+ ctx.transport.send(ws, degraded({ requestId, sessionId: targetSessionId, reason: NO_SESSION_REASON }))
174
+ return
175
+ }
176
+
177
+ if (isInFlight(client, targetSessionId)) {
178
+ ctx.transport.send(ws, degraded({ requestId, sessionId: targetSessionId, reason: IN_PROGRESS_REASON }))
179
+ return
180
+ }
181
+
182
+ // Checked AFTER the in-flight guard so a concurrent duplicate keeps its more
183
+ // specific reason, and the window is only stamped when a count actually
184
+ // starts — a replayed or refused request must not extend it.
185
+ const manager = ctx.sessions?.sessionManager
186
+ const nowMs = typeof ctx._nowMs === 'function' ? ctx._nowMs() : Date.now()
187
+ const sendCount = (snapshot) => {
188
+ ctx.transport.send(ws, { type: 'session_pr_threads', requestId, ...snapshot })
189
+ }
190
+ const gate = countThrottle.open(manager, targetSessionId, nowMs, COUNT_MIN_INTERVAL_MS)
191
+ if (!gate.admitted) {
192
+ // Never downgrade a usable answer: the cached count goes out under THIS
193
+ // request's id, with its original `countedAt` — honest about when it was
194
+ // taken. Only before the first completed count is there nothing to replay.
195
+ if (gate.cached) sendCount(gate.cached)
196
+ else ctx.transport.send(ws, degraded({ requestId, sessionId: targetSessionId, reason: RATE_LIMITED_REASON }))
197
+ return
198
+ }
199
+
200
+ // Tests inject `ctx.surveySessionPrThreads` to stub the count, matching the
201
+ // `ctx.surveySessionPrStatus` seam its sibling uses — so a handler test never
202
+ // shells out to real git/gh.
203
+ const surveyFn = typeof ctx?.surveySessionPrThreads === 'function' ? ctx.surveySessionPrThreads : surveySessionPrThreads
204
+
205
+ markInFlight(client, targetSessionId)
206
+ try {
207
+ const snapshot = await surveyFn({ sessionId: targetSessionId, cwd: entry.cwd })
208
+ // #7469 S1: cache ONLY a reading that actually carries a count. #7445's
209
+ // "replay, don't degrade" does not help when the replayed thing is itself a
210
+ // degradation — one transient `gh api graphql` failure would be handed to
211
+ // every client of this session for the whole window, long after the
212
+ // condition cleared. The requester that paid for the failed read still gets
213
+ // it below, under its own request id; the CACHE keeps the last good count.
214
+ //
215
+ // This is a STRICTER rule than the status survey's `!reason`, which is why
216
+ // the gate takes the decision as an argument rather than applying one of
217
+ // its own: a thread count additionally needs an actual number, since a
218
+ // count-free reading has nothing to say however it came about.
219
+ //
220
+ // The window is still STAMPED (that happened in `open()`): a read that
221
+ // reached `gh` spent the budget the throttle protects, whatever it came
222
+ // back with. Only a THROWN survey, which never got that far, rolls back.
223
+ gate.commit(snapshot, { replayable: snapshot?.reason == null && snapshot?.unresolvedCount != null })
224
+ sendCount(snapshot)
225
+ } catch (err) {
226
+ // A thrown count did not spend the subprocess budget the throttle protects,
227
+ // and the retry the user reaches for next must not be refused for it. The
228
+ // rollback is compare-and-restore inside the throttle, so a newer client's
229
+ // stamp survives this one's late failure.
230
+ gate.rollback()
231
+ // surveySessionPrThreads degrades environmental failures itself, so reaching
232
+ // here means a genuine defect — log it, and still answer.
233
+ const message = getErrorMessage(err, 'unknown error')
234
+ log.warn(`session_pr_threads_request failed: ${message}`)
235
+ ctx.transport.send(ws, degraded({
236
+ requestId,
237
+ sessionId: targetSessionId,
238
+ reason: `review-thread count failed: ${message}`,
239
+ }))
240
+ } finally {
241
+ clearInFlight(client, targetSessionId)
242
+ }
243
+ }
244
+
245
+ export const sessionPrThreadsHandlers = {
246
+ session_pr_threads_request: handleSessionPrThreadsRequest,
247
+ }