@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,422 @@
1
+ /**
2
+ * TurnDriver (engine foundations, epic #6691, step E-1) — the single primitive
3
+ * for driving one turn of a Chroxy session and getting its final text back.
4
+ * The orchestration engine never touches sessions directly; it drives them
5
+ * through here.
6
+ *
7
+ * Mechanics (design §4.2):
8
+ * - One `session_event` listener on the SessionManager; per-session FIFO mutex
9
+ * so at most one driven turn runs per session (committee reviews serialize on
10
+ * the architect session).
11
+ * - Epoch guard: events that arrive before our send, or a stray `result` with
12
+ * no active turn, are ignored. That guard only protects a QUEUED turn because
13
+ * the mutex handoff is deferred past the end of the current synchronous frame —
14
+ * see _scheduleNext.
15
+ * - Text is accumulated live from `stream_delta` (per messageId) + non-streamed
16
+ * `message {type:'response'}` events, bounded to MAX_ACCUM_BYTES with an
17
+ * explicit truncation marker (the decision parser scans from the tail).
18
+ * - SUCCESS keys ONLY off the `result` event (isRunning can stay true on
19
+ * pending background shells). `error` is turn-terminal → TurnError.
20
+ * - `stopped` is turn-terminal too → TURN_STOPPED (#7009). Every provider that
21
+ * emits `stopped` does so ONLY on its intentional-stop path (`wasIntentionalStop`:
22
+ * see sdk-session.js, cli-session.js, jsonl-subprocess-session.js,
23
+ * codex-app-server-session.js — #4881), i.e. someone called interrupt();
24
+ * claude-tui and claude-byok never emit it at all. Such a turn produces NO
25
+ * `result` and NO `error`, so without this the caller's promise hung until the
26
+ * watchdog fired. It gets its OWN code, never a success: an interrupted turn did
27
+ * not do the work it was asked to do.
28
+ * This settle deliberately does NOT drain, unlike the timeout path: `stopped` is
29
+ * the very event _endDrain keys off, so draining on it would always burn the full
30
+ * drainTimeoutMs. Trailing events are handled by dropping the ctx from `_active`
31
+ * at once and deferring the handoff instead (next bullet).
32
+ * - Mutex handoff crosses a tick. A queued turn is NEVER started from inside a
33
+ * session-event callback (_scheduleNext). Providers emit a turn's terminal
34
+ * events from ONE synchronous frame — CliSession._handleChildClose emits
35
+ * `stream_end` + a synthetic `result` and THEN `stopped`; _handleHardTimeout /
36
+ * _handleStreamStall emit `result` then `error`; jsonl-subprocess's child-close
37
+ * and codex's _failTurn are the same shape — so starting the queued turn
38
+ * synchronously on the FIRST of them handed the rest of that frame to the wrong
39
+ * turn: the epoch guard could not drop those events because a fresh live ctx was
40
+ * already registered. That is #6723's cross-turn misattribution through the door
41
+ * the post-timeout drain does not cover (it is the result/error/stopped path that
42
+ * releases the mutex, not the timeout path).
43
+ * RESIDUAL: `stopped` carries no turn id, so a provider that emitted a turn's
44
+ * terminal event and THEN `stopped` in a LATER macrotask would still settle the
45
+ * following turn. No in-tree provider does that (every emit site listed above is
46
+ * a single synchronous frame); closing it by construction needs a provider-side
47
+ * turn id on the event payload.
48
+ * - Interrupted turns that LOOK finished (#7036, #7072). CliSession emits its
49
+ * synthetic interrupted `result` (cost:null, load-bearing for clearing the
50
+ * dashboard spinner) BEFORE `stopped`. Two harms follow: the turn settles as a
51
+ * SUCCESS on the `result`, and (since #7033) the trailing `stopped` lands on the
52
+ * NEXT queued turn and kills it.
53
+ *
54
+ * The QUEUED-TURN KILL is closed by construction: only claude-cli emits `result`
55
+ * then `stopped` for one interrupt, and claude-cli cannot enter TurnDriver by ANY
56
+ * route — the scheduler requires capabilities.inProcessPermissions (cli-session
57
+ * sets it false), the orchestration WORKER roles are gated on
58
+ * AUDIT/IMPLEMENT_ELIGIBLE_PROVIDERS, and the ARCHITECT role on
59
+ * ARCHITECT_ELIGIBLE_PROVIDERS.
60
+ *
61
+ * The FALSE SUCCESS is closed by a provider-side flag: a `result` payload carries
62
+ * `interrupted: true` when the turn ended by abort/interrupt/stall rather than
63
+ * completion, and this driver rejects it (TURN_STOPPED, or TURN_ERROR when the
64
+ * payload also carries `failureMessage`). The flag is set by BaseSession.emit for
65
+ * every result whose `turnOutcome` is `stopped` (the SDK's aborted_* results, an
66
+ * ACP `cancelled`), by claude-byok when an interrupt lands in the tool phase, by
67
+ * claude-sdk's stream-stall result and by claude-cli's synthetic interrupted
68
+ * result. It is internal: event-normalizer whitelists the result fields it puts
69
+ * on the wire, so clients never see it.
70
+ *
71
+ * NOT covered: the Codex app-server. It ends an interrupted turn with
72
+ * `turn/completed` and `_finishTurn` reports it as a normal result without
73
+ * reading `turn.status` (see the comment there). Whether the real binary does
74
+ * that is tracked separately; until it is pinned, an operator Stop on a codex
75
+ * session can still settle as a success.
76
+ * - Watchdog: on timeout, interrupt() the session and reject TURN_TIMEOUT.
77
+ * - `session_destroyed` mid-turn → SESSION_GONE.
78
+ */
79
+
80
+ export const MAX_ACCUM_BYTES = 2 * 1024 * 1024
81
+ export const DEFAULT_TURN_TIMEOUT_MS = 30 * 60 * 1000
82
+ // After a timeout+interrupt the mutex is held in a "draining" state until the
83
+ // session confirms it stopped (a trailing result/error/stopped), so a late
84
+ // event from the interrupted turn can't be misattributed to the next turn.
85
+ // This bounds how long we wait for that confirmation before releasing anyway.
86
+ export const DEFAULT_DRAIN_TIMEOUT_MS = 10 * 1000
87
+ const TRUNCATION_MARKER = '\n…[chroxy-orch: output truncated at 2MB]…\n'
88
+
89
+ export class TurnError extends Error {
90
+ constructor(code, message, { partialText = '' } = {}) {
91
+ super(message || code)
92
+ this.name = 'TurnError'
93
+ this.code = code // TURN_ERROR | TURN_TIMEOUT | TURN_STOPPED | SESSION_GONE | SEND_FAILED
94
+ this.partialText = partialText
95
+ }
96
+ }
97
+
98
+ export class TurnDriver {
99
+ /**
100
+ * @param {{ sessionManager: import('node:events').EventEmitter, log?: object,
101
+ * defaultTimeoutMs?: number }} opts
102
+ */
103
+ constructor({ sessionManager, log = null, defaultTimeoutMs = DEFAULT_TURN_TIMEOUT_MS, drainTimeoutMs = DEFAULT_DRAIN_TIMEOUT_MS }) {
104
+ if (!sessionManager || typeof sessionManager.on !== 'function') {
105
+ throw new Error('TurnDriver requires a sessionManager EventEmitter')
106
+ }
107
+ this._sm = sessionManager
108
+ this._log = log
109
+ this._defaultTimeoutMs = defaultTimeoutMs
110
+ this._drainTimeoutMs = drainTimeoutMs
111
+ this._active = new Map() // sessionId -> active turn context
112
+ this._occupied = new Set() // sessionId -> has a turn running or reserved
113
+ this._waiters = new Map() // sessionId -> FIFO array of { start, reject }
114
+ this._handoff = new Set() // sessionId -> a deferred _startNext is already queued
115
+ this._onSessionEvent = this._handleSessionEvent.bind(this)
116
+ this._onSessionDestroyed = this._handleSessionDestroyed.bind(this)
117
+ this._sm.on('session_event', this._onSessionEvent)
118
+ this._sm.on('session_destroyed', this._onSessionDestroyed)
119
+ this._disposed = false
120
+ }
121
+
122
+ dispose() {
123
+ this._disposed = true
124
+ this._sm.off?.('session_event', this._onSessionEvent)
125
+ this._sm.off?.('session_destroyed', this._onSessionDestroyed)
126
+ // Reject queued (never-started) turns so their promises settle instead of
127
+ // hanging forever, then reject in-flight ones. Snapshot before mutating.
128
+ const waiters = [...this._waiters.values()].flat()
129
+ const active = [...this._active.values()]
130
+ this._waiters.clear()
131
+ this._active.clear()
132
+ this._occupied.clear()
133
+ this._handoff.clear()
134
+ for (const w of waiters) {
135
+ try { w.reject(new TurnError('SESSION_GONE', 'TurnDriver disposed')) } catch { /* ignore */ }
136
+ }
137
+ for (const ctx of active) {
138
+ if (ctx.drainTimer) { clearTimeout(ctx.drainTimer); ctx.drainTimer = null }
139
+ if (ctx.settled) continue
140
+ ctx.settled = true
141
+ if (ctx.timer) { clearTimeout(ctx.timer); ctx.timer = null }
142
+ ctx.reject(new TurnError('SESSION_GONE', 'TurnDriver disposed', { partialText: ctx.text() }))
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Drive one turn: send `prompt`, accumulate output, resolve on `result`.
148
+ * The turn's context is registered SYNCHRONOUSLY with its send, so no event can
149
+ * arrive before the accumulator exists (a fast provider can emit before the
150
+ * returned promise is even awaited). Contended turns queue FIFO and start on the
151
+ * tick after the prior turn releases — never inside the frame that released it
152
+ * (_scheduleNext).
153
+ * @returns {Promise<{ text: string, result: { cost, duration, usage, modelUsage, model, numTurns, apiDurationMs } }>}
154
+ * @throws {TurnError}
155
+ */
156
+ driveTurn(sessionId, prompt, { label = null, timeoutMs = null } = {}) {
157
+ if (this._disposed) return Promise.reject(new TurnError('SESSION_GONE', 'TurnDriver disposed'))
158
+ const entry = this._sm.getSession?.(sessionId)
159
+ if (!entry || !entry.session) return Promise.reject(new TurnError('SESSION_GONE', `session ${sessionId} not found`))
160
+
161
+ return new Promise((resolve, reject) => {
162
+ const start = () => this._beginTurn(sessionId, prompt, { label, timeoutMs }, resolve, reject)
163
+ if (!this._occupied.has(sessionId)) {
164
+ this._occupied.add(sessionId)
165
+ start()
166
+ } else {
167
+ const q = this._waiters.get(sessionId) || []
168
+ q.push({ start, reject })
169
+ this._waiters.set(sessionId, q)
170
+ }
171
+ })
172
+ }
173
+
174
+ _beginTurn(sessionId, prompt, { label, timeoutMs }, resolve, reject) {
175
+ // Re-fetch the session at START time, not at driveTurn() time: a queued turn
176
+ // may have waited behind the mutex while its session was destroyed/replaced.
177
+ const entry = this._sm.getSession?.(sessionId)
178
+ if (!entry || !entry.session) {
179
+ reject(new TurnError('SESSION_GONE', `session ${sessionId} gone before its turn started`))
180
+ this._scheduleNext(sessionId)
181
+ return
182
+ }
183
+ const ctx = {
184
+ sessionId,
185
+ label,
186
+ buffers: new Map(), // messageId -> streamed text
187
+ order: [], // {kind:'buf',mid} | {kind:'resp',text} in arrival order
188
+ bytes: 0,
189
+ truncated: false,
190
+ settled: false,
191
+ timer: null,
192
+ resolve,
193
+ reject,
194
+ }
195
+ ctx.text = () => this._assembleText(ctx)
196
+ this._active.set(sessionId, ctx)
197
+
198
+ const ms = Number.isFinite(timeoutMs) ? timeoutMs : this._defaultTimeoutMs
199
+ // NOT unref'd: an in-flight orchestration turn is real work that should hold
200
+ // the process open, and the timer is always cleared on turn completion /
201
+ // dispose (so it never leaks — cf. the #6027 leaked-handle family).
202
+ ctx.timer = setTimeout(() => {
203
+ try { entry.session.interrupt?.() } catch { /* best-effort */ }
204
+ // Drain: settle the caller now, but HOLD the mutex until the interrupted
205
+ // session confirms it stopped, so its trailing events don't leak into the
206
+ // next turn (finding #6723).
207
+ this._finishTurn(ctx, () => ctx.reject(new TurnError('TURN_TIMEOUT', `turn timed out after ${ms}ms`, { partialText: ctx.text() })), { drain: true })
208
+ }, ms)
209
+
210
+ // Fire-and-forget send; a rejection (closing socket, etc.) is SEND_FAILED —
211
+ // NEVER leave it unhandled (an unhandled rejection crashes the daemon).
212
+ try {
213
+ const ret = entry.session.sendMessage(prompt, [], { clientMessageId: `orch-${label || 'turn'}` })
214
+ if (ret && typeof ret.then === 'function') {
215
+ ret.catch((err) => {
216
+ this._finishTurn(ctx, () => ctx.reject(new TurnError('SEND_FAILED', (err && err.message) || 'sendMessage rejected', { partialText: ctx.text() })))
217
+ })
218
+ }
219
+ } catch (err) {
220
+ this._finishTurn(ctx, () => ctx.reject(new TurnError('SEND_FAILED', (err && err.message) || 'sendMessage threw', { partialText: ctx.text() })))
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Hand the per-session mutex to the next queued turn — but never from inside the
226
+ * frame that released it. A provider emits a turn's terminal events (`stream_end`
227
+ * + a synthetic `result` + `stopped`, or `result` + `error`) from ONE synchronous
228
+ * frame; starting the queued turn on the first of them registered a live ctx that
229
+ * the REST of the frame then landed on, which is how a finished turn's trailing
230
+ * `stopped` came to reject the next turn (#7033 review). Deferring to
231
+ * process.nextTick puts the ctx removal in _finishTurn and the next ctx's
232
+ * registration on opposite sides of the frame boundary, so the epoch guard in
233
+ * _handleSessionEvent drops those trailing events instead of misattributing them.
234
+ *
235
+ * `_occupied` stays set across the gap, so a driveTurn() landing inside it queues
236
+ * rather than racing ahead. At most ONE handoff may be pending per session: two
237
+ * would each shift a waiter off the FIFO and start it, breaking the mutex.
238
+ */
239
+ _scheduleNext(sessionId) {
240
+ if (this._handoff.has(sessionId)) return
241
+ this._handoff.add(sessionId)
242
+ process.nextTick(() => {
243
+ this._handoff.delete(sessionId)
244
+ if (this._disposed) return
245
+ this._startNext(sessionId)
246
+ })
247
+ }
248
+
249
+ _startNext(sessionId) {
250
+ const q = this._waiters.get(sessionId)
251
+ if (q && q.length > 0) {
252
+ const next = q.shift() // stays occupied — hand the slot to the next turn
253
+ next.start()
254
+ } else {
255
+ this._occupied.delete(sessionId)
256
+ this._waiters.delete(sessionId)
257
+ }
258
+ }
259
+
260
+ _handleSessionEvent({ sessionId, event, data } = {}) {
261
+ const ctx = this._active.get(sessionId)
262
+ if (!ctx) return // epoch guard: no active/draining turn for this session → drop
263
+ if (ctx.draining) {
264
+ // A settled-but-draining turn (post-timeout). Swallow its trailing output;
265
+ // a terminal event confirms the session stopped → release the mutex.
266
+ if (event === 'result' || event === 'error' || event === 'stopped' || event === 'stream_end') {
267
+ this._endDrain(ctx)
268
+ }
269
+ return
270
+ }
271
+ if (ctx.settled) return
272
+ switch (event) {
273
+ case 'stream_delta': {
274
+ const mid = data?.messageId ?? '_'
275
+ const delta = typeof data?.delta === 'string' ? data.delta : ''
276
+ if (!delta) break
277
+ if (!ctx.buffers.has(mid)) { ctx.buffers.set(mid, ''); ctx.order.push({ kind: 'buf', mid }) }
278
+ ctx.buffers.set(mid, ctx.buffers.get(mid) + this._boundedAccept(ctx, delta))
279
+ break
280
+ }
281
+ case 'message': {
282
+ if (data?.type === 'response' && typeof data.content === 'string' && data.content.length) {
283
+ const accepted = this._boundedAccept(ctx, data.content)
284
+ if (accepted.length) ctx.order.push({ kind: 'resp', text: accepted })
285
+ }
286
+ break
287
+ }
288
+ case 'result': {
289
+ // #7072 — a terminal-looking `result` the provider marked `interrupted:
290
+ // true` is terminal but NOT a success: the turn was cut short (a Stop that
291
+ // the provider answered with a normal result, a BYOK interrupt in the tool
292
+ // phase, a stalled stream). Settle it as a failure here, on the result,
293
+ // because the event that follows it in the same synchronous frame (`stopped`
294
+ // / `error`) is dropped by the epoch guard once this ctx is gone — which is
295
+ // exactly how a truncated plan or review came to be read as authoritative.
296
+ // A provider that also knows WHY it failed (a stall) names it in
297
+ // `failureMessage`, and the caller sees TURN_ERROR; otherwise it is the
298
+ // same TURN_STOPPED an interrupt that emits `stopped` instead produces.
299
+ if (data?.interrupted === true) {
300
+ const partialText = this._assembleText(ctx)
301
+ const failure = typeof data.failureMessage === 'string' && data.failureMessage ? data.failureMessage : null
302
+ this._finishTurn(ctx, () => ctx.reject(failure
303
+ ? new TurnError('TURN_ERROR', failure, { partialText })
304
+ : new TurnError('TURN_STOPPED', 'turn interrupted before completing', { partialText })))
305
+ break
306
+ }
307
+ // Forward the FULL terminal usage payload, not just cost/duration/usage:
308
+ // the ledger's recordTurnUsage keys off modelUsage/model/numTurns/
309
+ // apiDurationMs for per-model attribution (#6692). Dropping them here
310
+ // would silently collapse every metered run to a single unknown model.
311
+ const result = {
312
+ cost: data?.cost ?? null,
313
+ duration: data?.duration ?? null,
314
+ usage: data?.usage ?? null,
315
+ modelUsage: data?.modelUsage ?? null,
316
+ model: data?.model ?? null,
317
+ numTurns: Number.isFinite(data?.numTurns) ? data.numTurns : null,
318
+ apiDurationMs: Number.isFinite(data?.apiDurationMs) ? data.apiDurationMs : null,
319
+ }
320
+ const text = this._assembleText(ctx)
321
+ this._finishTurn(ctx, () => ctx.resolve({ text, result }))
322
+ break
323
+ }
324
+ case 'error': {
325
+ this._finishTurn(ctx, () => ctx.reject(new TurnError('TURN_ERROR', (data && data.message) || 'session error', { partialText: this._assembleText(ctx) })))
326
+ break
327
+ }
328
+ case 'stopped': {
329
+ // #7009 — someone interrupted this turn (the scheduler denying a
330
+ // permission prompt, an operator pressing Stop, an orchestration cancel).
331
+ // Providers emit `stopped` INSTEAD of `result`/`error` on that path
332
+ // (#4881), so ignoring it left driveTurn pending until the watchdog —
333
+ // 15 minutes of a held concurrency slot in the scheduler.
334
+ //
335
+ // Deliberately a REJECTION with its own code, never a resolve: the turn
336
+ // is over but its work did not complete, and resolving here would report
337
+ // an interrupted turn as a finished one. partialText carries whatever the
338
+ // turn managed to produce so the caller can still inspect it.
339
+ //
340
+ // This can only be THIS turn's `stopped`: a `stopped` trailing a turn that
341
+ // already settled arrives in the same synchronous frame as that settle, and
342
+ // the queued turn is not started until the next tick (_scheduleNext), so it
343
+ // hits the epoch guard with no active ctx. No drain here — `stopped` is the
344
+ // event _endDrain waits for, so draining on it would burn drainTimeoutMs
345
+ // every time.
346
+ this._finishTurn(ctx, () => ctx.reject(new TurnError('TURN_STOPPED', 'turn interrupted before completing', { partialText: this._assembleText(ctx) })))
347
+ break
348
+ }
349
+ default:
350
+ break
351
+ }
352
+ }
353
+
354
+ _handleSessionDestroyed({ sessionId } = {}) {
355
+ const ctx = this._active.get(sessionId)
356
+ if (!ctx || ctx.settled) return
357
+ this._finishTurn(ctx, () => ctx.reject(new TurnError('SESSION_GONE', `session ${sessionId} destroyed mid-turn`, { partialText: this._assembleText(ctx) })))
358
+ }
359
+
360
+ // Accept as much of `str` as fits under the 2MB accumulator budget; returns
361
+ // the accepted text (with a truncation marker appended once, on the crossing).
362
+ // Pure w.r.t. `order` — the caller decides where the accepted text lands.
363
+ _boundedAccept(ctx, str) {
364
+ if (ctx.truncated) return ''
365
+ const room = MAX_ACCUM_BYTES - ctx.bytes
366
+ const bytes = Buffer.byteLength(str, 'utf8')
367
+ if (bytes <= room) {
368
+ ctx.bytes += bytes
369
+ return str
370
+ }
371
+ // over budget — take the codepoints that fit (stream decode drops a trailing
372
+ // partial sequence), then mark truncated so later output is ignored.
373
+ const slice = new TextDecoder('utf8').decode(Buffer.from(str, 'utf8').subarray(0, Math.max(0, room)), { stream: true })
374
+ ctx.bytes = MAX_ACCUM_BYTES
375
+ ctx.truncated = true
376
+ return slice + TRUNCATION_MARKER
377
+ }
378
+
379
+ _assembleText(ctx) {
380
+ // Concatenate in arrival order: streamed buffers by messageId + inline
381
+ // response strings. Falls back to nothing if empty (caller may read history).
382
+ const parts = []
383
+ for (const item of ctx.order) {
384
+ if (item.kind === 'buf') parts.push(ctx.buffers.get(item.mid) || '')
385
+ else parts.push(item.text)
386
+ }
387
+ return parts.join('')
388
+ }
389
+
390
+ _finishTurn(ctx, settle, { drain = false } = {}) {
391
+ if (ctx.settled) return
392
+ ctx.settled = true
393
+ if (ctx.timer) { clearTimeout(ctx.timer); ctx.timer = null }
394
+ // Settle the caller's promise immediately either way.
395
+ try { settle() } catch { /* settle should not throw */ }
396
+ if (drain) {
397
+ // Keep the ctx in _active (marked draining) so the mutex stays held and
398
+ // this session's trailing events are swallowed until it confirms it
399
+ // stopped or the drain watchdog fires.
400
+ ctx.draining = true
401
+ // unref'd: the caller's promise is already settled, so nothing awaited
402
+ // depends on this; it's just a grace period before releasing the mutex,
403
+ // and the process shouldn't stay alive for it. Normally a trailing
404
+ // terminal event ends the drain well before this fires.
405
+ ctx.drainTimer = setTimeout(() => this._endDrain(ctx), this._drainTimeoutMs)
406
+ if (typeof ctx.drainTimer.unref === 'function') ctx.drainTimer.unref()
407
+ } else {
408
+ // Drop the ctx NOW so every remaining event in this frame hits the epoch
409
+ // guard, and hand the mutex over on the next tick (see _scheduleNext).
410
+ this._active.delete(ctx.sessionId)
411
+ this._scheduleNext(ctx.sessionId)
412
+ }
413
+ }
414
+
415
+ _endDrain(ctx) {
416
+ if (ctx.drainTimer) { clearTimeout(ctx.drainTimer); ctx.drainTimer = null }
417
+ if (this._active.get(ctx.sessionId) === ctx) {
418
+ this._active.delete(ctx.sessionId)
419
+ this._scheduleNext(ctx.sessionId)
420
+ }
421
+ }
422
+ }