@chroxy/server 0.10.0 → 0.11.10

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