@bitkyc08/opencodex 2.93.0 → 2.94.0

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 (435) hide show
  1. package/README.md +27 -8
  2. package/bin/ocx.mjs +215 -63
  3. package/gui/dist/assets/App-DmvwlhQq.js +58 -0
  4. package/gui/dist/assets/Tray-CZatQdoF.js +1 -0
  5. package/gui/dist/assets/index-3EPO_KbX.js +94 -0
  6. package/gui/dist/assets/index-CHWwDo9L.css +1 -0
  7. package/gui/dist/assets/{quota-summary-BXu4zE8H.js → quota-summary-BHvWg9mi.js} +1 -1
  8. package/gui/dist/index.html +2 -2
  9. package/gui/dist/provider-icons/t3code.svg +4 -0
  10. package/package.json +7 -4
  11. package/src/adapters/anthropic/account-metadata.ts +34 -3
  12. package/src/adapters/anthropic/beta-allowlist.ts +5 -5
  13. package/src/adapters/anthropic/passthrough.ts +5 -2
  14. package/src/adapters/anthropic.ts +17 -4
  15. package/src/adapters/antigravity-refusal.ts +29 -0
  16. package/src/adapters/base.ts +11 -1
  17. package/src/adapters/client-fingerprint.ts +43 -9
  18. package/src/adapters/coding-agent/protocol.ts +19 -9
  19. package/src/adapters/command-code.ts +4 -5
  20. package/src/adapters/cursor/catalog.ts +5 -3
  21. package/src/adapters/cursor/claude-id.ts +30 -19
  22. package/src/adapters/cursor/cursor-errors.ts +5 -2
  23. package/src/adapters/cursor/h2-pool.ts +9 -7
  24. package/src/adapters/cursor/http1-bidi.ts +1 -0
  25. package/src/adapters/cursor/live-models.ts +4 -2
  26. package/src/adapters/cursor.ts +4 -1
  27. package/src/adapters/devin/cloud-direct/chat.ts +18 -2
  28. package/src/adapters/google-antigravity-replay.ts +13 -2
  29. package/src/adapters/google-antigravity-wire.ts +8 -3
  30. package/src/adapters/google-errors.ts +33 -0
  31. package/src/adapters/google-http.ts +41 -16
  32. package/src/adapters/google-wire-compiler.ts +4 -0
  33. package/src/adapters/google.ts +21 -10
  34. package/src/adapters/kiro/adapter.ts +3 -0
  35. package/src/adapters/kiro/stream.ts +18 -13
  36. package/src/adapters/openai-chat/completed-tool-blocks.ts +65 -0
  37. package/src/adapters/openai-chat/messages.ts +22 -10
  38. package/src/adapters/openai-chat/required-tool-result.ts +3 -3
  39. package/src/adapters/openai-chat/serialized-tool-call-content.ts +5 -0
  40. package/src/adapters/openai-chat/wire.ts +9 -0
  41. package/src/adapters/openai-chat.ts +18 -17
  42. package/src/adapters/openai-responses/image-gen.ts +15 -1
  43. package/src/adapters/openai-responses/passthrough.ts +11 -34
  44. package/src/adapters/openai-responses/transport.ts +20 -2
  45. package/src/adapters/openai-responses/usage.ts +34 -0
  46. package/src/adapters/qoder/adapter.ts +9 -15
  47. package/src/adapters/qoder/image-input.ts +52 -0
  48. package/src/adapters/unique-tool-call-ids.ts +2 -2
  49. package/src/adapters/zed-additional-tools.ts +51 -0
  50. package/src/adapters/zed-diagnostic-usage.ts +22 -0
  51. package/src/adapters/zed-json-tokens.ts +166 -0
  52. package/src/adapters/zed-openai-stream.ts +723 -0
  53. package/src/adapters/zed-tool-arguments.ts +79 -0
  54. package/src/adapters/zed.ts +53 -3
  55. package/src/advisor/consult.ts +22 -0
  56. package/src/advisor/runtime.ts +3 -0
  57. package/src/bridge/errors.ts +22 -1
  58. package/src/bridge/response-json.ts +4 -1
  59. package/src/bridge/sse.ts +21 -12
  60. package/src/chat/inbound.ts +13 -2
  61. package/src/chatgpt/app-server-shim/bundle-trust-async.ts +111 -0
  62. package/src/chatgpt/app-server-shim/bundle-trust-policy.ts +83 -0
  63. package/src/chatgpt/app-server-shim/bundle-trust.ts +15 -72
  64. package/src/claude/desktop-first-party.ts +16 -5
  65. package/src/claude/desktop-gateway-state.ts +4 -0
  66. package/src/claude/inbound-tool-loading.ts +93 -0
  67. package/src/claude/intercept/picker-listener.ts +33 -1
  68. package/src/claude/model-info.ts +29 -4
  69. package/src/claude/outbound.ts +33 -13
  70. package/src/cli/account-main.ts +43 -5
  71. package/src/cli/capabilities-base.ts +22 -5
  72. package/src/cli/capabilities-integrations.ts +4 -4
  73. package/src/cli/claude-desktop.ts +139 -98
  74. package/src/cli/codex-cli-update.ts +102 -48
  75. package/src/cli/codex-launch-auth.ts +93 -0
  76. package/src/cli/codex-launch-command.ts +32 -0
  77. package/src/cli/codex-launch-diagnostics.ts +37 -0
  78. package/src/cli/codex-launch-ownership.ts +307 -0
  79. package/src/cli/codex-launch-policy.ts +84 -0
  80. package/src/cli/codex-launcher.ts +310 -0
  81. package/src/cli/codex-shim-autorestore.ts +2 -0
  82. package/src/cli/config-command.ts +9 -4
  83. package/src/cli/config-mutation.ts +13 -0
  84. package/src/cli/dispatch.ts +13 -7
  85. package/src/cli/effort.ts +19 -14
  86. package/src/cli/ensure-desired-integrations.ts +21 -14
  87. package/src/cli/ensure-desktop-cold-start.ts +41 -10
  88. package/src/cli/export-command.ts +8 -4
  89. package/src/cli/help.ts +3 -1
  90. package/src/cli/index.ts +58 -64
  91. package/src/cli/integration-input.ts +12 -0
  92. package/src/cli/integration-plan-dto.ts +2 -0
  93. package/src/cli/integration-preview.ts +6 -3
  94. package/src/cli/integrations.ts +2 -1
  95. package/src/cli/link-cleanup.ts +8 -23
  96. package/src/cli/link-enrollment.ts +1 -4
  97. package/src/cli/link.ts +1 -1
  98. package/src/cli/loopback-family.ts +2 -31
  99. package/src/cli/models.ts +62 -49
  100. package/src/cli/provider.ts +146 -139
  101. package/src/cli/registry.ts +34 -3
  102. package/src/cli/root.ts +2 -0
  103. package/src/cli/start-owner-fence.ts +22 -3
  104. package/src/cli/status-link.ts +28 -0
  105. package/src/cli/status.ts +15 -0
  106. package/src/cli/stop-restore-guard.ts +48 -0
  107. package/src/cli/stop-restore.ts +117 -36
  108. package/src/cli/system-command.ts +2 -0
  109. package/src/cli/v2.ts +17 -4
  110. package/src/client/lifecycle-lock.ts +1 -1
  111. package/src/client/link-connection.ts +19 -0
  112. package/src/client/link-relay-transport.ts +25 -3
  113. package/src/client/link-tunnel.ts +10 -0
  114. package/src/client/machine-listener.ts +7 -1
  115. package/src/client/restore-ownership.ts +45 -0
  116. package/src/client/runtime.ts +13 -1
  117. package/src/client/state.ts +1 -1
  118. package/src/clients/client-ids.ts +7 -0
  119. package/src/clients/client-path.ts +13 -5
  120. package/src/clients/config-export/agent-clients.ts +3 -6
  121. package/src/clients/config-export/alias-selectors.ts +85 -0
  122. package/src/clients/config-export/contracts.ts +6 -25
  123. package/src/clients/config-export/dsh.ts +8 -1
  124. package/src/clients/config-export/model-metadata.ts +19 -0
  125. package/src/clients/config-export/model-names.ts +31 -0
  126. package/src/clients/config-export/qoder.ts +3 -11
  127. package/src/clients/config-export/t3code.ts +141 -0
  128. package/src/clients/config-export.ts +51 -15
  129. package/src/clients/gentle-shell-path.ts +3 -3
  130. package/src/codex/account-lifecycle.ts +27 -13
  131. package/src/codex/account-store.ts +32 -6
  132. package/src/codex/app-server-processes.ts +84 -1
  133. package/src/codex/auth-api/main-account-probe.ts +50 -11
  134. package/src/codex/auth-api/pool-mode-gate.ts +16 -8
  135. package/src/codex/auth-context.ts +45 -4
  136. package/src/codex/catalog/antigravity-discovery.ts +59 -0
  137. package/src/codex/catalog/build-entries.ts +12 -13
  138. package/src/codex/catalog/bundled.ts +59 -9
  139. package/src/codex/catalog/derive-entry.ts +2 -0
  140. package/src/codex/catalog/gather-capture.ts +3 -0
  141. package/src/codex/catalog/metadata.ts +6 -5
  142. package/src/codex/catalog/model-hints.ts +36 -4
  143. package/src/codex/catalog/native-priority.ts +63 -0
  144. package/src/codex/catalog/provider-models.ts +20 -4
  145. package/src/codex/catalog/retained-sync.ts +1 -1
  146. package/src/codex/chatgpt-refresh-failure.ts +2 -2
  147. package/src/codex/cli-install-provenance.ts +57 -29
  148. package/src/codex/cli-installation-identity.ts +1 -1
  149. package/src/codex/cli-installation-limits.ts +7 -0
  150. package/src/codex/cli-update-apply.ts +391 -0
  151. package/src/codex/cli-update-artifacts.ts +257 -0
  152. package/src/codex/cli-update-files.ts +100 -0
  153. package/src/codex/cli-update-inspection-context.ts +49 -0
  154. package/src/codex/cli-update-job-execution.ts +77 -0
  155. package/src/codex/cli-update-job-store-windows.ts +1010 -0
  156. package/src/codex/cli-update-job-worker.ts +393 -0
  157. package/src/codex/cli-update-job.ts +369 -0
  158. package/src/codex/cli-update-lease.ts +71 -0
  159. package/src/codex/cli-update-paths.ts +76 -0
  160. package/src/codex/cli-update-plan.ts +180 -47
  161. package/src/codex/cli-update-recovery.ts +236 -0
  162. package/src/codex/cli-update-selection-gate.ts +235 -0
  163. package/src/codex/cli-update-windows-apply.ts +308 -0
  164. package/src/codex/cli-update-windows-layout.ts +110 -0
  165. package/src/codex/cli-update-windows-observation.ts +91 -0
  166. package/src/codex/cli-update-windows-paths.ts +26 -0
  167. package/src/codex/cli-update-worker-recovery.ts +32 -0
  168. package/src/codex/cli-update-worker.ts +185 -0
  169. package/src/codex/cli-windows-plan-provenance.ts +250 -0
  170. package/src/codex/desktop-app-restart.ts +22 -3
  171. package/src/codex/exec-boundary.ts +208 -0
  172. package/src/codex/forward-transport-headers.ts +80 -0
  173. package/src/codex/history-job.ts +7 -0
  174. package/src/codex/history-provider.ts +5 -2
  175. package/src/codex/history-worker.ts +20 -1
  176. package/src/codex/inject/restore.ts +57 -25
  177. package/src/codex/internal/history-writer.ts +2 -1
  178. package/src/codex/mac-app-bundle.ts +52 -0
  179. package/src/codex/main-account.ts +161 -23
  180. package/src/codex/native-main-auth-temp.ts +3 -2
  181. package/src/codex/native-main-refresh-mode.ts +18 -3
  182. package/src/codex/native-profile-manager.ts +8 -6
  183. package/src/codex/native-profile-store.ts +9 -0
  184. package/src/codex/ocx-compaction-history.ts +3 -2
  185. package/src/codex/prompt-text-probe.ts +211 -69
  186. package/src/codex/quota.ts +9 -0
  187. package/src/codex/role-model-history.ts +253 -0
  188. package/src/codex/runtime.ts +120 -71
  189. package/src/codex/shim-overlay.ts +22 -3
  190. package/src/codex/shim-templates.ts +5 -2
  191. package/src/codex/shim-wrapper-write.ts +136 -0
  192. package/src/codex/shim.ts +24 -125
  193. package/src/codex/windows-cli-child-native.ts +119 -0
  194. package/src/codex/windows-cli-child-pipe.ts +87 -0
  195. package/src/codex/windows-cli-child.ts +260 -0
  196. package/src/codex/windows-cli-recovery-guardian.ts +89 -0
  197. package/src/codex/windows-cli-recovery.ts +39 -0
  198. package/src/codex/windows-installation-files.ts +52 -6
  199. package/src/codex/windows-npm-execution.ts +25 -0
  200. package/src/combos/failover.ts +84 -5
  201. package/src/combos/index.ts +1 -0
  202. package/src/combos/resolve.ts +60 -22
  203. package/src/config/atomic-write.ts +75 -22
  204. package/src/config/diagnostics.ts +18 -10
  205. package/src/config/live-reconcile.ts +11 -3
  206. package/src/config/owner-registry.ts +5 -4
  207. package/src/config/persist-unlocked.ts +34 -8
  208. package/src/config/persisted-mutation.ts +7 -0
  209. package/src/config/process-state.ts +9 -5
  210. package/src/config/removed-opencode-free-backup.ts +99 -0
  211. package/src/config/removed-opencode-free.ts +4 -8
  212. package/src/config/salvage.ts +1 -0
  213. package/src/config/schema/config-schema.ts +16 -1
  214. package/src/config/schema/leaf-validators.ts +15 -0
  215. package/src/config.ts +4 -4
  216. package/src/generated/compatibility-version.json +743 -315
  217. package/src/grok/inject.ts +2 -1
  218. package/src/grok/sync.ts +5 -2
  219. package/src/images/loop.ts +14 -5
  220. package/src/integrations/catalog-refresh.ts +1 -1
  221. package/src/integrations/hermes-refresh.ts +28 -0
  222. package/src/integrations/model-name-guard.ts +31 -0
  223. package/src/integrations/mutation-plan.ts +17 -4
  224. package/src/integrations/ownership.ts +3 -0
  225. package/src/integrations/registry.ts +10 -1
  226. package/src/integrations/state.ts +6 -0
  227. package/src/integrations/writer.ts +64 -59
  228. package/src/lib/abort.ts +8 -4
  229. package/src/lib/bounded-body.ts +7 -1
  230. package/src/lib/config-ownership.ts +4 -0
  231. package/src/lib/errors.ts +2 -0
  232. package/src/lib/eventstream-decoder.ts +3 -2
  233. package/src/lib/http-response-semantics.ts +9 -6
  234. package/src/lib/inbound-body-policy.ts +11 -0
  235. package/src/lib/jsonc.ts +7 -2
  236. package/src/lib/local-management-capability.ts +3 -1
  237. package/src/lib/local-upstream.ts +22 -26
  238. package/src/lib/loopback-family.ts +31 -0
  239. package/src/lib/plain-data.ts +7 -5
  240. package/src/lib/process-control.ts +30 -5
  241. package/src/lib/shadow-call.ts +55 -1
  242. package/src/lib/tool-argument-integers.ts +99 -7
  243. package/src/lib/upstream-retry.ts +6 -1
  244. package/src/lib/windows-elevation.ts +34 -11
  245. package/src/lib/windows-owner-acl.ts +272 -32
  246. package/src/lib/windows-secret-acl.ts +310 -44
  247. package/src/lib/windows-service-wrappers.ts +10 -7
  248. package/src/lib/winsw.ts +8 -4
  249. package/src/link/relay-auth.ts +38 -1
  250. package/src/link/remote-platform.ts +11 -23
  251. package/src/link/remote-probe.ts +3 -1
  252. package/src/link/remote-windows.ts +150 -0
  253. package/src/link/ssh-argv.ts +13 -5
  254. package/src/link/store.ts +4 -1
  255. package/src/link/supervisor.ts +9 -0
  256. package/src/local-credentials/generation.ts +238 -0
  257. package/src/local-credentials/inventory.ts +281 -0
  258. package/src/local-credentials/observation-lease.ts +83 -0
  259. package/src/local-credentials/publication-fence.ts +81 -0
  260. package/src/local-credentials/references.ts +36 -0
  261. package/src/local-credentials/runtime-observation.ts +28 -0
  262. package/src/oauth/account-auto-pause-policy.ts +11 -0
  263. package/src/oauth/anthropic-account-refusal.ts +1 -0
  264. package/src/oauth/anthropic-rate-limit-policy.ts +26 -2
  265. package/src/oauth/anthropic-routing.ts +34 -44
  266. package/src/oauth/anthropic-session-affinity-store.ts +177 -0
  267. package/src/oauth/chatgpt.ts +11 -9
  268. package/src/oauth/cursor.ts +8 -2
  269. package/src/oauth/generic-account-failover.ts +33 -2
  270. package/src/oauth/generic-session-affinity.ts +7 -0
  271. package/src/oauth/google-antigravity.ts +29 -5
  272. package/src/oauth/index.ts +1 -0
  273. package/src/oauth/store.ts +32 -4
  274. package/src/protocols/encoders/adapter-events.ts +7 -4
  275. package/src/protocols/encoders/messages.ts +1 -1
  276. package/src/providers/antigravity-account-roster.ts +73 -7
  277. package/src/providers/antigravity-models.ts +8 -4
  278. package/src/providers/api-key-resolve.ts +16 -3
  279. package/src/providers/claude-cli-identity.ts +2 -0
  280. package/src/providers/codex-capacity.ts +3 -2
  281. package/src/providers/free-directory.ts +10 -2
  282. package/src/providers/key-store.ts +7 -2
  283. package/src/providers/provider-id-rewrite.ts +3 -0
  284. package/src/providers/quota/antigravity.ts +6 -4
  285. package/src/providers/quota/vendor-probes-oauth.ts +0 -1
  286. package/src/providers/stale-model-roster-migration.ts +3 -0
  287. package/src/quota-pool/assemble.ts +51 -21
  288. package/src/quota-pool/pooled.ts +162 -0
  289. package/src/remote-control/workspace-codex-runtime.ts +63 -20
  290. package/src/responses/apply-patch-envelope.ts +35 -0
  291. package/src/responses/compaction-history-framing.ts +15 -4
  292. package/src/responses/turn-membership.ts +111 -0
  293. package/src/server/advisor-admission-scope.ts +43 -0
  294. package/src/server/audio-upstream.ts +10 -2
  295. package/src/server/auth-cors.ts +23 -0
  296. package/src/server/bind-host.ts +5 -0
  297. package/src/server/chat-completions.ts +17 -2
  298. package/src/server/chat-native.ts +16 -11
  299. package/src/server/claude-messages.ts +9 -1
  300. package/src/server/codex-model-list.ts +46 -0
  301. package/src/server/gui-session.ts +5 -2
  302. package/src/server/inbound-body-admission.ts +21 -13
  303. package/src/server/inbound-body-budget.ts +128 -0
  304. package/src/server/index/link-listener.ts +3 -1
  305. package/src/server/index/link-relay-sessions.ts +9 -2
  306. package/src/server/index/optional-listeners.ts +1 -0
  307. package/src/server/index/serve-options.ts +9 -43
  308. package/src/server/index/websocket-handler.ts +7 -0
  309. package/src/server/index.ts +6 -5
  310. package/src/server/inference/client-encoder-delivery.ts +3 -1
  311. package/src/server/lifecycle.ts +8 -1
  312. package/src/server/management/advisor-routes.ts +26 -9
  313. package/src/server/management/agent-settings-routes.ts +424 -543
  314. package/src/server/management/anthropic-reset-grant-routes.ts +2 -1
  315. package/src/server/management/claude-code-settings-patch.ts +211 -0
  316. package/src/server/management/claude-desktop-config-writers.ts +78 -0
  317. package/src/server/management/codex-agent-role-routes.ts +79 -2
  318. package/src/server/management/codex-cli-update-routes.ts +55 -0
  319. package/src/server/management/codex-prompt-routes.ts +2 -1
  320. package/src/server/management/config-routes.ts +444 -380
  321. package/src/server/management/consent-session.ts +6 -0
  322. package/src/server/management/desktop-compatibility-authorization.ts +12 -0
  323. package/src/server/management/desktop-compatibility-routes.ts +3 -2
  324. package/src/server/management/desktop-compatibility-runtime-routes.ts +2 -1
  325. package/src/server/management/desktop-compatibility-settings-routes.ts +2 -1
  326. package/src/server/management/integration-routes.ts +45 -5
  327. package/src/server/management/link-enrollment.ts +21 -32
  328. package/src/server/management/link-route-state.ts +1 -0
  329. package/src/server/management/link-routes.ts +4 -1
  330. package/src/server/management/model-routes.ts +22 -6
  331. package/src/server/management/model-rows.ts +3 -1
  332. package/src/server/management/native-integration-routes.ts +90 -38
  333. package/src/server/management/oauth-account-routes.ts +8 -7
  334. package/src/server/management/route-registry.ts +8 -3
  335. package/src/server/management/session-routes.ts +20 -2
  336. package/src/server/management/shadow-call-validation.ts +43 -2
  337. package/src/server/management/sidebar-routes.ts +2 -1
  338. package/src/server/management/system-restart.ts +47 -7
  339. package/src/server/management-api.ts +61 -51
  340. package/src/server/management-auth.ts +11 -3
  341. package/src/server/messages-native.ts +21 -7
  342. package/src/server/messages-shared.ts +110 -18
  343. package/src/server/persistent-gui-session.ts +155 -0
  344. package/src/server/port-reclaim.ts +29 -5
  345. package/src/server/proxy-liveness.ts +110 -33
  346. package/src/server/request-decompress.ts +5 -1
  347. package/src/server/responses/account-change-state.ts +14 -2
  348. package/src/server/responses/adapter-continuation.ts +5 -4
  349. package/src/server/responses/adapter-delivery.ts +20 -5
  350. package/src/server/responses/adapter-dispatch.ts +39 -45
  351. package/src/server/responses/advisor-plan-slot.ts +3 -0
  352. package/src/server/responses/advisor-slot.ts +4 -2
  353. package/src/server/responses/antigravity-model-denial-recovery.ts +70 -0
  354. package/src/server/responses/antigravity-validation-refusal.ts +6 -0
  355. package/src/server/responses/combo-required-tool-contract.ts +2 -1
  356. package/src/server/responses/combo-required-tool-fulfillments.ts +58 -0
  357. package/src/server/responses/combo-required-tool-stream.ts +119 -0
  358. package/src/server/responses/combo-stream-preflight.ts +47 -7
  359. package/src/server/responses/compact.ts +14 -7
  360. package/src/server/responses/compaction-recovery.ts +2 -1
  361. package/src/server/responses/core-auth.ts +2 -1
  362. package/src/server/responses/core-codex-account.ts +1 -0
  363. package/src/server/responses/core-combo-failure.ts +11 -6
  364. package/src/server/responses/core-combo-native.ts +6 -5
  365. package/src/server/responses/core-combo.ts +93 -20
  366. package/src/server/responses/core-options.ts +7 -0
  367. package/src/server/responses/fetch-helpers.ts +5 -1
  368. package/src/server/responses/jev-model-invoke.ts +8 -3
  369. package/src/server/responses/memory-models.ts +3 -2
  370. package/src/server/responses/passthrough-delivery.ts +36 -8
  371. package/src/server/responses/passthrough-dispatch.ts +12 -12
  372. package/src/server/responses/request-prepare.ts +10 -1
  373. package/src/server/responses/request-transport.ts +41 -6
  374. package/src/server/responses/run-turn-execution.ts +11 -3
  375. package/src/server/responses/sidecar-execution.ts +5 -0
  376. package/src/server/responses/turn-membership.ts +30 -0
  377. package/src/server/responses-custom-tool-repair.ts +86 -11
  378. package/src/server/responses-image-gen-repair.ts +1 -1
  379. package/src/server/restart-parent-ownership.ts +49 -0
  380. package/src/server/stop-teardown.ts +46 -9
  381. package/src/server/windows-tcp-drop.ts +4 -2
  382. package/src/service/desktop-recovery-process.ts +341 -0
  383. package/src/service/desktop-recovery.ts +172 -0
  384. package/src/service/windows-ops.ts +6 -3
  385. package/src/service/windows-scheduler.ts +29 -6
  386. package/src/stall-timeout.ts +47 -0
  387. package/src/tray/windows.ts +6 -4
  388. package/src/types/config.ts +61 -10
  389. package/src/types/request.ts +1 -1
  390. package/src/types.ts +1 -0
  391. package/src/update/async-check.ts +4 -3
  392. package/src/update/bind-probe.ts +2 -2
  393. package/src/update/codex-cli-update-launch-policy.mjs +9 -0
  394. package/src/update/guarded-port-reclaim.ts +14 -0
  395. package/src/update/guarded-runtime-ops.ts +58 -0
  396. package/src/update/guarded-tray-ops.ts +9 -0
  397. package/src/update/index.ts +196 -58
  398. package/src/update/job-pinned-start.ts +53 -0
  399. package/src/update/job-supervised-restart.ts +23 -6
  400. package/src/update/job-update-home.ts +62 -0
  401. package/src/update/job-update-tray.ts +29 -0
  402. package/src/update/job-windows-restart.ts +39 -0
  403. package/src/update/job.ts +179 -193
  404. package/src/update/mutation-guard.d.mts +30 -0
  405. package/src/update/mutation-guard.mjs +103 -0
  406. package/src/update/notify.ts +2 -2
  407. package/src/update/npm-cache-preflight.mjs +4 -4
  408. package/src/update/npm-install.mjs +5 -3
  409. package/src/update/pnpm-read-policy.mjs +3 -2
  410. package/src/update/proxy-liveness-probe.mjs +2 -2
  411. package/src/update/service-home-authority.ts +35 -0
  412. package/src/update/service-home-package-only-protocol.json +1 -0
  413. package/src/update/service-home-policy.d.mts +25 -0
  414. package/src/update/service-home-policy.mjs +112 -0
  415. package/src/update/service-home-probe-entry.ts +9 -0
  416. package/src/update/service-home-probe.d.mts +15 -0
  417. package/src/update/service-home-probe.mjs +79 -0
  418. package/src/update/service-home-protocol.json +1 -0
  419. package/src/update/supervised-recovery.d.mts +2 -2
  420. package/src/update/supervised-recovery.mjs +14 -7
  421. package/src/update/transactional-install.d.mts +3 -1
  422. package/src/update/transactional-install.mjs +29 -19
  423. package/src/update/update-failure-guidance.mjs +1 -1
  424. package/src/update/worker-launch.ts +3 -3
  425. package/src/vision/anthropic-describe.ts +2 -1
  426. package/src/web-search/anthropic-executor.ts +2 -1
  427. package/src/web-search/anthropic-history.ts +1 -0
  428. package/src/web-search/format-result.ts +3 -2
  429. package/src/web-search/header-deadline.ts +3 -2
  430. package/src/web-search/loop.ts +10 -4
  431. package/src/web-search/parse.ts +191 -38
  432. package/gui/dist/assets/App-CizjBqyk.js +0 -58
  433. package/gui/dist/assets/Tray-DamiMqcX.js +0 -1
  434. package/gui/dist/assets/index-DQsht3vH.js +0 -94
  435. package/gui/dist/assets/index-DRe8Hhfz.css +0 -1
@@ -1,3 +1,8 @@
1
+ import { prepareClaudeCodePatch } from "./claude-code-settings-patch";
2
+ import { readConfigForAdmittedMutation } from "../../config/persisted-mutation";
3
+ import { mirrorDesiredEnabledOntoSnapshot, persistDesktopModeField, persistDesktopProfileField } from "./claude-desktop-config-writers";
4
+ import { getConfigDir as configRoot, withConfigDirHardeningSettled as settleConfigRoot } from "../../config/paths";
5
+ import { WindowsSecretAclSettleTimeoutError } from "../../lib/windows-secret-acl";
1
6
  import { ensureManagementClaudeIntercept, interceptStartRefusal, interceptStatus } from "./claude-intercept-routes";
2
7
  import { persistCommittedDesktopGateway } from "../../claude/desktop-gateway-state";
3
8
  import { captureDesktopAppliedMarker, commitDesktopAppliedMarker } from "../../claude/desktop-applied-marker";
@@ -13,7 +18,7 @@ import { mergeModelPinnedEfforts, modelPinnedEffortsConfigError } from "../../co
13
18
  import { MULTI_AGENT_SURFACE_ADVISORY_VERSION, multiAgentSurfaceAdvisory, resolveMultiAgentMode } from "../../config/multi-agent-surface";
14
19
  import { captureConfigTopLevelRollback, parsedConfigRebaseDeletionKeys, projectConfigRebaseProvenance } from "../../config/rebase-provenance";
15
20
  import { anthropicSidecarPatchError } from "../../config/schema/anthropic-account-pool";
16
- import { isAnthropicInstanceId, type AnthropicInstanceId } from "../../providers/anthropic-instance-id";
21
+ import { isAnthropicInstanceId } from "../../providers/anthropic-instance-id";
17
22
  import {
18
23
  adoptPersistedClaudeCode,
19
24
  DEFAULT_SUBAGENT_MODELS,
@@ -67,7 +72,7 @@ import {
67
72
  setDebugSettings,
68
73
  type DebugFlag,
69
74
  } from "../../lib/debug-settings";
70
- import type { OcxClaudeCodeConfig, OcxConfig, OcxCustomModel, OcxProviderConfig } from "../../types";
75
+ import type { OcxConfig, OcxCustomModel, OcxProviderConfig } from "../../types";
71
76
  import {
72
77
  visionCandidateRows,
73
78
  visionDescriberIsProvablyBlind,
@@ -103,66 +108,6 @@ let grokApplyTestHooks: { now?: () => number; run?: () => Promise<unknown> } | n
103
108
 
104
109
  class GrokApplyBusyError extends Error {}
105
110
 
106
- /**
107
- * Mirror a durable desired-state transition onto the long-lived server snapshot.
108
- *
109
- * `setIntegrationEnabled` writes DISK only. The server reuses one `config` object
110
- * for every request, so leaving it stale makes the native GET report the opposite
111
- * of what was just persisted, and makes any later whole-snapshot save (the Desktop
112
- * profile PUT does exactly that) write the stale value back over the transition.
113
- * ON is the ABSENCE of the key, matching `setIntegrationEnabled`'s on-disk shape.
114
- */
115
- function mirrorDesiredEnabledOntoSnapshot(config: OcxConfig, client: "claude-desktop", enabled: boolean): void {
116
- const integrations = { ...(config.clientIntegrations ?? {}) };
117
- if (enabled) delete integrations[client];
118
- else integrations[client] = false;
119
- if (Object.keys(integrations).length === 0) deleteConfigTopLevelKey(config, "clientIntegrations");
120
- else config.clientIntegrations = integrations;
121
- }
122
-
123
- /**
124
- * Persist ONLY `claudeCode.desktopProfile`, field-scoped, against the CURRENT
125
- * on-disk config.
126
- *
127
- * `saveConfigPreservingClaudeCode(ctx.config)` writes the whole long-lived server
128
- * snapshot. On the apply path that snapshot still carries the `clientIntegrations`
129
- * it was loaded with, so a save right after `setIntegrationEnabled("claude-desktop",
130
- * true)` carried the stale OFF back over the enable and made the route cancel its
131
- * own apply. Mutating one field under the config-mutation lock cannot regress an
132
- * unrelated key another writer just committed.
133
- */
134
- function persistDesktopProfileField(
135
- config: OcxConfig,
136
- desktopProfile: NonNullable<OcxConfig["claudeCode"]>["desktopProfile"],
137
- ): { ok: true } | { ok: false; reason: "missing" | "invalid" | "conflict" } {
138
- const outcome = mutatePersistedConfig(persisted => {
139
- persisted.claudeCode = { ...(persisted.claudeCode ?? {}), desktopProfile };
140
- return { changed: true, value: structuredClone(persisted.claudeCode) };
141
- });
142
- // Only mirror into memory once the durable write actually landed; an
143
- // `unavailable` outcome must not leave the snapshot claiming a saved profile.
144
- if (outcome.status === "unavailable") return { ok: false, reason: outcome.reason };
145
- adoptPersistedClaudeCode(config, outcome.value);
146
- return { ok: true };
147
- }
148
-
149
- async function persistDesktopModeField(
150
- config: OcxConfig,
151
- desktopMode: "first-party" | "gateway",
152
- ): Promise<{ ok: true } | { ok: false; reason: "missing" | "invalid" | "conflict" }> {
153
- const { recordClaudeDesktopMode } = await import("../../claude/desktop-first-party");
154
- const outcome = mutatePersistedConfig(persisted => {
155
- const mutation = recordClaudeDesktopMode(persisted, desktopMode);
156
- return { changed: mutation.changed, value: structuredClone(persisted.claudeCode) };
157
- });
158
- if (outcome.status === "unavailable") return { ok: false, reason: outcome.reason };
159
- // First-party apply ends here — no profile-marker write follows — so without
160
- // adopting, live diverges from the armed baseline and a later whole-config
161
- // save reads that divergence as a pending mutation and stomps hand edits.
162
- adoptPersistedClaudeCode(config, outcome.value);
163
- return { ok: true };
164
- }
165
-
166
111
  export function grokApplyFlightSnapshot(): { currentBytes: number; highWaterBytes: number; active: number } {
167
112
  return {
168
113
  currentBytes: grokApplyFlight?.bytes ?? 0,
@@ -258,6 +203,14 @@ export async function injectionModelView(config: OcxConfig, routed: readonly Cat
258
203
  }
259
204
 
260
205
  export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise<Response | null> {
206
+ try { return await handleAgentSettingsRoutesImpl(ctx); }
207
+ catch (error) {
208
+ if (!(error instanceof WindowsSecretAclSettleTimeoutError)) throw error;
209
+ return jsonResponse({ error: "Could not save settings", code: "write_failed", diagnostic: { stage: "ca", cause: "ETIMEDOUT" } }, 500);
210
+ }
211
+ }
212
+
213
+ async function handleAgentSettingsRoutesImpl(ctx: ManagementContext): Promise<Response | null> {
261
214
  const { req, url, config, deps, convergeCodexCatalog, syncClaudeAgentDefsBestEffort } = ctx;
262
215
 
263
216
  /** Best-effort Desktop 3P config auto-reconcile when providers change. */
@@ -282,9 +235,9 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
282
235
  if (siblingOfLivePort() !== null) return;
283
236
  // Serialized with Desktop mode transitions: a first-party switch cannot interleave with this write.
284
237
  const { runPickerTransition } = await import("./claude-desktop-picker-routes");
285
- await runPickerTransition(admitted, async () => {
238
+ await runPickerTransition(admitted, () => settleConfigRoot(configRoot(), () => {
286
239
  if (siblingOfLivePort() !== null) return undefined;
287
- const current = loadConfig();
240
+ const current = readConfigForAdmittedMutation();
288
241
  // This is the real guard: the catalog await admits a concurrent explicit OFF.
289
242
  if (!claudeDesktopIntegrationEnabled(current)) return undefined;
290
243
  // …and a concurrent switch to first-party.
@@ -313,7 +266,7 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
313
266
  console.warn("[claude-desktop] provider-change applied marker skipped");
314
267
  }
315
268
  }
316
- });
269
+ }));
317
270
  } catch { /* best-effort */ }
318
271
  }
319
272
 
@@ -412,19 +365,32 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
412
365
  return jsonResponse({ error: "body.multiAgentSurfaceAdvisoryAcknowledged must be a boolean" }, 400);
413
366
  }
414
367
  const mode = wantsMode ? body.multiAgentMode as "v1" | "default" | "v2" : undefined;
415
- const effectiveMode = mode ?? config.multiAgentMode ?? "default";
416
- const effectiveKeepNative = wantsKeepNative
417
- ? body.keepNativeChatGptOnV1 === true
418
- : config.keepNativeChatGptOnV1 === true;
419
- const hybridPinActive = effectiveMode === "v2" && effectiveKeepNative;
420
- const modeFlag = mode === "v2" ? !hybridPinActive : mode === "v1" ? false : undefined;
421
- if (wantsFlag && modeFlag !== undefined && body.enabled !== modeFlag) {
422
- return jsonResponse({
423
- error: hybridPinActive
424
- ? "body.enabled=true conflicts with keepNativeChatGptOnV1: Codex's global multi_agent_v2 override outranks catalog pins"
425
- : `body.enabled conflicts with multiAgentMode '${mode}'`,
426
- }, 400);
427
- }
368
+ const readModePlan = () => {
369
+ const effectiveMode = mode ?? config.multiAgentMode ?? "default";
370
+ const effectiveKeepNative = wantsKeepNative
371
+ ? body.keepNativeChatGptOnV1 === true
372
+ : config.keepNativeChatGptOnV1 === true;
373
+ const hybridPinActive = effectiveMode === "v2" && effectiveKeepNative;
374
+ const modeFlag = mode === "v2" ? !hybridPinActive : mode === "v1" ? false : undefined;
375
+ if (wantsFlag && modeFlag !== undefined && body.enabled !== modeFlag) {
376
+ return jsonResponse({
377
+ error: hybridPinActive
378
+ ? "body.enabled=true conflicts with keepNativeChatGptOnV1: Codex's global multi_agent_v2 override outranks catalog pins"
379
+ : `body.enabled conflicts with multiAgentMode '${mode}'`,
380
+ }, 400);
381
+ }
382
+ if (wantsFlag && body.enabled === true && hybridPinActive) {
383
+ return jsonResponse({
384
+ error: "body.enabled=true conflicts with keepNativeChatGptOnV1: Codex's global multi_agent_v2 override outranks catalog pins",
385
+ }, 400);
386
+ }
387
+ const requestedFlag = wantsFlag
388
+ ? body.enabled as boolean
389
+ : modeFlag ?? (wantsKeepNative && hybridPinActive ? false : undefined);
390
+ return { effectiveMode, requestedFlag };
391
+ };
392
+ const initialPlan = readModePlan();
393
+ if (initialPlan instanceof Response) return initialPlan;
428
394
  const {
429
395
  isMultiAgentV2Enabled, hasAgentsMaxThreads, getLogicalMaxThreads, transitionMultiAgentV2,
430
396
  getAgentsEnabled, getAgentsMaxDepth, getSubagentDeveloperInstructions,
@@ -442,14 +408,7 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
442
408
  }, 502);
443
409
  }
444
410
  const warnings: string[] = [];
445
- if (wantsFlag && body.enabled === true && hybridPinActive) {
446
- return jsonResponse({
447
- error: "body.enabled=true conflicts with keepNativeChatGptOnV1: Codex's global multi_agent_v2 override outranks catalog pins",
448
- }, 400);
449
- }
450
- const requestedFlag = wantsFlag
451
- ? body.enabled as boolean
452
- : modeFlag ?? (wantsKeepNative && hybridPinActive ? false : undefined);
411
+ let requestedFlag: boolean | undefined;
453
412
  /*
454
413
  * One held section for every config.toml write this PUT makes — the
455
414
  * feature transition plus each scalar edit. Individually-locked writers
@@ -457,82 +416,89 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
457
416
  * combination on disk; the lock is released before the post-write readers
458
417
  * and catalog converge below.
459
418
  */
460
- const needsCodexConfigWrites = requestedFlag !== undefined || wantsThreads
419
+ const needsCodexConfigWrites = initialPlan.requestedFlag !== undefined || wantsThreads
461
420
  || wantsAgentsEnabled || wantsMaxDepth || wantsSubagentInstructions || wantsModeHintText;
462
421
  if (needsCodexConfigWrites && codexHomeIsAbsent(dirname(activeCodexConfigPath()))) {
463
422
  return jsonResponse({ error: `config.toml not readable at ${activeCodexConfigPath()}` }, 502);
464
423
  }
465
424
  const { acquireConfigWriteLock, releaseConfigWriteLock, configWriteLockFailureMessage } = await import("../../codex/config-write-lock");
425
+ const { runCodexFeaturesCommand } = await import("../../cli/v2");
466
426
  const configWriteLock = needsCodexConfigWrites ? await acquireConfigWriteLock(activeCodexConfigPath()) : null;
467
427
  if (configWriteLock !== null && !configWriteLock.ok) {
468
428
  return jsonResponse({ error: configWriteLockFailureMessage(configWriteLock), retryable: configWriteLock.error === "locked" }, 502);
469
429
  }
470
430
  const heldWriteLock = configWriteLock !== null && configWriteLock.ok ? configWriteLock.handle : undefined;
471
431
  try {
472
- if (requestedFlag !== undefined || wantsThreads) {
473
- const targetFlag = requestedFlag ?? isMultiAgentV2Enabled();
474
- let toggle = deps.toggleCodexMultiAgentV2;
475
- if (!toggle) {
476
- const { runCodexFeaturesCommand } = await import("../../cli/v2");
477
- toggle = (enabled, env, validate) => runCodexFeaturesCommand(enabled ? "enable" : "disable", "multi_agent_v2", env, validate);
478
- }
479
- const result = transitionMultiAgentV2(targetFlag, toggle, {
480
- ...(wantsThreads ? { threadLimit: body.maxConcurrentThreadsPerSession as number } : {}),
481
- heldConfigWriteLock: heldWriteLock,
482
- });
483
- if (!result.ok) return jsonResponse({ error: `multi_agent_v2 transition failed: ${result.error}`, ...(result.retryable === false ? { retryable: false } : {}) }, 502);
484
- if (result.changed && result.threadLimit !== null) warnings.push(`Thread limit ${result.threadLimit} preserved for ${targetFlag ? "v2" : "v1"}.`);
485
- }
486
- if (wantsMode) {
487
- if (mode === "default") deleteConfigTopLevelKey(config, "multiAgentMode");
488
- else config.multiAgentMode = mode;
489
- saveConfigPreservingClaudeCode(config);
490
- warnings.push(`Multi-agent mode set to '${mode}'. Applies to new sessions.`);
491
- }
492
- if (wantsKeepNative) {
493
- if (body.keepNativeChatGptOnV1 === true) config.keepNativeChatGptOnV1 = true;
494
- else deleteConfigTopLevelKey(config, "keepNativeChatGptOnV1");
495
- saveConfigPreservingClaudeCode(config);
496
- warnings.push(body.keepNativeChatGptOnV1 === true
497
- ? (effectiveMode === "v2"
498
- ? "ChatGPT-native models stay on v1 while other models use v2. Applies to new sessions."
499
- : "keepNativeChatGptOnV1 is stored but inactive until multi-agent mode is v2. Applies to new sessions.")
500
- : "ChatGPT-native models follow the selected v1/v2/base surface. Applies to new sessions.");
501
- }
502
- // Written after the mode, so a landed acknowledgement implies the mode write it was
503
- // sent with already landed. The converse does not hold: this writer throws rather than
504
- // reporting, exactly as the mode write above it does, so a failure here surfaces the
505
- // mode change with the advisory still raised. That is the benign direction — the
506
- // operator is asked again — and it is why this is not claimed as a transaction.
507
- if (wantsAdvisoryAck && body.multiAgentSurfaceAdvisoryAcknowledged === true) {
508
- config.multiAgentSurfaceAdvisoryVersion = MULTI_AGENT_SURFACE_ADVISORY_VERSION;
509
- saveConfigPreservingClaudeCode(config);
510
- }
511
- // New-key scalar writes: each writer is individually atomic, so apply them in
512
- // sequence after the transition. A failure here is a persistence failure (the
513
- // writers' ok:false result or a throw from the underlying atomic write helper),
514
- // reported as 502 naming the failed key plus the writes that already landed.
515
- // NOTE: do not name that helper literally here — tests/providers/xai/grok-writer-boundary.test.ts
516
- // asserts this route file contains no direct write primitive, and matches on the
517
- // symbol name even inside a comment.
518
- const scalarWrites: Array<{ field: string; run: () => { ok: true; changed: boolean } | { ok: false; error: string } }> = [];
519
- if (wantsAgentsEnabled) scalarWrites.push({ field: "agentsEnabled", run: () => setAgentsEnabled(body.agentsEnabled as boolean | null, undefined, heldWriteLock) });
520
- if (wantsMaxDepth) scalarWrites.push({ field: "agentsMaxDepth", run: () => setAgentsMaxDepth(body.agentsMaxDepth as number | null, undefined, heldWriteLock) });
521
- if (wantsSubagentInstructions) scalarWrites.push({ field: "subagentDeveloperInstructions", run: () => setSubagentDeveloperInstructions(body.subagentDeveloperInstructions as string | null, undefined, heldWriteLock) });
522
- if (wantsModeHintText) scalarWrites.push({ field: "multiAgentModeHintText", run: () => setMultiAgentModeHintText(body.multiAgentModeHintText as string | null, undefined, heldWriteLock) });
523
- const landed: string[] = [];
524
- for (const write of scalarWrites) {
525
- try {
526
- const result = write.run();
527
- if (!result.ok) {
528
- return jsonResponse({ error: `writing ${write.field} failed: ${result.error}${landed.length > 0 ? ` (already applied: ${landed.join(", ")})` : ""}` }, 502);
432
+ const writeRefusal = await settleConfigRoot(configRoot(), () => {
433
+ const currentPlan = readModePlan();
434
+ if (currentPlan instanceof Response) return currentPlan;
435
+ const { effectiveMode } = currentPlan;
436
+ requestedFlag = currentPlan.requestedFlag;
437
+ if (requestedFlag !== undefined && !heldWriteLock) return jsonResponse({ error: "Multi-agent configuration changed during admission", code: "config_changed" }, 409);
438
+ if (requestedFlag !== undefined || wantsThreads) {
439
+ const targetFlag = requestedFlag ?? isMultiAgentV2Enabled();
440
+ const toggle = deps.toggleCodexMultiAgentV2
441
+ ?? ((enabled, env, validate) => runCodexFeaturesCommand(enabled ? "enable" : "disable", "multi_agent_v2", env, validate));
442
+ const result = transitionMultiAgentV2(targetFlag, toggle, {
443
+ ...(wantsThreads ? { threadLimit: body.maxConcurrentThreadsPerSession as number } : {}),
444
+ heldConfigWriteLock: heldWriteLock,
445
+ });
446
+ if (!result.ok) return jsonResponse({ error: `multi_agent_v2 transition failed: ${result.error}`, ...(result.retryable === false ? { retryable: false } : {}) }, 502);
447
+ if (result.changed && result.threadLimit !== null) warnings.push(`Thread limit ${result.threadLimit} preserved for ${targetFlag ? "v2" : "v1"}.`);
529
448
  }
530
- landed.push(write.field);
531
- } catch (err) {
532
- const message = err instanceof Error ? err.message : String(err);
533
- return jsonResponse({ error: `writing ${write.field} failed: ${message}${landed.length > 0 ? ` (already applied: ${landed.join(", ")})` : ""}` }, 502);
534
- }
535
- }
449
+ if (wantsMode) {
450
+ if (mode === "default") deleteConfigTopLevelKey(config, "multiAgentMode");
451
+ else config.multiAgentMode = mode;
452
+ saveConfigPreservingClaudeCode(config);
453
+ warnings.push(`Multi-agent mode set to '${mode}'. Applies to new sessions.`);
454
+ }
455
+ if (wantsKeepNative) {
456
+ if (body.keepNativeChatGptOnV1 === true) config.keepNativeChatGptOnV1 = true;
457
+ else deleteConfigTopLevelKey(config, "keepNativeChatGptOnV1");
458
+ saveConfigPreservingClaudeCode(config);
459
+ warnings.push(body.keepNativeChatGptOnV1 === true
460
+ ? (effectiveMode === "v2"
461
+ ? "ChatGPT-native models stay on v1 while other models use v2. Applies to new sessions."
462
+ : "keepNativeChatGptOnV1 is stored but inactive until multi-agent mode is v2. Applies to new sessions.")
463
+ : "ChatGPT-native models follow the selected v1/v2/base surface. Applies to new sessions.");
464
+ }
465
+ // Written after the mode, so a landed acknowledgement implies the mode write it was
466
+ // sent with already landed. The converse does not hold: this writer throws rather than
467
+ // reporting, exactly as the mode write above it does, so a failure here surfaces the
468
+ // mode change with the advisory still raised. That is the benign direction — the
469
+ // operator is asked again — and it is why this is not claimed as a transaction.
470
+ if (wantsAdvisoryAck && body.multiAgentSurfaceAdvisoryAcknowledged === true) {
471
+ config.multiAgentSurfaceAdvisoryVersion = MULTI_AGENT_SURFACE_ADVISORY_VERSION;
472
+ saveConfigPreservingClaudeCode(config);
473
+ }
474
+ // New-key scalar writes: each writer is individually atomic, so apply them in
475
+ // sequence after the transition. A failure here is a persistence failure (the
476
+ // writers' ok:false result or a throw from the underlying atomic write helper),
477
+ // reported as 502 naming the failed key plus the writes that already landed.
478
+ // NOTE: do not name that helper literally here — tests/providers/xai/grok-writer-boundary.test.ts
479
+ // asserts this route file contains no direct write primitive, and matches on the
480
+ // symbol name even inside a comment.
481
+ const scalarWrites: Array<{ field: string; run: () => { ok: true; changed: boolean } | { ok: false; error: string } }> = [];
482
+ if (wantsAgentsEnabled) scalarWrites.push({ field: "agentsEnabled", run: () => setAgentsEnabled(body.agentsEnabled as boolean | null, undefined, heldWriteLock) });
483
+ if (wantsMaxDepth) scalarWrites.push({ field: "agentsMaxDepth", run: () => setAgentsMaxDepth(body.agentsMaxDepth as number | null, undefined, heldWriteLock) });
484
+ if (wantsSubagentInstructions) scalarWrites.push({ field: "subagentDeveloperInstructions", run: () => setSubagentDeveloperInstructions(body.subagentDeveloperInstructions as string | null, undefined, heldWriteLock) });
485
+ if (wantsModeHintText) scalarWrites.push({ field: "multiAgentModeHintText", run: () => setMultiAgentModeHintText(body.multiAgentModeHintText as string | null, undefined, heldWriteLock) });
486
+ const landed: string[] = [];
487
+ for (const write of scalarWrites) {
488
+ try {
489
+ const result = write.run();
490
+ if (!result.ok) {
491
+ return jsonResponse({ error: `writing ${write.field} failed: ${result.error}${landed.length > 0 ? ` (already applied: ${landed.join(", ")})` : ""}` }, 502);
492
+ }
493
+ landed.push(write.field);
494
+ } catch (err) {
495
+ const message = err instanceof Error ? err.message : String(err);
496
+ return jsonResponse({ error: `writing ${write.field} failed: ${message}${landed.length > 0 ? ` (already applied: ${landed.join(", ")})` : ""}` }, 502);
497
+ }
498
+ }
499
+ return null;
500
+ });
501
+ if (writeRefusal) return writeRefusal;
536
502
  } finally {
537
503
  if (heldWriteLock) releaseConfigWriteLock(heldWriteLock);
538
504
  }
@@ -699,13 +665,11 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
699
665
  };
700
666
  const { isCodexReasoningEffort } = await import("../../reasoning-effort");
701
667
 
702
- let nextEnabled = config.multiAgentGuidanceEnabled;
703
- // Start from the effective state reported by GET. A stale hand-edited
704
- // `true` without a model must not spring back on during a model-only PUT.
705
- let nextSyncCodexSubagentDefaults = subagentDefaultSyncEffective(config);
706
- let nextModel = config.injectionModel;
707
- let nextEffort = config.injectionEffort;
708
- let nextPrompt = config.injectionPrompt;
668
+ let nextEnabled: OcxConfig["multiAgentGuidanceEnabled"];
669
+ let nextSyncCodexSubagentDefaults: boolean | undefined;
670
+ let nextModel: OcxConfig["injectionModel"];
671
+ let nextEffort: OcxConfig["injectionEffort"];
672
+ let nextPrompt: OcxConfig["injectionPrompt"];
709
673
 
710
674
  if ("multiAgentGuidanceEnabled" in body) {
711
675
  if (typeof body.multiAgentGuidanceEnabled !== "boolean") {
@@ -737,29 +701,38 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
737
701
  else if (body.prompt === null || body.prompt === "") nextPrompt = undefined;
738
702
  else return jsonResponse({ error: "prompt must be a string or null" }, 400);
739
703
  }
740
- // Clearing the model always clears model-dependent settings before sync/effort gates.
741
- if (!nextModel) {
742
- nextEffort = undefined;
743
- nextSyncCodexSubagentDefaults = false;
744
- }
745
- if (body.syncCodexSubagentDefaults === true && !nextModel?.trim()) {
746
- return jsonResponse({ error: "syncCodexSubagentDefaults requires an injection model" }, 400);
747
- }
748
- if (nextSyncCodexSubagentDefaults && nextEffort !== undefined && !isCodexReasoningEffort(nextEffort)) {
749
- return jsonResponse({ error: "syncCodexSubagentDefaults requires a supported Codex reasoning effort" }, 400);
750
- }
704
+ const refusal = await settleConfigRoot(configRoot(), () => {
705
+ if (!("multiAgentGuidanceEnabled" in body)) nextEnabled = config.multiAgentGuidanceEnabled;
706
+ if (!("syncCodexSubagentDefaults" in body)) nextSyncCodexSubagentDefaults = subagentDefaultSyncEffective(config);
707
+ if (!("model" in body)) nextModel = config.injectionModel;
708
+ if (!("effort" in body)) nextEffort = config.injectionEffort;
709
+ if (!("prompt" in body)) nextPrompt = config.injectionPrompt;
710
+ // Clearing the model always clears model-dependent settings before sync/effort gates.
711
+ if (!nextModel) {
712
+ nextEffort = undefined;
713
+ nextSyncCodexSubagentDefaults = false;
714
+ }
715
+ if (body.syncCodexSubagentDefaults === true && !nextModel?.trim()) {
716
+ return jsonResponse({ error: "syncCodexSubagentDefaults requires an injection model" }, 400);
717
+ }
718
+ if (nextSyncCodexSubagentDefaults && nextEffort !== undefined && !isCodexReasoningEffort(nextEffort)) {
719
+ return jsonResponse({ error: "syncCodexSubagentDefaults requires a supported Codex reasoning effort" }, 400);
720
+ }
751
721
 
752
- config.multiAgentGuidanceEnabled = nextEnabled;
753
- if (nextSyncCodexSubagentDefaults) config.syncCodexSubagentDefaults = true;
754
- else deleteConfigTopLevelKey(config, "syncCodexSubagentDefaults");
755
- if (nextModel) config.injectionModel = nextModel;
756
- else deleteConfigTopLevelKey(config, "injectionModel");
757
- if (nextEffort) config.injectionEffort = nextEffort;
758
- else deleteConfigTopLevelKey(config, "injectionEffort");
759
- if (nextPrompt) config.injectionPrompt = nextPrompt;
760
- else deleteConfigTopLevelKey(config, "injectionPrompt");
722
+ config.multiAgentGuidanceEnabled = nextEnabled;
723
+ if (nextSyncCodexSubagentDefaults) config.syncCodexSubagentDefaults = true;
724
+ else deleteConfigTopLevelKey(config, "syncCodexSubagentDefaults");
725
+ if (nextModel) config.injectionModel = nextModel;
726
+ else deleteConfigTopLevelKey(config, "injectionModel");
727
+ if (nextEffort) config.injectionEffort = nextEffort;
728
+ else deleteConfigTopLevelKey(config, "injectionEffort");
729
+ if (nextPrompt) config.injectionPrompt = nextPrompt;
730
+ else deleteConfigTopLevelKey(config, "injectionPrompt");
761
731
 
762
- saveConfigPreservingClaudeCode(config);
732
+ saveConfigPreservingClaudeCode(config);
733
+ return null;
734
+ });
735
+ if (refusal) return refusal;
763
736
  return jsonResponse({
764
737
  ok: true,
765
738
  multiAgentGuidanceEnabled: multiAgentGuidanceEnabled(config),
@@ -790,45 +763,57 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
790
763
  }
791
764
  const patch = body as Record<string, unknown>;
792
765
  const { isCodexReasoningEffort } = await import("../../reasoning-effort");
793
- const draft = { ...projectConfigRebaseProvenance(config) };
794
- const touched: (keyof OcxConfig)[] = [];
795
- for (const key of ["effortCap", "subagentEffortCap"] as const) {
796
- if (!Object.hasOwn(patch, key)) continue;
797
- const value = patch[key];
798
- if (value === null || value === "") deleteConfigTopLevelKey(draft, key);
799
- else if (typeof value === "string" && isCodexReasoningEffort(value)) draft[key] = value;
800
- else return jsonResponse({ error: "caps must be valid reasoning efforts or null" }, 400);
801
- touched.push(key);
802
- }
803
- if (Object.hasOwn(patch, "modelPinnedEfforts")) {
804
- const error = modelPinnedEffortsConfigError(patch.modelPinnedEfforts, "modelPinnedEfforts", true);
805
- if (error) return jsonResponse({ error }, 400);
806
- const pins = mergeModelPinnedEfforts(config.modelPinnedEfforts, patch.modelPinnedEfforts);
807
- if (pins) draft.modelPinnedEfforts = pins;
808
- else deleteConfigTopLevelKey(draft, "modelPinnedEfforts");
809
- touched.push("modelPinnedEfforts");
810
- }
811
- const validation = validateConfigCandidate(draft);
812
- if (!validation.ok) return jsonResponse({ error: validation.error }, 400);
813
- if (touched.some(key => !Object.hasOwn(draft, key)) && config.configRebaseProvenance !== undefined
814
- && parsedConfigRebaseDeletionKeys(config) === null) {
815
- return jsonResponse({ error: "unsupported config deletion provenance" }, 409);
816
- }
817
- const projected = projectConfigRebaseProvenance(draft);
818
- touched.push("configRebaseProvenance");
819
- const rollback = captureConfigTopLevelRollback(config, touched);
820
- try {
821
- for (const key of touched) {
822
- if (Object.hasOwn(projected, key)) Object.defineProperty(config, key, {
823
- value: projected[key], writable: true, enumerable: true, configurable: true,
824
- });
825
- else deleteConfigTopLevelKey(config, key);
766
+ const prepare = () => {
767
+ const draft = { ...projectConfigRebaseProvenance(config) };
768
+ const touched: (keyof OcxConfig)[] = [];
769
+ for (const key of ["effortCap", "subagentEffortCap"] as const) {
770
+ if (!Object.hasOwn(patch, key)) continue;
771
+ const value = patch[key];
772
+ if (value === null || value === "") deleteConfigTopLevelKey(draft, key);
773
+ else if (typeof value === "string" && isCodexReasoningEffort(value)) draft[key] = value;
774
+ else return jsonResponse({ error: "caps must be valid reasoning efforts or null" }, 400);
775
+ touched.push(key);
826
776
  }
827
- (deps.saveConfigPreservingClaudeCode ?? saveConfigPreservingClaudeCode)(config);
828
- } catch (error) {
829
- rollback();
830
- throw error;
831
- }
777
+ if (Object.hasOwn(patch, "modelPinnedEfforts")) {
778
+ const error = modelPinnedEffortsConfigError(patch.modelPinnedEfforts, "modelPinnedEfforts", true);
779
+ if (error) return jsonResponse({ error }, 400);
780
+ const pins = mergeModelPinnedEfforts(config.modelPinnedEfforts, patch.modelPinnedEfforts);
781
+ if (pins) draft.modelPinnedEfforts = pins;
782
+ else deleteConfigTopLevelKey(draft, "modelPinnedEfforts");
783
+ touched.push("modelPinnedEfforts");
784
+ }
785
+ const validation = validateConfigCandidate(draft);
786
+ if (!validation.ok) return jsonResponse({ error: validation.error }, 400);
787
+ if (touched.some(key => !Object.hasOwn(draft, key)) && config.configRebaseProvenance !== undefined
788
+ && parsedConfigRebaseDeletionKeys(config) === null) {
789
+ return jsonResponse({ error: "unsupported config deletion provenance" }, 409);
790
+ }
791
+ const projected = projectConfigRebaseProvenance(draft);
792
+ touched.push("configRebaseProvenance");
793
+ return { touched, projected };
794
+ };
795
+ const checked = prepare();
796
+ if (checked instanceof Response) return checked;
797
+ const refusal = await settleConfigRoot(configRoot(), () => {
798
+ const prepared = prepare();
799
+ if (prepared instanceof Response) return prepared;
800
+ const { touched, projected } = prepared;
801
+ const rollback = captureConfigTopLevelRollback(config, touched);
802
+ try {
803
+ for (const key of touched) {
804
+ if (Object.hasOwn(projected, key)) Object.defineProperty(config, key, {
805
+ value: projected[key], writable: true, enumerable: true, configurable: true,
806
+ });
807
+ else deleteConfigTopLevelKey(config, key);
808
+ }
809
+ (deps.saveConfigPreservingClaudeCode ?? saveConfigPreservingClaudeCode)(config);
810
+ } catch (error) {
811
+ rollback();
812
+ throw error;
813
+ }
814
+ return null;
815
+ });
816
+ if (refusal) return refusal;
832
817
  return jsonResponse({
833
818
  ok: true,
834
819
  effortCap: config.effortCap ?? null,
@@ -873,8 +858,8 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
873
858
  if (!body || typeof body !== "object" || Array.isArray(body)) {
874
859
  return jsonResponse({ error: "invalid JSON body" }, 400);
875
860
  }
876
- let nextModels = config.subagentModelFallback;
877
- let nextPollMs = config.subagentModelFallbackPollMs;
861
+ let nextModels: OcxConfig["subagentModelFallback"];
862
+ let nextPollMs: OcxConfig["subagentModelFallbackPollMs"];
878
863
  if ("models" in body) {
879
864
  if (!Array.isArray(body.models)) return jsonResponse({ error: "models must be an array" }, 400);
880
865
  const models: string[] = [];
@@ -900,11 +885,15 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
900
885
  return jsonResponse({ error: "pollMs must be an integer between 5000 and 600000" }, 400);
901
886
  }
902
887
  }
903
- if (nextModels !== undefined) config.subagentModelFallback = nextModels;
904
- else deleteConfigTopLevelKey(config, "subagentModelFallback");
905
- if (nextPollMs !== undefined) config.subagentModelFallbackPollMs = nextPollMs;
906
- else deleteConfigTopLevelKey(config, "subagentModelFallbackPollMs");
907
- saveConfigPreservingClaudeCode(config);
888
+ await settleConfigRoot(configRoot(), () => {
889
+ if (!("models" in body)) nextModels = config.subagentModelFallback;
890
+ if (!("pollMs" in body)) nextPollMs = config.subagentModelFallbackPollMs;
891
+ if (nextModels !== undefined) config.subagentModelFallback = nextModels;
892
+ else deleteConfigTopLevelKey(config, "subagentModelFallback");
893
+ if (nextPollMs !== undefined) config.subagentModelFallbackPollMs = nextPollMs;
894
+ else deleteConfigTopLevelKey(config, "subagentModelFallbackPollMs");
895
+ saveConfigPreservingClaudeCode(config);
896
+ });
908
897
  return jsonResponse({
909
898
  ok: true,
910
899
  models: config.subagentModelFallback ?? [],
@@ -944,9 +933,11 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
944
933
  // cannot grow config.json without bound.
945
934
  const excluded = [...new Set(raw as string[])].sort();
946
935
  if (excluded.length > 2000) return jsonResponse({ error: "excluded list is too large" }, 400);
947
- if (excluded.length === 0) deleteConfigTopLevelKey(config, "grokExcludedModels");
948
- else config.grokExcludedModels = excluded;
949
- saveConfigPreservingClaudeCode(config);
936
+ await settleConfigRoot(configRoot(), () => {
937
+ if (excluded.length === 0) deleteConfigTopLevelKey(config, "grokExcludedModels");
938
+ else config.grokExcludedModels = excluded;
939
+ saveConfigPreservingClaudeCode(config);
940
+ });
950
941
  return jsonResponse({ ok: true, excluded });
951
942
  }
952
943
 
@@ -1014,17 +1005,31 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1014
1005
  const state = await buildClaudeDesktopState(initial, editable);
1015
1006
  const rebuilt = reconcileDesktopProfile(state.profile, state.models);
1016
1007
  const expectedProfile = initial.claudeCode?.desktopProfile;
1017
- const outcome = mutatePersistedConfig<OcxConfig["claudeCode"] | null>(persisted => {
1018
- const latest = persisted.claudeCode?.desktopProfile;
1019
- if ((latest == null) !== (expectedProfile == null)
1020
- || (latest && expectedProfile && !sameProfileContent(latest, expectedProfile))) {
1021
- return { changed: false, value: null };
1008
+ const outcome = await settleConfigRoot(configRoot(), () => {
1009
+ const outcome = mutatePersistedConfig<OcxConfig["claudeCode"] | null>(persisted => {
1010
+ const latest = persisted.claudeCode?.desktopProfile;
1011
+ if ((latest == null) !== (expectedProfile == null)
1012
+ || (latest && expectedProfile && !sameProfileContent(latest, expectedProfile))) {
1013
+ return { changed: false, value: null };
1014
+ }
1015
+ persisted.claudeCode = {
1016
+ ...(persisted.claudeCode ?? {}),
1017
+ desktopProfile: preserveDesktopAppliedState(latest ?? current.profile, rebuilt),
1018
+ };
1019
+ return { changed: true, value: structuredClone(persisted.claudeCode) };
1020
+ });
1021
+ if (outcome.status !== "unavailable" && outcome.value !== null) {
1022
+ adoptPersistedClaudeCode(config, outcome.value);
1023
+ // An unarmed live snapshot may prefer its old marker during reconciliation.
1024
+ // Pin the field this route just committed while leaving other live leaves intact.
1025
+ if (outcome.value?.desktopProfile) {
1026
+ config.claudeCode = {
1027
+ ...(config.claudeCode ?? {}),
1028
+ desktopProfile: structuredClone(outcome.value.desktopProfile),
1029
+ };
1030
+ }
1022
1031
  }
1023
- persisted.claudeCode = {
1024
- ...(persisted.claudeCode ?? {}),
1025
- desktopProfile: preserveDesktopAppliedState(latest ?? current.profile, rebuilt),
1026
- };
1027
- return { changed: true, value: structuredClone(persisted.claudeCode) };
1032
+ return outcome;
1028
1033
  });
1029
1034
  if (outcome.status === "unavailable" && outcome.reason !== "conflict") {
1030
1035
  return jsonResponse({ error: "Claude Desktop profile could not be saved (config " + outcome.reason + ")" }, 500);
@@ -1032,23 +1037,17 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1032
1037
  if (outcome.status === "unavailable" || outcome.value === null) {
1033
1038
  return jsonResponse({ error: "Claude Desktop profile changed during save" }, 409);
1034
1039
  }
1035
- adoptPersistedClaudeCode(config, outcome.value);
1036
- // An unarmed live snapshot may prefer its old marker during reconciliation.
1037
- // Pin the field this route just committed while leaving other live leaves intact.
1038
- if (outcome.value?.desktopProfile) {
1039
- config.claudeCode = {
1040
- ...(config.claudeCode ?? {}),
1041
- desktopProfile: structuredClone(outcome.value.desktopProfile),
1042
- };
1043
- }
1044
1040
  const saved = await buildClaudeDesktopState(config);
1045
1041
  const runtimePort = managementInferencePort(ctx);
1046
1042
  return jsonResponse({ ok: true, ...saved, port: runtimePort });
1047
1043
  } catch (error) {
1044
+ if (error instanceof WindowsSecretAclSettleTimeoutError) return jsonResponse({ error: "Could not save settings", code: "write_failed", diagnostic: { stage: "ca", cause: "ETIMEDOUT" } }, 500);
1048
1045
  return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
1049
1046
  }
1050
1047
  }
1051
1048
  if (url.pathname === "/api/claude-desktop/apply" && req.method === "POST") {
1049
+ let committedIntent = false, savedProfile = false, pickerDisabled = false;
1050
+ let appliedMode: "first-party" | "gateway" | undefined, appliedPath = "", modeCommitted = false;
1052
1051
  try {
1053
1052
  // #859: the CLI delegates here so the registry is built in the serving
1054
1053
  // process. `mode` selects the Desktop mode: `first-party` (default when the
@@ -1062,7 +1061,7 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1062
1061
  rethrowManagementBodyTooLarge(error);
1063
1062
  return jsonResponse({ error: "invalid JSON body" }, 400);
1064
1063
  }
1065
- const { resolveClaudeDesktopApplyMode, observeClaudeDesktopMode, applyDesktopFirstParty, withFirstPartySecretsSettled, captureDesktopFirstPartyRollback, removeDesktopFirstPartySettled } = await import("../../claude/desktop-first-party");
1064
+ const { resolveClaudeDesktopApplyMode, observeClaudeDesktopMode, applyDesktopFirstParty, withFirstPartySecretsSettled, captureDesktopFirstPartyRollback, rollbackDesktopFirstPartySettled, removeDesktopFirstPartySettled } = await import("../../claude/desktop-first-party");
1066
1065
  const requested = (parsed as { mode?: unknown } | null)?.mode;
1067
1066
  let desktopMode: "first-party" | "gateway" = resolveClaudeDesktopApplyMode(config, observeClaudeDesktopMode(config));
1068
1067
  if (requested !== undefined) {
@@ -1097,16 +1096,21 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1097
1096
  const configured = claudeInterceptProxyPort(config, config.port ?? 10100);
1098
1097
  if (started.state.proxyPort !== configured) return jsonResponse({ ok: false, code: "port_mismatch", bound: started.state.proxyPort, configured }, 409);
1099
1098
  const { setIntegrationEnabled } = await import("../../codex/desired-state");
1100
- const desired = setIntegrationEnabled("claude-desktop", true);
1101
- if (!desired.ok) return jsonResponse({ error: desired.message }, desired.retryable ? 409 : 500);
1102
- mirrorDesiredEnabledOntoSnapshot(config, "claude-desktop", true);
1099
+ const desired = await withFirstPartySecretsSettled(configRoot(), () => {
1100
+ const result = setIntegrationEnabled("claude-desktop", true);
1101
+ if (result.ok) mirrorDesiredEnabledOntoSnapshot(config, "claude-desktop", true);
1102
+ return result;
1103
+ });
1104
+ if (!desired.ok) return "path" in desired ? jsonResponse({ ...desired, code: desired.reason }, 500)
1105
+ : jsonResponse({ error: desired.message }, desired.retryable ? 409 : 500);
1106
+ committedIntent = true;
1103
1107
  const { pickerPreferenceOn, pickerStatusFor, runPickerTransition } = await import("./claude-desktop-picker-routes");
1104
1108
  // The whole switch runs under the picker lock, in today's order: env first, then gateway cleanup.
1105
1109
  return await runPickerTransition(config, async ops => {
1106
1110
  const { inspectDesktop3pConfigLibrary, removeDesktop3pStandardPivot } = await import("../../claude/desktop-3p");
1107
- const rollback = captureDesktopFirstPartyRollback(config);
1108
- const { getConfigDir, withConfigDirHardeningSettled } = await import("../../config/paths");
1109
- const applied = await withFirstPartySecretsSettled(getConfigDir(), () => applyDesktopFirstParty(config));
1111
+ let rollback!: ReturnType<typeof captureDesktopFirstPartyRollback>;
1112
+ const { getConfigDir } = await import("../../config/paths");
1113
+ const applied = await withFirstPartySecretsSettled(getConfigDir(), () => { rollback = captureDesktopFirstPartyRollback(config); return applyDesktopFirstParty(config); });
1110
1114
  if (!applied.ok) {
1111
1115
  const { firstPartyRefusalMessage } = await import("./native-integration-routes");
1112
1116
  return jsonResponse({
@@ -1117,22 +1121,32 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1117
1121
  ...(applied.diagnostic ? { diagnostic: applied.diagnostic } : {}),
1118
1122
  }, applied.reason === "foreign_env" || applied.reason === "intercept_disabled" ? 409 : 500);
1119
1123
  }
1124
+ appliedMode = "first-party"; appliedPath = applied.path;
1125
+ let gatewayRemoved = false;
1126
+ try {
1120
1127
  // Remove the gateway only after the replacement env was written.
1121
1128
  const appliedFingerprint = config.claudeCode?.desktopProfile?.appliedFingerprint ?? null;
1122
1129
  const library = inspectDesktop3pConfigLibrary({ appliedFingerprint });
1123
- let gatewayRemoved = false;
1124
1130
  if (library.kind === "gateway_ours" || library.kind === "gateway_drifted") {
1125
- const removed = (deps.removeDesktop3pStandardPivot ?? removeDesktop3pStandardPivot)({ appliedFingerprint, replaceWhileEnabled: true });
1131
+ let removed: ReturnType<typeof removeDesktop3pStandardPivot>;
1132
+ try { removed = await settleConfigRoot(configRoot(), () => (deps.removeDesktop3pStandardPivot ?? removeDesktop3pStandardPivot)({ appliedFingerprint: readConfigForAdmittedMutation().claudeCode?.desktopProfile?.appliedFingerprint ?? null, replaceWhileEnabled: true })); }
1133
+ catch (error) {
1134
+ removed = { ok: false, changed: false, kind: "write_failed", libraryPath: library.libraryPath,
1135
+ reason: error instanceof WindowsSecretAclSettleTimeoutError ? "acl_settlement_timeout" : "desktop_mutation_failed" };
1136
+ }
1126
1137
  if (!removed.ok) {
1127
- const restored = removed.changed || !applied.changed || await withConfigDirHardeningSettled(getConfigDir(), rollback);
1138
+ const restored = removed.changed || !applied.changed || await rollbackDesktopFirstPartySettled(getConfigDir(), rollback).catch(() => false);
1139
+ if (!removed.changed && restored && applied.changed) appliedMode = undefined;
1128
1140
  const modeSaved = !removed.changed || (await persistDesktopModeField(config, "first-party")).ok;
1129
1141
  const warning = [restored ? "" : "first-party settings rollback did not complete",
1130
1142
  modeSaved ? "" : "first-party is active but its mode marker was not saved"].filter(Boolean).join("; ");
1131
1143
  return jsonResponse({
1132
1144
  error: removed.kind === "cleanup_incomplete"
1133
1145
  ? "Claude Desktop now points at standard mode, but gateway credential cleanup is incomplete; the first-party connection remains active."
1146
+ : !restored ? "The gateway profile could not be removed and first-party settings rollback did not complete; the mode switch is incomplete."
1134
1147
  : "The gateway profile could not be removed safely, so first-party mode was not applied.",
1135
1148
  code: "claude_desktop_gateway_removal_failed",
1149
+ desiredEnabled: true, saved: removed.changed && modeSaved, applied: removed.changed || !restored || !applied.changed,
1136
1150
  ...(warning ? { warning } : {}),
1137
1151
  reason: removed.reason ?? removed.kind,
1138
1152
  ...(removed.residualPaths ? { residualPaths: removed.residualPaths } : {}),
@@ -1141,6 +1155,7 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1141
1155
  gatewayRemoved = removed.changed;
1142
1156
  }
1143
1157
  const modeSaved = await persistDesktopModeField(config, "first-party");
1158
+ modeCommitted = modeSaved.ok;
1144
1159
  const { firstPartyAccountRisk } = await import("../../claude/desktop-risk");
1145
1160
  // Picker mode is on by default in first-party; only a committed mode turns it on.
1146
1161
  const picker = modeSaved.ok && pickerPreferenceOn(loadConfig())
@@ -1161,28 +1176,43 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1161
1176
  picker,
1162
1177
  ...(modeSaved.ok ? {} : { warning: `First-party env was applied, but the mode marker was not saved (${modeSaved.reason}).` }),
1163
1178
  });
1179
+ } catch {
1180
+ const retained = gatewayRemoved || modeCommitted;
1181
+ const restored = retained || !applied.changed || await rollbackDesktopFirstPartySettled(getConfigDir(), rollback).catch(() => false);
1182
+ return jsonResponse({ error: "First-party mode follow-up did not complete", code: "claude_desktop_gateway_removal_failed",
1183
+ desiredEnabled: true, saved: modeCommitted, applied: retained || !restored || !applied.changed,
1184
+ warning: retained ? "First-party settings remain applied."
1185
+ : restored ? "First-party settings were rolled back; Desktop enable intent remains saved." : "first-party settings rollback did not complete" }, 500);
1186
+ }
1164
1187
  });
1165
1188
  }
1166
1189
  const { setIntegrationEnabled, claudeDesktopIntegrationEnabled } = await import("../../codex/desired-state");
1167
- const desired = setIntegrationEnabled("claude-desktop", true);
1190
+ const desired = await settleConfigRoot(configRoot(), () => {
1191
+ const result = setIntegrationEnabled("claude-desktop", true);
1192
+ if (result.ok) mirrorDesiredEnabledOntoSnapshot(config, "claude-desktop", true);
1193
+ return result;
1194
+ });
1168
1195
  if (!desired.ok) return jsonResponse({ error: desired.message }, desired.retryable ? 409 : 500);
1196
+ committedIntent = true;
1169
1197
  // Disk now says ON; the reused server snapshot must agree, or the native
1170
1198
  // GET reports OFF and a later whole-snapshot save undoes this transition.
1171
- mirrorDesiredEnabledOntoSnapshot(config, "claude-desktop", true);
1199
+ const expectedProfile = structuredClone(loadConfig().claudeCode?.desktopProfile);
1172
1200
  const state = await buildClaudeDesktopState(config, profileOverride);
1173
1201
  // `setIntegrationEnabled` above wrote desired ON to DISK; it does not touch
1174
1202
  // this long-lived server snapshot. Saving the snapshot wholesale would carry
1175
1203
  // its stale `clientIntegrations` back over that write and turn the enable
1176
1204
  // action into an immediate self-cancelling OFF — the guard below would then
1177
1205
  // refuse the apply it was asked to perform. Persist ONLY the profile field.
1178
- const profileSaved = persistDesktopProfileField(config, state.profile);
1206
+ const profileSaved = await persistDesktopProfileField(config, state.profile, expectedProfile);
1179
1207
  if (!profileSaved.ok) {
1180
1208
  return jsonResponse({
1181
1209
  error: `Claude Desktop profile could not be saved (${profileSaved.reason}); nothing was applied.`,
1182
1210
  saved: false,
1183
1211
  applied: false,
1212
+ desiredEnabled: true,
1184
1213
  }, profileSaved.reason === "conflict" ? 409 : 500);
1185
1214
  }
1215
+ savedProfile = true;
1186
1216
  const { writeDesktop3pConfig } = await import("../../claude/desktop-3p");
1187
1217
  const { desktopVisibleNativeSlugs } = await import("../../codex/catalog");
1188
1218
  const routed = state.models
@@ -1195,7 +1225,7 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1195
1225
  const outcome = await runPickerTransition(config, async ops => {
1196
1226
  // State construction can await catalog work; never write from the stale
1197
1227
  // config captured before that await if another request turned Desktop off.
1198
- const latest = loadConfig();
1228
+ let latest = loadConfig();
1199
1229
  if (!claudeDesktopIntegrationEnabled(latest)) {
1200
1230
  return { response: jsonResponse({
1201
1231
  error: "Claude Desktop apply was cancelled because the desired state changed to off.",
@@ -1208,7 +1238,11 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1208
1238
  }
1209
1239
  // Picker mode belongs to first-party: stop terminating claude.ai before the gateway lands.
1210
1240
  const pickerOff = await ops.disableLocked({ persist: false });
1211
- const result = (deps.writeDesktop3pConfig ?? writeDesktop3pConfig)(
1241
+ pickerDisabled = true;
1242
+ const result = await settleConfigRoot(configRoot(), () => {
1243
+ latest = readConfigForAdmittedMutation();
1244
+ if (!claudeDesktopIntegrationEnabled(latest) || JSON.stringify(latest.claudeCode?.desktopProfile) !== JSON.stringify(state.profile)) return null;
1245
+ return (deps.writeDesktop3pConfig ?? writeDesktop3pConfig)(
1212
1246
  managementInferencePort({ config: latest, deps }),
1213
1247
  [...desktopVisibleNativeSlugs(latest)],
1214
1248
  routed,
@@ -1216,9 +1250,14 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1216
1250
  mode,
1217
1251
  state.profile,
1218
1252
  nativeContextLimits(latest),
1219
- );
1253
+ ); });
1254
+ if (result === null) return { response: jsonResponse({ error: "Desktop configuration changed during apply", code: "config_changed", saved: true, applied: false }, 409) };
1220
1255
  if (!result.written) return { response: jsonResponse({ error: result.reason ?? "Claude Desktop apply failed", saved: true, path: result.path }, 500) };
1221
- const committed = persistCommittedDesktopGateway(config, state.profile, result.fingerprint);
1256
+ appliedMode = "gateway"; appliedPath = result.path;
1257
+ const committed = await settleConfigRoot(configRoot(), () => persistCommittedDesktopGateway(config, state.profile, result.fingerprint)).catch(() => {
1258
+ return { ok: false, reason: "unavailable" } as const;
1259
+ });
1260
+ modeCommitted = committed.ok;
1222
1261
  const modeWarning = committed.ok ? undefined : `Gateway applied, but its mode/profile state was not saved (${committed.reason}).`;
1223
1262
  // The durable marker describes the committed gateway even if old-mode cleanup fails.
1224
1263
  const firstPartyRemoved = await removeDesktopFirstPartySettled(loadConfig);
@@ -1257,6 +1296,13 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1257
1296
  });
1258
1297
  } catch (error) {
1259
1298
  rethrowManagementBodyTooLarge(error);
1299
+ if (committedIntent || error instanceof WindowsSecretAclSettleTimeoutError) return jsonResponse({
1300
+ error: error instanceof WindowsSecretAclSettleTimeoutError ? "Config-directory ACL settlement timed out" : "Desktop apply did not complete", code: "write_failed",
1301
+ ...(error instanceof WindowsSecretAclSettleTimeoutError ? { diagnostic: { stage: "ca", cause: "ETIMEDOUT" } } : {}),
1302
+ ...(committedIntent ? { desiredEnabled: true, saved: appliedMode ? modeCommitted : savedProfile, applied: appliedMode !== undefined,
1303
+ ...(appliedMode ? { mode: appliedMode, path: appliedPath } : {}),
1304
+ warning: `Desktop enable intent${savedProfile ? " and profile were" : " was"} saved; Desktop ${appliedMode ? "was applied but follow-up did not complete" : "was not applied"}.${pickerDisabled ? " Picker disable was already attempted." : ""}` } : {}),
1305
+ }, 500);
1260
1306
  return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
1261
1307
  }
1262
1308
  }
@@ -1364,7 +1410,8 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1364
1410
  const state = await buildClaudeDesktopState(config);
1365
1411
  const availableRoutes = new Set(state.models.filter(model => model.available).map(model => model.route));
1366
1412
  let rejection: string | null = null;
1367
- const outcome = mutatePersistedConfig<OcxConfig["claudeCode"]>(persisted => {
1413
+ const outcome = await settleConfigRoot(configRoot(), () => {
1414
+ const outcome = mutatePersistedConfig<OcxConfig["claudeCode"]>(persisted => {
1368
1415
  const current = readInterceptBindings(persisted.claudeCode);
1369
1416
  const next = applyInterceptBindingPatch(current, patch, availableRoutes);
1370
1417
  if (!next.ok) {
@@ -1381,10 +1428,7 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1381
1428
  persisted.claudeCode = claudeCode;
1382
1429
  return { changed: true, value: structuredClone(persisted.claudeCode) };
1383
1430
  });
1384
- if (rejection) return jsonResponse({ error: rejection }, 400);
1385
- if (outcome.status === "unavailable") {
1386
- return jsonResponse({ error: `First-party bindings could not be saved (config ${outcome.reason})` }, outcome.reason === "conflict" ? 409 : 500);
1387
- }
1431
+ if (!rejection && outcome.status !== "unavailable") {
1388
1432
  adoptPersistedClaudeCode(config, outcome.value);
1389
1433
  // Pin the committed leaf: an unarmed live snapshot may otherwise keep its old intercept block.
1390
1434
  const committedIntercept = outcome.value?.intercept;
@@ -1392,8 +1436,16 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1392
1436
  if (committedIntercept) liveClaudeCode.intercept = structuredClone(committedIntercept);
1393
1437
  else delete liveClaudeCode.intercept;
1394
1438
  config.claudeCode = liveClaudeCode;
1439
+ }
1440
+ return outcome;
1441
+ });
1442
+ if (rejection) return jsonResponse({ error: rejection }, 400);
1443
+ if (outcome.status === "unavailable") {
1444
+ return jsonResponse({ error: `First-party bindings could not be saved (config ${outcome.reason})` }, outcome.reason === "conflict" ? 409 : 500);
1445
+ }
1395
1446
  return jsonResponse({ ok: true, modelBindings: readInterceptBindings(config.claudeCode) });
1396
1447
  } catch (error) {
1448
+ if (error instanceof WindowsSecretAclSettleTimeoutError) return jsonResponse({ error: "Could not save settings", code: "write_failed", diagnostic: { stage: "ca", cause: "ETIMEDOUT" } }, 500);
1397
1449
  return jsonResponse({ error: error instanceof Error ? error.message : String(error) }, 400);
1398
1450
  }
1399
1451
  }
@@ -1587,7 +1639,8 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1587
1639
  pinnedMode: "first-party" | "gateway" | undefined; retainedAmbiguous: boolean };
1588
1640
  let outcome: ReturnType<typeof mutatePersistedConfig<FirstPartyMutation>>;
1589
1641
  try {
1590
- outcome = mutatePersistedConfig<FirstPartyMutation>(persisted => {
1642
+ outcome = await settleConfigRoot(configRoot(), () => {
1643
+ const outcome = mutatePersistedConfig<FirstPartyMutation>(persisted => {
1591
1644
  if (body.cliFirstParty) {
1592
1645
  if (!claudeInterceptEnabled(persisted)) return { changed: false, value: {
1593
1646
  refusal: { error: "Claude intercept is disabled", code: "disabled" as const } } };
@@ -1617,20 +1670,27 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1617
1670
  const retainedAmbiguous = !body.cliFirstParty && previous.value && pinnedMode === "first-party";
1618
1671
  return { changed: true, value: { claudeCode: structuredClone(persisted.claudeCode), previous, pinnedMode, retainedAmbiguous } };
1619
1672
  });
1620
- } catch { return jsonResponse({ error: "Could not save Claude settings", code: "write_failed" }, 500); }
1621
- if (outcome.status === "unavailable") return jsonResponse({ error: "Could not save Claude settings", code: "write_failed" }, 500);
1622
- const committed = outcome.value;
1623
- if ("refusal" in committed) return jsonResponse(committed.refusal, 409);
1673
+ if (outcome.status !== "unavailable" && !("refusal" in outcome.value)) {
1674
+ const committed = outcome.value;
1624
1675
  adoptPersistedClaudeCode(config, committed.claudeCode);
1625
1676
  const live = { ...(config.claudeCode ?? {}) };
1626
1677
  if (body.cliFirstParty) live.cliFirstParty = true; else delete live.cliFirstParty;
1627
1678
  if (committed.pinnedMode) live.desktopMode = committed.pinnedMode;
1628
1679
  config.claudeCode = live;
1680
+ }
1681
+ return outcome;
1682
+ });
1683
+ } catch (error) { return jsonResponse({ error: "Could not save Claude settings", code: "write_failed",
1684
+ ...(error instanceof WindowsSecretAclSettleTimeoutError ? { diagnostic: { stage: "ca", cause: "ETIMEDOUT" } } : {}) }, 500); }
1685
+ if (outcome.status === "unavailable") return jsonResponse({ error: "Could not save Claude settings", code: "write_failed" }, 500);
1686
+ const committed = outcome.value;
1687
+ if ("refusal" in committed) return jsonResponse(committed.refusal, 409);
1629
1688
  let result: ReturnType<typeof reconcileClaudeFirstPartySettings> | undefined;
1630
1689
  const { getConfigDir, withConfigDirHardeningSettled } = await import("../../config/paths");
1631
- try { result = await withFirstPartySecretsSettled(getConfigDir(), () =>
1632
- (deps.reconcileClaudeFirstPartySettings ?? reconcileClaudeFirstPartySettings)(config,
1633
- firstPartyDesired(config, observeClaudeDesktopMode(config)))); }
1690
+ try { result = await withFirstPartySecretsSettled(getConfigDir(), () => {
1691
+ if (body.cliFirstParty) restoreSettings = captureDesktopFirstPartyRollback(config);
1692
+ return (deps.reconcileClaudeFirstPartySettings ?? reconcileClaudeFirstPartySettings)(config,
1693
+ firstPartyDesired(config, observeClaudeDesktopMode(config))); }); }
1634
1694
  catch { /* An unexpected settings failure is mapped after conditional rollback. */ }
1635
1695
  if (!result?.ok) {
1636
1696
  let settingsRestored = true;
@@ -1638,7 +1698,7 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1638
1698
  try { settingsRestored = result?.reason === "ca_unavailable" || await withConfigDirHardeningSettled(getConfigDir(), () => restoreSettings?.() ?? false); } catch { settingsRestored = false; }
1639
1699
  let rollback: ReturnType<typeof mutatePersistedConfig<OcxConfig["claudeCode"]>>;
1640
1700
  try {
1641
- rollback = mutatePersistedConfig(persisted => {
1701
+ rollback = await settleConfigRoot(configRoot(), () => mutatePersistedConfig(persisted => {
1642
1702
  const block = { ...(persisted.claudeCode ?? {}) };
1643
1703
  if (block.cliFirstParty === true) {
1644
1704
  if (committed.previous.present) block.cliFirstParty = committed.previous.value;
@@ -1648,10 +1708,10 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1648
1708
  delete block.desktopMode;
1649
1709
  persisted.claudeCode = block;
1650
1710
  return { changed: true, value: structuredClone(block) };
1651
- });
1652
- } catch { return jsonResponse({ error: "Claude settings rollback failed", code: "write_failed",
1711
+ }));
1712
+ } catch { return jsonResponse({ error: "Claude settings rollback failed", code: "write_failed", cliFirstParty: true,
1653
1713
  warnings: ["settings_rollback_incomplete"] }, 500); }
1654
- if (rollback.status === "unavailable") return jsonResponse({ error: "Claude settings rollback failed", code: "write_failed",
1714
+ if (rollback.status === "unavailable") return jsonResponse({ error: "Claude settings rollback failed", code: "write_failed", cliFirstParty: true,
1655
1715
  warnings: ["settings_rollback_incomplete"] }, 500);
1656
1716
  adoptPersistedClaudeCode(config, rollback.value);
1657
1717
  }
@@ -1675,274 +1735,95 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1675
1735
  ...(residual ? ["settings_residual"] : []),
1676
1736
  ] });
1677
1737
  }
1678
- const instanceError = anthropicSidecarPatchError(config, body, true);
1679
- if (instanceError) return jsonResponse({ error: instanceError }, 400);
1680
- for (const field of ["webSearchSidecar", "visionSidecar"] as const) {
1681
- const section = body[field];
1682
- if (section === undefined || section === null) continue;
1683
- if (!isPlainObject(section)) return jsonResponse({ error: `${field} must be an object or null` }, 400);
1684
- if (section.enabled !== undefined && typeof section.enabled !== "boolean") {
1685
- return jsonResponse({ error: `${field}.enabled must be a boolean` }, 400);
1686
- }
1687
- // Both overrides now speak their full unions (roadmap 060 web, 170
1688
- // vision revised). Vision's third arm is "routed" (loopback through the
1689
- // proxy's own router), never exa: exa is not an LLM, and accepting an
1690
- // unknown literal would persist a backend the vision resolver reads as
1691
- // unset (review F1's failure mode).
1692
- const allowedBackends = field === "webSearchSidecar"
1693
- ? ["openai", "anthropic", "xai", "gemini", "exa"]
1694
- : ["openai", "anthropic", "routed"];
1695
- if (section.backend !== undefined && section.backend !== null
1696
- && !allowedBackends.includes(section.backend as string)) {
1697
- return jsonResponse({ error: `${field}.backend must be ${allowedBackends.join(", ")}, or null` }, 400);
1698
- }
1699
- if (section.model !== undefined && typeof section.model !== "string") {
1700
- return jsonResponse({ error: `${field}.model must be a string` }, 400);
1701
- }
1702
- // Vision override only: reject a model we can prove is blind. Unknown ids stay
1703
- // allowed. Shares one policy module with /api/sidecar-settings so the two
1704
- // gates cannot drift.
1705
- if (field === "visionSidecar" && typeof section.model === "string" && section.model !== "") {
1706
- const requested = section.model;
1707
- const candidates = await visionCandidateRows({ ...config, visionSidecar: {
1708
- ...config.visionSidecar, ...sidecarSettingsAfterPatch(config.claudeCode?.visionSidecar, section),
1709
- } });
1710
- const hint = section.backend === "anthropic" || section.backend === "openai"
1711
- || section.backend === "routed"
1712
- ? section.backend
1713
- : config.claudeCode?.visionSidecar?.backend;
1714
- // Same coherence rule as /api/sidecar-settings (roadmap 170 r2).
1715
- const effectiveBackend = hint ?? "openai";
1716
- const namespaced = requested.includes("/");
1717
- if (namespaced && effectiveBackend !== "routed") {
1718
- return jsonResponse({ error: `visionSidecar.model "${requested}" is provider-namespaced; it requires backend "routed"` }, 400);
1719
- }
1720
- if (!namespaced && effectiveBackend === "routed") {
1721
- return jsonResponse({ error: `visionSidecar.backend "routed" requires a provider-namespaced model ("provider/model"); got "${requested}"` }, 400);
1722
- }
1723
- if (visionDescriberIsProvablyBlind(config, requested, candidates, hint)) {
1724
- return jsonResponse(visionDescriberRejection("visionSidecar.model", requested, config, candidates), 400);
1725
- }
1726
- }
1727
- // Web-search override: membership gate (#2188). The executor set is closed,
1728
- // so an id outside (runnable candidates ∪ auth slots) can never run. Same
1729
- // module as /api/sidecar-settings — a gate on one route and a stale copy on
1730
- // the other is no gate at all.
1731
- if (field === "webSearchSidecar"
1732
- && (section.model !== undefined || section.backend !== undefined || section.anthropicInstance !== undefined)) {
1733
- const stored = config.claudeCode?.webSearchSidecar;
1734
- // Validate against the SUBMITTED backend across the whole union, not
1735
- // just openai/anthropic (#2457). allowedBackends above already refused
1736
- // unknown literals; Array.includes does not narrow, hence the cast.
1737
- // null keeps its own meaning here — drop the override and inherit the
1738
- // global backend — which is deliberately NOT the sidecar-settings rule.
1739
- const submittedBackend = section.backend;
1740
- const effectiveBackend = typeof submittedBackend === "string"
1741
- && allowedBackends.includes(submittedBackend)
1742
- ? submittedBackend as WebSearchBackend
1743
- : submittedBackend === null
1744
- ? config.webSearchSidecar?.backend ?? "openai"
1745
- : stored?.backend ?? config.webSearchSidecar?.backend ?? "openai";
1746
- const effectiveModel = section.model === ""
1747
- ? config.webSearchSidecar?.model
1748
- : typeof section.model === "string"
1749
- ? section.model
1750
- : stored?.model ?? config.webSearchSidecar?.model;
1751
- const candidates = await webSearchCandidateRows({ ...config, webSearchSidecar: {
1752
- ...config.webSearchSidecar, ...sidecarSettingsAfterPatch(config.claudeCode?.webSearchSidecar, section),
1753
- } });
1754
- if (effectiveModel && webSearchModelIsRejected(effectiveBackend, effectiveModel, candidates)) {
1755
- return jsonResponse(webSearchModelRejection(
1756
- "webSearchSidecar.model",
1757
- effectiveBackend,
1758
- effectiveModel,
1759
- candidates,
1760
- ), 400);
1761
- }
1762
- }
1763
- }
1764
- const next = { ...(config.claudeCode ?? {}) };
1765
- for (const field of ["webSearchSidecar", "visionSidecar"] as const) {
1766
- const section = body[field];
1767
- if (section === undefined) continue;
1768
- if (section === null || Object.keys(section as Record<string, unknown>).length === 0) {
1769
- delete next[field];
1770
- continue;
1771
- }
1772
- // The per-field validation above guarantees vision only ever carries the two-member
1773
- // union; the cast is the loop's shared-shape compromise, not a wider write path.
1774
- const requested = section as { enabled?: boolean; backend?: "openai" | "anthropic" | "xai" | "gemini" | "exa" | null; model?: string; anthropicInstance?: AnthropicInstanceId | null };
1775
- const override = { ...next[field] } as NonNullable<OcxClaudeCodeConfig[typeof field]>;
1776
- if (requested.enabled !== undefined) override.enabled = requested.enabled;
1777
- if (requested.anthropicInstance === null) delete override.anthropicInstance;
1778
- else if (isAnthropicInstanceId(requested.anthropicInstance)) override.anthropicInstance = requested.anthropicInstance;
1779
- if (requested.backend === null) delete override.backend;
1780
- else if (requested.backend !== undefined) override.backend = requested.backend as never;
1781
- if (requested.model === "") delete override.model;
1782
- else if (requested.model !== undefined) override.model = requested.model;
1783
- // Indexed write across the field union collapses to an intersection; runtime
1784
- // validation above already guarantees the per-field shape.
1785
- if (Object.keys(override).length > 0) next[field] = override as never;
1786
- else delete next[field];
1787
- }
1788
- if (body.enabled !== undefined) {
1789
- if (typeof body.enabled !== "boolean") return jsonResponse({ error: "enabled must be a boolean" }, 400);
1790
- next.enabled = body.enabled;
1791
- }
1792
- if (body.authMode !== undefined) {
1793
- // Three-state intent: "proxy" and "subscription" are stored literally and stick
1794
- // forever; "auto" DELETES the key so the mode is resolved from detected Claude
1795
- // auth on every launch. The 260720 round-trip contract survives as a superset —
1796
- // storing "subscription" literally is also backward-safe, since older readers
1797
- // only ever recognised "proxy".
1798
- if (body.authMode !== "proxy" && body.authMode !== "subscription" && body.authMode !== "auto") {
1799
- return jsonResponse({ error: "authMode must be \"auto\", \"proxy\", or \"subscription\"" }, 400);
1800
- }
1801
- if (body.authMode === "auto") delete next.authMode;
1802
- else next.authMode = body.authMode;
1803
- }
1804
- if (body.systemEnv !== undefined) {
1805
- if (typeof body.systemEnv !== "boolean") return jsonResponse({ error: "systemEnv must be a boolean" }, 400);
1806
- next.systemEnv = body.systemEnv;
1807
- }
1808
- if (body.alwaysEnableEffort !== undefined) {
1809
- if (typeof body.alwaysEnableEffort !== "boolean") return jsonResponse({ error: "alwaysEnableEffort must be a boolean" }, 400);
1810
- if (body.alwaysEnableEffort) next.alwaysEnableEffort = true;
1811
- else delete next.alwaysEnableEffort;
1812
- }
1813
- if (body.maxContextTokens !== undefined) {
1814
- // CONFIG-ONLY back-compat (GUI control removed — superseded by auto-context):
1815
- // null clears; otherwise a positive integer (devlog 136 B6).
1816
- if (body.maxContextTokens === null) {
1817
- delete next.maxContextTokens;
1818
- } else if (typeof body.maxContextTokens !== "number" || !Number.isInteger(body.maxContextTokens) || body.maxContextTokens <= 0) {
1819
- return jsonResponse({ error: "maxContextTokens must be a positive integer or null" }, 400);
1820
- } else {
1821
- next.maxContextTokens = body.maxContextTokens;
1822
- }
1823
- }
1824
- if (body.autoContext !== undefined) {
1825
- // Default-on boolean (devlog 260712 020): true = drop the key, false = store.
1826
- if (typeof body.autoContext !== "boolean") return jsonResponse({ error: "autoContext must be a boolean" }, 400);
1827
- if (body.autoContext) delete next.autoContext;
1828
- else next.autoContext = false;
1829
- }
1830
- if (body.contextAccounting !== undefined) {
1831
- // Sparse like autoContext (devlog/_plan/261009_claude_1m_default/030): "1m" is the default
1832
- // and drops the key; "200k" is the only stored value.
1833
- if (body.contextAccounting !== "1m" && body.contextAccounting !== "200k") {
1834
- return jsonResponse({ error: "contextAccounting must be \"1m\" or \"200k\"" }, 400);
1835
- }
1836
- if (body.contextAccounting === "200k") next.contextAccounting = "200k";
1837
- else delete next.contextAccounting;
1838
- }
1839
- if (body.injectAgents !== undefined) {
1840
- // Default-on boolean (devlog 260712 070): true = drop the key, false = store.
1841
- if (typeof body.injectAgents !== "boolean") return jsonResponse({ error: "injectAgents must be a boolean" }, 400);
1842
- if (body.injectAgents) delete next.injectAgents;
1843
- else next.injectAgents = false;
1844
- }
1845
- if (body.autoCompactWindow !== undefined) {
1846
- // null resets to the 350k default; otherwise the binary-accepted range
1847
- // 100_000..1_000_000 (2.1.207 pSo/yDs — audit 021 #1).
1848
- if (body.autoCompactWindow === null) {
1849
- delete next.autoCompactWindow;
1850
- } else if (typeof body.autoCompactWindow !== "number" || !Number.isInteger(body.autoCompactWindow) || body.autoCompactWindow < 100_000 || body.autoCompactWindow > 1_000_000) {
1851
- return jsonResponse({ error: "autoCompactWindow must be an integer between 100000 and 1000000, or null" }, 400);
1852
- } else {
1853
- next.autoCompactWindow = body.autoCompactWindow;
1854
- }
1855
- }
1856
- if (body.blockedSkills !== undefined) {
1857
- // null resets to the default (["claude-api"]); an array (possibly empty = off)
1858
- // must contain non-empty strings (devlog 060).
1859
- if (body.blockedSkills === null) {
1860
- delete next.blockedSkills;
1861
- } else if (!Array.isArray(body.blockedSkills) || body.blockedSkills.some(s => typeof s !== "string" || s.trim() === "")) {
1862
- return jsonResponse({ error: "blockedSkills must be an array of non-empty strings, or null" }, 400);
1863
- } else {
1864
- next.blockedSkills = (body.blockedSkills as string[]).map(s => s.trim());
1865
- }
1866
- }
1867
- if (body.tierModels !== undefined) {
1868
- // Family defaults also serve third-party callers that request native tier aliases.
1869
- if (body.tierModels === null) {
1870
- delete next.tierModels;
1871
- } else if (!isPlainObject(body.tierModels)) {
1872
- return jsonResponse({ error: "tierModels must be an object with string values, or null" }, 400);
1873
- } else {
1874
- for (const [tier, value] of Object.entries(body.tierModels)) {
1875
- if (typeof value !== "string") return jsonResponse({ error: `tierModels.${tier} must be a string` }, 400);
1876
- }
1877
- const tierModels = body.tierModels as Record<string, string>;
1878
- const tiers: Record<string, string> = {};
1879
- for (const tier of ["opus", "sonnet", "haiku", "fable"] as const) {
1880
- const value = tierModels[tier];
1881
- if (value !== undefined && value.trim() !== "") tiers[tier] = value.trim();
1882
- }
1883
- if (Object.keys(tiers).length > 0) next.tierModels = tiers;
1884
- else delete next.tierModels;
1885
- }
1886
- }
1887
- let nextFastMode = config.fastMode;
1888
- if (body.fastMode !== undefined) {
1889
- if (body.fastMode !== true && body.fastMode !== false && body.fastMode !== null) {
1890
- return jsonResponse({ error: "fastMode must be true, false, or null" }, 400);
1891
- }
1892
- nextFastMode = body.fastMode === null ? undefined : body.fastMode;
1893
- }
1894
- for (const field of ["model", "smallFastModel", "classifierModel"] as const) {
1895
- const value = body[field];
1896
- if (value === undefined) continue;
1897
- if (typeof value !== "string") return jsonResponse({ error: `${field} must be a string` }, 400);
1898
- if (value.trim() === "") delete next[field];
1899
- else next[field] = value.trim();
1900
- }
1901
- if (body.classifierFallbacks !== undefined) {
1902
- if (body.classifierFallbacks === null) {
1903
- delete next.classifierFallbacks;
1904
- } else {
1905
- if (!Array.isArray(body.classifierFallbacks)) {
1906
- return jsonResponse({ error: "classifierFallbacks must be an array of strings, or null" }, 400);
1907
- }
1908
- const list: string[] = [];
1909
- for (const entry of body.classifierFallbacks) {
1910
- if (typeof entry !== "string" || entry.trim() === "") {
1911
- return jsonResponse({ error: "classifierFallbacks entries must be non-empty strings" }, 400);
1738
+ const checked = prepareClaudeCodePatch(config, body);
1739
+ if (checked instanceof Response) return checked;
1740
+ const evidenceState = JSON.stringify(config);
1741
+ const visionPatch = body.visionSidecar;
1742
+ const webPatch = body.webSearchSidecar;
1743
+ const visionEvidence = isPlainObject(visionPatch) && typeof visionPatch.model === "string" && visionPatch.model !== ""
1744
+ ? await visionCandidateRows({ ...config, visionSidecar: { ...config.visionSidecar, ...sidecarSettingsAfterPatch(config.claudeCode?.visionSidecar, visionPatch) } }) : undefined;
1745
+ const webEvidence = isPlainObject(webPatch) && (webPatch.model !== undefined || webPatch.backend !== undefined || webPatch.anthropicInstance !== undefined)
1746
+ ? await webSearchCandidateRows({ ...config, webSearchSidecar: { ...config.webSearchSidecar, ...sidecarSettingsAfterPatch(config.claudeCode?.webSearchSidecar, webPatch) } }) : undefined;
1747
+ const { commitClaudeCodeBlock } = await import("../../claude/claude-code-block");
1748
+ const { saveConfigPreservingClaudeCode: save } = await import("../../config");
1749
+ const refusal = await settleConfigRoot(configRoot(), () => {
1750
+ if ((visionEvidence || webEvidence) && JSON.stringify(config) !== evidenceState) return jsonResponse({ error: "Sidecar validation state changed during discovery", code: "config_changed" }, 409);
1751
+ const instanceError = anthropicSidecarPatchError(config, body, true);
1752
+ if (instanceError) return jsonResponse({ error: instanceError }, 400);
1753
+ for (const field of ["webSearchSidecar", "visionSidecar"] as const) {
1754
+ const section = body[field] as Record<string, unknown> | null | undefined;
1755
+ if (section === undefined || section === null) continue;
1756
+ // Vision override only: reject a model we can prove is blind. Unknown ids stay
1757
+ // allowed. Shares one policy module with /api/sidecar-settings so the two
1758
+ // gates cannot drift.
1759
+ if (field === "visionSidecar" && typeof section.model === "string" && section.model !== "") {
1760
+ const requested = section.model;
1761
+ const candidates = visionEvidence!;
1762
+ const hint = section.backend === "anthropic" || section.backend === "openai"
1763
+ || section.backend === "routed"
1764
+ ? section.backend
1765
+ : config.claudeCode?.visionSidecar?.backend;
1766
+ // Same coherence rule as /api/sidecar-settings (roadmap 170 r2).
1767
+ const effectiveBackend = hint ?? "openai";
1768
+ const namespaced = requested.includes("/");
1769
+ if (namespaced && effectiveBackend !== "routed") {
1770
+ return jsonResponse({ error: `visionSidecar.model "${requested}" is provider-namespaced; it requires backend "routed"` }, 400);
1771
+ }
1772
+ if (!namespaced && effectiveBackend === "routed") {
1773
+ return jsonResponse({ error: `visionSidecar.backend "routed" requires a provider-namespaced model ("provider/model"); got "${requested}"` }, 400);
1774
+ }
1775
+ if (visionDescriberIsProvablyBlind(config, requested, candidates, hint)) {
1776
+ return jsonResponse(visionDescriberRejection("visionSidecar.model", requested, config, candidates), 400);
1912
1777
  }
1913
- list.push(entry.trim());
1914
- }
1915
- if (list.length > 0) next.classifierFallbacks = list;
1916
- else delete next.classifierFallbacks;
1917
- }
1918
- }
1919
- if (body.modelMap !== undefined) {
1920
- if (body.modelMap === null) {
1921
- delete next.modelMap;
1922
- } else {
1923
- if (!isPlainObject(body.modelMap)) {
1924
- return jsonResponse({ error: "modelMap must be an object of string->string, or null" }, 400);
1925
1778
  }
1926
- const map: Record<string, string> = {};
1927
- for (const [k, v] of Object.entries(body.modelMap)) {
1928
- if (typeof v !== "string" || k.trim() === "" || v.trim() === "") {
1929
- return jsonResponse({ error: "modelMap entries must be non-empty strings" }, 400);
1779
+ // Web-search override: membership gate (#2188). The executor set is closed,
1780
+ // so an id outside (runnable candidates ∪ auth slots) can never run. Same
1781
+ // module as /api/sidecar-settings — a gate on one route and a stale copy on
1782
+ // the other is no gate at all.
1783
+ if (field === "webSearchSidecar"
1784
+ && (section.model !== undefined || section.backend !== undefined || section.anthropicInstance !== undefined)) {
1785
+ const stored = config.claudeCode?.webSearchSidecar;
1786
+ // Validate against the SUBMITTED backend across the whole union, not
1787
+ // just openai/anthropic (#2457). allowedBackends above already refused
1788
+ // unknown literals; Array.includes does not narrow, hence the cast.
1789
+ // null keeps its own meaning here — drop the override and inherit the
1790
+ // global backend — which is deliberately NOT the sidecar-settings rule.
1791
+ const submittedBackend = section.backend;
1792
+ const effectiveBackend = typeof submittedBackend === "string"
1793
+ ? submittedBackend as WebSearchBackend
1794
+ : submittedBackend === null
1795
+ ? config.webSearchSidecar?.backend ?? "openai"
1796
+ : stored?.backend ?? config.webSearchSidecar?.backend ?? "openai";
1797
+ const effectiveModel = section.model === ""
1798
+ ? config.webSearchSidecar?.model
1799
+ : typeof section.model === "string"
1800
+ ? section.model
1801
+ : stored?.model ?? config.webSearchSidecar?.model;
1802
+ const candidates = webEvidence!;
1803
+ if (effectiveModel && webSearchModelIsRejected(effectiveBackend, effectiveModel, candidates)) {
1804
+ return jsonResponse(webSearchModelRejection(
1805
+ "webSearchSidecar.model",
1806
+ effectiveBackend,
1807
+ effectiveModel,
1808
+ candidates,
1809
+ ), 400);
1930
1810
  }
1931
- map[k.trim()] = v.trim();
1932
1811
  }
1933
- if (Object.keys(map).length > 0) next.modelMap = map;
1934
- else delete next.modelMap;
1935
1812
  }
1936
- }
1937
- if (body.fastMode !== undefined) config.fastMode = nextFastMode;
1938
- // Stamps the auth-mode migration sentinel on EVERY persist of this block. Without it,
1939
- // choosing Auto (which DELETES authMode) or merely toggling Claude on (App.tsx PUTs
1940
- // `{enabled}` alone and creates the block) would be converted into a sticky manual
1941
- // subscription by the next startServer, with no way back.
1942
- const { commitClaudeCodeBlock } = await import("../../claude/claude-code-block");
1943
- commitClaudeCodeBlock(config, next);
1944
- const { saveConfigPreservingClaudeCode: save } = await import("../../config");
1945
- save(config);
1813
+ const prepared = prepareClaudeCodePatch(config, body);
1814
+ if (prepared instanceof Response) return prepared;
1815
+ const { next, nextFastMode } = prepared;
1816
+ // Stamps the auth-mode migration sentinel on EVERY persist of this block. Without it,
1817
+ // choosing Auto (which DELETES authMode) or merely toggling Claude on (App.tsx PUTs
1818
+ // `{enabled}` alone and creates the block) would be converted into a sticky manual
1819
+ // subscription by the next startServer, with no way back.
1820
+
1821
+ if (body.fastMode !== undefined) config.fastMode = nextFastMode;
1822
+ commitClaudeCodeBlock(config, next);
1823
+ save(config);
1824
+ return null;
1825
+ });
1826
+ if (refusal) return refusal;
1946
1827
  const warnings: string[] = [];
1947
1828
  // authMode changes must reconcile the injected system env too: switching back to
1948
1829
  // Subscription has to remove the opencodex-owned dummy ANTHROPIC_AUTH_TOKEN
@@ -1961,7 +1842,7 @@ export async function handleAgentSettingsRoutes(ctx: ManagementContext): Promise
1961
1842
  // Keep the file-backed live registry symmetric: OFF prunes immediately, while
1962
1843
  // ON and config changes restore definitions without requiring a restart.
1963
1844
  await syncClaudeAgentDefsBestEffort();
1964
- return jsonResponse({ ok: true, enabled: next.enabled !== false, warnings });
1845
+ return jsonResponse({ ok: true, enabled: config.claudeCode?.enabled !== false, warnings });
1965
1846
  }
1966
1847
  return null;
1967
1848
  }