@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,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
+ }
@@ -17,6 +17,8 @@
17
17
 
18
18
  import { readFileSync, writeFileSync, renameSync, mkdirSync, rmSync } from 'node:fs'
19
19
  import { dirname } from 'node:path'
20
+ import { toWireCount } from './utils/wire-counters.js'
21
+ import { BILLING_CLASSES, isProgrammaticCreditEra } from './billing-class.js'
20
22
 
21
23
  /** Per-tier monthly programmatic-credit caps (USD), per Anthropic's 2026-06-15 change. */
22
24
  export const CREDIT_TIER_BUDGETS_USD = Object.freeze({
@@ -101,7 +103,10 @@ export class MonthlyProgrammaticBudgetManager {
101
103
  this._state = {
102
104
  month: raw.month,
103
105
  spentUsd: Number.isFinite(raw.spentUsd) ? raw.spentUsd : 0,
104
- turnsBilled: Number.isFinite(raw.turnsBilled) && raw.turnsBilled >= 0 ? raw.turnsBilled : 0,
106
+ // #7082: `.int().nonnegative()` on the wire — the finite+sign guard let a
107
+ // fractional or past-2^53 value through from a hand-edited state file.
108
+ // `spentUsd` above is deliberately untouched: USD, no `.int()`.
109
+ turnsBilled: toWireCount(raw.turnsBilled),
105
110
  warnNotified: raw.warnNotified === true,
106
111
  exceededNotified: raw.exceededNotified === true,
107
112
  }
@@ -169,6 +174,20 @@ export class MonthlyProgrammaticBudgetManager {
169
174
  /**
170
175
  * Current meter snapshot. `spentUsd` floors at 0 (a refund turn can drive the
171
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.
172
191
  */
173
192
  getStatus(now = Date.now()) {
174
193
  this._rollIfNeeded(now)
@@ -177,6 +196,9 @@ export class MonthlyProgrammaticBudgetManager {
177
196
  const percent = budgetUsd != null && budgetUsd > 0 ? (spentUsd / budgetUsd) * 100 : null
178
197
  const warning = percent != null && percent >= this._warningPercent
179
198
  const exceeded = budgetUsd != null && spentUsd >= budgetUsd
199
+ const billingClass = isProgrammaticCreditEra(now)
200
+ ? BILLING_CLASSES.PROGRAMMATIC_CREDIT
201
+ : BILLING_CLASSES.SUBSCRIPTION
180
202
  return {
181
203
  month: this._state.month,
182
204
  spentUsd,
@@ -186,6 +208,7 @@ export class MonthlyProgrammaticBudgetManager {
186
208
  percent,
187
209
  warning,
188
210
  exceeded,
211
+ billingClass,
189
212
  }
190
213
  }
191
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.
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Provider-binary provenance trust ledger (#6858).
3
+ *
4
+ * Pins the SHA-256 hash of every spawned provider binary (`claude`, `codex`,
5
+ * `gemini`, `cloudflared`) the daemon has seen. A later change to a pinned hash
6
+ * re-gates the binary (warn / block) — catching an in-place binary swap
7
+ * regardless of code signature or macOS quarantine state. See
8
+ * `utils/verify-provenance.js` for the verification logic and
9
+ * `docs/security/spawned-binary-provenance.md` for the threat model.
10
+ *
11
+ * Storage shape (sidecar JSON file, next to skills-trust.json / session-preset-
12
+ * trust.json):
13
+ *
14
+ * {
15
+ * "binaries": {
16
+ * "/opt/homebrew/bin/codex": {
17
+ * "sha256": "<64 hex chars>", // the binary's CONTENT hash
18
+ * "firstSeen": "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.
24
+ * }
25
+ * }
26
+ * }
27
+ *
28
+ * A path is TRUSTED only when its stored `sha256` equals the hash of the
29
+ * currently-resolved binary. First sight (no record) → pin + allow
30
+ * (trust-on-first-use). A changed hash → re-gated. The operator re-approves the
31
+ * CURRENT hash via `approve(path, hash)`; `revoke(path)` drops the record.
32
+ *
33
+ * Since #5580 the ledger mechanics (load/isTrusted/approve/revoke/getRecord +
34
+ * atomic 0600 persist + fail-open) live in `PathHashTrustLedger`; this class is
35
+ * a thin subclass that pins the `binaries` wrapper key and the `approvedAt`
36
+ * timestamp field. Best-effort flush (a read-only $HOME must never break
37
+ * spawning — provenance is a defence-in-depth layer, not a hard dependency).
38
+ */
39
+ import { existsSync } from 'fs'
40
+ import { createLogger } from './logger.js'
41
+ import { PathHashTrustLedger } from './path-hash-trust-ledger.js'
42
+ import { configPath } from './config-dir.js'
43
+
44
+ const log = createLogger('binary-provenance-trust')
45
+
46
+ export function defaultBinaryTrustFile() {
47
+ return configPath('binary-trust.json')
48
+ }
49
+
50
+ /**
51
+ * Normalise a ledger key for storage / lookup. On case-insensitive filesystems
52
+ * (macOS APFS, Windows NTFS) the same binary can resolve to different casings,
53
+ * so keys are lowercased there; on case-sensitive Linux the key is kept verbatim.
54
+ * Mirrors the skills/preset stores' normaliser (kept local per the base-ledger
55
+ * convention that each subclass owns its own key hook).
56
+ *
57
+ * @param {string} absPath
58
+ * @returns {string}
59
+ */
60
+ export function _normalizeKey(absPath) {
61
+ if (typeof absPath !== 'string') return ''
62
+ return (process.platform === 'darwin' || process.platform === 'win32')
63
+ ? absPath.toLowerCase()
64
+ : absPath
65
+ }
66
+
67
+ /**
68
+ * In-memory + on-disk pin ledger for spawned provider binaries. One instance per
69
+ * daemon, constructed by SessionManager; that SAME instance is threaded into the
70
+ * tunnel config (server-cli.js → `binaryProvenance.ledger`) so the cloudflared
71
+ * gate and the provider spawns share one ledger and one set of pins — no second
72
+ * instance. Tests pass an explicit `filePath` so they never touch the real ledger.
73
+ */
74
+ export class BinaryProvenanceLedger extends PathHashTrustLedger {
75
+ /**
76
+ * @param {{ filePath?: string }} [opts]
77
+ */
78
+ constructor({ filePath } = {}) {
79
+ super({
80
+ filePath: filePath || defaultBinaryTrustFile(),
81
+ log,
82
+ normalizeKey: _normalizeKey,
83
+ approvalField: 'approvedAt',
84
+ wrapperKey: 'binaries',
85
+ throwOnFlushError: false, // best-effort: a read-only $HOME never breaks spawning
86
+ extraFields: ['kind'], // #8040: 'file' | 'tree' — see verify-provenance.js
87
+ })
88
+ const loaded = this._loadRecords()
89
+ this._records = loaded.records
90
+ this._dirty = false
91
+ }
92
+ }
93
+
94
+ // Helper so tests / callers can confirm the ledger file exists.
95
+ export function binaryTrustFileExists(filePath) {
96
+ try {
97
+ return existsSync(filePath)
98
+ } catch {
99
+ return false
100
+ }
101
+ }
@@ -0,0 +1,279 @@
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
+ submit_mcp_auth_code: 'stores a credential shared by every session using the server',
133
+ list_providers: 'host-wide configuration status',
134
+ byok_get_credentials_status: 'host-wide credential status',
135
+ get_credentials_status: 'host-wide credential status',
136
+ byok_set_credentials: 'host-wide credentials',
137
+ byok_clear_credentials: 'host-wide credentials',
138
+ set_credential: 'host-wide credentials',
139
+ delete_credential: 'host-wide credentials',
140
+ test_credential: 'uses a host-wide credential',
141
+ skill_trust_accept: 'host-wide skill trust',
142
+ skill_trust_grant: 'host-wide skill trust',
143
+ github_webhook_config_request: 'host-wide configuration',
144
+ github_webhook_set_secret: 'host-wide configuration',
145
+ github_webhook_clear_secret: 'host-wide configuration',
146
+ notification_prefs_get: 'host-wide notification settings',
147
+ notification_prefs_set: 'host-wide notification settings',
148
+ session_preset_get: 'host-wide presets',
149
+ session_preset_set: 'host-wide presets',
150
+ session_preset_approve: 'host-wide presets',
151
+ session_preset_revoke: 'host-wide presets',
152
+ daemon_update_action: 'host lifecycle',
153
+ revoke_token: 'credential management',
154
+ pair_approve: 'credential management',
155
+ pair_deny: 'credential management',
156
+
157
+ // -- repositories, directories, workspace mutation --
158
+ list_repos: 'host-wide repository inventory',
159
+ add_repo: 'host-wide repository configuration',
160
+ remove_repo: 'host-wide repository configuration',
161
+ list_directory: 'enumerates directories outside the bound session',
162
+ check_git_repo: 'probes arbitrary host directories',
163
+ write_file: 'mutates the workspace',
164
+ append_memory: 'mutates the workspace',
165
+ git_stage: 'mutates the workspace',
166
+ git_unstage: 'mutates the workspace',
167
+ git_commit: 'mutates the workspace',
168
+ git_create_pr: 'mutates the workspace and the remote',
169
+ restore_checkpoint: 'rewrites the workspace, which other sessions may share',
170
+
171
+ // -- web tasks, previews, environments --
172
+ launch_web_task: 'starts independent execution',
173
+ teleport_web_task: 'starts independent execution',
174
+ list_web_tasks: 'tasks carry no owning session',
175
+ open_dev_preview: 'publishes a host service',
176
+ close_dev_preview: 'host service lifecycle',
177
+ create_environment: 'host-wide environments',
178
+ list_environments: 'host-wide environments',
179
+ destroy_environment: 'host-wide environments',
180
+ get_environment: 'host-wide environments',
181
+
182
+ // -- control room, orchestration, scheduling --
183
+ host_status_request: 'host-wide survey',
184
+ runner_status_request: 'host-wide survey',
185
+ containers_status_request: 'host-wide survey',
186
+ repo_runtime_config_request: 'host-wide survey',
187
+ byok_pool_status_request: 'host-wide survey',
188
+ host_prune_status_request: 'host-wide survey',
189
+ simulator_status_request: 'host-wide survey',
190
+ emulator_status_request: 'host-wide survey',
191
+ wsl_status_request: 'host-wide survey',
192
+ integration_status_request: 'host-wide survey',
193
+ skills_inventory_request: 'host-wide survey',
194
+ mailbox_status_request: 'host-wide survey',
195
+ external_sessions_request: 'host-wide survey',
196
+ repo_events_request: 'host-wide survey',
197
+ containers_action: 'host-wide action',
198
+ byok_pool_action: 'host-wide action',
199
+ host_prune_action: 'host-wide action',
200
+ simulator_action: 'host-wide action',
201
+ emulator_action: 'host-wide action',
202
+ wsl_action: 'host-wide action',
203
+ integration_action: 'host-wide action',
204
+ orchestration_runs_request: 'host-wide runs',
205
+ orchestration_run_detail_request: 'host-wide runs',
206
+ orchestration_run_start: 'host-wide runs',
207
+ orchestration_gate_response: 'host-wide runs',
208
+ orchestration_run_action: 'host-wide runs',
209
+ orchestration_run_annotate: 'host-wide runs',
210
+ scheduled_tasks_request: 'host-wide schedule',
211
+ scheduled_task_action: 'host-wide schedule',
212
+ set_scheduler_enabled: 'host-wide schedule',
213
+ })
214
+
215
+ /**
216
+ * May a session-scoped connection use this message type? Closed by default:
217
+ * only an explicit allowed entry passes, and own-property lookup keeps
218
+ * `__proto__` / `constructor` style type strings from matching.
219
+ * @param {unknown} type
220
+ * @returns {boolean}
221
+ */
222
+ export function isBoundAllowedMessageType(type) {
223
+ return typeof type === 'string' && Object.hasOwn(BOUND_ALLOWED_MESSAGE_TYPES, type)
224
+ }
225
+
226
+ /** The one refusal text for a request a session-scoped connection may not make. */
227
+ export const BOUND_REFUSAL_MESSAGE = 'Not available to a session-scoped connection'
228
+
229
+ const MAX_ECHOED_LENGTH = 128
230
+
231
+ /**
232
+ * Send the one refusal reply to a session-scoped connection. The decision is
233
+ * the caller's; use `refuseBoundMessage` to decide by the allowlist.
234
+ *
235
+ * The reply names only the connection's own session. `requestType` and
236
+ * `requestId` are echoed only when they are strings of at most
237
+ * MAX_ECHOED_LENGTH characters; anything else is dropped, not truncated (a
238
+ * truncated id cannot correlate with the request).
239
+ *
240
+ * @param {WebSocket} ws
241
+ * @param {object} client
242
+ * @param {object} msg
243
+ * @param {object} ctx
244
+ */
245
+ export function sendBoundRefusal(ws, client, msg, ctx) {
246
+ const type = msg?.type
247
+ log.info(`Session-scoped client ${client?.id} refused message type ${loggableValue(type)}`)
248
+ ctx.transport.send(ws, {
249
+ type: 'session_error',
250
+ ...buildSessionTokenMismatchPayload({
251
+ sessionManager: ctx.sessions?.sessionManager,
252
+ boundSessionId: client?.boundSessionId,
253
+ message: BOUND_REFUSAL_MESSAGE,
254
+ }),
255
+ ...(typeof type === 'string' && type.length <= MAX_ECHOED_LENGTH ? { requestType: type } : {}),
256
+ ...(typeof msg?.requestId === 'string' && msg.requestId.length <= MAX_ECHOED_LENGTH ? { requestId: msg.requestId } : {}),
257
+ })
258
+ }
259
+
260
+ /**
261
+ * The single place the allowlist is applied to a session-scoped connection's
262
+ * request. Returns true when `msg` was refused (and replied to), false when the
263
+ * connection may use it. A missing or non-string `type` is refused.
264
+ *
265
+ * ws-server calls this before schema validation so a malformed denied request
266
+ * is refused rather than answered with a schema error, and handleSessionMessage
267
+ * calls it again as the dispatch gate. The refusal has no other effect.
268
+ *
269
+ * @param {WebSocket} ws
270
+ * @param {object} client
271
+ * @param {object} msg
272
+ * @param {object} ctx
273
+ * @returns {boolean}
274
+ */
275
+ export function refuseBoundMessage(ws, client, msg, ctx) {
276
+ if (!isBoundClient(client) || isBoundAllowedMessageType(msg?.type)) return false
277
+ sendBoundRefusal(ws, client, msg, ctx)
278
+ return true
279
+ }
@@ -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)