@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,1645 @@
1
+ /**
2
+ * agent-control: a provider-neutral client for chroxy's existing authenticated
3
+ * WebSocket protocol, built for an EXTERNAL AGENT HARNESS (Codex, Claude,
4
+ * Gemini, …) driving an ordinary chroxy session — not a new control plane.
5
+ *
6
+ * This is deliberately a THIN client over the protocol chroxy already ships:
7
+ * - Auth + E2E encryption: `packages/server/src/ws-auth.js` +
8
+ * `@chroxy/store-core/crypto` (see docs/security/encryption-threat-model.md).
9
+ * - Token authority: `packages/server/src/ws-server.js` /
10
+ * docs/security/bearer-token-authority.md — this client never widens what
11
+ * the presented token is allowed to do; the SERVER enforces authority.
12
+ * - Correlated input admission: `packages/server/src/handlers/input-handlers.js`
13
+ * (#7822's `input_ack` contract) — this client negotiates
14
+ * `input_context_v1` and reports the ack exactly as the server sent it.
15
+ * - Permission relay: `handlePermissionResponse`
16
+ * (`packages/server/src/handlers/settings-handlers.js`) — `respondPermission`
17
+ * sends only `allow`/`deny` (never `allowAlways`, which persists a durable
18
+ * project rule — out of scope for an external planner relay) for a
19
+ * permission this client has itself observed as pending and owns, and
20
+ * never `allow` for one the daemon marked (or failed to mark, #7968)
21
+ * `floored: true`/absent — see `respondPermission`'s doc comment.
22
+ *
23
+ * Ownership (`_ownedSessions`, `_ownershipRejection`) gates every mutation
24
+ * that targets an EXISTING session — `sendInput`, `interrupt`, and
25
+ * `respondPermission` — the same way for all three: only a session created
26
+ * by THIS process via `createSession` may be mutated. Observing any session
27
+ * this connection is subscribed to (`getEvents`) is unrestricted; only
28
+ * mutating one this process did not create is refused.
29
+ *
30
+ * It does NOT introduce a second scheduler, task database, token class, or
31
+ * mailbox store. Durable task/handoff identity across daemon restarts is
32
+ * #7823's job, not this client's; a universal mailbox is #7437's; in-daemon
33
+ * orchestration is epic #6691's. See docs/guides/agent-control.md for how
34
+ * this connects to (without duplicating) each of those.
35
+ *
36
+ * Design contract this file holds itself to:
37
+ * - Never log, throw, or return the bearer token in any error message,
38
+ * event, or generated text.
39
+ * - Never silently retry a MUTATION (`createSession` / `sendInput` /
40
+ * `interrupt` / `respondPermission`) after a timeout or disconnect — an
41
+ * uncertain outcome is returned/reported as uncertain, not retried and
42
+ * not reported as success.
43
+ * - Never infer task completion from a socket closing, `agent_idle`, or the
44
+ * presence of a `result` message — those are exposed as events for the
45
+ * caller to interpret, never collapsed into a synthetic "done".
46
+ * - Bound every wait (connect, request/response, event long-poll) so a
47
+ * hung daemon cannot hang the caller forever.
48
+ * - Never let this process crash on a transport error — an internal
49
+ * default listener backstops every EventEmitter-special 'error' emission.
50
+ */
51
+ import { EventEmitter } from 'node:events'
52
+ import { randomUUID } from 'node:crypto'
53
+ import WebSocket from 'ws'
54
+ import {
55
+ createKeyPair,
56
+ deriveSharedKey,
57
+ deriveConnectionKey,
58
+ generateConnectionSalt,
59
+ encrypt,
60
+ decrypt,
61
+ verifyExchangeKeySignature,
62
+ DIRECTION_SERVER,
63
+ DIRECTION_CLIENT,
64
+ } from '@chroxy/store-core/crypto'
65
+ import { SessionEventLog, StreamAccumulator, classifyBroadcast, DEFAULT_RETENTION, MAX_WAIT_MS } from './events.js'
66
+ import { redactValue, SENSITIVE_KEY_NAMES } from '../redaction.js'
67
+ // #7973 / #7975 (S3) — the SAME exclusion/allow sets the daemon defines,
68
+ // imported (never hand-rolled as a second list) so `respondPermission` cannot
69
+ // drift from permission-manager.js's own idea of "never auto-allow"/"carries
70
+ // an arbitrary command"/"the floor can actually see this tool's paths". Each
71
+ // is re-exported below so a test can assert import IDENTITY (not just equal
72
+ // values) between what this client uses and the canonical export — see
73
+ // permission-manager.js's doc comments for the full rationale, including the
74
+ // #7975 fix to autoAllowPending's parallel use of NOT_DELEGABLE_TOOLS.
75
+ import { NOT_DELEGABLE_TOOLS, COMMAND_TOOLS, FLOOR_ALLOWLISTED_TOOLS } from '../permission-manager.js'
76
+
77
+ export { NOT_DELEGABLE_TOOLS, COMMAND_TOOLS, FLOOR_ALLOWLISTED_TOOLS }
78
+
79
+ export const PROTOCOL_CAPABILITY_INPUT_CONTEXT = 'input_context_v1'
80
+ export const DEFAULT_CONNECT_TIMEOUT_MS = 10_000
81
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 15_000
82
+ export const DEFAULT_INTERRUPT_GRACE_MS = 2_000
83
+ const ALLOWED_PERMISSION_DECISIONS = new Set(['allow', 'deny'])
84
+ // A caller-supplied `clientMessageId` (for a deliberate dedup retry) must
85
+ // match the CANONICAL wire rule the daemon itself enforces — see
86
+ // `InputContextEnvelopeSchema`'s superRefine in
87
+ // `packages/protocol/src/schemas/client.ts` (`/^[A-Za-z0-9_-]{1,128}$/`,
88
+ // reserved: 'thinking'/'pending'/'queued') and the same 128-char cap in
89
+ // `handlers/input-handlers.js`. Anything looser here would let this client
90
+ // accept an id the daemon then rejects or reinterprets, breaking ack
91
+ // correlation. A few extra reserved values are added defensively — being
92
+ // stricter than the wire schema is safe, being looser is not.
93
+ export const CLIENT_MESSAGE_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/
94
+ export const RESERVED_CLIENT_MESSAGE_IDS = new Set(['thinking', 'pending', 'queued', 'null', 'undefined', '__proto__', 'constructor', 'prototype'])
95
+
96
+ // (kind of the one in-flight uncorrelated op) -> the reply type(s) that
97
+ // satisfy it. `list_sessions`/`create_session`/`subscribe_sessions` have NO
98
+ // requestId on the wire, so this connection serializes them (see
99
+ // `_runSerial`) and matches strictly by kind -> allowed reply type, never by
100
+ // "any reply of a type ANY pending kind might accept" (that OR-precedence
101
+ // bug let a stray `session_list` broadcast satisfy a pending `create_session`
102
+ // op).
103
+ const SERIAL_REPLY_TYPES = {
104
+ list_sessions: ['session_list'],
105
+ create_session: ['session_switched', 'session_error'],
106
+ subscribe_sessions: ['subscriptions_updated'],
107
+ }
108
+
109
+ // Broadcast types worth preserving even when they arrive DURING the
110
+ // handshake/startup fence (before this connection is "ready") — see
111
+ // `_dispatch`'s pre-ready buffer. Deliberately narrow: a `permission_request`
112
+ // for an already-pending permission is real state this client must not lose,
113
+ // not "login replay noise" to discard along with everything else the fence
114
+ // exists to drain. Its two terminal counterparts are buffered too, so a
115
+ // request that is resolved/expired inside the same pre-ready window is
116
+ // replayed in order and does not flush as still-pending.
117
+ //
118
+ // Buffered frames are NOT trusted on arrival: each carries whether it
119
+ // arrived under the connection key, and the flush discards the unencrypted
120
+ // ones when the daemon turned out to require encryption (see `connect()`).
121
+ const PRE_READY_BUFFERED_TYPES = new Set(['permission_request', 'permission_resolved', 'permission_expired'])
122
+ const MAX_PRE_READY_BUFFER = 100
123
+
124
+ /** A mutation was requested while the client is in read-only mode. */
125
+ export class ReadOnlyModeError extends Error {
126
+ constructor(operation) {
127
+ super(`agent-control client is read-only: '${operation}' is not permitted`)
128
+ this.name = 'ReadOnlyModeError'
129
+ this.code = 'READ_ONLY_MODE'
130
+ this.operation = operation
131
+ }
132
+ }
133
+
134
+ /** The daemon rejected authentication, key exchange, or identity pinning. */
135
+ export class ConnectionRefusedError extends Error {
136
+ constructor(reason, message) {
137
+ super(message || reason)
138
+ this.name = 'ConnectionRefusedError'
139
+ this.code = reason
140
+ }
141
+ }
142
+
143
+ /** A bounded wait (connect / request / handshake) elapsed with no reply. */
144
+ export class TimeoutError extends Error {
145
+ constructor(what, ms) {
146
+ super(`timed out after ${ms}ms waiting for: ${what}`)
147
+ this.name = 'TimeoutError'
148
+ this.code = 'TIMEOUT'
149
+ }
150
+ }
151
+
152
+ /** Sent while not connected/ready, or the socket dropped mid-request. */
153
+ export class NotConnectedError extends Error {
154
+ constructor(detail) {
155
+ super(detail || 'agent-control client is not connected')
156
+ this.name = 'NotConnectedError'
157
+ this.code = 'NOT_CONNECTED'
158
+ }
159
+ }
160
+
161
+ function noopLogger() {}
162
+
163
+ function stderrLogger(...args) {
164
+ // MCP stdio requires stdout to carry ONLY JSON-RPC frames — every log line
165
+ // from this client (and anything it wraps) must go to stderr, never stdout.
166
+ console.error('[agent-control]', ...args)
167
+ }
168
+
169
+ /**
170
+ * Replace every exact occurrence of `token` in `text` with a placeholder.
171
+ * This is deliberately EXACT-match, not a heuristic "looks like a secret"
172
+ * pattern — the one value this client actually knows is a secret is its own
173
+ * bearer token, and an exact match can never false-negative on it the way a
174
+ * shape-based heuristic could. Defense in depth: normal operation never
175
+ * embeds the token in a server-supplied string, but a compromised/buggy
176
+ * daemon echoing it back (e.g. in an `auth_fail` reason) must not leak it
177
+ * back out through this client's errors/logs/tool results.
178
+ */
179
+ export function redactToken(text, token) {
180
+ if (typeof text !== 'string' || typeof token !== 'string' || !token) return text
181
+ return text.split(token).join('[REDACTED_TOKEN]')
182
+ }
183
+
184
+ export function redactPublicText(text, token) {
185
+ return redactValue(redactToken(String(text), token))
186
+ }
187
+
188
+ /**
189
+ * @typedef {object} AgentControlClientOptions
190
+ * @property {string} url - `ws://` or `wss://` daemon URL. Never inferred here.
191
+ * @property {string} token - bearer token. Held in memory only; never logged.
192
+ * @property {boolean} [readOnly] - when true, every mutating method throws
193
+ * synchronously before any network I/O.
194
+ * @property {number} [connectTimeoutMs]
195
+ * @property {number} [requestTimeoutMs]
196
+ * @property {number} [eventRetention] - per-session ring buffer size.
197
+ * @property {boolean} [includeThinking] - forward thinking-stream text into
198
+ * the event log (default false — see events.js doc comment).
199
+ * @property {string} [identityPublicKey] - base64 Ed25519 daemon identity
200
+ * public key to PIN (see docs/security/encryption-threat-model.md §3.1).
201
+ * When set, a handshake that lacks a valid signature over the offered
202
+ * exchange key — or offers plaintext — is refused, never silently accepted.
203
+ * @property {string} [deviceName]
204
+ * @property {Map} [modelExpectations] - injection seam so a caller managing
205
+ * reconnects (multiple client instances over time) can carry model
206
+ * expectations across them; defaults to a fresh, connection-local Map.
207
+ * @property {Set<string>} [ownedSessions] - same injection seam for the set
208
+ * of session ids this process created (the only sessions whose permission
209
+ * prompts `respondPermission` answers); defaults to a fresh Set.
210
+ * @property {boolean} [allowCommandApprovals] - #7973: when true, `allow` is
211
+ * permitted for a command-style tool (`COMMAND_TOOLS` — Bash, PowerShell, Monitor, codex shell), still
212
+ * subject to the floored/ownership gates. Default false: `allow` for one of
213
+ * these is refused with `reason: 'command_approval_disabled'` — the
214
+ * protected-path floor cannot see through an arbitrary command string, so
215
+ * `floored: false` on a Bash prompt does not mean the command is safe.
216
+ * @property {(...args: unknown[]) => void} [log] - defaults to a stderr logger.
217
+ * @property {typeof WebSocket} [WebSocketImpl] - injection seam for tests.
218
+ */
219
+
220
+ export class AgentControlClient extends EventEmitter {
221
+ /** @param {AgentControlClientOptions} opts */
222
+ constructor(opts = {}) {
223
+ super()
224
+ if (!opts.url) throw new Error('AgentControlClient requires opts.url')
225
+ if (!opts.token) throw new Error('AgentControlClient requires opts.token')
226
+
227
+ // EventEmitter throws if 'error' is emitted with zero listeners. This
228
+ // client legitimately needs to report transport failures via 'error' for
229
+ // callers that want them, but a caller that doesn't attach a listener
230
+ // must never crash the host process for it — this permanent internal
231
+ // listener is the backstop. It does NOT suppress the event from other
232
+ // listeners; it only satisfies Node's "at least one" requirement.
233
+ this.on('error', () => {})
234
+
235
+ this._url = opts.url
236
+ this._token = opts.token
237
+ this.readOnly = opts.readOnly === true
238
+ this._connectTimeoutMs = opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS
239
+ this._requestTimeoutMs = opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS
240
+ this._pinnedIdentityKey = opts.identityPublicKey || null
241
+ this._deviceName = opts.deviceName || 'chroxy-agent-control'
242
+ const rawLog = opts.log || (opts.silent ? noopLogger : stderrLogger)
243
+ // Every log line is redacted for the token before it reaches the raw
244
+ // logger — see `redactToken`'s doc comment.
245
+ this._log = (...args) => rawLog(...args.map((a) => redactPublicText(a, this._token)))
246
+ this._WebSocket = opts.WebSocketImpl || WebSocket
247
+
248
+ this._state = 'idle' // idle -> connecting -> ready -> closed
249
+ this._ws = null
250
+ this._encryptionState = null // { sharedKey, sendNonce, recvNonce }
251
+ this._encryptionRequired = null
252
+ this._daemonMeta = null
253
+
254
+ this._eventLog = new SessionEventLog({ retention: opts.eventRetention ?? DEFAULT_RETENTION })
255
+ this._streamAccumulator = new StreamAccumulator()
256
+ this._includeThinking = opts.includeThinking === true
257
+ this._replayingSessions = new Set()
258
+ this._subscribedSessionIds = new Set()
259
+
260
+ // clientMessageId -> { resolve, timer, sessionId, lastKnown }
261
+ this._pendingInputAcks = new Map()
262
+ // requestId -> { sessionId, resolve, timer }
263
+ this._pendingPermissionResponses = new Map()
264
+ // requestId -> { sessionId, seenAt } — permissions THIS client has
265
+ // observed as pending, from `permission_request` broadcasts. A
266
+ // `respondPermission` call for any other requestId is refused before any
267
+ // network I/O — "only answer a still-observed, session-owned pending
268
+ // permission".
269
+ this._observedPermissions = new Map()
270
+
271
+ // one in-flight "uncorrelated" op (list_sessions / create_session /
272
+ // subscribe_sessions) at a time on this connection — see SERIAL_REPLY_TYPES.
273
+ this._serialQueue = Promise.resolve()
274
+ this._pendingSerialOp = null // { kind, resolve, reject, timer }
275
+ // management requests in flight (`request()`): each entry settles one with an error
276
+ this._pendingRequests = new Set()
277
+
278
+ // sessionId -> { requestedModel: string|null, lastKnownStatus }. Accepts
279
+ // an INJECTED Map so a caller managing reconnects across multiple
280
+ // AgentControlClient instances (see mcp-server.js's ClientManager) can
281
+ // pass the SAME Map through each reconnect — a model expectation
282
+ // recorded by `createSession` on a connection that later drops must not
283
+ // evaporate just because the transport reconnected within the same
284
+ // process; it has nothing to do with the connection's own lifetime.
285
+ this._modelExpectations = opts.modelExpectations instanceof Map ? opts.modelExpectations : new Map()
286
+
287
+ // Session ids THIS process created via `createSession` — the only
288
+ // sessions whose permission prompts `respondPermission` will answer.
289
+ // Injectable for the same reason as `modelExpectations`: ownership is a
290
+ // property of the planner process, not of one transport connection, so
291
+ // ClientManager passes one Set through every reconnect.
292
+ this._ownedSessions = opts.ownedSessions instanceof Set ? opts.ownedSessions : new Set()
293
+
294
+ // #7973 — see the typedef above. Read once at construction; the CLI's
295
+ // startup warning is the operator-facing signal that this is enabled, not
296
+ // a per-call log line.
297
+ this.allowCommandApprovals = opts.allowCommandApprovals === true
298
+
299
+ // Handshake-phase waiters that must be aborted immediately (not left to
300
+ // time out) if the socket closes/errors before the handshake completes.
301
+ this._handshakeAbortListeners = new Set()
302
+ // Bounded buffer of state-bearing broadcasts seen during the handshake —
303
+ // see PRE_READY_BUFFERED_TYPES / `_dispatch`.
304
+ this._preReadyBuffer = []
305
+ }
306
+
307
+ get state() {
308
+ return this._state
309
+ }
310
+
311
+ /** Safe, bounded metadata about the daemon — never the raw auth_ok/connection.json. */
312
+ get daemonInfo() {
313
+ if (!this._daemonMeta) return null
314
+ return { ...this._daemonMeta }
315
+ }
316
+
317
+ // ---------------------------------------------------------------------
318
+ // Connect / handshake
319
+ // ---------------------------------------------------------------------
320
+
321
+ async connect() {
322
+ if (this._state !== 'idle') {
323
+ throw new Error(`connect() called in state '${this._state}' — a client is single-use per connection`)
324
+ }
325
+ this._state = 'connecting'
326
+
327
+ const overallDeadline = Date.now() + this._connectTimeoutMs
328
+ const timeLeft = () => Math.max(0, overallDeadline - Date.now())
329
+
330
+ const ws = new this._WebSocket(this._url)
331
+ this._ws = ws
332
+ ws.on('message', (raw) => this._onRawMessage(raw))
333
+ ws.on('close', (code, reason) => this._onSocketClosed(code, reason))
334
+ ws.on('error', (err) => this._onSocketError(err))
335
+
336
+ try {
337
+ await this._waitForOpen(ws, timeLeft())
338
+
339
+ const clientKp = createKeyPair()
340
+ const salt = generateConnectionSalt()
341
+
342
+ this._sendPlain({
343
+ type: 'auth',
344
+ token: this._token,
345
+ deviceInfo: {
346
+ deviceName: this._deviceName,
347
+ deviceType: 'desktop',
348
+ platform: process.platform,
349
+ },
350
+ capabilities: [PROTOCOL_CAPABILITY_INPUT_CONTEXT],
351
+ // Eager key exchange (#5555) — fold our half of the handshake into
352
+ // `auth` so an encrypting daemon can reply in the SAME auth_ok frame
353
+ // instead of a second round trip. A daemon that doesn't support this
354
+ // simply ignores the extra fields and we fall back to the discrete
355
+ // `key_exchange` path below.
356
+ eagerPublicKey: clientKp.publicKey,
357
+ eagerSalt: salt,
358
+ })
359
+
360
+ // `onMatch` runs SYNCHRONOUSLY inside the message-received callback,
361
+ // before this awaited promise's continuation gets a chance to run as a
362
+ // microtask. This matters: the underlying `ws` library can emit
363
+ // several 'message' events synchronously, back-to-back in the SAME
364
+ // call stack, for frames that arrived coalesced in one TCP read (e.g.
365
+ // auth_ok immediately followed by the post-auth encrypted flush). If
366
+ // key derivation happened only AFTER `await`, a coalesced encrypted
367
+ // frame could be processed before `_encryptionState` was set and get
368
+ // silently dropped. Deriving inside `onMatch` closes that window.
369
+ await this._waitForOneOf(['auth_ok', 'auth_fail'], timeLeft(), {
370
+ onMatch: (msg) => {
371
+ if (msg.type === 'auth_fail') {
372
+ // `reason` is SERVER-supplied. Redact our own token from it
373
+ // before it becomes an Error message a caller might log/print —
374
+ // a buggy or compromised daemon echoing it back must not leak it
375
+ // back out through this client.
376
+ const reason = redactPublicText(msg.reason || 'unknown reason', this._token)
377
+ throw new ConnectionRefusedError('AUTH_FAILED', `daemon rejected authentication: ${reason}`)
378
+ }
379
+ this._encryptionRequired = msg.encryption === 'required'
380
+ this._daemonMeta = this._buildDaemonMeta(msg)
381
+
382
+ if (this._pinnedIdentityKey && !this._encryptionRequired) {
383
+ // Mirrors the server's own #5614 gate: a pinned client must never
384
+ // be routed onto a plaintext connection, even if auth_ok claims
385
+ // one is fine — that is exactly the downgrade #5614 closes
386
+ // server-side.
387
+ throw new ConnectionRefusedError('IDENTITY_PIN_REQUIRES_ENCRYPTION', 'a pinned daemon identity requires encryption; the daemon offered none — refusing (possible downgrade)')
388
+ }
389
+
390
+ if (this._encryptionRequired && typeof msg.serverPublicKey === 'string' && msg.serverPublicKey) {
391
+ // Eager path completed in this same frame.
392
+ this._verifyPinIfConfigured(msg.serverPublicKey, msg.serverKeySig)
393
+ const raw = deriveSharedKey(msg.serverPublicKey, clientKp.secretKey)
394
+ this._encryptionState = { sharedKey: deriveConnectionKey(raw, salt), sendNonce: 0, recvNonce: 0 }
395
+ return { eager: true }
396
+ }
397
+ return { eager: false }
398
+ },
399
+ })
400
+
401
+ if (this._encryptionRequired && !this._encryptionState) {
402
+ // Discrete fallback — daemon didn't fold the eager fields into
403
+ // auth_ok. Send the documented key_exchange message and wait for
404
+ // key_exchange_ok, deriving the key synchronously in `onMatch` for
405
+ // the same coalesced-frame reason as above.
406
+ // Construct the waiter FIRST (its Promise executor registers the
407
+ // '_handshake' listener synchronously) and only THEN send — sending
408
+ // before awaiting is fine (no `await` happens in between, so the
409
+ // event loop cannot deliver a reply before the listener exists
410
+ // either way), but awaiting before sending would deadlock until the
411
+ // timeout, since nothing would ever trigger the reply.
412
+ const kePromise = this._waitForOneOf(['key_exchange_ok'], timeLeft(), {
413
+ onMatch: (keOk) => {
414
+ if (typeof keOk.publicKey !== 'string' || !keOk.publicKey) {
415
+ throw new ConnectionRefusedError('MALFORMED_KEY_EXCHANGE', 'key_exchange_ok missing a valid publicKey')
416
+ }
417
+ this._verifyPinIfConfigured(keOk.publicKey, keOk.serverKeySig)
418
+ const raw = deriveSharedKey(keOk.publicKey, clientKp.secretKey)
419
+ this._encryptionState = { sharedKey: deriveConnectionKey(raw, salt), sendNonce: 0, recvNonce: 0 }
420
+ },
421
+ })
422
+ this._sendPlain({ type: 'key_exchange', publicKey: clientKp.publicKey, salt })
423
+ await kePromise
424
+ } else if (this._pinnedIdentityKey && !this._encryptionRequired) {
425
+ // Unreachable given the gate above, kept as defense-in-depth.
426
+ throw new ConnectionRefusedError('IDENTITY_PIN_REQUIRES_ENCRYPTION', 'refusing unencrypted connection with a pinned identity configured')
427
+ }
428
+
429
+ // Startup fence (#7822-adjacent hardening): drain whatever the daemon
430
+ // already queued to send right after auth (session replay, an initial
431
+ // session_switched for a default session, etc.) before this client is
432
+ // considered "ready" and before any correlated request can be issued.
433
+ // A `ping`/`pong` round trip is ordered on the same connection, so by
434
+ // the time `pong` arrives every message the daemon had already queued
435
+ // ahead of it has been delivered. Messages seen during the fence are
436
+ // NOT dispatched into the event log or serial-op correlation — they
437
+ // predate any request this client will ever make.
438
+ const pongPromise = this._waitForOneOf(['pong'], timeLeft())
439
+ this._send({ type: 'ping' })
440
+ await pongPromise
441
+
442
+ this._state = 'ready'
443
+ this._eventLog.reset()
444
+ this._streamAccumulator.clear()
445
+ // Flush anything the fence buffered (see PRE_READY_BUFFERED_TYPES)
446
+ // through the SAME path a live message takes, now that `reset()` has
447
+ // minted the fresh epoch they'll be recorded under.
448
+ //
449
+ // A daemon that requires encryption sends every application frame
450
+ // under the connection key (eager: from the frame after auth_ok;
451
+ // discrete: nothing until key_exchange_ok), so a PLAINTEXT application
452
+ // frame buffered during the handshake did not come from the daemon we
453
+ // authenticated — it is an on-path injection (the pre-auth_ok window,
454
+ // or the discrete key-exchange window). Identity pinning authenticates
455
+ // the exchange key, not frames that were never under it; recording
456
+ // such a frame as an observed permission would let an injector plant a
457
+ // request (with a description of its choosing) that this client would
458
+ // then answer. Drop it instead.
459
+ const buffered = this._preReadyBuffer
460
+ this._preReadyBuffer = []
461
+ for (const { msg, authenticated } of buffered) {
462
+ if (this._encryptionRequired && !authenticated) {
463
+ this._log(`dropping a plaintext '${msg.type}' frame received before the encrypted handshake completed — not authenticated by the daemon`)
464
+ continue
465
+ }
466
+ this._trackPermissionObservation(msg)
467
+ this._processReadyMessage(msg)
468
+ }
469
+ this.emit('ready', this.daemonInfo)
470
+ } catch (err) {
471
+ this._state = 'error'
472
+ try { ws.close() } catch { /* already closing/closed */ }
473
+ throw this._safeError(err)
474
+ }
475
+ }
476
+
477
+ _verifyPinIfConfigured(offeredPublicKey, sig) {
478
+ if (!this._pinnedIdentityKey) return
479
+ if (typeof sig !== 'string' || !sig) {
480
+ throw new ConnectionRefusedError('IDENTITY_UNSIGNED', 'server identity is pinned but the daemon offered no signature over its exchange key — refusing (possible downgrade or impersonation)')
481
+ }
482
+ const ok = verifyExchangeKeySignature(offeredPublicKey, sig, this._pinnedIdentityKey)
483
+ if (!ok) {
484
+ throw new ConnectionRefusedError('IDENTITY_MISMATCH', 'server identity signature does not match the pinned identity — refusing (server identity changed)')
485
+ }
486
+ }
487
+
488
+ _buildDaemonMeta(authOk) {
489
+ // Deliberately an ALLOWLIST, not a forward of the raw auth_ok frame —
490
+ // auth_ok can carry a bootstrap burst (providers, slash commands,
491
+ // agents, tunnelUrl) that is more than "safe version/capability
492
+ // metadata" and is not this tool's business to redistribute. Same for
493
+ // `capabilities`: only the specific boolean flags a planner might
494
+ // legitimately want to know about (e.g. "does this daemon support
495
+ // input_context_v1 at all") are copied, by name, as booleans.
496
+ const rawCaps = authOk.capabilities && typeof authOk.capabilities === 'object' ? authOk.capabilities : {}
497
+ const safeString = value => typeof value === 'string' ? redactPublicText(value, this._token).slice(0, 512) : null
498
+ return {
499
+ serverVersion: safeString(authOk.serverVersion),
500
+ latestVersion: safeString(authOk.latestVersion),
501
+ protocolVersion: typeof authOk.protocolVersion === 'number' && Number.isFinite(authOk.protocolVersion) ? authOk.protocolVersion : safeString(authOk.protocolVersion),
502
+ serverCommit: safeString(authOk.serverCommit),
503
+ serverMode: safeString(authOk.serverMode),
504
+ encryption: safeString(authOk.encryption) ?? 'disabled',
505
+ connectedClients: typeof authOk.connectedClients === 'number' && Number.isFinite(authOk.connectedClients) ? authOk.connectedClients : null,
506
+ capabilities: {
507
+ inputContextV1: rawCaps.inputContextV1 === true,
508
+ createRequestIdV1: rawCaps.createRequestIdV1 === true,
509
+ },
510
+ }
511
+ }
512
+
513
+ async close() {
514
+ if (this._state === 'closed') return
515
+ this._state = 'closed'
516
+ this._teardownConnectionState()
517
+ this._abortHandshakeWaiters(new NotConnectedError('client closed'))
518
+ this._rejectAllPending(new NotConnectedError('client closed'))
519
+ if (this._ws) {
520
+ try { this._ws.close() } catch { /* already closed */ }
521
+ }
522
+ this._ws = null
523
+ }
524
+
525
+ // ---------------------------------------------------------------------
526
+ // Public API
527
+ // ---------------------------------------------------------------------
528
+
529
+ /**
530
+ * Send one correlated management request and resolve with the first `replyType`
531
+ * frame that echoes its `requestId` (#9116: `chroxy agent ...` asks the daemon, which
532
+ * is the only writer of the principal store). Bounded by the request timeout; never
533
+ * retried, so an uncertain outcome is reported as uncertain.
534
+ * @param {string} type
535
+ * @param {object} fields
536
+ * @param {{ replyType: string, timeoutMs?: number }} opts
537
+ * @returns {Promise<object>}
538
+ */
539
+ async request(type, fields, { replyType, timeoutMs = this._requestTimeoutMs }) {
540
+ this._assertReady()
541
+ const requestId = randomUUID()
542
+ return new Promise((resolve, reject) => {
543
+ // Registered with the common pending-operation cleanup (`_rejectAllPending`), so
544
+ // close(), a socket close and a connection failure all settle it with that error.
545
+ const abort = (err) => done(reject, err)
546
+ const done = (fn, v) => { clearTimeout(timer); this.removeListener('message', onMsg); this._pendingRequests.delete(abort); fn(v) }
547
+ const timer = setTimeout(() => done(reject, new TimeoutError(type, timeoutMs)), timeoutMs)
548
+ this._pendingRequests.add(abort)
549
+ const onMsg = (msg) => { if (msg?.type === replyType && msg.requestId === requestId) done(resolve, msg) }
550
+ this.on('message', onMsg)
551
+ try { this._send({ type, requestId, ...fields }) } catch (err) { done(reject, err) }
552
+ })
553
+ }
554
+
555
+ async listSessions() {
556
+ this._assertReady()
557
+ const msg = await this._runSerial('list_sessions', this._requestTimeoutMs, () => {
558
+ this._send({ type: 'list_sessions' })
559
+ })
560
+ const sessions = Array.isArray(msg.sessions) ? msg.sessions.map((s) => this._annotateModelStatus(s)) : []
561
+ return { sessions }
562
+ }
563
+
564
+ /**
565
+ * @param {object} opts
566
+ * @param {string} [opts.name]
567
+ * @param {string} [opts.cwd]
568
+ * @param {string} [opts.provider] - explicitly NEVER 'user-shell' (see class doc)
569
+ * @param {string} [opts.model]
570
+ * @param {string} [opts.permissionMode] - defaults to 'approve'; NEVER 'auto'
571
+ * through this client (that mode requires host-level confirmation this
572
+ * client cannot honestly supply).
573
+ * @param {boolean} [opts.worktree]
574
+ */
575
+ async createSession(opts = {}) {
576
+ this._assertMutationAllowed('createSession')
577
+ this._assertReady()
578
+
579
+ // Trim BEFORE comparing — `' user-shell '` must be refused exactly like
580
+ // `'user-shell'`, not slip through an exact-match guard on the untrimmed
581
+ // value.
582
+ const trimmedProvider = typeof opts.provider === 'string' ? opts.provider.trim() : undefined
583
+ if (trimmedProvider === 'user-shell') {
584
+ throw new Error("createSession: provider 'user-shell' is not permitted through agent-control (arbitrary host shell access is out of scope — see docs/guides/agent-control.md)")
585
+ }
586
+ if ('skipPermissions' in opts) {
587
+ throw new Error('createSession: skipPermissions is not permitted through agent-control (this client always sends skipPermissions:false explicitly)')
588
+ }
589
+ const permissionMode = typeof opts.permissionMode === 'string' && opts.permissionMode.trim() ? opts.permissionMode.trim() : 'approve'
590
+ if (permissionMode === 'auto') {
591
+ throw new Error("createSession: permissionMode 'auto' is not permitted through agent-control")
592
+ }
593
+
594
+ // #7977: ownership is minted only from a reply echoing our requestId. A
595
+ // daemon that predates the echo would still CREATE the session (it ignores
596
+ // the unknown field), never answer with the id, and leave us timed out with
597
+ // an orphan that a retry would duplicate. Refuse before anything is sent.
598
+ if (this._daemonMeta?.capabilities?.createRequestIdV1 !== true) {
599
+ const err = new Error('createSession: this daemon does not advertise create_session requestId support (auth_ok.capabilities.createRequestIdV1), so the create reply cannot be correlated — refusing to create rather than risk an orphaned session. Upgrade the daemon.')
600
+ err.code = 'CREATE_REQUEST_ID_UNSUPPORTED'
601
+ throw err
602
+ }
603
+
604
+ const payload = {
605
+ type: 'create_session',
606
+ // Explicit, not omitted: a host with `defaultSkipPermissions: true`
607
+ // configured would otherwise hand an agent-control-created session an
608
+ // unmediated permission bypass by default. This client never wants
609
+ // that, so it says so on every create rather than relying on the
610
+ // daemon's default.
611
+ skipPermissions: false,
612
+ permissionMode,
613
+ }
614
+ if (typeof opts.name === 'string' && opts.name.trim()) payload.name = opts.name.trim()
615
+ if (typeof opts.cwd === 'string' && opts.cwd.trim()) payload.cwd = opts.cwd.trim()
616
+ if (trimmedProvider) payload.provider = trimmedProvider
617
+ if (typeof opts.model === 'string' && opts.model.trim()) payload.model = opts.model.trim()
618
+ if (opts.worktree === true) payload.worktree = true
619
+
620
+ // #7977: `session_switched` is ALSO what the daemon sends when it re-homes
621
+ // a client whose active session was destroyed (handleDestroySession ->
622
+ // `firstSessionId`, someone else's session), so the reply type alone cannot
623
+ // say whose session a frame names. Correlate on a client-chosen `requestId`
624
+ // the daemon echoes on the create-confirm (and on every error for this
625
+ // create); a re-home never carries one. A frame without OUR id is never the
626
+ // reply, whatever it names, so ownership is minted only from a genuine
627
+ // create reply. Needs a daemon that echoes the id (>= this change): an older
628
+ // one never answers with it and the create times out rather than guessing.
629
+ const requestId = `ac-${randomUUID()}`
630
+ payload.requestId = requestId
631
+ const result = await this._runSerial('create_session', this._requestTimeoutMs, () => {
632
+ this._send(payload)
633
+ }, { accept: (msg) => msg.requestId === requestId })
634
+
635
+ if (result.type === 'session_error') {
636
+ const err = new Error(result.message || 'create_session failed')
637
+ err.code = result.code || 'SESSION_ERROR'
638
+ throw err
639
+ }
640
+
641
+ const sessionId = result.sessionId
642
+ if (typeof sessionId === 'string' && sessionId) this._ownedSessions.add(sessionId)
643
+ if (payload.model) this._modelExpectations.set(sessionId, { requestedModel: payload.model })
644
+ await this._ensureSubscribed(sessionId).catch((err) => this._log('createSession: subscribe failed (non-fatal):', err.message))
645
+
646
+ // The success reply (`session_switched`) does not itself carry the
647
+ // resolved `model` — only `list_sessions` does (see session-manager.js
648
+ // listSessions(): `model: entry.session.model || entry.session.bootedModel
649
+ // || null`). One follow-up round trip is the honest way to learn what
650
+ // model actually got resolved, rather than assuming the request was
651
+ // honored (see the live sonnet -> claude-sonnet-4-6 /
652
+ // silent-fallback-to-Opus incident this client exists to catch).
653
+ let modelStatus = { requested: payload.model || null, observed: null, unknown: true, mismatch: false }
654
+ try {
655
+ const { sessions } = await this.listSessions()
656
+ const row = sessions.find((s) => s.sessionId === sessionId)
657
+ if (row) modelStatus = row.modelStatus
658
+ } catch (err) {
659
+ this._log('createSession: follow-up listSessions failed, model status unknown:', err.message)
660
+ }
661
+
662
+ return {
663
+ sessionId,
664
+ name: result.name ?? null,
665
+ cwd: result.cwd ?? null,
666
+ modelStatus,
667
+ }
668
+ }
669
+
670
+ /**
671
+ * Send input to a session and return the daemon's `input_ack` exactly as
672
+ * reported — status/delivery/retrySafe/dedupScope are NEVER reinterpreted
673
+ * as success/failure by this client. `status: 'uncertain'` (this client's
674
+ * own synthetic status, `ackTimedOut: true` or `disconnected: true`) means
675
+ * no FINAL ack arrived in time — this is NOT a failure and NOT permission
676
+ * to retry; the caller decides what to do with an unconfirmed send. An
677
+ * intermediate ack carrying `reason: 'admission_pending'` (the provider
678
+ * has not yet confirmed admission) is explicitly NOT treated as final —
679
+ * this method keeps waiting for either a later, conclusive ack or the
680
+ * deadline.
681
+ *
682
+ * When this session has a recorded model EXPECTATION (a `model` was passed
683
+ * to `createSession`) and that expectation has resolved to `mismatch` or
684
+ * `unknown`, this method REFUSES to send by default — sending an
685
+ * implementation task under a falsely-claimed model is exactly the failure
686
+ * this client exists to prevent. Pass `{ acknowledgeModelMismatch: true }`
687
+ * to send anyway (e.g. once a human/planner has consciously decided the
688
+ * mismatch is acceptable).
689
+ *
690
+ * Owner-only, like every mutation that targets an existing session (see
691
+ * `_ownershipRejection`): a session this process did not create with
692
+ * `chroxy_create_session` refuses with `reason: 'not_owned'`, before any
693
+ * network I/O — observing it via `chroxy_get_events` remains unrestricted.
694
+ *
695
+ * @param {string} sessionId
696
+ * @param {string} data
697
+ * @param {object} [opts]
698
+ * @param {number} [opts.timeoutMs]
699
+ * @param {string} [opts.clientMessageId] - supply your own id to make a
700
+ * retry land on the daemon's dedup path (`dedupScope: 'process'`) instead
701
+ * of being treated as a brand-new send. Must be a non-empty string.
702
+ * @param {boolean} [opts.acknowledgeModelMismatch]
703
+ */
704
+ async sendInput(sessionId, data, opts = {}) {
705
+ this._assertMutationAllowed('sendInput')
706
+ this._assertReady()
707
+ if (typeof sessionId !== 'string' || !sessionId) throw new Error('sendInput requires sessionId')
708
+ if (typeof data !== 'string') throw new Error('sendInput requires string data')
709
+ const ownershipRejection = this._ownershipRejection(sessionId, 'be sent input')
710
+ if (ownershipRejection) return ownershipRejection
711
+
712
+ // This client's whole correlated-ack contract depends on the daemon
713
+ // actually supporting #7822's input_context_v1 negotiation (advertised,
714
+ // unconditionally, in `auth_ok.capabilities.inputContextV1` on every
715
+ // daemon that has it — see ws-history.js). A daemon that predates it
716
+ // will never send a correlated `input_ack` at all, so every send would
717
+ // silently degrade into an "uncertain" timeout on every call — refuse
718
+ // up front instead, with a clear reason, rather than let that happen
719
+ // silently.
720
+ if (this._daemonMeta?.capabilities?.inputContextV1 !== true) {
721
+ return {
722
+ status: 'blocked',
723
+ reason: 'input_context_v1_unsupported',
724
+ sessionId,
725
+ message: 'This daemon does not advertise input_context_v1 support (auth_ok.capabilities.inputContextV1) — correlated input_ack is not available, so this client refuses to send rather than silently time out on every call.',
726
+ }
727
+ }
728
+
729
+ let clientMessageId
730
+ if (opts.clientMessageId !== undefined) {
731
+ if (typeof opts.clientMessageId !== 'string' || !CLIENT_MESSAGE_ID_PATTERN.test(opts.clientMessageId) || RESERVED_CLIENT_MESSAGE_IDS.has(opts.clientMessageId.toLowerCase())) {
732
+ throw new Error(`sendInput: opts.clientMessageId must match ${CLIENT_MESSAGE_ID_PATTERN} and not be a reserved value`)
733
+ }
734
+ clientMessageId = opts.clientMessageId
735
+ } else {
736
+ clientMessageId = randomUUID()
737
+ }
738
+
739
+ const ackKey = this._inputAckKey(sessionId, clientMessageId)
740
+ // Reserve the slot SYNCHRONOUSLY — before ANY `await` below — so two
741
+ // concurrent sendInput calls racing on the same (sessionId,
742
+ // clientMessageId) cannot both pass this check and then stomp each
743
+ // other's pending entry once their awaits resolve. `has()`+`set()` with
744
+ // no yield point in between is atomic under JS's single-threaded
745
+ // execution; the SAME check re-run after an await would NOT be (that was
746
+ // the bug this reservation replaces).
747
+ if (this._pendingInputAcks.has(ackKey)) {
748
+ throw new Error(`sendInput: a send with clientMessageId '${clientMessageId}' is already in flight for session ${sessionId} — supply a different id or await the first call`)
749
+ }
750
+ const reservation = { reserved: true, sessionId, clientMessageId }
751
+ this._pendingInputAcks.set(ackKey, reservation)
752
+ const releaseIfStillReserved = () => {
753
+ if (this._pendingInputAcks.get(ackKey) === reservation) this._pendingInputAcks.delete(ackKey)
754
+ }
755
+
756
+ try {
757
+ // Fresh, not cached: a model expectation is safety-critical (the whole
758
+ // point of this gate is not sending an implementation task under a
759
+ // falsely-claimed model), so this re-checks against the daemon rather
760
+ // than trusting a snapshot that might predate a `model_changed`
761
+ // broadcast this client hasn't processed yet.
762
+ const modelGate = await this._checkModelGate(sessionId, opts)
763
+ if (modelGate) { releaseIfStillReserved(); return modelGate }
764
+ this._assertReady() // re-check: the await above could have outlived the connection
765
+
766
+ // Subscription failures are FATAL here, not logged-and-ignored — an
767
+ // unauthorized/denied/unknown-session subscription means this client
768
+ // has no way to ever OBSERVE the outcome of the send it's about to
769
+ // make, and silently proceeding would make `getEvents` return
770
+ // misleadingly-empty "no new events" for a session this client was
771
+ // never actually granted.
772
+ await this._ensureSubscribed(sessionId)
773
+ this._assertReady()
774
+ } catch (err) {
775
+ releaseIfStillReserved()
776
+ throw err
777
+ }
778
+
779
+ const timeoutMs = opts.timeoutMs ?? this._requestTimeoutMs
780
+
781
+ const ackPromise = new Promise((resolve) => {
782
+ // Registered BEFORE the send below, so an ack that arrives even
783
+ // pathologically fast can never race ahead of the listener. This
784
+ // REPLACES the reservation above with the real waiting entry — the
785
+ // reservation already guaranteed exclusivity for this
786
+ // (sessionId, clientMessageId); this step attaches what to actually do
787
+ // when the ack (or the timeout) arrives.
788
+ const timer = setTimeout(() => {
789
+ const pending = this._pendingInputAcks.get(ackKey)
790
+ this._pendingInputAcks.delete(ackKey)
791
+ resolve({
792
+ status: 'uncertain',
793
+ delivery: 'unknown',
794
+ retrySafe: false,
795
+ dedupScope: pending?.lastKnown?.dedupScope ?? 'process',
796
+ // Read from the pending record, not the (sessionId::id) map key —
797
+ // the map key is an internal correlation detail and must never
798
+ // leak into a result field a caller reads as "the clientMessageId".
799
+ clientMessageId: pending?.clientMessageId ?? clientMessageId,
800
+ sessionId,
801
+ ackTimedOut: true,
802
+ lastKnownStatus: pending?.lastKnown ?? null,
803
+ message: 'No FINAL input_ack received within the timeout. The server explicitly does not retry automatically on timeout — do not assume the input was or was not delivered.',
804
+ })
805
+ }, timeoutMs)
806
+ this._pendingInputAcks.set(ackKey, { resolve, timer, sessionId, clientMessageId })
807
+ })
808
+
809
+ try {
810
+ this._send({ type: 'input', sessionId, data, clientMessageId })
811
+ } catch (err) {
812
+ const pending = this._pendingInputAcks.get(ackKey)
813
+ if (pending) {
814
+ clearTimeout(pending.timer)
815
+ this._pendingInputAcks.delete(ackKey)
816
+ }
817
+ throw err
818
+ }
819
+
820
+ return ackPromise
821
+ }
822
+
823
+ /**
824
+ * Best-effort interrupt. The protocol defines no correlated ack for
825
+ * `interrupt` (see ws-server.js protocol doc) — this resolves once a short
826
+ * grace window passes with no `session_error` naming this session, or
827
+ * immediately on such an error. It reports what was OBSERVED, not a
828
+ * synthesized "the agent stopped".
829
+ *
830
+ * Owner-only, like every mutation that targets an existing session (see
831
+ * `_ownershipRejection`): a session this process did not create refuses
832
+ * with `reason: 'not_owned'`, before any network I/O.
833
+ */
834
+ async interrupt(sessionId) {
835
+ this._assertMutationAllowed('interrupt')
836
+ this._assertReady()
837
+ if (typeof sessionId !== 'string' || !sessionId) throw new Error('interrupt requires sessionId')
838
+ const ownershipRejection = this._ownershipRejection(sessionId, 'be interrupted')
839
+ if (ownershipRejection) return ownershipRejection
840
+
841
+ // Fatal, not logged-and-ignored — interrupt's own grace-window
842
+ // "was there a session_error" observation depends on actually being
843
+ // subscribed; proceeding unsubscribed would silently make a real error
844
+ // invisible to the caller.
845
+ await this._ensureSubscribed(sessionId)
846
+ this._assertReady()
847
+
848
+ const graceMs = Math.min(DEFAULT_INTERRUPT_GRACE_MS, this._requestTimeoutMs)
849
+ return new Promise((resolve) => {
850
+ let settled = false
851
+ const onMessage = (msg) => {
852
+ if (msg.type !== 'session_error') return
853
+ if (msg.sessionId && msg.sessionId !== sessionId) return
854
+ settle({ sent: true, acknowledged: false, error: msg })
855
+ }
856
+ const onClose = () => settle({ sent: true, acknowledged: false, disconnected: true })
857
+ const timer = setTimeout(() => settle({ sent: true, acknowledged: false }), graceMs)
858
+ const settle = (result) => {
859
+ if (settled) return
860
+ settled = true
861
+ clearTimeout(timer)
862
+ this.removeListener('message', onMessage)
863
+ this.removeListener('close', onClose)
864
+ this.removeListener('error', onClose)
865
+ resolve(result)
866
+ }
867
+ // `AgentControlClient` itself (not `_eventLog`, which is a plain class
868
+ // with no event emission) is the EventEmitter every dispatched message
869
+ // is re-emitted on as 'message' — see `_dispatch`.
870
+ this.on('message', onMessage)
871
+ this.on('close', onClose)
872
+ this.on('error', onClose)
873
+ try {
874
+ this._send({ type: 'interrupt', sessionId })
875
+ } catch (err) {
876
+ settle({ sent: false, acknowledged: false, error: { message: err.message } })
877
+ }
878
+ })
879
+ }
880
+
881
+ /**
882
+ * Answer an OBSERVED, session-owned pending permission request with
883
+ * `allow` or `deny` — never `allowAlways` (that persists a durable project
884
+ * rule; out of scope for an external planner relay). Refuses, before any
885
+ * network I/O, to answer a requestId this client has not itself seen as
886
+ * pending (via a `permission_request` event), that it has already seen
887
+ * resolved/expired, or whose session this process did not create.
888
+ *
889
+ * "Session-owned" means CREATED BY THIS PROCESS (`createSession`, tracked
890
+ * in `_ownedSessions`, which survives reconnects via ClientManager). It is
891
+ * not merely "the sessionId the caller passed matches the request": a
892
+ * primary-token connection can subscribe to — and so observe the prompts
893
+ * of — every session on the daemon, including ones a human is driving, so
894
+ * observation alone would let a planner approve a human's prompt. The
895
+ * server's own binding/authority checks in `handlePermissionResponse`
896
+ * still apply on top of this; this gate only ever narrows.
897
+ *
898
+ * `allow` runs through FOUR gates, in this fixed order (every one of them
899
+ * only ever narrows; `deny` is never gated by any of them):
900
+ *
901
+ * 1. **Ownership** (`_ownershipRejection`, above) — `reason: 'not_owned'`
902
+ * for a session this process did not create.
903
+ * 2. **`NOT_DELEGABLE_TOOLS`** (`mcp_spawn`, codex `request_permissions`)
904
+ * — `reason: 'not_delegable'` WHATEVER `floored` says. These are
905
+ * high-authority independent of any path field (an `mcp_spawn` allow
906
+ * persists a permanent binary-trust grant; `request_permissions` is a
907
+ * sandbox-scope escalation). Checked first so one of these is never
908
+ * merely reported as "floor_unknown" or "not_allowlisted".
909
+ * 3. **The tool ALLOWLIST** (#7975, S3 — inverted from the original
910
+ * denylist shape): a tool must be one of {@link FLOOR_ALLOWLISTED_TOOLS}
911
+ * (`Read`/`Write`/`Edit`/`NotebookEdit`/codex `apply_patch` — exactly
912
+ * the tools whose ENTIRE file-selecting input the protected-path floor
913
+ * inspects) or a {@link COMMAND_TOOLS} member with
914
+ * `allowCommandApprovals: true`. Everything else — an MCP tool
915
+ * (`mcp__*`), `WebFetch`/`WebSearch`, `Task`/`Agent`, codex
916
+ * `mcp_elicitation`, `Glob`/`Grep` (see below), or any future Claude
917
+ * Code tool this client doesn't yet know about — is refused
918
+ * `reason: 'not_allowlisted'`. This is the load-bearing fix: under the
919
+ * old denylist, `floored: false` on one of these tools meant "the
920
+ * floor never looked at this tool's input at all" (it has no path
921
+ * field to inspect), not "this is safe" — so a planner could `allow`
922
+ * an MCP tool that runs an arbitrary command, or a `mcp_elicitation`
923
+ * connector-write confirmation, exactly the class of decision the
924
+ * floor exists to put in front of a human. A `COMMAND_TOOLS` member
925
+ * without the flag is refused `reason: 'command_approval_disabled'`
926
+ * (unchanged from #7973) rather than the generic `not_allowlisted`,
927
+ * since that case has its own, more specific remedy (restart with the
928
+ * flag).
929
+ *
930
+ * `Glob` and `Grep` are deliberately NOT on this allowlist (adversarial
931
+ * review of 71e78ba38, same #7975 tracking) even though both are in
932
+ * {@link ACCEPT_EDITS_TOOLS} and both carry a `path` field the floor
933
+ * inspects: for neither is `floored: false` the complete safety signal
934
+ * it is for the tools above. `Glob`'s `pattern` selects files the floor
935
+ * never inspects (it returns names only). `Grep`'s `glob` IS inspected
936
+ * since #7978, but a Grep with no glob reads every non-ignored file under
937
+ * `path`, a committed secret included, and the floor sees only the path. See
938
+ * `permission-manager.js`'s doc comment on `FLOOR_ALLOWLISTED_TOOLS`
939
+ * for the measured ripgrep proof.
940
+ * 4. **The floor** (#7968) — even for an allowlisted/flagged tool,
941
+ * `allow` is refused when the OBSERVED request was floor-forced. The
942
+ * protected-path permission floor (docs/security/permission-floor.md)
943
+ * forces a *prompt* — never a deny — for a protected target (a secret
944
+ * read, a write into `.git/`/`.claude/`, …) so a PERSON decides. The
945
+ * daemon marks this on the wire as `floored: true|false` on the
946
+ * `permission_request` broadcast; this client reads that flag
947
+ * VERBATIM off the observed request (`_trackPermissionObservation`)
948
+ * and never re-derives it — a second implementation of the floor is
949
+ * exactly what `permission-floor.md` says not to build.
950
+ * - `floored === false` (explicit): permitted — an ordinary prompt.
951
+ * - `floored === true`: refused, `reason: 'floored'`.
952
+ * - `floored` absent (an older daemon predating #7968, or any
953
+ * non-boolean value): refused, `reason: 'floor_unknown'` — fail
954
+ * closed, since this client cannot tell a floored prompt from an
955
+ * ordinary one without the flag.
956
+ *
957
+ * @param {string} sessionId
958
+ * @param {string} requestId
959
+ * @param {'allow'|'deny'} decision
960
+ */
961
+ async respondPermission(sessionId, requestId, decision) {
962
+ this._assertMutationAllowed('respondPermission')
963
+ this._assertReady()
964
+ if (typeof sessionId !== 'string' || !sessionId) throw new Error('respondPermission requires sessionId')
965
+ if (typeof requestId !== 'string' || !requestId) throw new Error('respondPermission requires requestId')
966
+ if (!ALLOWED_PERMISSION_DECISIONS.has(decision)) {
967
+ throw new Error("respondPermission: decision must be 'allow' or 'deny' (allowAlways is not permitted through agent-control)")
968
+ }
969
+
970
+ const observed = this._observedPermissions.get(requestId)
971
+ if (!observed) {
972
+ return { status: 'rejected', requestId, reason: 'not_observed', message: 'This requestId was never observed as pending by this client — refusing to answer an unknown/unscoped permission.' }
973
+ }
974
+ if (observed.sessionId !== sessionId) {
975
+ return { status: 'rejected', requestId, reason: 'sibling_session', message: `This permission belongs to session ${observed.sessionId}, not ${sessionId} — refusing.` }
976
+ }
977
+ const ownershipRejection = this._ownershipRejection(sessionId, 'have its permission prompts answered here')
978
+ if (ownershipRejection) return { ...ownershipRejection, requestId }
979
+ // Gate 2: never delegable to an external planner, WHATEVER `floored`
980
+ // says — checked before the allowlist/floor gates below so one of these
981
+ // is never merely reported as "not_allowlisted" or "floor_unknown" (see
982
+ // the doc comment above).
983
+ if (decision === 'allow' && (NOT_DELEGABLE_TOOLS.has(observed.tool) || observed.explicitConsent !== false || observed.nonDelegable !== false)) {
984
+ return { status: 'rejected', requestId, sessionId, reason: 'not_delegable', message: `This request requires explicit human consent or its consent metadata is unknown. An external planner cannot approve it; deny is still permitted.` }
985
+ }
986
+ // Gate 3: the allowlist (#7975, S3). A tool must be affirmatively known
987
+ // to be one the floor can inspect (FLOOR_ALLOWLISTED_TOOLS), or a
988
+ // COMMAND_TOOLS member with the explicit opt-in — everything else is
989
+ // refused regardless of what `floored` says, since `floored: false` on a
990
+ // tool the floor cannot see into at all is not a safety signal.
991
+ if (decision === 'allow' && !FLOOR_ALLOWLISTED_TOOLS.has(observed.tool)) {
992
+ if (COMMAND_TOOLS.has(observed.tool)) {
993
+ if (!this.allowCommandApprovals) {
994
+ return { status: 'rejected', requestId, sessionId, reason: 'command_approval_disabled', message: `'${observed.tool}' carries an arbitrary command string the protected-path floor cannot inspect — approving command-tool calls through agent-control is disabled by default. Restart this MCP server with --allow-command-approvals to permit it (still subject to the floored/ownership gates). \`deny\` is still permitted.` }
995
+ }
996
+ // COMMAND_TOOLS + the flag: fall through to the floor gate below,
997
+ // same as any allowlisted file tool.
998
+ } else {
999
+ return { status: 'rejected', requestId, sessionId, reason: 'not_allowlisted', message: `'${observed.tool}' is not one of the tools an external planner may ever approve — only Read/Write/Edit/NotebookEdit/apply_patch (the tools whose ENTIRE file-selecting input the protected-path floor actually inspects), plus Bash/PowerShell/Monitor/shell with --allow-command-approvals, can be allowed here. Glob and Grep are refused too, even though the floor can see their \`path\` field: \`floored: false\` on either is not a complete safety signal. Glob's \`pattern\` selects files the floor never inspects, and a Grep with no \`glob\` reads every non-ignored file under its \`path\`, a committed secret included, while the floor sees only the path. An MCP tool, WebFetch/WebSearch, Task/Agent, codex mcp_elicitation, and any tool this client doesn't recognize all fail closed the same way. \`deny\` is still permitted; the prompt stays pending for a human otherwise.` }
1000
+ }
1001
+ }
1002
+ // Gate 4: the floor (#7968). Read straight off what was OBSERVED for
1003
+ // this requestId — never re-derived — per the doc comment above.
1004
+ if (decision === 'allow' && observed.floored !== false) {
1005
+ if (observed.floored === true) {
1006
+ return { status: 'rejected', requestId, sessionId, reason: 'floored', message: "This request was forced by the daemon's protected-path permission floor (floored:true) — only a human may allow it. `deny` is still permitted; the prompt stays pending for a human otherwise." }
1007
+ }
1008
+ return { status: 'rejected', requestId, sessionId, reason: 'floor_unknown', message: "This request's floored flag was not observed as an explicit `false` (absent — an older daemon that predates #7968 — or a non-boolean value) — refusing `allow` fail-closed, since this client cannot tell a floored prompt from an ordinary one without it. `deny` is still permitted." }
1009
+ }
1010
+ // A second concurrent call for the SAME requestId must not silently
1011
+ // overwrite the first caller's pending entry — that would leak the
1012
+ // first caller's timer and permanently strand its promise (it would
1013
+ // never resolve, since its map entry was replaced and any later reply
1014
+ // now only reaches the second caller). Checked synchronously before any
1015
+ // mutation of `_pendingPermissionResponses`, matching `sendInput`'s
1016
+ // reservation discipline.
1017
+ if (this._pendingPermissionResponses.has(requestId)) {
1018
+ return { status: 'rejected', requestId, sessionId, reason: 'already_in_flight', message: 'A response to this requestId is already in flight — the first caller retains the pending correlation; await it instead of calling again.' }
1019
+ }
1020
+
1021
+ const timeoutMs = this._requestTimeoutMs
1022
+ const ackPromise = new Promise((resolve) => {
1023
+ const timer = setTimeout(() => {
1024
+ this._pendingPermissionResponses.delete(requestId)
1025
+ resolve({
1026
+ status: 'uncertain',
1027
+ requestId,
1028
+ sessionId,
1029
+ ackTimedOut: true,
1030
+ message: 'No confirmation (permission_resolved/permission_expired/error) received within the timeout — do not assume the decision was or was not applied, and do not retry automatically.',
1031
+ })
1032
+ }, timeoutMs)
1033
+ // Registered BEFORE the send below.
1034
+ this._pendingPermissionResponses.set(requestId, { sessionId, resolve, timer })
1035
+ })
1036
+
1037
+ try {
1038
+ this._send({ type: 'permission_response', requestId, decision })
1039
+ } catch (err) {
1040
+ const pending = this._pendingPermissionResponses.get(requestId)
1041
+ if (pending) {
1042
+ clearTimeout(pending.timer)
1043
+ this._pendingPermissionResponses.delete(requestId)
1044
+ }
1045
+ throw err
1046
+ }
1047
+
1048
+ return ackPromise
1049
+ }
1050
+
1051
+ /**
1052
+ * Bounded read of the retained, normalized event log for one session.
1053
+ * `waitMs` (default 0, clamped to MAX_WAIT_MS) long-polls for new events;
1054
+ * an empty result means no NEW retained events arrived — never "the
1055
+ * executor finished". See events.js for the retention/gap contract.
1056
+ */
1057
+ async getEvents(sessionId, opts = {}) {
1058
+ this._assertReady()
1059
+ if (typeof sessionId !== 'string' || !sessionId) throw new Error('getEvents requires sessionId')
1060
+ // Fatal, not logged-and-ignored — an unauthorized/unknown session would
1061
+ // otherwise silently return an empty (but successful-looking) event log
1062
+ // forever, indistinguishable from "subscribed but genuinely idle".
1063
+ await this._ensureSubscribed(sessionId)
1064
+ this._assertReady()
1065
+ const waitMs = Math.min(Math.max(0, Number(opts.waitMs) || 0), MAX_WAIT_MS)
1066
+ return this._eventLog.waitAndRead(sessionId, { cursor: opts.cursor ?? null, limit: opts.limit, waitMs })
1067
+ }
1068
+
1069
+ /**
1070
+ * Connection-level events whose broadcast carried no `sessionId` at all
1071
+ * (a legacy/unscoped reply path — see events.js `UNSCOPED_KEY`). These are
1072
+ * NEVER folded into a specific session's log (that would risk
1073
+ * misattributing an unscoped event to the wrong session); this is the
1074
+ * explicit, documented way to inspect them.
1075
+ */
1076
+ async getUnscopedEvents(opts = {}) {
1077
+ this._assertReady()
1078
+ const waitMs = Math.min(Math.max(0, Number(opts.waitMs) || 0), MAX_WAIT_MS)
1079
+ return this._eventLog.waitAndRead(null, { cursor: opts.cursor ?? null, limit: opts.limit, waitMs })
1080
+ }
1081
+
1082
+ // ---------------------------------------------------------------------
1083
+ // Internals
1084
+ // ---------------------------------------------------------------------
1085
+
1086
+ _assertReady() {
1087
+ if (this._state !== 'ready') throw new NotConnectedError(`client is in state '${this._state}', not 'ready'`)
1088
+ }
1089
+
1090
+ _assertMutationAllowed(operation) {
1091
+ if (this.readOnly) throw new ReadOnlyModeError(operation)
1092
+ }
1093
+
1094
+ /**
1095
+ * Shared ownership gate for every MUTATION that targets an EXISTING
1096
+ * session — `sendInput`, `interrupt`, and `respondPermission`. "Owned"
1097
+ * means CREATED BY THIS PROCESS (`createSession`, tracked in
1098
+ * `_ownedSessions`, which survives reconnects via ClientManager's injected
1099
+ * Set) — not merely "the caller named this session". A primary-token
1100
+ * connection can subscribe to, and so observe and target, every session on
1101
+ * the daemon, including ones a human is driving; without this gate a
1102
+ * planner could send input to, interrupt, or answer permissions for a
1103
+ * session it never created. `chroxy_create_session` deliberately does NOT
1104
+ * go through this gate — it is the ownership SOURCE, not a
1105
+ * session-targeting mutation.
1106
+ *
1107
+ * Returns a structured rejection (never a silent no-op, and checked before
1108
+ * any network I/O) when the session is not owned, or `null` when the
1109
+ * caller may proceed. This is the ONE place that check lives — `sendInput`
1110
+ * and `interrupt` call it directly; `respondPermission` reuses it too, so
1111
+ * there is exactly one ownership check to keep in sync, never a second
1112
+ * implementation that could drift from it.
1113
+ *
1114
+ * @param {string} sessionId
1115
+ * @param {string} verb - describes the refused action in the message, e.g. 'be sent input'.
1116
+ */
1117
+ _ownershipRejection(sessionId, verb) {
1118
+ if (this._ownedSessions.has(sessionId)) return null
1119
+ return {
1120
+ status: 'rejected',
1121
+ sessionId,
1122
+ reason: 'not_owned',
1123
+ message: `This session was not created by this agent-control process — only a session created with chroxy_create_session in this process can ${verb}. Use chroxy_get_events to observe it instead.`,
1124
+ }
1125
+ }
1126
+
1127
+ /**
1128
+ * FRESH (not cached) model-mismatch gate. A model expectation is
1129
+ * safety-critical, so this pays a `list_sessions` round trip on every
1130
+ * `sendInput` for a session that has one, rather than trusting a snapshot
1131
+ * that could predate a `model_changed` broadcast, a reconnect, or simply
1132
+ * never having been checked (a fresh expectation with no `lastKnownStatus`
1133
+ * yet is treated as UNKNOWN, not as "nothing to block on" — fail closed).
1134
+ */
1135
+ async _checkModelGate(sessionId, opts) {
1136
+ if (opts.acknowledgeModelMismatch === true) return null
1137
+ if (!this._modelExpectations.has(sessionId)) return null
1138
+
1139
+ let modelStatus
1140
+ try {
1141
+ const { sessions } = await this.listSessions()
1142
+ const row = sessions.find((s) => s.sessionId === sessionId)
1143
+ modelStatus = row ? row.modelStatus : { requested: this._modelExpectations.get(sessionId)?.requestedModel ?? null, observed: null, unknown: true, mismatch: false }
1144
+ } catch (err) {
1145
+ // Could not refresh — fail closed rather than fall back to a
1146
+ // possibly-stale cached status or, worse, silently proceed.
1147
+ modelStatus = { requested: this._modelExpectations.get(sessionId)?.requestedModel ?? null, observed: null, unknown: true, mismatch: false }
1148
+ this._log('sendInput: model-status refresh failed, treating as unknown:', err.message)
1149
+ }
1150
+
1151
+ if (modelStatus.mismatch || modelStatus.unknown) {
1152
+ return {
1153
+ status: 'blocked',
1154
+ reason: modelStatus.mismatch ? 'model_mismatch' : 'model_unknown',
1155
+ sessionId,
1156
+ modelStatus,
1157
+ message: 'Refusing to send input: the session may not be running the requested model (see modelStatus). Pass acknowledgeModelMismatch:true to send anyway.',
1158
+ }
1159
+ }
1160
+ return null
1161
+ }
1162
+
1163
+ _annotateModelStatus(sessionRow) {
1164
+ const expectation = this._modelExpectations.get(sessionRow.sessionId)
1165
+ const requested = expectation ? expectation.requestedModel : null
1166
+ const observed = sessionRow.model ?? null
1167
+ const unknown = observed === null
1168
+ const mismatch = !unknown && requested !== null && requested !== observed
1169
+ const modelStatus = { requested, observed, unknown, mismatch }
1170
+ if (expectation) expectation.lastKnownStatus = modelStatus
1171
+ return { ...sessionRow, modelStatus }
1172
+ }
1173
+
1174
+ /**
1175
+ * Subscribes this connection to `sessionId`'s broadcasts (`subscribe_sessions`
1176
+ * / `subscriptions_updated` — see `handleSubscribeSessions`) and THROWS if
1177
+ * the daemon's reply does not actually include `sessionId` — a bound token
1178
+ * scoped to a different session, or a sessionId the daemon doesn't
1179
+ * recognize, causes `subscribe_sessions` to silently omit it from the
1180
+ * reply rather than erroring, so checking membership (not just "did we get
1181
+ * a reply") is the only way to detect a denied/unknown subscription.
1182
+ */
1183
+ async _ensureSubscribed(sessionId) {
1184
+ if (this._subscribedSessionIds.has(sessionId)) return
1185
+ const result = await this._runSerial('subscribe_sessions', this._requestTimeoutMs, () => {
1186
+ this._send({ type: 'subscribe_sessions', sessionIds: [sessionId] })
1187
+ })
1188
+ const granted = Array.isArray(result.subscribedSessionIds) ? result.subscribedSessionIds : []
1189
+ for (const sid of granted) this._subscribedSessionIds.add(sid)
1190
+ if (!granted.includes(sessionId)) {
1191
+ const err = new Error(`subscribe_sessions did not grant session ${sessionId} — it may not exist, or this token is not authorized for it`)
1192
+ err.code = 'SUBSCRIPTION_DENIED'
1193
+ throw err
1194
+ }
1195
+ }
1196
+
1197
+ _waitForOpen(ws, timeoutMs) {
1198
+ return new Promise((resolve, reject) => {
1199
+ const timer = setTimeout(() => {
1200
+ cleanup()
1201
+ reject(new TimeoutError('WebSocket open', timeoutMs))
1202
+ }, Math.max(1, timeoutMs))
1203
+ const onOpen = () => { cleanup(); resolve() }
1204
+ const onError = (err) => { cleanup(); reject(err) }
1205
+ const cleanup = () => {
1206
+ clearTimeout(timer)
1207
+ ws.removeListener('open', onOpen)
1208
+ ws.removeListener('error', onError)
1209
+ }
1210
+ ws.once('open', onOpen)
1211
+ ws.once('error', onError)
1212
+ })
1213
+ }
1214
+
1215
+ /**
1216
+ * @param {string[]} types
1217
+ * @param {number} timeoutMs
1218
+ * @param {{ onMatch?: (msg: object) => any }} [opts] - `onMatch` runs
1219
+ * SYNCHRONOUSLY in the message-handling call stack before this promise
1220
+ * resolves — see the coalesced-frame comment in `connect()`. Its return
1221
+ * value becomes the resolved value; a thrown error rejects.
1222
+ */
1223
+ _waitForOneOf(types, timeoutMs, opts = {}) {
1224
+ return new Promise((resolve, reject) => {
1225
+ const timer = setTimeout(() => {
1226
+ cleanup()
1227
+ reject(new TimeoutError(types.join('|'), timeoutMs))
1228
+ }, Math.max(1, timeoutMs))
1229
+ const onMsg = (msg) => {
1230
+ if (!types.includes(msg.type)) return
1231
+ cleanup()
1232
+ try {
1233
+ const result = opts.onMatch ? opts.onMatch(msg) : msg
1234
+ resolve(result)
1235
+ } catch (err) {
1236
+ reject(err)
1237
+ }
1238
+ }
1239
+ const onAbort = (err) => { cleanup(); reject(err) }
1240
+ const cleanup = () => {
1241
+ clearTimeout(timer)
1242
+ this.removeListener('_handshake', onMsg)
1243
+ this._handshakeAbortListeners.delete(onAbort)
1244
+ }
1245
+ this.on('_handshake', onMsg)
1246
+ this._handshakeAbortListeners.add(onAbort)
1247
+ })
1248
+ }
1249
+
1250
+ _abortHandshakeWaiters(err) {
1251
+ const listeners = [...this._handshakeAbortListeners]
1252
+ this._handshakeAbortListeners.clear()
1253
+ for (const onAbort of listeners) onAbort(err)
1254
+ }
1255
+
1256
+ /**
1257
+ * @param {string} kind - a SERIAL_REPLY_TYPES key
1258
+ * @param {number} timeoutMs
1259
+ * @param {() => void} sendFn
1260
+ * @param {{ accept?: (msg: object) => boolean }} [opts] - `accept` narrows
1261
+ * which reply of an accepted TYPE may settle this op (see createSession's
1262
+ * re-home filter); a frame it rejects is left for the op to keep waiting.
1263
+ */
1264
+ _runSerial(kind, timeoutMs, sendFn, { accept } = {}) {
1265
+ const run = () => new Promise((resolve, reject) => {
1266
+ const timer = setTimeout(() => {
1267
+ this._pendingSerialOp = null
1268
+ // "Invalidate the ambiguous connection after an uncorrelated
1269
+ // timeout": with no requestId on the wire for these operations, a
1270
+ // reply that arrives AFTER we gave up waiting could otherwise be
1271
+ // mistaken for the answer to a LATER call of the same kind. Rather
1272
+ // than accept that ambiguity, the whole connection is torn down —
1273
+ // callers must open a fresh one. This is deliberately conservative.
1274
+ this._failConnection(new TimeoutError(kind, timeoutMs))
1275
+ reject(new TimeoutError(kind, timeoutMs))
1276
+ }, timeoutMs)
1277
+ this._pendingSerialOp = { kind, resolve, reject, timer, accept }
1278
+ try {
1279
+ sendFn()
1280
+ } catch (err) {
1281
+ clearTimeout(timer)
1282
+ this._pendingSerialOp = null
1283
+ reject(err)
1284
+ }
1285
+ })
1286
+ // Chain so a second caller's op waits for the first to resolve/timeout —
1287
+ // list_sessions/create_session/subscribe_sessions have no requestId, so
1288
+ // this connection only ever has ONE such op in flight (see class doc).
1289
+ const chained = this._serialQueue.then(run, run)
1290
+ this._serialQueue = chained.catch(() => {})
1291
+ return chained
1292
+ }
1293
+
1294
+ _sendPlain(payload) {
1295
+ if (!this._ws || this._ws.readyState !== this._ws.OPEN) {
1296
+ throw new NotConnectedError('socket is not open')
1297
+ }
1298
+ this._ws.send(JSON.stringify(payload))
1299
+ }
1300
+
1301
+ _send(payload) {
1302
+ if (!this._ws || this._ws.readyState !== this._ws.OPEN) {
1303
+ throw new NotConnectedError('socket is not open')
1304
+ }
1305
+ if (this._encryptionState) {
1306
+ const envelope = encrypt(JSON.stringify(payload), this._encryptionState.sharedKey, this._encryptionState.sendNonce, DIRECTION_CLIENT)
1307
+ this._encryptionState.sendNonce++
1308
+ this._ws.send(JSON.stringify(envelope))
1309
+ } else {
1310
+ this._ws.send(JSON.stringify(payload))
1311
+ }
1312
+ }
1313
+
1314
+ _onRawMessage(raw) {
1315
+ let msg
1316
+ try {
1317
+ msg = JSON.parse(raw.toString())
1318
+ } catch {
1319
+ this._log('dropping non-JSON frame')
1320
+ return
1321
+ }
1322
+ if (!msg || typeof msg !== 'object') return
1323
+
1324
+ // True only for a frame that decrypted under the connection key — i.e.
1325
+ // one the daemon we key-exchanged with actually sent.
1326
+ let authenticated = false
1327
+ if (msg.type === 'encrypted') {
1328
+ if (!this._encryptionState) {
1329
+ this._log('received encrypted frame before key exchange completed — dropping')
1330
+ return
1331
+ }
1332
+ try {
1333
+ msg = decrypt(msg, this._encryptionState.sharedKey, this._encryptionState.recvNonce, DIRECTION_SERVER)
1334
+ this._encryptionState.recvNonce++
1335
+ authenticated = true
1336
+ } catch (err) {
1337
+ // Tamper or replay (Poly1305 MAC failure, or nonce mismatch) —
1338
+ // per the documented contract this is a hard failure: close the
1339
+ // connection rather than continue on a socket that has just proven
1340
+ // untrustworthy.
1341
+ this._log('decryption failed (tamper/replay) — closing connection:', err.message)
1342
+ this._failConnection(new ConnectionRefusedError('DECRYPTION_FAILED', `message decryption failed: ${err.message}`))
1343
+ return
1344
+ }
1345
+ } else if (this._encryptionRequired && (this._state === 'ready' || this._encryptionState)) {
1346
+ // Mirrors the server's own enforcement (ws-server.js #5614 test:
1347
+ // "REJECTS plaintext frames after encryption is established") in the
1348
+ // other direction — a daemon that starts sending PLAINTEXT after we
1349
+ // negotiated encryption is not behaving as documented and is treated
1350
+ // as a protocol failure, not silently accepted.
1351
+ this._log('plaintext frame received after encryption was established — closing connection')
1352
+ this._failConnection(new ConnectionRefusedError('ENCRYPTION_DOWNGRADE', 'daemon sent a plaintext frame after encryption was established'))
1353
+ return
1354
+ }
1355
+
1356
+ this._dispatch(msg, authenticated)
1357
+ }
1358
+
1359
+ /**
1360
+ * Record/retire a pending permission this client has OBSERVED. Called for
1361
+ * every live (ready-state) message, and for each pre-ready buffered message
1362
+ * that survives the flush's authentication filter — never directly on a
1363
+ * pre-ready arrival, because at that point the frame's provenance is not
1364
+ * yet known (see `connect()`'s flush).
1365
+ */
1366
+ _trackPermissionObservation(msg) {
1367
+ if (msg.type === 'permission_request' && typeof msg.requestId === 'string' && msg.sessionId) {
1368
+ // #7968: `floored` is stored EXACTLY as the daemon sent it on THIS
1369
+ // observed request — never re-derived (see respondPermission's
1370
+ // floor-forced doc comment, and permission-floor.md "the floor has
1371
+ // exactly one implementation"). Anything other than the literal
1372
+ // boolean `true`/`false` (an older daemon that omits the field
1373
+ // entirely, or a malformed non-boolean value) is normalized to
1374
+ // `undefined` here — respondPermission treats that as "unknown" and
1375
+ // refuses `allow` for it, fail-closed.
1376
+ const floored = msg.floored === true ? true : msg.floored === false ? false : undefined
1377
+ // #7973: the tool name is stored EXACTLY as observed (never re-derived)
1378
+ // for the not_delegable / command-tool gates in respondPermission —
1379
+ // same "read straight off what was observed" discipline as `floored`.
1380
+ const tool = typeof msg.tool === 'string' ? msg.tool : undefined
1381
+ this._observedPermissions.set(msg.requestId, { sessionId: msg.sessionId, seenAt: Date.now(), floored, tool,
1382
+ explicitConsent: msg.explicitConsent, nonDelegable: msg.nonDelegable })
1383
+ } else if ((msg.type === 'permission_resolved' || msg.type === 'permission_expired') && typeof msg.requestId === 'string') {
1384
+ this._observedPermissions.delete(msg.requestId)
1385
+ }
1386
+ }
1387
+
1388
+ _dispatch(msg, authenticated = false) {
1389
+ if (this._state !== 'ready') {
1390
+ // During the handshake/startup fence, request/response correlation
1391
+ // (input acks, list/create/subscribe replies) is deliberately BLIND —
1392
+ // nothing we've sent yet could have a reply pending. But state-bearing
1393
+ // broadcasts the daemon replays right after auth (most importantly
1394
+ // `permission_request` for an already-pending permission) are real and
1395
+ // must not be silently lost just because they arrived before the
1396
+ // fence's `pong`. Buffer them (bounded), tagged with whether they
1397
+ // arrived under the connection key, and flush through the same path a
1398
+ // live message takes — observation included — immediately after
1399
+ // `reset()` mints the fresh epoch they'll be recorded under.
1400
+ // `respondPermission` requires the ready state, so deferring the
1401
+ // observation to the (synchronous) flush cannot make a real pending
1402
+ // request unanswerable.
1403
+ if (PRE_READY_BUFFERED_TYPES.has(msg.type)) {
1404
+ if (this._preReadyBuffer.length >= MAX_PRE_READY_BUFFER) this._preReadyBuffer.shift()
1405
+ this._preReadyBuffer.push({ msg, authenticated })
1406
+ }
1407
+ this.emit('_handshake', msg)
1408
+ return
1409
+ }
1410
+
1411
+ // Ready state: a plaintext frame on an encryption-required connection
1412
+ // never gets here (`_onRawMessage` fails the connection first), so every
1413
+ // message reaching this point is as authenticated as the connection is.
1414
+ this._trackPermissionObservation(msg)
1415
+ this._processReadyMessage(msg)
1416
+ }
1417
+
1418
+ /**
1419
+ * The "connection is ready" half of message processing — request/response
1420
+ * correlation, event-log recording, and the `message` re-emission. Shared
1421
+ * between live dispatch and the post-handshake flush of
1422
+ * `_preReadyBuffer` (see `_dispatch`), so a buffered pre-ready message is
1423
+ * processed through EXACTLY the same logic a live one would be.
1424
+ *
1425
+ * The FIRST thing this does is redact the message deeply, in place of the
1426
+ * original — every downstream consumer (serial-op resolution, input_ack
1427
+ * resolution, permission resolution, the retained event log, the
1428
+ * `message` re-emission every public method's promises ultimately resolve
1429
+ * from) therefore only ever sees the redacted copy. This is deliberately
1430
+ * BEFORE `classifyBroadcast`'s truncation — truncating first could split a
1431
+ * secret across the cut point and leave a still-recognizable fragment on
1432
+ * one side.
1433
+ */
1434
+ _processReadyMessage(rawMsg) {
1435
+ const msg = this._redactMessageDeep(rawMsg)
1436
+ if (msg.type === 'input_ack' && typeof msg.clientMessageId === 'string') {
1437
+ const key = this._inputAckKey(msg.sessionId, msg.clientMessageId)
1438
+ const pending = this._pendingInputAcks.get(key)
1439
+ // Exact sessionId match required — a MISSING sessionId on the ack is
1440
+ // NOT treated as a match (a legacy reply path that omits sessionId
1441
+ // must not be silently assumed to be about whichever session we
1442
+ // happen to be waiting on). `typeof pending.resolve === 'function'`
1443
+ // excludes a bare reservation (see sendInput) that hasn't reached the
1444
+ // "actually waiting" stage yet — see `_rejectAllPending` for why that
1445
+ // state can exist at all.
1446
+ if (pending && typeof pending.resolve === 'function' && msg.sessionId === pending.sessionId) {
1447
+ pending.lastKnown = msg
1448
+ if (msg.reason === 'admission_pending') {
1449
+ // Intermediate status update, not the final word — keep waiting
1450
+ // for a conclusive ack or the deadline.
1451
+ } else {
1452
+ this._pendingInputAcks.delete(key)
1453
+ clearTimeout(pending.timer)
1454
+ pending.resolve(msg)
1455
+ }
1456
+ }
1457
+ // An ack for an id/session we don't recognize (another connection's
1458
+ // message, or one we already timed out) is intentionally NOT
1459
+ // re-correlated — see class doc "never silently retry".
1460
+ } else if ((msg.type === 'permission_resolved' || msg.type === 'permission_expired' || (msg.type === 'error' && msg.requestId)) && typeof msg.requestId === 'string') {
1461
+ const pending = this._pendingPermissionResponses.get(msg.requestId)
1462
+ if (pending) {
1463
+ this._pendingPermissionResponses.delete(msg.requestId)
1464
+ clearTimeout(pending.timer)
1465
+ const status = msg.type === 'permission_resolved' ? 'resolved' : msg.type === 'permission_expired' ? 'expired' : 'rejected'
1466
+ pending.resolve({ status, requestId: msg.requestId, sessionId: pending.sessionId, decision: msg.decision, detail: msg })
1467
+ }
1468
+ } else if (msg.type === 'history_replay_start' && msg.sessionId) {
1469
+ this._replayingSessions.add(msg.sessionId)
1470
+ } else if (msg.type === 'history_replay_end' && msg.sessionId) {
1471
+ this._replayingSessions.delete(msg.sessionId)
1472
+ } else if (msg.type === 'model_changed' && msg.sessionId) {
1473
+ const expectation = this._modelExpectations.get(msg.sessionId)
1474
+ if (expectation) {
1475
+ const observed = msg.model ?? null
1476
+ const unknown = observed === null
1477
+ const mismatch = !unknown && expectation.requestedModel !== null && expectation.requestedModel !== observed
1478
+ expectation.lastKnownStatus = { requested: expectation.requestedModel, observed, unknown, mismatch }
1479
+ }
1480
+ }
1481
+
1482
+ if (this._pendingSerialOp) {
1483
+ const acceptTypes = SERIAL_REPLY_TYPES[this._pendingSerialOp.kind]
1484
+ // A `create_session` failure reply (`session_error`) is UNSCOPED —
1485
+ // the session was never created, so `handleCreateSession`'s error
1486
+ // path never stamps a `sessionId` (see session-handlers.js). A
1487
+ // SCOPED `session_error` (one naming a sessionId) belongs to some
1488
+ // OTHER concurrent session-targeted operation on this connection
1489
+ // (e.g. a sibling `interrupt`/`sendInput` failure broadcast) and must
1490
+ // never be mistaken for this create's own result — accepting it would
1491
+ // let an unrelated sibling error falsely fail (or, worse, silently
1492
+ // settle) a create that is actually still pending or already succeeded.
1493
+ const matchesKind = acceptTypes && acceptTypes.includes(msg.type)
1494
+ && !(this._pendingSerialOp.kind === 'create_session' && msg.type === 'session_error' && msg.sessionId != null)
1495
+ && (typeof this._pendingSerialOp.accept !== 'function' || this._pendingSerialOp.accept(msg))
1496
+ if (matchesKind) {
1497
+ const op = this._pendingSerialOp
1498
+ this._pendingSerialOp = null
1499
+ clearTimeout(op.timer)
1500
+ op.resolve(msg)
1501
+ }
1502
+ }
1503
+
1504
+ const events = classifyBroadcast(msg, this._streamAccumulator, { includeThinking: this._includeThinking })
1505
+ for (const evt of events) {
1506
+ const data = this._replayingSessions.has(evt.sessionId) && evt.data && typeof evt.data === 'object'
1507
+ ? { ...evt.data, replay: true }
1508
+ : evt.data
1509
+ this._eventLog.push(evt.sessionId, evt.type, data)
1510
+ }
1511
+ this.emit('message', msg)
1512
+ }
1513
+
1514
+ _inputAckKey(sessionId, clientMessageId) {
1515
+ return `${sessionId}::${clientMessageId}`
1516
+ }
1517
+
1518
+ /**
1519
+ * Deep-copy `value`, redacting every string for (a) an EXACT match of this
1520
+ * connection's own bearer token — the one secret this client actually
1521
+ * knows, so an exact match can never miss it regardless of length or
1522
+ * shape, (b) `redactValue`'s pattern-based heuristics for OTHER secret
1523
+ * shapes (API keys, JWTs, webhook URLs, …), and (c) whole-value redaction
1524
+ * for any key NAME in the shared `SENSITIVE_KEY_NAMES` set (token/
1525
+ * password/secret/credential/…) — a value under one of those keys is
1526
+ * masked outright regardless of its shape, matching the broadcast
1527
+ * sanitizer's own key-name rule (redaction.js) so a plaintext
1528
+ * password/credential field can't slip through just because it doesn't
1529
+ * match any of the VALUE-shape patterns. Applied only to post-handshake
1530
+ * application messages (see `_processReadyMessage`) — never to the
1531
+ * handshake's own crypto material (exchange keys / signatures), which
1532
+ * this must not risk mangling.
1533
+ *
1534
+ * Depth overflow returns a bounded MARKER, not the raw (unredacted, and
1535
+ * potentially attacker-controlled-depth) subtree — returning the raw value
1536
+ * would be exactly the kind of "the guard fires but hands back the
1537
+ * un-guarded content anyway" failure this exists to prevent.
1538
+ */
1539
+ _redactMessageDeep(value, depth = 0) {
1540
+ if (depth > 10) return '[max depth exceeded]'
1541
+ if (typeof value === 'string') return redactValue(redactToken(value, this._token))
1542
+ if (Array.isArray(value)) return value.map((v) => this._redactMessageDeep(v, depth + 1))
1543
+ if (value && typeof value === 'object') {
1544
+ const out = {}
1545
+ for (const [k, v] of Object.entries(value)) {
1546
+ // Mask WHOLE-VALUE under a sensitive key name regardless of shape —
1547
+ // an object/array value (a nested `{ credentials: { user, pass } }`
1548
+ // blob, say) under a sensitive key is exactly as much a leak as a
1549
+ // bare string one; recursing into it instead of masking it outright
1550
+ // would miss that.
1551
+ if (SENSITIVE_KEY_NAMES.has(k.toLowerCase()) && v !== null && v !== undefined) {
1552
+ out[k] = '[REDACTED]'
1553
+ } else {
1554
+ out[k] = this._redactMessageDeep(v, depth + 1)
1555
+ }
1556
+ }
1557
+ return out
1558
+ }
1559
+ return value
1560
+ }
1561
+
1562
+ _onSocketClosed(code, reason) {
1563
+ if (this._state === 'closed') return
1564
+ const wasReady = this._state === 'ready'
1565
+ this._state = 'closed'
1566
+ this._teardownConnectionState()
1567
+ this._abortHandshakeWaiters(new NotConnectedError(`connection closed (code=${code})`))
1568
+ this._rejectAllPending(new NotConnectedError(`connection closed (code=${code})`))
1569
+ if (wasReady) this.emit('close', { code, reason: redactPublicText(reason?.toString?.() ?? '', this._token) })
1570
+ }
1571
+
1572
+ /**
1573
+ * Every place a connection ends (explicit `close()`, an unexpected socket
1574
+ * close, or `_failConnection`) must wake/clear the SAME state — a
1575
+ * long-poll `getEvents` waiter left registered past disconnect would sit
1576
+ * until its own timeout fires instead of resolving immediately, and stale
1577
+ * stream/permission/subscription state would otherwise survive into
1578
+ * whatever the caller does next (which, for THIS client instance, is
1579
+ * nothing — `_assertReady()` blocks all further calls — but leaving it
1580
+ * live is still a real leak, not just cosmetic).
1581
+ */
1582
+ _teardownConnectionState() {
1583
+ this._eventLog.reset() // wakes every waiter (see SessionEventLog.reset) and clears retained events
1584
+ this._streamAccumulator.clear()
1585
+ this._observedPermissions.clear()
1586
+ this._replayingSessions.clear()
1587
+ this._subscribedSessionIds.clear()
1588
+ this._preReadyBuffer = [] // a connect() that failed mid-fence must not leave buffered messages referenced
1589
+ }
1590
+
1591
+ _onSocketError(err) {
1592
+ err = this._safeError(err)
1593
+ this._log('socket error:', err.message)
1594
+ if (this._state !== 'closed') {
1595
+ this._abortHandshakeWaiters(err)
1596
+ }
1597
+ this.emit('error', err)
1598
+ }
1599
+
1600
+ _failConnection(err) {
1601
+ err = this._safeError(err)
1602
+ this._state = 'closed'
1603
+ this._teardownConnectionState()
1604
+ this._abortHandshakeWaiters(err)
1605
+ this._rejectAllPending(err)
1606
+ try { this._ws?.close() } catch { /* already closing */ }
1607
+ this.emit('error', err)
1608
+ }
1609
+
1610
+ _safeError(err) {
1611
+ const safe = new Error(redactPublicText(err?.message ?? String(err), this._token))
1612
+ if (err instanceof Error) Object.setPrototypeOf(safe, Object.getPrototypeOf(err))
1613
+ safe.name = redactPublicText(err?.name || 'Error', this._token)
1614
+ if (typeof err?.code === 'string') safe.code = redactPublicText(err.code, this._token)
1615
+ else if (typeof err?.code === 'number') safe.code = err.code
1616
+ if (typeof err?.stack === 'string') safe.stack = redactPublicText(err.stack, this._token)
1617
+ return safe
1618
+ }
1619
+
1620
+ _rejectAllPending(err) {
1621
+ for (const pending of this._pendingInputAcks.values()) {
1622
+ // A bare RESERVATION (sendInput still awaiting its model/subscription
1623
+ // checks — see sendInput's reservation comment) has no `resolve`/timer
1624
+ // yet; the in-flight `sendInput` call's own catch block cleans it up
1625
+ // when the awaited failure propagates to it. Nothing to settle here.
1626
+ if (typeof pending.resolve !== 'function') continue
1627
+ clearTimeout(pending.timer)
1628
+ // sendInput's contract is "never throw on timeout/disconnect" — resolve
1629
+ // with an uncertain result instead of rejecting, matching the timeout path.
1630
+ pending.resolve({ status: 'uncertain', delivery: 'unknown', retrySafe: false, dedupScope: pending.lastKnown?.dedupScope ?? 'process', clientMessageId: pending.clientMessageId, sessionId: pending.sessionId, disconnected: true, lastKnownStatus: pending.lastKnown ?? null, message: err.message })
1631
+ }
1632
+ this._pendingInputAcks.clear()
1633
+ for (const [requestId, pending] of this._pendingPermissionResponses) {
1634
+ clearTimeout(pending.timer)
1635
+ pending.resolve({ status: 'uncertain', requestId, sessionId: pending.sessionId, disconnected: true, message: err.message })
1636
+ }
1637
+ this._pendingPermissionResponses.clear()
1638
+ for (const abort of [...this._pendingRequests]) abort(err)
1639
+ if (this._pendingSerialOp) {
1640
+ clearTimeout(this._pendingSerialOp.timer)
1641
+ this._pendingSerialOp.reject(err)
1642
+ this._pendingSerialOp = null
1643
+ }
1644
+ }
1645
+ }