@chroxy/server 0.11.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 (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +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 +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  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 +69 -5
  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 +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -79,6 +79,9 @@ async function fetchWithRetry(url, options) {
79
79
  // Exported for testing (re-exported from push.js for existing importers)
80
80
  export { fetchWithRetry, FETCH_TIMEOUT_MS, MAX_RETRIES, BACKOFF_BASE_MS }
81
81
 
82
+ // The owner recorded for a registration restored from disk (see _loadFromDisk).
83
+ const RESTORED_OWNER = Symbol('restored-registration')
84
+
82
85
  export class ExpoPushSink extends NotificationSink {
83
86
  constructor({ storagePath } = {}) {
84
87
  super({ name: 'expo-push' })
@@ -95,6 +98,11 @@ export class ExpoPushSink extends NotificationSink {
95
98
  // review on PR #2806). Owner IDs are client connection IDs in
96
99
  // production; tests can use any unique string.
97
100
  this._tokenOwners = new Map()
101
+ // Session scope of a registration: token -> Map<ownerId, sessionId> for the
102
+ // owners that registered it on behalf of ONE session (a session-scoped
103
+ // connection). An owner absent from the inner map registered it unscoped.
104
+ // See `_sessionsFor`.
105
+ this._ownerSessions = new Map()
98
106
  this._loadFromDisk()
99
107
  }
100
108
 
@@ -109,6 +117,10 @@ export class ExpoPushSink extends NotificationSink {
109
117
  for (const token of pushTokens) {
110
118
  if (typeof token === 'string' && token.length > 0) {
111
119
  this.tokens.add(token)
120
+ // A destination restored from disk was registered unscoped, by the host.
121
+ // Record that as an owner so a session-scoped registration of the same
122
+ // token can neither narrow it nor remove it when that connection leaves.
123
+ this._tokenOwners.set(token, new Set([RESTORED_OWNER]))
112
124
  }
113
125
  }
114
126
  for (const token of laTokens) {
@@ -127,7 +139,10 @@ export class ExpoPushSink extends NotificationSink {
127
139
  try {
128
140
  mkdirSync(dirname(this._storagePath), { recursive: true })
129
141
  writeFileRestricted(this._storagePath, JSON.stringify({
130
- tokens: [...this.tokens],
142
+ // A session-scoped registration lasts as long as its connection (it is
143
+ // released when that connection goes), so it is never written down:
144
+ // restored from disk it would come back without its scope.
145
+ tokens: [...this.tokens].filter((t) => this._sessionsFor(t) === null),
131
146
  liveActivityTokens: [...this._liveActivityTokens],
132
147
  }))
133
148
  } catch (err) {
@@ -150,7 +165,14 @@ export class ExpoPushSink extends NotificationSink {
150
165
  * registered token to the connection that registered it, so tokens get
151
166
  * pruned on client disconnect.
152
167
  */
153
- registerToken(token, ownerId = null) {
168
+ registerToken(token, ownerId = null, { sessionId = null } = {}) {
169
+ // A registration made on behalf of one session (`sessionId`) needs an owner:
170
+ // its scope is tracked per owner and ends with it. Without one there would be
171
+ // nothing to release it, and it would outlive the connection unscoped.
172
+ if (sessionId != null && ownerId == null) {
173
+ log.warn('Rejected session-scoped push credential without an owner')
174
+ return false
175
+ }
154
176
  if (typeof token !== 'string' || token.length === 0) {
155
177
  log.warn(`Rejected invalid push credential: ${String(token).slice(0, 40)}`)
156
178
  return false
@@ -159,10 +181,11 @@ export class ExpoPushSink extends NotificationSink {
159
181
  log.warn(`Rejected malformed push credential (unrecognized format): ${token.slice(0, 40)}`)
160
182
  return false
161
183
  }
162
- if (!this.tokens.has(token)) {
163
- this.tokens.add(token)
164
- this._persistToDisk()
165
- }
184
+ const isNew = !this.tokens.has(token)
185
+ if (isNew) this.tokens.add(token)
186
+ // An unscoped owner joining a token that only scoped owners held makes it
187
+ // unscoped, which is what the persisted set is keyed on.
188
+ const widens = sessionId == null && this._ownerSessions.has(token)
166
189
  // Track ownership for ref-counted prune-on-disconnect (2026-04-11
167
190
  // audit blocker 6 + Copilot review on PR #2806). Multiple clients
168
191
  // may register the same token (reconnect race, multi-device); the
@@ -174,11 +197,51 @@ export class ExpoPushSink extends NotificationSink {
174
197
  this._tokenOwners.set(token, owners)
175
198
  }
176
199
  owners.add(ownerId)
200
+ let scoped = this._ownerSessions.get(token)
201
+ if (sessionId != null) {
202
+ if (!scoped) {
203
+ scoped = new Map()
204
+ this._ownerSessions.set(token, scoped)
205
+ }
206
+ scoped.set(ownerId, sessionId)
207
+ } else if (scoped) {
208
+ scoped.delete(ownerId)
209
+ if (scoped.size === 0) this._ownerSessions.delete(token)
210
+ }
177
211
  }
212
+ // After the owner and scope bookkeeping above: what is written to disk
213
+ // depends on it (a session-scoped registration is never persisted).
214
+ if (isNew || widens) this._persistToDisk()
178
215
  log.info(`Registered push credential ${token.slice(0, 30)}...`)
179
216
  return true
180
217
  }
181
218
 
219
+ /**
220
+ * The sessions a registered token may receive notifications for, or null when
221
+ * it may receive all of them.
222
+ *
223
+ * A token is limited only when EVERY owner holding it registered it for a
224
+ * session; one unscoped owner (the host's own device) makes it unscoped, and a
225
+ * token with no recorded owner (restored from disk) is unscoped. So a
226
+ * session-scoped connection can narrow what it receives but can never widen the
227
+ * delivery of a token someone else registered.
228
+ * @param {string} token
229
+ * @returns {Set<string>|null}
230
+ */
231
+ _sessionsFor(token) {
232
+ const scoped = this._ownerSessions.get(token)
233
+ if (!scoped || scoped.size === 0) return null
234
+ const owners = this._tokenOwners.get(token)
235
+ if (!owners || owners.size === 0) return null
236
+ const sessions = new Set()
237
+ for (const owner of owners) {
238
+ const sid = scoped.get(owner)
239
+ if (sid === undefined) return null
240
+ sessions.add(sid)
241
+ }
242
+ return sessions
243
+ }
244
+
182
245
  /**
183
246
  * Release one owner's claim on a token. If the last owner goes away,
184
247
  * the token is removed from the registry entirely. Returns true if
@@ -195,10 +258,19 @@ export class ExpoPushSink extends NotificationSink {
195
258
  return this.removeToken(token)
196
259
  }
197
260
  owners.delete(ownerId)
261
+ const scoped = this._ownerSessions.get(token)
262
+ let hadScope = false
263
+ if (scoped) {
264
+ hadScope = scoped.delete(ownerId)
265
+ if (scoped.size === 0) this._ownerSessions.delete(token)
266
+ }
198
267
  if (owners.size === 0) {
199
268
  this._tokenOwners.delete(token)
200
269
  return this.removeToken(token)
201
270
  }
271
+ // The registration that was limited to a session may have been the only thing
272
+ // keeping the token off disk: persist now that it may be unscoped.
273
+ if (hadScope) this._persistToDisk()
202
274
  return false
203
275
  }
204
276
 
@@ -242,6 +314,7 @@ export class ExpoPushSink extends NotificationSink {
242
314
  removeToken(token) {
243
315
  if (this.tokens.delete(token)) {
244
316
  this._tokenOwners.delete(token)
317
+ this._ownerSessions.delete(token)
245
318
  this._persistToDisk()
246
319
  return true
247
320
  }
@@ -314,7 +387,13 @@ export class ExpoPushSink extends NotificationSink {
314
387
  const shouldBypassQuietHours = context.shouldBypassQuietHours ?? (() => false)
315
388
 
316
389
  const eligibleTokens = []
390
+ const notificationSession = typeof data?.sessionId === 'string' ? data.sessionId : null
317
391
  for (const token of this.tokens) {
392
+ // A token registered for specific sessions receives only notifications
393
+ // that name one of them. One with no session (a host-wide notice) is not
394
+ // for it.
395
+ const sessions = this._sessionsFor(token)
396
+ if (sessions && !(notificationSession !== null && sessions.has(notificationSession))) continue
318
397
  if (!isCategoryEnabled(category, token)) continue
319
398
  if (isInQuietHours(now, token) && !shouldBypassQuietHours(category, token)) continue
320
399
  eligibleTokens.push(token)
@@ -114,8 +114,8 @@ function formatRelativeWakeup(at, now) {
114
114
  *
115
115
  * @param {{ backgroundTasks?: Array<{toolUseId:string, description?:string, startedAt?:number}>,
116
116
  * scheduledWakeup?: { at:number, reason?:string } | null } | null | undefined} snapshot
117
- * Output of `getBackgroundTaskSnapshot()` (#5436), or null when the session
118
- * type doesn't expose one / the transcript scan degraded.
117
+ * Output of `peekBackgroundTaskSnapshot()` (#5436 / #8052), or null when
118
+ * the session type doesn't expose one / the transcript scan degraded.
119
119
  * @param {number} [now] Reference epoch ms for the relative wakeup offset —
120
120
  * defaults to `Date.now()`. Parameterized so tests can pin the offset against
121
121
  * a fixed `at` without freezing the global clock.
@@ -162,14 +162,25 @@ export function composeReadyNotificationBody(snapshot, now = Date.now()) {
162
162
  /**
163
163
  * Read a session's background-task snapshot for notification enrichment.
164
164
  * Returns null (= "no information", body unchanged) when the session type
165
- * doesn't implement `getBackgroundTaskSnapshot()` or the read throws —
165
+ * doesn't implement `peekBackgroundTaskSnapshot()` or the read throws —
166
166
  * the same degrade-to-plain-ready posture as event-normalizer's
167
167
  * backgroundTaskFields().
168
+ *
169
+ * #8052: this call is deliberately side-effect-free — it goes through
170
+ * `peekBackgroundTaskSnapshot()`, never `getBackgroundTaskSnapshot()`. This
171
+ * composes an idle-push body whenever the session has no active viewers, so
172
+ * nothing here ever broadcasts a `claude_ready` / `background_tasks_changed`
173
+ * message to a client. Reading through the side-effecting method would
174
+ * silently advance the idle-poll's dedup baseline (and could stop the poll
175
+ * outright on a drained snapshot) with nobody ever told what changed —
176
+ * stranding a client's already-shown background-task indicator forever
177
+ * (`ws-history.js` replays a bare `claude_ready`, where an absent field means
178
+ * "keep state").
168
179
  */
169
180
  export function readBackgroundTaskSnapshot(session) {
170
181
  try {
171
- return typeof session?.getBackgroundTaskSnapshot === 'function'
172
- ? session.getBackgroundTaskSnapshot()
182
+ return typeof session?.peekBackgroundTaskSnapshot === 'function'
183
+ ? session.peekBackgroundTaskSnapshot()
173
184
  : null
174
185
  } catch {
175
186
  return null
@@ -17,8 +17,14 @@
17
17
  * `getAllowedModels()` returns null (session-manager treats a
18
18
  * non-array as "no restriction"). `getFallbackModels()` seeds the
19
19
  * dashboard picker with Ollama's recommended coder models; dynamic
20
- * discovery via GET /api/tags (#5421, ollama-tags.js) replaces the
21
- * seed with the actually-installed list when the daemon is reachable.
20
+ * discovery via GET /api/tags (#5421, ollama-tags.js) ADDS the
21
+ * actually-installed list when the daemon is reachable. It does not
22
+ * replace the seed — this line said "replaces" until #7761 and the code
23
+ * never did, which is the comment-claims-more-than-the-code class
24
+ * (#7290/#7291): the recommendations stay in the picker so a machine
25
+ * that has pulled two models is still offered the other three. That
26
+ * union is now declared, not incidental — see
27
+ * `staticModelsAreRecommendations` below.
22
28
  * Discovery is ADVISORY only — it feeds the picker, never validation.
23
29
  * - Zero pricing. Local inference is free; `_getPricing` returns a
24
30
  * zero-rate entry (not null) so byok-session's "no pricing entry"
@@ -42,6 +48,7 @@ import Anthropic from '@anthropic-ai/sdk'
42
48
  import { ClaudeByokSession } from './byok-session.js'
43
49
  import { resolveOllamaBaseUrl, ollamaEnvOverride, refreshOllamaModels } from './ollama-tags.js'
44
50
  import { BILLING_CLASSES } from './billing-class.js'
51
+ import { BYOK_CUSTOMIZATION, customizationWithEgress } from './provider-customization.js'
45
52
 
46
53
  // Compatibility re-export — resolution moved to ollama-tags.js (#5421).
47
54
  export { resolveOllamaBaseUrl }
@@ -71,6 +78,13 @@ const OLLAMA_FALLBACK_MODELS = Object.freeze([
71
78
  const OLLAMA_ZERO_PRICING = Object.freeze({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 })
72
79
 
73
80
  export class OllamaSession extends ClaudeByokSession {
81
+ static get customizationDescriptor() {
82
+ // Localhost is the default, but both CHROXY_OLLAMA_BASE_URL and OLLAMA_HOST
83
+ // may point at a remote origin. The descriptor must not claim local-only.
84
+ return customizationWithEgress(BYOK_CUSTOMIZATION, 'unknown')
85
+ }
86
+
87
+ static agentConnectionRoutes = ['local']
74
88
  // #5858: NOT Claude-family — Ollama rides ClaudeByokSession's agent loop but
75
89
  // serves locally-pulled models (getAllowedModels() returns null, #5418), so
76
90
  // override the inherited flag to false (never soft-fall-back to claude).
@@ -133,6 +147,24 @@ export class OllamaSession extends ClaudeByokSession {
133
147
  return OLLAMA_FALLBACK_MODELS
134
148
  }
135
149
 
150
+ /**
151
+ * #7761 — this provider's static seed is a RECOMMENDATION list, not a roster
152
+ * claim: `OLLAMA_FALLBACK_MODELS` names coder models worth pulling, and
153
+ * `/api/tags` reports the ones this machine has actually pulled. The two are
154
+ * different facts, so a discovery refresh must UNION rather than replace, or
155
+ * the picker stops suggesting anything the user has not already installed
156
+ * (pinned in ollama-tags.test.js: "merged fallbacks").
157
+ *
158
+ * Every other non-Claude provider leaves this false — for them the refresh IS
159
+ * the provider's own roster, and unioning a hand-maintained table back in is
160
+ * exactly how a retired model reached the wire forever (#7761).
161
+ *
162
+ * @returns {boolean}
163
+ */
164
+ static get staticModelsAreRecommendations() {
165
+ return true
166
+ }
167
+
136
168
  static getAllowedModels() {
137
169
  // null = no restriction. Valid models are whatever `ollama list`
138
170
  // shows on this machine; the daemon can't know that statically, and
@@ -41,10 +41,17 @@ export function buildOrchestrationManager({ sessionManager, config, chroxyDir, l
41
41
  })
42
42
  // The factory owns construction, so it owns teardown: extend dispose() to
43
43
  // also stop the turn driver (SessionManager listeners) and flush the ledger.
44
+ //
45
+ // Async since #7142: the manager's dispose settles once its backgrounded
46
+ // starts have. The order is load-bearing — mark the manager disposed, then
47
+ // abort in-flight turns (the driver rejects them), wait for the starts that
48
+ // rejection unwinds, and only THEN flush and close the ledger they would
49
+ // otherwise journal to.
44
50
  const managerDispose = manager.dispose.bind(manager)
45
- manager.dispose = () => {
46
- managerDispose()
51
+ manager.dispose = async () => {
52
+ const drained = managerDispose()
47
53
  try { turnDriver.dispose() } catch { /* idempotent best-effort */ }
54
+ try { await drained } catch { /* allSettled never rejects; belt and braces */ }
48
55
  try { ledger.dispose() } catch { /* flushes pending snapshot writes */ }
49
56
  }
50
57
  log?.info?.('Orchestration engine enabled (features.orchestration)')
@@ -27,9 +27,10 @@
27
27
  import { execFile as execFileCb } from 'node:child_process'
28
28
  import { promisify } from 'node:util'
29
29
  import { join, resolve, sep } from 'node:path'
30
- import { homedir } from 'node:os'
31
30
  import { rmSync, mkdirSync, existsSync } from 'node:fs'
32
31
  import { GIT } from '../git.js'
32
+ import { configDir } from '../config-dir.js'
33
+ import { assertSafeArgvValue } from '../utils/argv-safety.js'
33
34
 
34
35
  const execFileAsync = promisify(execFileCb)
35
36
 
@@ -44,9 +45,28 @@ const DIFF_MAX_BUFFER = 64 * 1024 * 1024
44
45
  // carries a NUL/newline — defense-in-depth so a caller can never turn a branch
45
46
  // name into a git flag. execFile already blocks SHELL injection; this blocks
46
47
  // ARGUMENT injection.
48
+ //
49
+ // #7290: the CHECK now lives in utils/argv-safety.js and is shared with
50
+ // ws-file-ops/reader.js. This wrapper exists only to translate its Error into
51
+ // a GitOpsError; both messages (`empty <kind>` / `unsafe <kind>: <json>`) are
52
+ // produced there, and orchestration-git-ops.test.js pins the `unsafe` half.
53
+ // Do not re-inline the check here — #7290 was filed because a SECOND, weaker
54
+ // spelling had grown in reader.js. A THIRD spelling — `rejectGitOptionLike`
55
+ // in environments/backends/k8s.js, scoped to gitRepo fields — was folded
56
+ // into the shared guard by #7869.
47
57
  function assertSafeRef(name, kind = 'ref') {
48
- if (typeof name !== 'string' || name.length === 0) throw new GitOpsError(`empty ${kind}`)
49
- if (name.startsWith('-') || /[\0\n\r]/.test(name)) throw new GitOpsError(`unsafe ${kind}: ${JSON.stringify(name)}`)
58
+ try {
59
+ assertSafeArgvValue(name, kind)
60
+ } catch (err) {
61
+ // Only validation errors are expected here. Anything else would be a bug
62
+ // inside the shared guard, so keep the original rather than silently
63
+ // relabelling it as an unsafe ref. GitOpsError's constructor takes
64
+ // { args, stderr } and does not forward `cause` to super(), so it is set
65
+ // here rather than passed in — passing it would be dropped on the floor.
66
+ const wrapped = new GitOpsError(err.message)
67
+ wrapped.cause = err
68
+ throw wrapped
69
+ }
50
70
  }
51
71
 
52
72
  // Byte-accurate UTF-8 truncation that drops an incomplete trailing multibyte
@@ -64,10 +84,10 @@ function byteSliceUtf8(str, maxBytes) {
64
84
  // written to any user config.
65
85
  const ORCH_IDENTITY = { name: 'chroxy-orch', email: 'orch@chroxy.local' }
66
86
 
67
- /** ~/.chroxy (honoring CHROXY_CONFIG_DIR), matching the rest of the daemon. */
68
- export function configDir() {
69
- return process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
70
- }
87
+ // Re-exported for the orchestration tests, which resolve the root the same way
88
+ // the provisioner does. The resolver itself lives in config-dir.js (#7052) —
89
+ // this module used to carry its own copy.
90
+ export { configDir }
71
91
 
72
92
  /** The root the orphan sweep and the provisioner MUST agree on. Never `runs/`. */
73
93
  export function defaultWorktreesRoot() {
@@ -147,6 +167,17 @@ export function createGitOps({ git = GIT, now = () => Date.now(), worktreesRoot
147
167
  // and total byte caps with explicit truncation markers so a small worker
148
168
  // model isn't handed a 2MB patch.
149
169
  const computeCappedDiff = async ({ repoDir, baseSha, headRef = 'HEAD', maxBytes = 65_536, maxFileBytes = 8_192 }) => {
170
+ // #7342: these were the only ref slots in this module that skipped the
171
+ // guard every neighbour applies. `<base>..<head>` is a positional REVISION,
172
+ // and a `--` separator does NOT protect one (measured in
173
+ // utils/argv-safety.js: `git diff -O/etc/nope --` still reads the
174
+ // orderfile), so rejection is the only correct shape. Both values come
175
+ // from captureHead()'s rev-parse output today — this closes the gap before
176
+ // a caller wires a client-supplied ref in. Unlike a git failure (returned
177
+ // as a structured result below), an unsafe ref is a programming error and
178
+ // throws.
179
+ assertSafeRef(baseSha, 'base ref')
180
+ assertSafeRef(headRef, 'head ref')
150
181
  const statR = await run(['-C', repoDir, 'diff', '--stat', `${baseSha}..${headRef}`], { maxBuffer: DIFF_MAX_BUFFER })
151
182
  const patchR = await run(['-C', repoDir, 'diff', `${baseSha}..${headRef}`], { maxBuffer: DIFF_MAX_BUFFER })
152
183
  const stat = statR.ok ? statR.stdout : ''
@@ -249,6 +280,9 @@ export function createGitOps({ git = GIT, now = () => Date.now(), worktreesRoot
249
280
 
250
281
  const createIntegrationWorktree = async ({ repoDir, runId, branchName, baseSha }) => {
251
282
  assertSafeRef(branchName, 'branch')
283
+ // #7342: `baseSha` is the final positional operand of `worktree add`, so a
284
+ // dash-leading value would be read as an option there too.
285
+ assertSafeRef(baseSha, 'base ref')
252
286
  const worktreePath = integrationWorktreePath(runId)
253
287
  fs.mkdirSync(runWorktreesDir(runId), { recursive: true })
254
288
  await runOrThrow(['-C', repoDir, 'worktree', 'add', '-b', branchName, worktreePath, baseSha])
@@ -76,34 +76,27 @@ const AUDIT_ELIGIBLE_PROVIDERS = new Set(['claude-sdk', 'claude-byok', 'codex'])
76
76
  // `stopped` land on turn 2. None of the three below emit `stopped` after a
77
77
  // `result`, so excluding claude-cli removes this failure by construction.
78
78
  //
79
- // NOT CLOSED — false success on an interrupted turn. This is broader than
80
- // claude-cli and membership here does NOT imply immunity:
81
- // * claude-byok: an interrupt landing in the TOOL phase (not mid-stream)
82
- // breaks the loop at the `signal.aborted` check and falls THROUGH to the
83
- // normal `emit('result')` with real usage (byok-session.js ~1328 -> ~1459).
84
- // * claude-sdk: a stream STALL emits a synthetic `result` then `error`;
85
- // TurnDriver settles on the `result` and the trailing `error` is dropped by
86
- // the epoch guard.
87
- // * codex app-server: safe if the binary's answer to `turn/interrupt` routes
88
- // to `_failTurn` (which emits `stopped`) rather than to `turn/completed`.
89
- // Client exit and the result-timeout also reach `_failTurn`, so an `error`
90
- // notification is sufficient but not necessary — which of these the real
91
- // binary actually does is unverified in-repo (#7072).
92
- // Closing that needs the provider-side `interrupted: true` flag the turn-driver
93
- // doc-block names, so a terminal-looking result can be marked
94
- // terminal-but-not-successful. Tracked separately; it is a cross-provider wire
95
- // change, not something this gate can express.
79
+ // CLOSED (#7072) — false success on an interrupted turn, for claude-sdk and
80
+ // claude-byok. A `result` payload carries `interrupted: true` when the turn
81
+ // ended by abort/interrupt/stall rather than completion, and TurnDriver rejects
82
+ // it (TURN_STOPPED, or TURN_ERROR for a stall) instead of resolving it:
83
+ // * claude-byok: an interrupt landing in the TOOL phase (not mid-stream) ends
84
+ // the loop at the `signal.aborted` check and emits its `result` marked
85
+ // stopped + interrupted.
86
+ // * claude-sdk: the stream-STALL synthetic `result` is marked interrupted and
87
+ // names the failure; a Stop the SDK answers with an `aborted_*` result is
88
+ // marked by BaseSession.emit for every result whose turnOutcome is `stopped`.
96
89
  //
97
- // So this set means "vetted to not kill the NEXT turn", not "cannot report a
98
- // truncated turn as complete". Anything outside it is unvetted for either.
90
+ // NOT CLOSED — codex app-server. It ends an interrupted turn with
91
+ // `turn/completed`, which `_finishTurn` reports as a normal result without
92
+ // reading `turn.status` (the protocol's TurnStatus has an `interrupted` value).
93
+ // Whether the real binary answers `turn/interrupt` that way is unverified
94
+ // against a live process (#7072 follow-up), so an operator Stop on a codex
95
+ // architect session may still settle as a completed turn.
99
96
  //
100
- // Keeping claude-byok here is deliberate on that reading: it genuinely satisfies
101
- // the enforceable predicate (it never emits `stopped`), and dropping it while
102
- // retaining claude-sdk — which has its own false-success path via the stall —
103
- // would re-encode the very mistake this comment exists to correct, namely set
104
- // membership implying a safety property it does not deliver. That position holds
105
- // only while #7072 is open and honest; if #7072 is ever closed wontfix, revisit
106
- // byok's membership rather than leaving this comment to rot.
97
+ // So this set means "vetted to not kill the NEXT turn", and — for claude-sdk and
98
+ // claude-byok — "cannot report an interrupted turn as complete". Anything outside
99
+ // it is unvetted for either.
107
100
  const ARCHITECT_ELIGIBLE_PROVIDERS = new Set(['claude-sdk', 'claude-byok', 'codex'])
108
101
 
109
102
  // v1: write/implement workers are codex-ONLY. codexSandbox:'workspace-write' is a
@@ -153,6 +146,11 @@ export class OrchestrationManager extends EventEmitter {
153
146
  this._now = now
154
147
  this._log = log
155
148
  this._runs = new Map() // runId -> engine state
149
+ // #7142: the backgrounded `startRun` promises `createAndStartRun` launches.
150
+ // A start is a multi-minute architect turn that nothing awaits, so without a
151
+ // handle `dispose()` could neither wait for it nor tell it the manager is
152
+ // gone. Each entry removes itself when it settles (it never rejects).
153
+ this._starts = new Set()
156
154
  this._reports = new Map() // runId -> the architect's synthesis narrative markdown
157
155
  this._reportDocs = new Map() // runId -> { json, markdown } — the persisted M-4 report artifacts
158
156
  this._maxReports = 32
@@ -184,11 +182,29 @@ export class OrchestrationManager extends EventEmitter {
184
182
  }
185
183
  }
186
184
 
185
+ /**
186
+ * Tear the engine down. Everything that stops the manager from touching its
187
+ * collaborators happens SYNCHRONOUSLY, before this returns: `_disposed` is set
188
+ * first, and `_failRun`, the background-start handlers and `startRun`'s
189
+ * post-plan continuation all check it (#7142). So a start still in flight
190
+ * when the manager goes away can no longer journal onto — or log through — a
191
+ * torn-down ledger/log, whether or not the caller waits.
192
+ *
193
+ * The returned promise resolves once every backgrounded start has settled.
194
+ * An in-flight start only settles when its architect turn does, and the turn
195
+ * is the TurnDriver's to abort, not this class's — the driver is injected and
196
+ * its owner disposes it (`dispose()` rejects in-flight turns SESSION_GONE).
197
+ * Dispose the driver BEFORE awaiting this, and before disposing the ledger the
198
+ * start would otherwise journal to.
199
+ *
200
+ * @returns {Promise<void>}
201
+ */
187
202
  dispose() {
188
203
  this._disposed = true
189
204
  if (this._onSessionFreed && typeof this._sm.off === 'function') this._sm.off('session_destroyed', this._onSessionFreed)
190
205
  this._onSessionFreed = null
191
206
  this._gate?.dispose?.()
207
+ return Promise.allSettled([...this._starts]).then(() => undefined)
192
208
  }
193
209
 
194
210
  // --- status writes: the FSM choke point (#6732) --------------------------
@@ -313,6 +329,10 @@ export class OrchestrationManager extends EventEmitter {
313
329
  try {
314
330
  plan = await this._plan(run)
315
331
  } catch (err) {
332
+ // The owner disposed the manager (and so its TurnDriver) mid-plan: the
333
+ // turn rejecting SESSION_GONE is the teardown, not a plan failure, and
334
+ // there is no ledger left to journal it to (#7142).
335
+ if (this._disposed) return { runId, phase: run.phase }
316
336
  return this._failRun(run, `PLAN_${err instanceof DecisionParseError ? 'PARSE' : 'FAILED'}`, err)
317
337
  }
318
338
  // A cancel that landed while this turn was in flight wins. Destroying a
@@ -323,6 +343,10 @@ export class OrchestrationManager extends EventEmitter {
323
343
  // record ends up with phantom subtasks AND a rejected startRun.) `_runSubtask`
324
344
  // makes the same re-check after its awaits.
325
345
  if (run.cancelled) return { runId, phase: run.phase }
346
+ // Same for a dispose (#7142): the plan resolved after the manager went away,
347
+ // and everything below journals to a ledger its owner is about to (or has
348
+ // already) disposed.
349
+ if (this._disposed) return { runId, phase: run.phase }
326
350
  // Materialize subtasks. A subtask runs 'implement' (write-capable) ONLY when
327
351
  // the architect asked for it AND the run's worker provider is
328
352
  // implement-eligible (codex, #6735) AND no preset forces audit. Otherwise it
@@ -370,25 +394,36 @@ export class OrchestrationManager extends EventEmitter {
370
394
  */
371
395
  createAndStartRun(opts = {}) {
372
396
  const record = this.createRun(opts)
373
- this.startRun(record.runId)
397
+ const start = this.startRun(record.runId)
374
398
  .catch((err) => {
375
399
  // The run may already be gone (cancelled, or _failRun ran inside startRun).
376
400
  const run = this._runs.get(record.runId)
377
- if (!run) return null
401
+ if (!run || this._disposed) return null
378
402
  return this._failRun(run, 'START_FAILED', err)
379
403
  })
380
404
  .catch((err) => {
405
+ // A disposed manager's log/ledger belong to someone else now (#7142).
406
+ if (this._disposed) return
381
407
  this._log?.warn?.(`orchestration: run ${record.runId} failed to start and could not be journaled: ${err?.message || String(err)}`)
382
408
  })
409
+ // Track it so `dispose()` can wait for it (#7142). `start` should never reject, but if
410
+ // the final handler itself throws, removal still runs and no derived promise
411
+ // is left rejecting unhandled.
412
+ this._starts.add(start)
413
+ const forget = () => { this._starts.delete(start) }
414
+ start.then(forget, forget)
383
415
  return record
384
416
  }
385
417
 
386
418
  /**
387
419
  * Wire-level run control (`orchestration_run_action`). `cancel` is the only
388
- * action this engine implements: `pause`/`resume` are on the wire schema but
389
- * have no user-driven implementation — `_pauseForBudget`/`_pauseForResources`
390
- * are internal stalls the scheduler clears itself, not a pause a client can
391
- * hold. Fail loudly rather than acking a no-op (#7140).
420
+ * action this engine implements, and the only one the wire schema carries
421
+ * (#7140). `pause`/`resume` have no user-driven implementation —
422
+ * `_pauseForBudget`/`_pauseForResources` are internal stalls the scheduler
423
+ * clears itself, not a pause a client can hold — so the schema no longer
424
+ * admits them. This refusal stays as the engine's own backstop for a caller
425
+ * that reaches it without the wire validator: fail loudly rather than ack a
426
+ * no-op.
392
427
  */
393
428
  async runAction(runId, action) {
394
429
  if (action === 'cancel') {
@@ -435,7 +470,12 @@ export class OrchestrationManager extends EventEmitter {
435
470
 
436
471
  if (gate.kind === 'epic_plan') {
437
472
  if (decision === 'approve') return this._beginExecuting(run)
438
- return this._failRun(run, 'PLAN_REJECTED', new Error(note || 'epic plan rejected'))
473
+ // Any non-approve decision on the plan (reject, revise, skip) declines it,
474
+ // and a declined plan is a cancellation, not a failure (design §3.2:
475
+ // plan_review --reject--> cancelled; #7131). The reason code tells it apart
476
+ // from a manual cancel ('user'); the reviewer's note is already journaled on
477
+ // the gate_resolved timeline entry.
478
+ return this.cancelRun(run.runId, { reason: 'plan_rejected' })
439
479
  }
440
480
  if (gate.kind === 'escalation') {
441
481
  return this._resolveEscalation(run, gate, decision, note)
@@ -644,6 +684,8 @@ export class OrchestrationManager extends EventEmitter {
644
684
  const st = subtaskId ? run.subtasks.get(subtaskId) : null
645
685
  if (!st) return { runId: run.runId, resolved: true }
646
686
  if (decision === 'skip') { await this._finishSubtask(run, subtaskId, 'skipped'); return { runId: run.runId, subtaskId, skipped: true } }
687
+ // The escalation verb is `fail-run` (engine.md §3.3): the user is deliberately
688
+ // failing the run, unlike a rejected plan, which cancels it (#7131).
647
689
  if (decision === 'reject') return this._failRun(run, 'ESCALATION_REJECTED', new Error(note || 'user failed the run'))
648
690
  // approve / revise → re-drive the subtask (iteration reset via a fresh worker)
649
691
  st.state = 'pending'
@@ -966,6 +1008,11 @@ export class OrchestrationManager extends EventEmitter {
966
1008
  }
967
1009
 
968
1010
  async _failRun(run, code, err) {
1011
+ // A manager that has been disposed owns nothing any more: its ledger may be
1012
+ // flushed and closed, its log gone. A start that was in flight at dispose
1013
+ // time is rejected by the TurnDriver teardown and lands here a tick later;
1014
+ // journaling `failed` then would write to a disposed ledger (#7142).
1015
+ if (this._disposed) return { runId: run.runId, phase: run.phase }
969
1016
  // A cancel that already tore the run down wins: don't overwrite the
970
1017
  // terminal 'cancelled' status with 'failed' (or double-emit lifecycle
971
1018
  // events) when an in-flight turn rejects SESSION_GONE on the next tick.
@@ -19,7 +19,18 @@
19
19
 
20
20
  // Tools a worker must never be allowed to use headlessly: sub-delegation and
21
21
  // network fetches (the committee owns the delegation tree; keeps cost flat).
22
- const ALWAYS_DENY = new Set(['Task', 'WebFetch', 'WebSearch'])
22
+ // #7340: `Agent` is Claude Code's current name for the sub-delegation tool and
23
+ // `Task` the older one — both listed, since chroxy runs against whatever
24
+ // `claude` the user has installed. `_decide` already ends in `return 'deny'`,
25
+ // so the omission was not a fail-open; it did mean an `Agent` call was denied
26
+ // by the catch-all rather than by the rule that exists to say why.
27
+ // Exported so its test can assert MEMBERSHIP directly. A behavioural test
28
+ // cannot: `_decide` ends in `return 'deny'`, so every tool in this set is
29
+ // denied whether or not the set is consulted, and the whole branch can be
30
+ // deleted with no observable change today. That makes the branch a guard
31
+ // against a FUTURE allow path being added above it, and the invariant worth
32
+ // testing is its POSITION, not its effect (see the test).
33
+ export const ALWAYS_DENY = new Set(['Task', 'Agent', 'WebFetch', 'WebSearch'])
23
34
 
24
35
  export class OrchestrationPermissionGate {
25
36
  /**
@@ -65,6 +76,7 @@ export class OrchestrationPermissionGate {
65
76
  const toolName = data?.toolName ?? data?.tool ?? ''
66
77
  const requestId = data?.requestId ?? data?.id ?? null
67
78
  if (requestId == null) return
79
+ if (toolName === 'dev_preview' || data?.explicitConsent !== false || data?.nonDelegable !== false) return
68
80
  const decision = this._decide(role, toolName, data?.input ?? {})
69
81
  if (decision === 'escalate') {
70
82
  // Implement-worker Bash that isn't allowlisted: surface to the user. Until
@@ -105,7 +105,8 @@ export function assertRunTransition(from, to) {
105
105
  if (!RUN_STATUSES.has(to)) throw new TransitionError('run', from, `${to} (unknown state)`)
106
106
  if (from === to && to === 'executing') return true
107
107
  // `failed` is an ERROR terminal, not forward progress: an unrecoverable engine
108
- // error (or a user rejecting the plan / an escalation) can end a run from any
108
+ // error (or a user choosing fail-run on an escalation; a declined plan cancels
109
+ // instead, #7131) can end a run from any
109
110
  // non-terminal state. Enumerating it per-row would leave whichever row was
110
111
  // missed as a fail-closed landmine that wedges a live run.
111
112
  if ((to === 'cancelling' || to === 'suspended' || to === 'failed') && !TERMINAL_RUN_STATUSES.has(from)) return true