@chroxy/server 0.11.0 → 0.11.11

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 (386) hide show
  1. package/CONFIG.md +206 -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 +958 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +304 -0
  14. package/src/agent-control/client.js +1645 -0
  15. package/src/agent-control/events.js +551 -0
  16. package/src/agent-control/local-connection.js +293 -0
  17. package/src/agent-control/mcp-server.js +547 -0
  18. package/src/anthropic-compatible-config.js +30 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-gemini-shim.js +444 -0
  21. package/src/anthropic-gemini-translate.js +1030 -0
  22. package/src/anthropic-openai-shim.js +0 -1
  23. package/src/archive-continuation.js +164 -0
  24. package/src/assistant-response.js +24 -0
  25. package/src/auth-probes.js +120 -13
  26. package/src/background-shell-tracker.js +27 -0
  27. package/src/base-session.js +1520 -36
  28. package/src/bearer-recheck.js +49 -0
  29. package/src/billing-budget.js +19 -0
  30. package/src/billing-class.js +40 -7
  31. package/src/binary-provenance-trust.js +11 -5
  32. package/src/bound-client-policy.js +291 -0
  33. package/src/built-in-tools/bash-exec.js +46 -7
  34. package/src/built-in-tools/file-ops.js +69 -5
  35. package/src/built-in-tools/tool-transforms.js +1113 -13
  36. package/src/byok-compose-state.js +6 -9
  37. package/src/byok-credentials.js +2 -3
  38. package/src/byok-mcp-client.js +92 -7
  39. package/src/byok-mcp-config.js +633 -122
  40. package/src/byok-mcp-fleet.js +49 -7
  41. package/src/byok-mcp-oauth-store.js +18 -16
  42. package/src/byok-mcp-trust.js +37 -23
  43. package/src/byok-session.js +707 -179
  44. package/src/byok-tool-executor.js +2742 -26
  45. package/src/byok-tools.js +9 -2
  46. package/src/channels/chroxy-channel-server.js +2 -3
  47. package/src/checkpoint-manager.js +64 -46
  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-setting-sources.js +74 -0
  53. package/src/claude-stream-parser.js +53 -3
  54. package/src/claude-tui/diagnostic-tail.js +83 -0
  55. package/src/claude-tui/form-driver.js +44 -7
  56. package/src/claude-tui/model-error.js +41 -0
  57. package/src/claude-tui/pty-driver.js +215 -88
  58. package/src/claude-tui/sanitize-question-payload.js +109 -0
  59. package/src/claude-tui/usage-limit.js +239 -0
  60. package/src/claude-tui-session.js +3563 -284
  61. package/src/claude-tui-tool-response.js +300 -0
  62. package/src/cli/agent-cmd.js +236 -0
  63. package/src/cli/agent-control-cmd.js +65 -0
  64. package/src/cli/config-cmd.js +4 -4
  65. package/src/cli/config-dir-cmd.js +234 -0
  66. package/src/cli/connection-state.js +54 -0
  67. package/src/cli/deploy-cmd.js +45 -10
  68. package/src/cli/doctor-cmd.js +7 -3
  69. package/src/cli/freshness-cmd.js +53 -0
  70. package/src/cli/init-cmd.js +15 -16
  71. package/src/cli/pages-cmd.js +6 -4
  72. package/src/cli/pair-code-cmd.js +7 -6
  73. package/src/cli/pair-discord-cmd.js +7 -6
  74. package/src/cli/providers-cmd.js +3 -3
  75. package/src/cli/schedule-cmd.js +91 -40
  76. package/src/cli/server-cmd.js +54 -1
  77. package/src/cli/service-cmd.js +33 -10
  78. package/src/cli/session-cmd.js +227 -74
  79. package/src/cli/shared.js +162 -11
  80. package/src/cli/shell-cmd.js +7 -4
  81. package/src/cli/status-cmd.js +19 -5
  82. package/src/cli/tokens-cmd.js +4 -5
  83. package/src/cli/tunnel-cmd.js +255 -24
  84. package/src/cli/worktree-gc-cmd.js +2 -2
  85. package/src/cli-session.js +1250 -126
  86. package/src/cli.js +8 -0
  87. package/src/codex-app-server-client.js +36 -3
  88. package/src/codex-app-server-session.js +1517 -81
  89. package/src/codex-bundled-client.js +66 -0
  90. package/src/codex-error-text.js +114 -0
  91. package/src/codex-model-catalog.js +548 -0
  92. package/src/codex-model-rejections.js +87 -0
  93. package/src/codex-native-resume.js +104 -0
  94. package/src/codex-protocol-capabilities.js +188 -0
  95. package/src/codex-session.js +450 -27
  96. package/src/config-dir-migration.js +449 -0
  97. package/src/config-dir.js +108 -0
  98. package/src/config.js +306 -26
  99. package/src/connection-authority.js +48 -0
  100. package/src/connection-info.js +78 -23
  101. package/src/connection-locality.js +60 -0
  102. package/src/container-liveness-monitor.js +189 -0
  103. package/src/continuation-metadata-worker.js +17 -0
  104. package/src/continuations.js +227 -0
  105. package/src/control-room/host-prune.js +5 -0
  106. package/src/control-room/integrations.js +7 -20
  107. package/src/control-room/skills-inventory.js +2 -2
  108. package/src/conversation-scanner.js +42 -39
  109. package/src/conversation-scope.js +59 -39
  110. package/src/conversation-search.js +28 -39
  111. package/src/credential-store.js +23 -19
  112. package/src/daemon-commit.js +92 -0
  113. package/src/daemon-idle-state.js +171 -0
  114. package/src/daemon-update-status.js +314 -0
  115. package/src/dashboard-build.js +70 -0
  116. package/src/declared-status.js +90 -0
  117. package/src/deepseek-credentials.js +2 -3
  118. package/src/dev-preview.js +170 -182
  119. package/src/device-preferences.js +2 -2
  120. package/src/diff-parser.js +87 -0
  121. package/src/discord-credentials.js +2 -3
  122. package/src/docker-byok-pool.js +3 -1
  123. package/src/docker-byok-session.js +678 -78
  124. package/src/docker-image-allowlist.js +23 -1
  125. package/src/docker-sdk-session.js +172 -3
  126. package/src/docker-session.js +294 -11
  127. package/src/doctor.js +781 -64
  128. package/src/durable-write.js +35 -0
  129. package/src/edited-input.js +264 -0
  130. package/src/environment-manager.js +175 -36
  131. package/src/environments/authority.js +101 -0
  132. package/src/environments/backends/container-claude-spawn.js +94 -0
  133. package/src/environments/backends/docker.js +31 -10
  134. package/src/environments/backends/k8s.js +49 -24
  135. package/src/environments/destroy-with-sessions.js +142 -0
  136. package/src/event-ingest.js +118 -13
  137. package/src/event-normalizer.js +186 -235
  138. package/src/folder-trust-wire.js +137 -0
  139. package/src/folder-trust-worker.js +17 -0
  140. package/src/folder-trust.js +1572 -0
  141. package/src/freshness/activity-meter.js +101 -0
  142. package/src/freshness/adapter.js +199 -0
  143. package/src/freshness/checks.js +239 -0
  144. package/src/freshness/config.js +98 -0
  145. package/src/freshness/core.js +185 -0
  146. package/src/freshness/derive.js +680 -0
  147. package/src/freshness/exchange.js +305 -0
  148. package/src/freshness/file-ledger.js +400 -0
  149. package/src/freshness/grade.js +81 -0
  150. package/src/freshness/hash.js +45 -0
  151. package/src/freshness/inbox.js +163 -0
  152. package/src/freshness/index.js +20 -0
  153. package/src/freshness/investigation.js +474 -0
  154. package/src/freshness/keys.js +177 -0
  155. package/src/freshness/ledger.js +122 -0
  156. package/src/freshness/outbox.js +131 -0
  157. package/src/freshness/policy.js +599 -0
  158. package/src/freshness/queue.js +843 -0
  159. package/src/freshness/read-errors.js +23 -0
  160. package/src/freshness/render.js +153 -0
  161. package/src/freshness/runtime.js +113 -0
  162. package/src/freshness/session-registry-adapter.js +161 -0
  163. package/src/freshness/state-file-adapter.js +167 -0
  164. package/src/freshness-runner/build-info.js +139 -0
  165. package/src/freshness-runner/cli.js +105 -0
  166. package/src/freshness-runner/run-tick.js +109 -0
  167. package/src/freshness-runner/stamp.js +57 -0
  168. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  169. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  170. package/src/freshness-sources/index.js +8 -0
  171. package/src/gemini-byok-session.js +292 -0
  172. package/src/gemini-credentials.js +67 -0
  173. package/src/gemini-key-safety.js +246 -0
  174. package/src/gemini-models.js +386 -0
  175. package/src/gemini-session.js +81 -5
  176. package/src/handler-utils.js +540 -80
  177. package/src/handlers/checkpoint-handlers.js +47 -4
  178. package/src/handlers/control-room-handlers.js +51 -11
  179. package/src/handlers/conversation-handlers.js +469 -56
  180. package/src/handlers/daemon-update-handlers.js +81 -0
  181. package/src/handlers/evaluator-handlers.js +14 -1
  182. package/src/handlers/feature-handlers.js +186 -69
  183. package/src/handlers/file-handlers.js +57 -13
  184. package/src/handlers/folder-trust-handlers.js +90 -0
  185. package/src/handlers/input-handlers.js +714 -48
  186. package/src/handlers/orchestration-handlers.js +3 -3
  187. package/src/handlers/principal-admin-handlers.js +229 -0
  188. package/src/handlers/principal-handlers.js +262 -0
  189. package/src/handlers/scheduler-handlers.js +92 -18
  190. package/src/handlers/session-handlers.js +551 -20
  191. package/src/handlers/session-pr-status-handlers.js +283 -0
  192. package/src/handlers/session-pr-threads-handlers.js +247 -0
  193. package/src/handlers/settings-handlers.js +372 -50
  194. package/src/handlers/skills-handlers.js +20 -4
  195. package/src/handlers/summarize-handlers.js +32 -1
  196. package/src/handlers/survey-throttle.js +380 -0
  197. package/src/health-proof.js +40 -0
  198. package/src/history-page.js +112 -0
  199. package/src/http-routes.js +127 -8
  200. package/src/ide/search.js +24 -6
  201. package/src/ide/symbols.js +20 -6
  202. package/src/input-context.js +117 -0
  203. package/src/instruction-policy-compiler.js +229 -0
  204. package/src/instruction-policy.js +250 -0
  205. package/src/jsonl-reader.js +378 -91
  206. package/src/jsonl-subprocess-session.js +96 -9
  207. package/src/keychain.js +1 -1
  208. package/src/logger.js +166 -30
  209. package/src/mailbox-route.js +113 -22
  210. package/src/message-wire.js +386 -0
  211. package/src/model-discovery.js +43 -3
  212. package/src/models.js +1276 -174
  213. package/src/notification-prefs.js +27 -4
  214. package/src/notifications/discord-billing-sink.js +22 -5
  215. package/src/notifications/discord-ci-sink.js +243 -0
  216. package/src/notifications/discord-webhook-client.js +71 -0
  217. package/src/notifications/discord-webhook-sink.js +64 -23
  218. package/src/notifications/expo-push-sink.js +85 -6
  219. package/src/notifications/ready-body.js +16 -5
  220. package/src/ollama-session.js +34 -2
  221. package/src/orchestration/build-manager.js +9 -2
  222. package/src/orchestration/git-ops.js +41 -7
  223. package/src/orchestration/orchestration-manager.js +112 -36
  224. package/src/orchestration/permission-gate.js +17 -2
  225. package/src/orchestration/run-model.js +2 -1
  226. package/src/orchestration/run-record.js +11 -0
  227. package/src/orchestration/turn-driver.js +185 -43
  228. package/src/orphan-reaper.js +470 -0
  229. package/src/outgoing-policy.js +189 -0
  230. package/src/pairing.js +92 -13
  231. package/src/path-hash-trust-ledger.js +642 -25
  232. package/src/permission-deadlines.js +82 -0
  233. package/src/permission-floor.js +1410 -43
  234. package/src/permission-hook.js +180 -69
  235. package/src/permission-manager.js +737 -89
  236. package/src/permission-mode-support.js +35 -0
  237. package/src/permission-resolved-by.js +89 -0
  238. package/src/permission-resolver.js +126 -8
  239. package/src/permission-scope.js +43 -0
  240. package/src/platform.js +315 -47
  241. package/src/preview-ingress.js +54 -0
  242. package/src/preview-target.js +213 -0
  243. package/src/principal-audit.js +189 -0
  244. package/src/principal-binding.js +25 -0
  245. package/src/principal-brakes.js +21 -0
  246. package/src/principal-effect.js +101 -0
  247. package/src/principal-journal.js +905 -0
  248. package/src/principal-kill-switch.js +183 -0
  249. package/src/principal-label.js +5 -0
  250. package/src/principal-pending-permissions.js +177 -0
  251. package/src/principal-policy.js +1094 -0
  252. package/src/principal-sessions-snapshot.js +208 -0
  253. package/src/principal-store.js +488 -0
  254. package/src/principal-subscriptions.js +283 -0
  255. package/src/prompt-evaluator.js +34 -4
  256. package/src/provider-customization.js +180 -0
  257. package/src/providers.js +209 -4
  258. package/src/push.js +30 -4
  259. package/src/question-route-map.js +130 -0
  260. package/src/redaction.js +531 -20
  261. package/src/roster-broadcast.js +186 -0
  262. package/src/scheduled-task-store.js +330 -26
  263. package/src/scheduler.js +368 -11
  264. package/src/sdk-session.js +2114 -188
  265. package/src/server-cli/preview-shutdown.js +22 -0
  266. package/src/server-cli/push-notification-handler.js +17 -3
  267. package/src/server-cli/server-orchestrator.js +28 -5
  268. package/src/server-cli-child.js +33 -18
  269. package/src/server-cli.js +553 -38
  270. package/src/server-identity.js +15 -11
  271. package/src/service.js +396 -25
  272. package/src/session-archive-limits.js +15 -0
  273. package/src/session-archive.js +1029 -0
  274. package/src/session-busy-state.js +72 -0
  275. package/src/session-ci-watcher.js +1099 -0
  276. package/src/session-context.js +7 -2
  277. package/src/session-manager.js +4062 -312
  278. package/src/session-message-history.js +841 -16
  279. package/src/session-name-allocator.js +685 -0
  280. package/src/session-pr-status.js +654 -0
  281. package/src/session-pr-threads.js +271 -0
  282. package/src/session-preset-trust.js +3 -3
  283. package/src/session-preset.js +10 -5
  284. package/src/session-state-persistence.js +94 -17
  285. package/src/session-timeout-manager.js +20 -0
  286. package/src/session-token-store.js +17 -8
  287. package/src/session-wake.js +240 -0
  288. package/src/shell-approval-info.js +2 -2
  289. package/src/shell-approval-store.js +3 -1
  290. package/src/skills-loader.js +7 -4
  291. package/src/skills-manager.js +2 -2
  292. package/src/skills-trust.js +95 -13
  293. package/src/skills-usage.js +2 -3
  294. package/src/snapshots-store.js +2 -3
  295. package/src/statusline.js +100 -29
  296. package/src/summarize-session.js +53 -4
  297. package/src/supervisor.js +22 -11
  298. package/src/sweep-stale-provider-dirs.js +95 -0
  299. package/src/thinking-level-wire.js +39 -0
  300. package/src/thinking-stream.js +179 -0
  301. package/src/tool-result.js +61 -0
  302. package/src/transcript-sources.js +109 -0
  303. package/src/transcript-tasks.js +372 -25
  304. package/src/trusted-file-read.js +302 -0
  305. package/src/tunnel/base.js +0 -8
  306. package/src/tunnel/cloudflare.js +34 -31
  307. package/src/tunnel/index.js +9 -0
  308. package/src/tunnel/preview.js +64 -0
  309. package/src/turn-outcome.js +140 -0
  310. package/src/usage-normalize.js +9 -5
  311. package/src/user-shell-session.js +59 -5
  312. package/src/utils/agent-sdk-version.js +107 -0
  313. package/src/utils/argv-safety.js +770 -0
  314. package/src/utils/auth-cause.js +60 -0
  315. package/src/utils/binary-package-manifest.js +639 -0
  316. package/src/utils/binary-version.js +224 -0
  317. package/src/utils/bounded-regex-worker.js +29 -0
  318. package/src/utils/bounded-regex.js +162 -0
  319. package/src/utils/claude-binary.js +43 -0
  320. package/src/utils/claude-config-dir.js +245 -0
  321. package/src/utils/claude-login-command.js +16 -0
  322. package/src/utils/claude-native-route.js +81 -0
  323. package/src/utils/componentwise-resolver.js +133 -37
  324. package/src/utils/deploy-control-files.js +87 -0
  325. package/src/utils/exec-failure-reason.js +21 -0
  326. package/src/utils/git-repo.js +42 -0
  327. package/src/utils/is-entry-point.js +137 -0
  328. package/src/utils/node-pty-probe.js +95 -0
  329. package/src/utils/node-pty-support.js +118 -0
  330. package/src/utils/opened-file-path.js +167 -0
  331. package/src/utils/path-containment.js +165 -0
  332. package/src/utils/permission-mode-sidecar.js +51 -0
  333. package/src/utils/pid-liveness.js +47 -0
  334. package/src/utils/preflight.js +360 -16
  335. package/src/utils/read-limiter.js +217 -0
  336. package/src/utils/regular-file.js +375 -0
  337. package/src/utils/safe-regex.js +113 -0
  338. package/src/utils/small-file.js +129 -0
  339. package/src/utils/spawn-env.js +189 -4
  340. package/src/utils/stale-session-dirs.js +182 -0
  341. package/src/utils/stat-identity.js +43 -0
  342. package/src/utils/verify-provenance.js +406 -13
  343. package/src/web-task-manager.js +297 -16
  344. package/src/worktree-gc.js +202 -6
  345. package/src/ws-auth.js +163 -31
  346. package/src/ws-broadcaster.js +49 -5
  347. package/src/ws-client-manager.js +24 -1
  348. package/src/ws-client-sender.js +7 -0
  349. package/src/ws-file-ops/browser.js +363 -58
  350. package/src/ws-file-ops/common.js +320 -14
  351. package/src/ws-file-ops/git.js +395 -42
  352. package/src/ws-file-ops/index.js +2 -0
  353. package/src/ws-file-ops/memory.js +137 -35
  354. package/src/ws-file-ops/open-nofollow.js +354 -0
  355. package/src/ws-file-ops/reader.js +571 -113
  356. package/src/ws-forwarding.js +349 -39
  357. package/src/ws-handler-context.js +88 -2
  358. package/src/ws-history.js +1010 -175
  359. package/src/ws-message-handlers.js +25 -1
  360. package/src/ws-permissions.js +307 -37
  361. package/src/ws-schemas.js +5 -0
  362. package/src/ws-server.js +885 -98
  363. package/sidecar/node_modules/.package-lock.json +0 -29
  364. package/sidecar/node_modules/ws/LICENSE +0 -20
  365. package/sidecar/node_modules/ws/README.md +0 -548
  366. package/sidecar/node_modules/ws/browser.js +0 -8
  367. package/sidecar/node_modules/ws/index.js +0 -22
  368. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  369. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  370. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  371. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  372. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  373. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  374. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  375. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  376. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  377. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  378. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  379. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  380. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  381. package/sidecar/node_modules/ws/package.json +0 -70
  382. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  383. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  384. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  385. package/src/dashboard-next/dist/index.html +0 -13
  386. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -0,0 +1,49 @@
1
+ /**
2
+ * A bearer is checked again once the body has arrived.
3
+ *
4
+ * A route that validates its bearer and then waits for a request body keeps
5
+ * acting on the first answer for as long as the body takes. The one rule for
6
+ * such a route: capture the bearer when it is first validated, and call
7
+ * `bearerStillValid` once the body is complete and BEFORE anything changes.
8
+ * Every route that reads a body after a primary or pairing bearer validation
9
+ * goes through these two functions. tests/bearer-recheck.test.js is a tripwire
10
+ * over named body readers, not a proof; it fails on a new route that skips them
11
+ * unless the route is listed there as a named, reasoned exclusion.
12
+ *
13
+ * - auth off: there is no bearer to re-check;
14
+ * - a pairing token: it must still be live (`isSessionTokenLive`: stored and
15
+ * unexpired); with no pairing manager any more, that is a refusal;
16
+ * - any other token: the daemon's own validity check.
17
+ */
18
+
19
+ /**
20
+ * @param {{ authRequired: boolean, _pairingManager?: object|null }} server
21
+ * @param {{ headers?: Record<string, string|undefined> }} req
22
+ * @returns {{ required: boolean, token: string|null, wasPairing: boolean }}
23
+ */
24
+ export function captureBearer(server, req) {
25
+ const header = (req?.headers && req.headers.authorization) || ''
26
+ const token = header.startsWith('Bearer ') ? header.slice(7) : null
27
+ const pairing = server._pairingManager
28
+ return {
29
+ required: !!server.authRequired,
30
+ token,
31
+ wasPairing: !!(token && pairing && pairing.isSessionTokenValid(token) === true),
32
+ }
33
+ }
34
+
35
+ /**
36
+ * @param {{ _pairingManager?: object|null, _isTokenValid: (t: string) => boolean }} server
37
+ * @param {{ required: boolean, token: string|null, wasPairing: boolean }|null|undefined} captured
38
+ * null or undefined (nothing was captured) is refused
39
+ * @returns {boolean}
40
+ */
41
+ export function bearerStillValid(server, captured) {
42
+ if (!captured) return false
43
+ if (!captured.required) return true
44
+ if (!captured.token) return false
45
+ if (captured.wasPairing) {
46
+ return server._pairingManager?.isSessionTokenLive?.(captured.token) === true
47
+ }
48
+ return server._isTokenValid(captured.token) === true
49
+ }
@@ -18,6 +18,7 @@
18
18
  import { readFileSync, writeFileSync, renameSync, mkdirSync, rmSync } from 'node:fs'
19
19
  import { dirname } from 'node:path'
20
20
  import { toWireCount } from './utils/wire-counters.js'
21
+ import { BILLING_CLASSES, isProgrammaticCreditEra } from './billing-class.js'
21
22
 
22
23
  /** Per-tier monthly programmatic-credit caps (USD), per Anthropic's 2026-06-15 change. */
23
24
  export const CREDIT_TIER_BUDGETS_USD = Object.freeze({
@@ -173,6 +174,20 @@ export class MonthlyProgrammaticBudgetManager {
173
174
  /**
174
175
  * Current meter snapshot. `spentUsd` floors at 0 (a refund turn can drive the
175
176
  * raw total negative; a negative pool reading would be nonsense to surface).
177
+ *
178
+ * #7377: `billingClass` tells clients how to LABEL the snapshot. The
179
+ * running total only ever grows from programmatic-credit-billed turns
180
+ * (`recordSpend`'s caller in session-manager.js gates on
181
+ * `billingClass === 'programmatic-credit'` before calling in), so the
182
+ * meter's class tracks the same era check that gate's classifier uses —
183
+ * `isProgrammaticCreditEra(now)`: the operator flag AND the era start
184
+ * date, evaluated at this snapshot's `now` — `programmatic-credit` while
185
+ * the era is in force,
186
+ * `subscription` while it is not (the era never started; #7333/#7361).
187
+ * A stale `spentUsd` left over from a build that misclassified turns
188
+ * before #7361 is real dollars once observed, but must not keep reading
189
+ * as live "Credit spend" once the era flag says it isn't — hence this is
190
+ * computed from the CURRENT flag, not cached at accrual time.
176
191
  */
177
192
  getStatus(now = Date.now()) {
178
193
  this._rollIfNeeded(now)
@@ -181,6 +196,9 @@ export class MonthlyProgrammaticBudgetManager {
181
196
  const percent = budgetUsd != null && budgetUsd > 0 ? (spentUsd / budgetUsd) * 100 : null
182
197
  const warning = percent != null && percent >= this._warningPercent
183
198
  const exceeded = budgetUsd != null && spentUsd >= budgetUsd
199
+ const billingClass = isProgrammaticCreditEra(now)
200
+ ? BILLING_CLASSES.PROGRAMMATIC_CREDIT
201
+ : BILLING_CLASSES.SUBSCRIPTION
184
202
  return {
185
203
  month: this._state.month,
186
204
  spentUsd,
@@ -190,6 +208,7 @@ export class MonthlyProgrammaticBudgetManager {
190
208
  percent,
191
209
  warning,
192
210
  exceeded,
211
+ billingClass,
193
212
  }
194
213
  }
195
214
  }
@@ -2,11 +2,14 @@
2
2
  * Era-aware billing classification (#5630 / #5629).
3
3
  *
4
4
  * Chroxy bills Claude usage three different ways depending on the provider
5
- * and (for the programmatic providers) the date. Historically the dashboard
5
+ * and (for the programmatic providers) whether an operator has declared the
6
+ * programmatic-credit era in force. Historically the dashboard
6
7
  * labelled every dollar figure "Cost (BYOK)" — wrong for subscription and
7
8
  * programmatic-credit sessions (#5630) — and the provider copy still said
8
- * "subscription" for claude-cli / claude-sdk even though Anthropic moves
9
- * those onto a metered programmatic-credit pool on 2026-06-15 (#5629).
9
+ * "subscription" for claude-cli / claude-sdk ahead of a metered
10
+ * programmatic-credit pool Anthropic announced for 2026-06-15 (#5629). That
11
+ * pool was PAUSED on the day it was due and never shipped, so subscription is
12
+ * the correct copy after all; see `programmaticCreditEraEnabled` (#7333).
10
13
  *
11
14
  * This module is the single source of truth for "which billing class is
12
15
  * this session/provider in right now?" Every provider `resolveAuth()` and the
@@ -22,10 +25,11 @@
22
25
  * claude-channel). No per-turn dollar figure. Era-
23
26
  * independent.
24
27
  * - programmatic-credit — host claude-cli / claude-sdk when auth is the
25
- * OAuth/subscription pool. BEFORE 2026-06-15 these
26
- * bill as flat `subscription`; ON/AFTER they draw from
27
- * Anthropic's monthly metered programmatic-credit pool,
28
- * so spend becomes a real dollar figure.
28
+ * OAuth/subscription pool AND an operator has declared
29
+ * the era in force via CHROXY_PROGRAMMATIC_CREDIT_ERA=1.
30
+ * NOT IN FORCE TODAY (#7333): Anthropic paused the
31
+ * change on 2026-06-15 and it never shipped, so these
32
+ * providers bill as flat `subscription`.
29
33
  *
30
34
  * Refinement: a claude-cli / claude-sdk session authed with an explicit
31
35
  * ANTHROPIC_API_KEY (the raw-API branch in resolveAuth, source === 'env') is
@@ -94,9 +98,38 @@ const API_KEY_PROVIDERS = new Set([
94
98
  * @returns {boolean}
95
99
  */
96
100
  export function isProgrammaticCreditEra(now = Date.now()) {
101
+ if (!programmaticCreditEraEnabled()) return false
97
102
  return now >= PROGRAMMATIC_CREDIT_ERA_START
98
103
  }
99
104
 
105
+ /**
106
+ * Has an operator declared the programmatic-credit era in force? (#7333)
107
+ *
108
+ * THE ERA NEVER STARTED. Anthropic paused the change on 2026-06-15, the day it
109
+ * was due to take effect, and it has not shipped: `claude -p`, the Agent SDK
110
+ * and third-party app usage still draw from the subscription's usage limits.
111
+ * The date comparison above had no feature check, so it silently flipped true
112
+ * on the announced date and chroxy has been asserting a billing regime that
113
+ * does not exist every day since — telling users `claude-cli`/`claude-sdk`
114
+ * bill against a "monthly metered credit pool", and showing a real dollar
115
+ * figure where a subscription session should read "Included".
116
+ *
117
+ * That misdirects provider choice: it steers users away from `claude-cli`, at
118
+ * present the best-working Claude provider, toward `claude-tui`, which can
119
+ * neither report nor switch models (#7327), on the basis of a cost that is not
120
+ * being charged.
121
+ *
122
+ * A date with no way to observe whether the event happened is the
123
+ * "cannot check this, so assume it did" cause in docs/false-safety-guards.md.
124
+ * The observable replaces it: an operator sets `CHROXY_PROGRAMMATIC_CREDIT_ERA=1`
125
+ * when the regime actually arrives. The constant and every consumer stay wired
126
+ * up, because the pause is explicitly "for now" — a revival is this flag plus,
127
+ * if the announced date moves, one edit to PROGRAMMATIC_CREDIT_ERA_START.
128
+ */
129
+ export function programmaticCreditEraEnabled() {
130
+ return process.env.CHROXY_PROGRAMMATIC_CREDIT_ERA === '1'
131
+ }
132
+
100
133
  /**
101
134
  * Classify a provider into one of the three billing classes for a given
102
135
  * instant.
@@ -16,7 +16,11 @@
16
16
  * "/opt/homebrew/bin/codex": {
17
17
  * "sha256": "<64 hex chars>", // the binary's CONTENT hash
18
18
  * "firstSeen": "2026-07-22T12:34:56.000Z",
19
- * "approvedAt": "2026-07-22T12:34:56.000Z"
19
+ * "approvedAt": "2026-07-22T12:34:56.000Z",
20
+ * "kind": "tree" // "file" (single-file hash) or
21
+ * // "tree" (package-manifest digest,
22
+ * // #8040) — a record with no `kind`
23
+ * // is a legacy single-file pin.
20
24
  * }
21
25
  * }
22
26
  * }
@@ -33,14 +37,15 @@
33
37
  * spawning — provenance is a defence-in-depth layer, not a hard dependency).
34
38
  */
35
39
  import { existsSync } from 'fs'
36
- import { homedir } from 'os'
37
- import { join } from 'path'
38
40
  import { createLogger } from './logger.js'
39
41
  import { PathHashTrustLedger } from './path-hash-trust-ledger.js'
42
+ import { configPath } from './config-dir.js'
40
43
 
41
44
  const log = createLogger('binary-provenance-trust')
42
45
 
43
- export const DEFAULT_BINARY_TRUST_FILE = join(homedir(), '.chroxy', 'binary-trust.json')
46
+ export function defaultBinaryTrustFile() {
47
+ return configPath('binary-trust.json')
48
+ }
44
49
 
45
50
  /**
46
51
  * Normalise a ledger key for storage / lookup. On case-insensitive filesystems
@@ -72,12 +77,13 @@ export class BinaryProvenanceLedger extends PathHashTrustLedger {
72
77
  */
73
78
  constructor({ filePath } = {}) {
74
79
  super({
75
- filePath: filePath || DEFAULT_BINARY_TRUST_FILE,
80
+ filePath: filePath || defaultBinaryTrustFile(),
76
81
  log,
77
82
  normalizeKey: _normalizeKey,
78
83
  approvalField: 'approvedAt',
79
84
  wrapperKey: 'binaries',
80
85
  throwOnFlushError: false, // best-effort: a read-only $HOME never breaks spawning
86
+ extraFields: ['kind'], // #8040: 'file' | 'tree' — see verify-provenance.js
81
87
  })
82
88
  const loaded = this._loadRecords()
83
89
  this._records = loaded.records
@@ -0,0 +1,291 @@
1
+ /**
2
+ * Which WebSocket message types a session-scoped connection may use.
3
+ *
4
+ * A session-scoped ("bound") connection is one authenticated with a pairing
5
+ * token that names a single session (`client.boundSessionId`). It exists to
6
+ * work on THAT session and nothing else, so the registry is closed by default:
7
+ * a message type is dispatched for a bound connection only when it is listed in
8
+ * `BOUND_ALLOWED_MESSAGE_TYPES` below. Everything else is listed in
9
+ * `BOUND_DENIED_MESSAGE_TYPES` (with the reason) or, if nobody has classified it
10
+ * yet, is refused anyway — a handler added without a decision is unavailable to
11
+ * a session-scoped connection rather than silently open to it.
12
+ *
13
+ * The allowlist is applied by ONE function, `refuseBoundMessage` (below), not
14
+ * inside each handler. ws-server calls it before schema validation and
15
+ * `handleSessionMessage` in ws-message-handlers.js calls it again as the dispatch
16
+ * gate. A per-handler check can be forgotten by the next handler; a check applied
17
+ * to every message cannot. A handler may still refuse a scoped connection on its
18
+ * own account, through `sendBoundRefusal`.
19
+ *
20
+ * Every allowed entry is one of:
21
+ * - session-local by construction: it only ever reads or acts on the
22
+ * connection's own session (the handler resolves the session through the
23
+ * bound id, and refuses a different one); or
24
+ * - guarded: it touches something shared, and the handler carries its own
25
+ * ownership check, named in the reason.
26
+ *
27
+ * tests/bound-client-policy.test.js asserts the classification is total, in
28
+ * both directions: every registered handler is allowed or denied (exactly one),
29
+ * and every name listed here is a real handler.
30
+ */
31
+
32
+ import { createLogger, loggableValue } from './logger.js'
33
+ import { isBoundClient } from './environments/authority.js'
34
+ import { buildSessionTokenMismatchPayload } from './handler-utils.js'
35
+
36
+ const log = createLogger('bound-client-policy')
37
+
38
+ /** @type {Readonly<Record<string, string>>} */
39
+ export const BOUND_ALLOWED_MESSAGE_TYPES = Object.freeze({
40
+ // -- session-local: input and control of the connection's own session --
41
+ input: 'session-local: sends to the resolved (bound) session only',
42
+ interrupt: 'session-local: refuses a sessionId other than the bound one',
43
+ cancel_queued: 'session-local: refuses a sessionId other than the bound one',
44
+ cancel_activity: 'session-local: refuses a sessionId other than the bound one',
45
+ resume_budget: 'session-local: resumes the budget pause of the resolved session',
46
+ user_question_response: 'session-local: only answers a question routed to the bound session',
47
+ terminal_input: 'session-local: refuses a sessionId other than the bound one',
48
+ terminal_subscribe: 'session-local: subscription index refuses other sessions',
49
+ terminal_unsubscribe: 'connection-local: drops this connection\'s own subscription',
50
+ terminal_resize: 'session-local: acts on the bound session\'s terminal',
51
+ terminal_resync: 'session-local: replays the bound session\'s terminal',
52
+ client_visible: 'connection-local: records this connection\'s own visibility',
53
+
54
+ // -- session roster / navigation: filtered or refused for other sessions --
55
+ list_sessions: 'guarded: the list is filtered to the bound session',
56
+ switch_session: 'guarded: refuses any target other than the bound session',
57
+ subscribe_sessions: 'guarded: subscriptions to other sessions are refused',
58
+ unsubscribe_sessions: 'connection-local: drops this connection\'s own subscriptions',
59
+ rename_session: 'guarded: refuses a target other than the bound session',
60
+ destroy_session: 'guarded: refuses a target other than the bound session',
61
+ claim_primary: 'guarded: refuses a target other than the bound session',
62
+
63
+ // -- per-session settings and permissions --
64
+ set_model: 'session-local: resolves the bound session or refuses',
65
+ set_thinking_level: 'session-local: resolves the bound session or refuses',
66
+ set_permission_mode: 'guarded: bound session only, and the unattended mode is refused',
67
+ set_prompt_evaluator: 'session-local: resolves the bound session or refuses',
68
+ set_chroxy_context_hint: 'session-local: resolves the bound session or refuses',
69
+ set_session_preamble: 'session-local: resolves the bound session or refuses',
70
+ set_mcp_server_enabled: 'guarded: per-session toggle, bound session only',
71
+ permission_response: 'guarded: only the bound session\'s own prompts; a standing "always allow" is downgraded to a one-time allow',
72
+ get_permission_input: 'guarded: only the bound session\'s own prompts',
73
+ query_permission_audit: 'guarded: refused unless it names the bound session',
74
+ register_push_token: 'guarded: the registration is limited to notifications of the bound session',
75
+
76
+ // -- skills, files, git, IDE: confined to the bound session's directory --
77
+ list_skills: 'guarded: the bound session\'s own skills; nothing without a resolved session',
78
+ skill_activate: 'session-local: resolves the bound session or refuses',
79
+ skill_deactivate: 'session-local: resolves the bound session or refuses',
80
+ browse_files: 'guarded: confined to the bound session\'s directory',
81
+ list_files: 'guarded: confined to the bound session\'s directory',
82
+ read_file: 'guarded: confined to the bound session\'s directory',
83
+ memory_read: 'guarded: the bound session\'s directory; nothing without a resolved session',
84
+ get_diff: 'guarded: limited to paths inside the bound session\'s directory',
85
+ git_status: 'guarded: limited to paths inside the bound session\'s directory',
86
+ git_branches: 'guarded: the bound session\'s own checkout only',
87
+ list_slash_commands: 'guarded: the project\'s commands only (not the user-level catalog); nothing without a resolved session',
88
+ list_agents: 'guarded: the project\'s agents only (not the user-level catalog); nothing without a resolved session',
89
+ list_symbols: 'guarded: the workspace of the resolved (bound) session',
90
+ resolve_symbol: 'guarded: the workspace of the resolved (bound) session',
91
+ search_content: 'guarded: the workspace of the resolved (bound) session',
92
+ find_references: 'guarded: the workspace of the resolved (bound) session',
93
+
94
+ // -- history and conversations --
95
+ list_conversations: 'guarded: only the conversation of the bound session',
96
+ search_conversations: 'guarded: only the conversation of the bound session',
97
+ request_conversation_transcript: 'guarded: only the conversation of the bound session; reads are concurrency-limited',
98
+ request_full_history: 'session-local: refuses a sessionId other than the bound one',
99
+ request_session_context: 'session-local: refuses a sessionId other than the bound one',
100
+ summarize_session: 'session-local: binding is checked before the session is looked up',
101
+ evaluate_draft: 'session-local: resolves the bound session or refuses',
102
+ session_pr_status_request: 'session-local: binding is checked before the lookup',
103
+ session_pr_threads_request: 'session-local: binding is checked before the lookup',
104
+ extension_message: 'session-local: delivered to the resolved (bound) session only',
105
+
106
+ // -- checkpoints: snapshots of the bound session (restoring one is denied) --
107
+ create_checkpoint: 'session-local: records a checkpoint for the bound session',
108
+ list_checkpoints: 'session-local: lists the bound session\'s checkpoints',
109
+ delete_checkpoint: 'guarded: only a checkpoint of the bound session',
110
+ })
111
+
112
+ /** @type {Readonly<Record<string, string>>} */
113
+ export const BOUND_DENIED_MESSAGE_TYPES = Object.freeze({
114
+ // -- creating or reaching other sessions --
115
+ create_session: 'creates a new session',
116
+ resume_conversation: 'creates a new session',
117
+ list_failed_restores: 'host-wide roster',
118
+ retry_failed_restore: 'acts on sessions other than the bound one',
119
+ get_failed_restore_history: 'host-wide roster',
120
+ list_archived_sessions: 'host-wide roster',
121
+ get_archived_session_history: 'host-wide roster',
122
+ delete_archived_session: 'host-wide roster',
123
+ restore_archived_session: 'creates a session',
124
+ set_session_archive_policy: 'host-wide policy',
125
+ request_cost_summary: 'host-wide roster, totals and budget',
126
+
127
+ // -- host-wide configuration and credentials --
128
+ set_permission_rules: 'standing rules shared across sessions',
129
+ set_prompt_evaluator_skip_pattern: 'a pattern the daemon runs on its own event loop for every input',
130
+ add_mcp_server: 'host-wide server configuration',
131
+ remove_mcp_server: 'host-wide server configuration',
132
+ trust_folder: 'lets a folder\'s project settings run on this machine',
133
+ untrust_folder: 'changes which folders run project settings on this machine',
134
+ submit_mcp_auth_code: 'stores a credential shared by every session using the server',
135
+ list_providers: 'host-wide configuration status',
136
+ byok_get_credentials_status: 'host-wide credential status',
137
+ get_credentials_status: 'host-wide credential status',
138
+ byok_set_credentials: 'host-wide credentials',
139
+ byok_clear_credentials: 'host-wide credentials',
140
+ set_credential: 'host-wide credentials',
141
+ delete_credential: 'host-wide credentials',
142
+ test_credential: 'uses a host-wide credential',
143
+ skill_trust_accept: 'host-wide skill trust',
144
+ skill_trust_grant: 'host-wide skill trust',
145
+ github_webhook_config_request: 'host-wide configuration',
146
+ github_webhook_set_secret: 'host-wide configuration',
147
+ github_webhook_clear_secret: 'host-wide configuration',
148
+ notification_prefs_get: 'host-wide notification settings',
149
+ notification_prefs_set: 'host-wide notification settings',
150
+ session_preset_get: 'host-wide presets',
151
+ session_preset_set: 'host-wide presets',
152
+ session_preset_approve: 'host-wide presets',
153
+ session_preset_revoke: 'host-wide presets',
154
+ daemon_update_action: 'host lifecycle',
155
+ revoke_token: 'credential management',
156
+ principal_admin_grant: 'credential management',
157
+ principal_admin_list: 'credential management',
158
+ principal_admin_revoke: 'credential management',
159
+ principal_admin_disable: 'credential management',
160
+ principal_admin_enable: 'credential management',
161
+ principal_subscribe: 'agent-principal journal read path, never a bound client\'s',
162
+ principal_unsubscribe: 'agent-principal journal read path, never a bound client\'s',
163
+ principal_events_read: 'agent-principal journal read path, never a bound client\'s',
164
+ principal_pending_permissions: 'agent-principal pending-permission snapshot, never a bound client\'s',
165
+ principal_sessions_snapshot: 'agent-principal session roster snapshot, never a bound client\'s',
166
+ pair_approve: 'credential management',
167
+ pair_deny: 'credential management',
168
+
169
+ // -- repositories, directories, workspace mutation --
170
+ list_repos: 'host-wide repository inventory',
171
+ add_repo: 'host-wide repository configuration',
172
+ remove_repo: 'host-wide repository configuration',
173
+ list_directory: 'enumerates directories outside the bound session',
174
+ check_git_repo: 'probes arbitrary host directories',
175
+ write_file: 'mutates the workspace',
176
+ append_memory: 'mutates the workspace',
177
+ git_stage: 'mutates the workspace',
178
+ git_unstage: 'mutates the workspace',
179
+ git_commit: 'mutates the workspace',
180
+ git_create_pr: 'mutates the workspace and the remote',
181
+ restore_checkpoint: 'rewrites the workspace, which other sessions may share',
182
+
183
+ // -- web tasks, previews, environments --
184
+ launch_web_task: 'starts independent execution',
185
+ teleport_web_task: 'starts independent execution',
186
+ list_web_tasks: 'tasks carry no owning session',
187
+ open_dev_preview: 'publishes a host service',
188
+ close_dev_preview: 'host service lifecycle',
189
+ create_environment: 'host-wide environments',
190
+ list_environments: 'host-wide environments',
191
+ destroy_environment: 'host-wide environments',
192
+ get_environment: 'host-wide environments',
193
+
194
+ // -- control room, orchestration, scheduling --
195
+ host_status_request: 'host-wide survey',
196
+ runner_status_request: 'host-wide survey',
197
+ containers_status_request: 'host-wide survey',
198
+ repo_runtime_config_request: 'host-wide survey',
199
+ byok_pool_status_request: 'host-wide survey',
200
+ host_prune_status_request: 'host-wide survey',
201
+ simulator_status_request: 'host-wide survey',
202
+ emulator_status_request: 'host-wide survey',
203
+ wsl_status_request: 'host-wide survey',
204
+ integration_status_request: 'host-wide survey',
205
+ skills_inventory_request: 'host-wide survey',
206
+ mailbox_status_request: 'host-wide survey',
207
+ external_sessions_request: 'host-wide survey',
208
+ repo_events_request: 'host-wide survey',
209
+ containers_action: 'host-wide action',
210
+ byok_pool_action: 'host-wide action',
211
+ host_prune_action: 'host-wide action',
212
+ simulator_action: 'host-wide action',
213
+ emulator_action: 'host-wide action',
214
+ wsl_action: 'host-wide action',
215
+ integration_action: 'host-wide action',
216
+ orchestration_runs_request: 'host-wide runs',
217
+ orchestration_run_detail_request: 'host-wide runs',
218
+ orchestration_run_start: 'host-wide runs',
219
+ orchestration_gate_response: 'host-wide runs',
220
+ orchestration_run_action: 'host-wide runs',
221
+ orchestration_run_annotate: 'host-wide runs',
222
+ scheduled_tasks_request: 'host-wide schedule',
223
+ scheduled_task_action: 'host-wide schedule',
224
+ set_scheduler_enabled: 'host-wide schedule',
225
+ })
226
+
227
+ /**
228
+ * May a session-scoped connection use this message type? Closed by default:
229
+ * only an explicit allowed entry passes, and own-property lookup keeps
230
+ * `__proto__` / `constructor` style type strings from matching.
231
+ * @param {unknown} type
232
+ * @returns {boolean}
233
+ */
234
+ export function isBoundAllowedMessageType(type) {
235
+ return typeof type === 'string' && Object.hasOwn(BOUND_ALLOWED_MESSAGE_TYPES, type)
236
+ }
237
+
238
+ /** The one refusal text for a request a session-scoped connection may not make. */
239
+ export const BOUND_REFUSAL_MESSAGE = 'Not available to a session-scoped connection'
240
+
241
+ const MAX_ECHOED_LENGTH = 128
242
+
243
+ /**
244
+ * Send the one refusal reply to a session-scoped connection. The decision is
245
+ * the caller's; use `refuseBoundMessage` to decide by the allowlist.
246
+ *
247
+ * The reply names only the connection's own session. `requestType` and
248
+ * `requestId` are echoed only when they are strings of at most
249
+ * MAX_ECHOED_LENGTH characters; anything else is dropped, not truncated (a
250
+ * truncated id cannot correlate with the request).
251
+ *
252
+ * @param {WebSocket} ws
253
+ * @param {object} client
254
+ * @param {object} msg
255
+ * @param {object} ctx
256
+ */
257
+ export function sendBoundRefusal(ws, client, msg, ctx) {
258
+ const type = msg?.type
259
+ log.info(`Session-scoped client ${client?.id} refused message type ${loggableValue(type)}`)
260
+ ctx.transport.send(ws, {
261
+ type: 'session_error',
262
+ ...buildSessionTokenMismatchPayload({
263
+ sessionManager: ctx.sessions?.sessionManager,
264
+ boundSessionId: client?.boundSessionId,
265
+ message: BOUND_REFUSAL_MESSAGE,
266
+ }),
267
+ ...(typeof type === 'string' && type.length <= MAX_ECHOED_LENGTH ? { requestType: type } : {}),
268
+ ...(typeof msg?.requestId === 'string' && msg.requestId.length <= MAX_ECHOED_LENGTH ? { requestId: msg.requestId } : {}),
269
+ })
270
+ }
271
+
272
+ /**
273
+ * The single place the allowlist is applied to a session-scoped connection's
274
+ * request. Returns true when `msg` was refused (and replied to), false when the
275
+ * connection may use it. A missing or non-string `type` is refused.
276
+ *
277
+ * ws-server calls this before schema validation so a malformed denied request
278
+ * is refused rather than answered with a schema error, and handleSessionMessage
279
+ * calls it again as the dispatch gate. The refusal has no other effect.
280
+ *
281
+ * @param {WebSocket} ws
282
+ * @param {object} client
283
+ * @param {object} msg
284
+ * @param {object} ctx
285
+ * @returns {boolean}
286
+ */
287
+ export function refuseBoundMessage(ws, client, msg, ctx) {
288
+ if (!isBoundClient(client) || isBoundAllowedMessageType(msg?.type)) return false
289
+ sendBoundRefusal(ws, client, msg, ctx)
290
+ return true
291
+ }
@@ -33,11 +33,47 @@
33
33
  */
34
34
 
35
35
  import { spawn } from 'node:child_process'
36
+ import { forceKill, killProcessTree } from '../platform.js'
37
+ import { CHROXY_SECRET_DENYLIST, stripInheritedChroxySecrets, stripParentClaudeSessionEnv } from '../utils/spawn-env.js'
36
38
 
37
39
  export const DEFAULT_BASH_TIMEOUT_MS = 30_000
38
40
  export const DEFAULT_BASH_MAX_OUTPUT_BYTES = 1_000_000 // 1 MB
39
41
  export const HARD_KILL_GRACE_MS = 2_000
40
42
 
43
+ // How long to wait, after the child exits, for its stdout/stderr pipes to
44
+ // finish delivering data (#8120). Bounded so a backgrounded grandchild that
45
+ // keeps the pipe open (`cmd &`) cannot stall the tool.
46
+ export const STDIO_DRAIN_GRACE_MS = 250
47
+
48
+ function streamEnded(stream) {
49
+ if (!stream || stream.readableEnded || stream.destroyed) return Promise.resolve()
50
+ return new Promise((resolve) => {
51
+ stream.once('end', resolve)
52
+ stream.once('close', resolve)
53
+ stream.once('error', resolve)
54
+ })
55
+ }
56
+
57
+ async function drainStdio(child, graceMs) {
58
+ let timer
59
+ await Promise.race([
60
+ Promise.all([streamEnded(child.stdout), streamEnded(child.stderr)]),
61
+ new Promise((resolve) => { timer = setTimeout(resolve, graceMs) }),
62
+ ])
63
+ clearTimeout(timer)
64
+ }
65
+
66
+ // A caller that omits `env` must not hand bash the daemon's own secrets
67
+ // (API_TOKEN, the hook secret): fall back to a stripped copy of process.env,
68
+ // never process.env itself (#8111 review, #8113).
69
+ function defaultChildEnv() {
70
+ const out = { ...process.env }
71
+ for (const key of CHROXY_SECRET_DENYLIST) delete out[key]
72
+ stripInheritedChroxySecrets(out)
73
+ stripParentClaudeSessionEnv(out) // #8262
74
+ return out
75
+ }
76
+
41
77
  export async function executeBash({
42
78
  command,
43
79
  cwd = process.cwd(),
@@ -69,7 +105,7 @@ export async function executeBash({
69
105
 
70
106
  const child = spawn('bash', ['-c', command], {
71
107
  cwd,
72
- env: env || process.env,
108
+ env: env || defaultChildEnv(),
73
109
  stdio: ['ignore', 'pipe', 'pipe'],
74
110
  })
75
111
 
@@ -104,11 +140,11 @@ export async function executeBash({
104
140
  let hardKillTimer = null
105
141
  const killChild = (sig, _reason) => {
106
142
  if (child.killed || child.exitCode !== null) return
107
- try {
108
- child.kill(sig)
109
- } catch {
110
- // ignore — process already gone
111
- }
143
+ // #7606: signal the whole tree, not just bash. `bash -c` keeps itself as
144
+ // the parent of a compound command (`a && b`, `x | y`, `cmd &`), so a
145
+ // direct `child.kill()` here left the real work running — reparented to
146
+ // pid 1, unbounded — after the tool had already reported a timeout.
147
+ killProcessTree(child, { force: sig === 'SIGKILL' })
112
148
  if (sig === 'SIGTERM' && hardKillTimer === null) {
113
149
  hardKillTimer = setTimeout(() => {
114
150
  try {
@@ -119,7 +155,7 @@ export async function executeBash({
119
155
  // exit signal: exitCode set (normal exit) or signalCode set
120
156
  // (received a signal). Either means the process is gone.
121
157
  if (child.exitCode === null && child.signalCode === null) {
122
- child.kill('SIGKILL')
158
+ forceKill(child)
123
159
  }
124
160
  } catch {}
125
161
  }, HARD_KILL_GRACE_MS)
@@ -149,6 +185,9 @@ export async function executeBash({
149
185
  child.on('exit', (code, signalName) => resolve({ code, sig: signalName }))
150
186
  child.on('error', () => resolve({ code: null, sig: null }))
151
187
  })
188
+ // 'exit' can fire before the stdio pipes are drained, so a fast command's
189
+ // output may still be in flight here (#8120). Wait for both streams to end.
190
+ await drainStdio(child, STDIO_DRAIN_GRACE_MS)
152
191
 
153
192
  clearTimeout(timeoutHandle)
154
193
  if (hardKillTimer !== null) clearTimeout(hardKillTimer)