@bitkyc08/opencodex 2.93.0-preview.20261027 → 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-DxToX1rV.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-CJZoq-uF.js +0 -58
  433. package/gui/dist/assets/Tray-BWQPcgZn.js +0 -1
  434. package/gui/dist/assets/index-DRe8Hhfz.css +0 -1
  435. package/gui/dist/assets/index-Xfct8owH.js +0 -94
@@ -0,0 +1,281 @@
1
+ import { watch, lstatSync, readdirSync, type FSWatcher } from "node:fs";
2
+ import { dirname, join, resolve, parse } from "node:path";
3
+ import { getConfigDir } from "../config/paths";
4
+ import { readUnderCredentialPublicationFence } from "./publication-fence";
5
+ import { getCodexHome } from "../codex/paths";
6
+ import { readBounded, nativeProfileHomeId, countLocalNativeProfileSlots } from "../codex/native-profile-store";
7
+ import { countLocalOAuthCredentialSlots } from "../oauth/store";
8
+ import { inspectLocalCodexCredentialSlots } from "../codex/account-store";
9
+ import {
10
+ claimCredentialObservation, generationToken, observationAlive, readCredentialGeneration,
11
+ registerCredentialObserver, updateCredentialObservation,
12
+ } from "./generation";
13
+
14
+ /**
15
+ * This installation's stored provider credentials, counted passively: OAuth accounts (with the
16
+ * pre-multiauth backup), provider API-key slots including disabled and private references, Codex
17
+ * pool records, native Codex auth and inactive native profiles. Link, management and incoming API
18
+ * keys are not provider credentials and never count. Any unreadable or unfamiliar source throws,
19
+ * so a caller omits the attestation instead of reporting zero.
20
+ */
21
+ export type LocalCredentialSnapshot = { count: number; generation: string };
22
+ const RECONCILE_RETRIES = 20;
23
+ const RECONCILE_RETRY_MS = 100;
24
+ const FENCED_READ_ATTEMPTS = 40;
25
+ const FENCED_READ_RETRY_MS = 50;
26
+ const decoder = new TextDecoder("utf-8", { fatal: true });
27
+ const MAX_BYTES = 4 * 1024 * 1024;
28
+ function object(value: unknown): Record<string, unknown> {
29
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid credential object");
30
+ return value as Record<string, unknown>;
31
+ }
32
+ function missing(error: unknown): boolean { return (error as NodeJS.ErrnoException)?.code === "ENOENT"; }
33
+ function exists(path: string): boolean {
34
+ try { lstatSync(path); return true; } catch (error) { if (missing(error)) return false; throw error; }
35
+ }
36
+ function assertParents(path: string): void {
37
+ for (let p = dirname(path); ; p = dirname(p)) {
38
+ try { const s = lstatSync(p); if (!s.isDirectory() || s.isSymbolicLink()) throw new Error("Unsafe credential parent"); }
39
+ catch (error) { if (!missing(error)) throw error; }
40
+ if (p === parse(p).root) break;
41
+ }
42
+ }
43
+ export function scanLocalCredentials(accounts: readonly string[] = []): { count: number; vector: string; targets: string[] } {
44
+ const home = getConfigDir();
45
+ const codex = getCodexHome();
46
+ const vector: string[] = [];
47
+ const targets = new Set<string>();
48
+ function bytes(path: string, limit = MAX_BYTES): Buffer | null {
49
+ path = resolve(path);
50
+ targets.add(path);
51
+ assertParents(path);
52
+ try {
53
+ const before = lstatSync(path, { bigint: true });
54
+ if (!before.isFile() || before.isSymbolicLink()) throw new Error("Unsafe credential file");
55
+ const raw = readBounded(path, limit);
56
+ const after = lstatSync(path, { bigint: true });
57
+ const identity = (s: typeof before) => `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`;
58
+ if (identity(before) !== identity(after)) throw new Error("Credential changed while reading");
59
+ vector.push(`${path}:${identity(after)}`);
60
+ return raw;
61
+ } catch (error) {
62
+ if (!missing(error)) throw error;
63
+ vector.push(`${path}:absent`);
64
+ return null;
65
+ }
66
+ }
67
+ function json(path: string): Record<string, unknown> | null {
68
+ const raw = bytes(path);
69
+ return raw === null ? null : object(JSON.parse(decoder.decode(raw)));
70
+ }
71
+ function emptyDirectory(path: string, child?: string): void {
72
+ targets.add(path);
73
+ assertParents(path);
74
+ if (!exists(path)) { vector.push(`${path}:absent`); return; }
75
+ const s = lstatSync(path, { bigint: true });
76
+ if (!s.isDirectory() || s.isSymbolicLink()) throw new Error("Unsafe credential directory");
77
+ const names = readdirSync(path);
78
+ vector.push(`${path}:${s.dev}:${s.ino}:${JSON.stringify(names.sort())}`);
79
+ if (child !== undefined) {
80
+ if (names.some(name => name !== child)) throw new Error("Unknown staging home");
81
+ emptyDirectory(join(path, child));
82
+ } else if (names.length) throw new Error("Pending credential directory");
83
+ }
84
+ for (const [root, prefixes] of [
85
+ [home, ["auth.json.ocx.", "codex-accounts.json.ocx.", "config.json.ocx."]],
86
+ [codex, ["auth.json.ocx."]],
87
+ ] as const) {
88
+ targets.add(join(root, "auth.json"));
89
+ if (exists(root) && readdirSync(root).some(name => prefixes.some(prefix => name.startsWith(prefix)))) {
90
+ throw new Error("Retained credential write residue");
91
+ }
92
+ }
93
+ let count = countLocalOAuthCredentialSlots(json(join(home, "auth.json")))
94
+ + countLocalOAuthCredentialSlots(json(join(home, "auth.json.pre-multiauth")));
95
+ const configuredAccounts = new Set<string>();
96
+ const config = json(join(home, "config.json"));
97
+ if (config !== null) {
98
+ const providers = object(config.providers ?? {});
99
+ for (const row of Object.values(providers)) {
100
+ const provider = object(row);
101
+ const pool = provider.apiKeyPool ?? [];
102
+ if (!Array.isArray(pool)) throw new Error("Invalid provider pool");
103
+ const keys: string[] = [];
104
+ const ids = new Set<string>();
105
+ for (const value of pool) {
106
+ const entry = object(value);
107
+ if (typeof entry.id !== "string" || ids.has(entry.id) || typeof entry.key !== "string" || !entry.key) {
108
+ throw new Error("Invalid provider key slot");
109
+ }
110
+ ids.add(entry.id);
111
+ keys.push(entry.key);
112
+ }
113
+ if (provider.apiKey !== undefined) {
114
+ if (typeof provider.apiKey !== "string") throw new Error("Invalid provider key");
115
+ if (provider.apiKey && !keys.includes(provider.apiKey)) keys.push(provider.apiKey);
116
+ }
117
+ count += keys.length;
118
+ for (const key of keys) {
119
+ for (const prefix of ["keychain:", "gcp-sa:"]) if (key.startsWith(prefix)) {
120
+ const account = key.slice(prefix.length);
121
+ if (!account.trim()) throw new Error("Invalid private key reference");
122
+ configuredAccounts.add(account);
123
+ }
124
+ }
125
+ }
126
+ }
127
+ count += accounts.filter(a => !configuredAccounts.has(a)).length;
128
+ const pool = inspectLocalCodexCredentialSlots(json(join(home, "codex-accounts.json")));
129
+ count += pool.count;
130
+ for (const path of pool.sourcePaths) if (json(path) === null) throw new Error("Missing source-backed credential");
131
+
132
+ const tomlBytes = bytes(join(codex, "config.toml"), 1024 * 1024);
133
+ const toml = tomlBytes === null ? {} : object(Bun.TOML.parse(decoder.decode(tomlBytes)));
134
+ if (toml.cli_auth_credentials_store !== undefined && toml.cli_auth_credentials_store !== "file") {
135
+ throw new Error("Native credential store is not file-backed");
136
+ }
137
+ for (const profile of Object.values(object(toml.profiles ?? {}))) {
138
+ const mode = object(profile).cli_auth_credentials_store;
139
+ if (mode !== undefined && mode !== "file") throw new Error("Profile credential store is not file-backed");
140
+ }
141
+ const auth = json(join(codex, "auth.json"));
142
+ let main = 0;
143
+ if (auth !== null) {
144
+ if (typeof auth.OPENAI_API_KEY === "string" && auth.OPENAI_API_KEY) main = 1;
145
+ if (auth.tokens !== undefined && auth.tokens !== null) {
146
+ const tokens = object(auth.tokens);
147
+ if (![tokens.access_token, tokens.refresh_token, tokens.id_token].some(v => typeof v === "string" && v)) {
148
+ throw new Error("Invalid native token envelope");
149
+ }
150
+ main = 1;
151
+ }
152
+ if (!main) throw new Error("Unsupported native auth envelope");
153
+ }
154
+ const shared = join(codex, ".opencodex-native-main-profiles");
155
+ const homeId = nativeProfileHomeId(codex);
156
+ emptyDirectory(join(home, "native-main-profiles"));
157
+ emptyDirectory(join(home, "native-main-profile-staging"), homeId);
158
+ for (const suffix of ["journal", "recovery-block"]) {
159
+ if (bytes(join(shared, `${homeId}.${suffix}.json`)) !== null) throw new Error("Pending native profile transaction");
160
+ }
161
+ const stages = json(join(shared, `${homeId}.stages.json`));
162
+ if (stages !== null && (stages.version !== 1 || stages.homeId !== homeId
163
+ || !Number.isSafeInteger(stages.revision) || Number(stages.revision) < 0
164
+ || !Array.isArray(stages.stages) || stages.stages.length !== 0)) throw new Error("Pending native stage registry");
165
+ const vault = json(join(shared, `${homeId}.vault.json`));
166
+ const profiles = countLocalNativeProfileSlots(vault, homeId);
167
+ if (profiles.active && !main) throw new Error("Active native profile has no readable auth");
168
+ count += main + profiles.inactive;
169
+ if (exists(shared)) {
170
+ if (!lstatSync(shared).isDirectory() || lstatSync(shared).isSymbolicLink()) throw new Error("Unsafe native vault");
171
+ const expected = new Set([`${homeId}.vault.json`, `${homeId}.stages.json`]);
172
+ if (readdirSync(shared).some(name => !expected.has(name))) throw new Error("Unknown native profile metadata");
173
+ }
174
+ if (!Number.isSafeInteger(count) || count < 0) throw new Error("Invalid credential count");
175
+ return { count, vector: JSON.stringify(vector.sort()), targets: [...targets].sort() };
176
+ }
177
+ function snapshotOnce(home: string): LocalCredentialSnapshot | undefined {
178
+ try {
179
+ const before = readCredentialGeneration(home);
180
+ if (!before?.coverage || before.pending.length || !observationAlive(before, home)) return undefined;
181
+ const snapshot = scanLocalCredentials(before.keyAccounts);
182
+ const after = readCredentialGeneration(home);
183
+ if (!after?.coverage || after.pending.length || !observationAlive(after, home)
184
+ || generationToken(before) !== generationToken(after)
185
+ || before.coverage.owner !== after.coverage.owner
186
+ || before.coverage.vector !== snapshot.vector || after.coverage.vector !== snapshot.vector) return undefined;
187
+ return { count: snapshot.count, generation: generationToken(after) };
188
+ } catch { return undefined; }
189
+ }
190
+
191
+ /**
192
+ * The attestation for "ocx status --json". Each attempt holds the publication fence shared across
193
+ * both generation reads and the scan, so no instrumented write can land in between; while a
194
+ * publication holds it, retry briefly, then omit rather than attest a snapshot that could race.
195
+ */
196
+ export async function collectLocalCredentials(): Promise<LocalCredentialSnapshot | undefined> {
197
+ const home = getConfigDir();
198
+ for (let attempt = 0; attempt < FENCED_READ_ATTEMPTS; attempt += 1) {
199
+ const read = readUnderCredentialPublicationFence(home, () => snapshotOnce(home));
200
+ if (read.kind === "read") return read.value;
201
+ if (read.kind === "unavailable") return undefined;
202
+ await new Promise(resolve => setTimeout(resolve, FENCED_READ_RETRY_MS));
203
+ }
204
+ return undefined;
205
+ }
206
+ export function startLocalCredentialObservation(): { stop(): void; reconcile(): void } {
207
+ const home = getConfigDir();
208
+ let watchers: FSWatcher[] = [];
209
+ let owner: string | undefined;
210
+ let releaseLease = () => {};
211
+ let failed = false;
212
+ let unregister = () => {};
213
+ const fail = () => {
214
+ if (failed) return;
215
+ failed = true;
216
+ if (retry) clearTimeout(retry);
217
+ unregister();
218
+ releaseLease();
219
+ for (const watcher of watchers) watcher.close();
220
+ if (owner) {
221
+ try { updateCredentialObservation(home, owner, null); }
222
+ catch { /* The kernel lease is already closed; a busy metadata writer cannot keep evidence alive. */ }
223
+ }
224
+ };
225
+ const install = (targets: string[]) => {
226
+ const watched = new Map<string, Set<string>>();
227
+ for (const target of targets) {
228
+ for (let path = target; dirname(path) !== path; path = dirname(path)) {
229
+ const parent = dirname(path);
230
+ if (!exists(parent)) continue;
231
+ assertParents(path);
232
+ const names = watched.get(parent) ?? new Set<string>();
233
+ names.add(path.slice(parent.length + (parent.endsWith("/") || parent.endsWith("\\") ? 0 : 1)));
234
+ watched.set(parent, names);
235
+ }
236
+ }
237
+ const next: FSWatcher[] = [];
238
+ try {
239
+ for (const [parent, names] of watched) {
240
+ const watcher = watch(parent, { persistent: false }, (_event, name) => {
241
+ if (name === null) { fail(); return; }
242
+ if (names.has(String(name)) || /^(auth|config|codex-accounts)\.json\.ocx\./.test(String(name))) reconcile();
243
+ });
244
+ watcher.on("error", fail);
245
+ next.push(watcher);
246
+ }
247
+ } catch (error) { for (const watcher of next) watcher.close(); throw error; }
248
+ const previous = watchers;
249
+ watchers = next;
250
+ for (const watcher of previous) watcher.close();
251
+ };
252
+ const observe = (keys: readonly string[]) => {
253
+ const before = scanLocalCredentials(keys);
254
+ install(before.targets);
255
+ const after = scanLocalCredentials(keys);
256
+ if (before.vector !== after.vector || JSON.stringify(before.targets) !== JSON.stringify(after.targets)) {
257
+ throw new Error("Credential coverage changed during observer installation");
258
+ }
259
+ if (failed) throw new Error("Credential observation lost");
260
+ return after.vector;
261
+ };
262
+ let retries = 0;
263
+ let retry: ReturnType<typeof setTimeout> | undefined;
264
+ const reconcile = () => {
265
+ if (failed || !owner) return;
266
+ try { updateCredentialObservation(home, owner, observe); retries = 0; }
267
+ catch {
268
+ // A peer holding the config lock only delays this; the stale vector withholds attestation meanwhile.
269
+ if (++retries > RECONCILE_RETRIES) { fail(); return; }
270
+ retry ??= setTimeout(() => { retry = undefined; reconcile(); }, RECONCILE_RETRY_MS);
271
+ (retry as { unref?: () => void }).unref?.();
272
+ }
273
+ };
274
+ try {
275
+ const claim = claimCredentialObservation(home, observe);
276
+ owner = claim.owner;
277
+ releaseLease = claim.close;
278
+ unregister = registerCredentialObserver(home, reconcile);
279
+ return { stop: fail, reconcile };
280
+ } catch (error) { fail(); throw error; }
281
+ }
@@ -0,0 +1,83 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { chmodSync, lstatSync, mkdirSync, readdirSync, unlinkSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { hardenSecretDir, windowsSecretAclApplies } from "../lib/windows-secret-acl";
5
+ import { assertNotRealHomeUnderTest } from "../lib/test-home-guard";
6
+
7
+ /**
8
+ * A per-observer SQLite file held in an exclusive transaction for the observer's lifetime. It is
9
+ * an OS lock that process death releases, so status can tell a live observer from surviving
10
+ * metadata without trusting a PID. Status opens it read-only and only an exact SQLITE_BUSY on the
11
+ * same file identity counts as alive.
12
+ */
13
+ const UUID = /^[0-9a-f-]{36}$/;
14
+ function pathFor(home: string, owner: string): string {
15
+ if (!UUID.test(owner)) throw new Error("Invalid credential observer owner");
16
+ return join(home, "local-credential-observers", `${owner}.sqlite`);
17
+ }
18
+ function safeDirectory(path: string): void {
19
+ const stat = lstatSync(path);
20
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Unsafe credential observer directory");
21
+ }
22
+ export function acquireCredentialObservationLease(home: string, owner: string): { close(): void } {
23
+ assertNotRealHomeUnderTest(home);
24
+ safeDirectory(home);
25
+ const dir = join(home, "local-credential-observers");
26
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
27
+ safeDirectory(dir);
28
+ if (windowsSecretAclApplies()) hardenSecretDir(dir, { required: true });
29
+ else chmodSync(dir, 0o700);
30
+ const path = pathFor(home, owner);
31
+ try { lstatSync(path); throw new Error("Credential observer lease already exists"); }
32
+ catch (error) { if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") throw error; }
33
+ const db = new Database(path, { create: true });
34
+ let held = false;
35
+ try {
36
+ if (process.platform !== "win32") chmodSync(path, 0o600);
37
+ db.exec("PRAGMA busy_timeout=0; PRAGMA journal_mode=DELETE; CREATE TABLE liveness (id INTEGER PRIMARY KEY)");
38
+ // No writes after BEGIN: process death releases the lock without a hot rollback journal.
39
+ db.exec("BEGIN EXCLUSIVE");
40
+ held = true;
41
+ return { close() {
42
+ if (!held) return;
43
+ held = false;
44
+ try { db.exec("ROLLBACK"); }
45
+ finally {
46
+ db.close();
47
+ try { unlinkSync(path); } catch { /* An unlocked residue never proves observer liveness. */ }
48
+ }
49
+ } };
50
+ } catch (error) { db.close(); throw error; }
51
+ }
52
+ export function credentialObservationLeaseAlive(home: string, owner: string): boolean {
53
+ let db: Database | undefined;
54
+ try {
55
+ safeDirectory(home);
56
+ safeDirectory(join(home, "local-credential-observers"));
57
+ const path = pathFor(home, owner);
58
+ const before = lstatSync(path, { bigint: true });
59
+ if (!before.isFile() || before.isSymbolicLink() || before.size > 1024n * 1024n) return false;
60
+ try {
61
+ db = new Database(path, { readonly: true });
62
+ db.exec("PRAGMA busy_timeout=0");
63
+ db.query("SELECT id FROM liveness LIMIT 1").get();
64
+ return false;
65
+ } catch (error) {
66
+ const after = lstatSync(path, { bigint: true });
67
+ return (error as { code?: string })?.code === "SQLITE_BUSY"
68
+ && before.dev === after.dev && before.ino === after.ino && after.isFile() && !after.isSymbolicLink();
69
+ }
70
+ } catch { return false; }
71
+ finally { db?.close(); }
72
+ }
73
+
74
+ /** Removes the leases of observers that died without closing them; callers hold the config lock. */
75
+ export function sweepDeadCredentialObservationLeases(home: string, keep: string): void {
76
+ let names: string[];
77
+ try { names = readdirSync(join(home, "local-credential-observers")); } catch { return; }
78
+ for (const name of names) {
79
+ const owner = name.endsWith(".sqlite") ? name.slice(0, -".sqlite".length) : "";
80
+ if (!UUID.test(owner) || owner === keep || credentialObservationLeaseAlive(home, owner)) continue;
81
+ try { unlinkSync(pathFor(home, owner)); } catch { /* a lease that cannot be removed proves nothing either */ }
82
+ }
83
+ }
@@ -0,0 +1,81 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { chmodSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { recordOwnedConfigPath } from "../lib/config-ownership";
5
+ import { assertNotRealHomeUnderTest } from "../lib/test-home-guard";
6
+
7
+ /**
8
+ * The credential-publication fence: the OS lock of one small SQLite file, separate from the config
9
+ * mutation lock. Instrumented credential writers hold it EXCLUSIVE across their ticket, the
10
+ * credential write and the ticket's close; `ocx status` holds it SHARED across its generation
11
+ * reads and source scan, so a snapshot can never interleave with a publication. Nothing is written
12
+ * inside the transaction, so process death releases the lock without a hot journal. Holding is
13
+ * reentrant per process and per home, which also covers an async publication that awaits inside it.
14
+ */
15
+ export const CREDENTIAL_FENCE_FILENAME = "local-credential-publication.sqlite";
16
+ /** How long a writer waits for readers and other writers; a reader never waits inside SQLite. */
17
+ export const CREDENTIAL_FENCE_WRITER_WAIT_MS = 10_000;
18
+
19
+ const held = new Map<string, { db: Database; holders: number }>();
20
+
21
+ function acquire(home: string, waitMs: number): () => void {
22
+ const current = held.get(home);
23
+ if (current) current.holders += 1;
24
+ else {
25
+ assertNotRealHomeUnderTest(home);
26
+ const path = join(home, CREDENTIAL_FENCE_FILENAME);
27
+ recordOwnedConfigPath(home, path);
28
+ const db = new Database(path, { create: true });
29
+ try {
30
+ if (process.platform !== "win32") chmodSync(path, 0o600);
31
+ db.exec(`PRAGMA busy_timeout=${Math.max(0, Math.floor(waitMs))}; PRAGMA journal_mode=DELETE; CREATE TABLE IF NOT EXISTS fence (id INTEGER PRIMARY KEY)`);
32
+ db.exec("BEGIN EXCLUSIVE");
33
+ } catch (error) { db.close(); throw error; }
34
+ held.set(home, { db, holders: 1 });
35
+ }
36
+ let released = false;
37
+ return () => {
38
+ if (released) return;
39
+ released = true;
40
+ const entry = held.get(home);
41
+ if (!entry || --entry.holders > 0) return;
42
+ held.delete(home);
43
+ try { entry.db.exec("ROLLBACK"); } catch { /* close below releases the lock */ }
44
+ entry.db.close();
45
+ };
46
+ }
47
+
48
+ export function withCredentialPublicationFence<T>(home: string, fn: () => T, waitMs = CREDENTIAL_FENCE_WRITER_WAIT_MS): T {
49
+ const release = acquire(home, waitMs);
50
+ try { return fn(); } finally { release(); }
51
+ }
52
+
53
+ export async function withCredentialPublicationFenceAsync<T>(home: string, fn: () => Promise<T>): Promise<T> {
54
+ const release = acquire(home, CREDENTIAL_FENCE_WRITER_WAIT_MS);
55
+ try { return await fn(); } finally { release(); }
56
+ }
57
+
58
+ export type FencedRead<T> = { kind: "read"; value: T } | { kind: "busy" } | { kind: "unavailable" };
59
+
60
+ /** One consistent read with no publication in flight; never creates the fence or waits. */
61
+ export function readUnderCredentialPublicationFence<T>(home: string, fn: () => T): FencedRead<T> {
62
+ if (held.has(home)) return { kind: "busy" };
63
+ let db: Database;
64
+ try { db = new Database(join(home, CREDENTIAL_FENCE_FILENAME), { readonly: true }); }
65
+ catch { return { kind: "unavailable" }; }
66
+ let open = false;
67
+ try {
68
+ db.exec("PRAGMA busy_timeout=0");
69
+ db.exec("BEGIN");
70
+ open = true;
71
+ try { db.query("SELECT count(*) FROM sqlite_master").get(); }
72
+ catch (error) {
73
+ return String((error as { code?: unknown })?.code ?? "").startsWith("SQLITE_BUSY") ? { kind: "busy" } : { kind: "unavailable" };
74
+ }
75
+ return { kind: "read", value: fn() };
76
+ } catch { return { kind: "unavailable" }; }
77
+ finally {
78
+ if (open) { try { db.exec("COMMIT"); } catch { /* close below releases the shared lock */ } }
79
+ db.close();
80
+ }
81
+ }
@@ -0,0 +1,36 @@
1
+ import { join } from "node:path";
2
+ import { readBoundedRegularFileSync } from "../lib/bounded-file-read";
3
+
4
+ const OS_STORE_PREFIXES = ["keychain:", "gcp-sa:"] as const;
5
+ const decoder = new TextDecoder("utf-8", { fatal: true });
6
+
7
+ /**
8
+ * The OS credential-store accounts a config document references: `keychain:<account>` API keys and
9
+ * `gcp-sa:<account>` service-account JSON, as the active key or a pool entry. These accounts are
10
+ * registered in local-credentials.json before a reference can leave the config, so a secret whose
11
+ * deletion fails or never happens keeps counting after its config slot is gone.
12
+ */
13
+ export function osStoreAccounts(config: unknown): string[] {
14
+ const accounts = new Set<string>();
15
+ const providers = config && typeof config === "object" ? (config as { providers?: unknown }).providers : undefined;
16
+ if (!providers || typeof providers !== "object") return [];
17
+ for (const row of Object.values(providers)) {
18
+ if (!row || typeof row !== "object") continue;
19
+ const provider = row as { apiKey?: unknown; apiKeyPool?: unknown };
20
+ const pool = Array.isArray(provider.apiKeyPool) ? provider.apiKeyPool : [];
21
+ for (const key of [provider.apiKey, ...pool.map(entry => entry && typeof entry === "object" ? (entry as { key?: unknown }).key : undefined)]) {
22
+ if (typeof key !== "string") continue;
23
+ for (const prefix of OS_STORE_PREFIXES) {
24
+ const account = key.startsWith(prefix) ? key.slice(prefix.length) : "";
25
+ if (account.trim() && account.length <= 1024) accounts.add(account);
26
+ }
27
+ }
28
+ }
29
+ return [...accounts];
30
+ }
31
+
32
+ /** The references in this home's config.json; an absent or unreadable file names none. */
33
+ export function configuredOsStoreAccounts(home: string): string[] {
34
+ try { return osStoreAccounts(JSON.parse(decoder.decode(readBoundedRegularFileSync(join(home, "config.json"), 4 * 1024 * 1024)))); }
35
+ catch { return []; }
36
+ }
@@ -0,0 +1,28 @@
1
+ import { startLocalCredentialObservation } from "./inventory";
2
+
3
+ /**
4
+ * The one way a runtime owns the local-credential observer. `ocx status` attests only while the
5
+ * runtime holding the observer's OS lease lives, so each runtime stops it before it stops serving:
6
+ * a replacement process can then claim its own. A failure leaves the attestation omitted.
7
+ */
8
+ export function observeLocalCredentials(): { stop(): void } {
9
+ try { return startLocalCredentialObservation(); }
10
+ catch { return { stop() {} }; }
11
+ }
12
+
13
+ /** Starts the observer before a server, and stops it with that server or its failed start. */
14
+ export function withLocalCredentialObservation<S extends { stop(closeActiveConnections?: boolean): Promise<void> }>(start: () => S): S {
15
+ const observation = observeLocalCredentials();
16
+ let server: S;
17
+ try { server = start(); }
18
+ catch (error) { observation.stop(); throw error; }
19
+ const stop = server.stop.bind(server);
20
+ Object.defineProperty(server, "stop", {
21
+ configurable: true,
22
+ value: async (closeActiveConnections?: boolean): Promise<void> => {
23
+ observation.stop();
24
+ await stop(closeActiveConnections);
25
+ },
26
+ });
27
+ return server;
28
+ }
@@ -17,8 +17,19 @@ export function classifyPermanentAccountRefusal(status: number, payload: unknown
17
17
  if (/^(?:(?:Your |The )?(?:Claude |ChatGPT )?subscription is inactive|Your account does not have an active subscription)[.!]?$/i.test(text)) return "subscription_inactive";
18
18
  if (/^Your (?:account|plan) (?:has been |was )?downgraded to (?:the )?free(?: plan)? (?:and |with )?(?:has )?(?:no|without) (?:remaining )?credits[.!]?$/i.test(text)) return "plan_downgraded";
19
19
  if (type === "permission_error" && /^Your account (?:does not have access to Claude Code|is (?:disabled|suspended)|is not permitted to use (?:the |this )?API)[.!]?$/i.test(text)) return "account_permission_denied";
20
+ // Cloud Code Assist (Antigravity / Gemini CLI OAuth) account ban (#7803). Google's backend has
21
+ // returned the sentence alone and with exactly two closing sentences (google-gemini/gemini-cli
22
+ // #19501, #20813, #27199, #27388); only those whole messages, on a consistent 403 / numeric 403
23
+ // / PERMISSION_DENIED envelope, qualify. Project-scoped CONSUMER_SUSPENDED, SERVICE_DISABLED
24
+ // and model-permission errors name a project or a model, not the sending identity.
25
+ if (status === 403 && code === 403 && googleStatus === "PERMISSION_DENIED"
26
+ && CCA_TOS_ACCOUNT_BAN.test(text.replace(/\s+/g, " "))) return "account_permission_denied";
20
27
  }
21
28
 
29
+ const CCA_TOS_ACCOUNT_BAN = new RegExp("^This service has been disabled in this account for violation of Terms of Service\\."
30
+ + "(?: If you believe this is an error, contact gemini-code-assist-user-feedback@google\\.com\\."
31
+ + "| Please submit an appeal to continue using this product\\.)?$");
32
+
22
33
  export async function permanentAccountRefusal(response: Response, signal?: AbortSignal): Promise<AccountPauseReason | undefined> {
23
34
  if (response.status !== 401 && response.status !== 403) return;
24
35
  try {
@@ -119,6 +119,7 @@ export async function rotateAnthropicAccountOnResponseForInstance(
119
119
  const { recordAnthropicAccountRefusal, rotateAnthropicAccountOnRefusal,
120
120
  hasAnthropicFailoverQuorum, isAnthropicAccountPoolEnabled, pickAlternateAnthropicAccount } = routing;
121
121
  if (wasAccountAutoPaused(response)) {
122
+ routing.clearAnthropicSessionAffinityForAccount(sent.accountId);
122
123
  if (!options.canRetry || options.signal?.aborted) return null;
123
124
  return pickAlternateAnthropicAccount(options.config, sent.accountId, Date.now(),
124
125
  options.currentDecision ? options.currentDecision() : options.decision ?? null, options.model, options.excludedAccountIds);
@@ -6,6 +6,12 @@ export type AnthropicRateLimitKind = "shared-quota" | "family-quota" | "transien
6
6
  export type RateLimitHeaders = Pick<Headers, "get">;
7
7
  export const ANTHROPIC_SHORT_RETRY_MS = 100;
8
8
  export const ANTHROPIC_MAX_INLINE_THROTTLE_MS = 1_000;
9
+ /**
10
+ * How long a transient pause keeps marking its account as only detoured from (#7813). A detour
11
+ * awaits the alternate's credential and selection commit after the pause is set; a pause that
12
+ * expires during those awaits must not turn the detour into a permanent rebinding.
13
+ */
14
+ export const ANTHROPIC_DETOUR_GRACE_MS = 5 * 60_000;
9
15
 
10
16
  export function anthropicRetryAfterMs(value: string | null | undefined, now: number): number | undefined {
11
17
  const text = value?.trim();
@@ -27,6 +33,9 @@ export function classifyAnthropic429(headers: RateLimitHeaders, now = Date.now()
27
33
 
28
34
  function createAnthropicRatePolicy(instance: AnthropicInstanceId) {
29
35
  let pauses: Map<string, { until: number; generation: string }> | undefined;
36
+ // Accounts paused within the detour grace window, by credential generation. Bounded by the
37
+ // stored account set (one row per account) and pruned with the pauses.
38
+ let recent: Map<string, { at: number; generation: string }> | undefined;
30
39
  function pauseAnthropicRateAdmission(accountId: string, until: number): void {
31
40
  const credential = getAccountCredential(instance, accountId);
32
41
  if (!credential) return;
@@ -36,6 +45,9 @@ function createAnthropicRatePolicy(instance: AnthropicInstanceId) {
36
45
  for (const [id, pause] of rows) if (pause.until <= now) rows.delete(id);
37
46
  const previous = rows.get(accountId);
38
47
  rows.set(accountId, { until: Math.max(previous?.generation === generation ? previous.until : 0, until), generation });
48
+ const marks = recent ??= new Map();
49
+ for (const [id, mark] of marks) if (now - mark.at > ANTHROPIC_DETOUR_GRACE_MS) marks.delete(id);
50
+ marks.set(accountId, { at: now, generation });
39
51
  }
40
52
  function anthropicRatePauseUntil(accountId: string, now = Date.now()): number | undefined {
41
53
  const pause = pauses?.get(accountId);
@@ -46,21 +58,33 @@ function createAnthropicRatePolicy(instance: AnthropicInstanceId) {
46
58
  }
47
59
  return pause.until;
48
60
  }
49
- function clearAnthropicRatePauses(): void { pauses = undefined; }
61
+ /** True while the account's latest transient pause is younger than the detour grace window. */
62
+ function anthropicRatePausedRecently(accountId: string, now = Date.now()): boolean {
63
+ const mark = recent?.get(accountId);
64
+ if (!mark) return false;
65
+ const credential = getAccountCredential(instance, accountId);
66
+ if (now - mark.at > ANTHROPIC_DETOUR_GRACE_MS || !credential || credentialGeneration(credential) !== mark.generation) {
67
+ recent!.delete(accountId); return false;
68
+ }
69
+ return true;
70
+ }
71
+ function clearAnthropicRatePauses(): void { pauses = undefined; recent = undefined; }
50
72
  function reconcileAnthropicRatePauses(context: GenerationContext): number {
51
73
  let removed = 0;
52
74
  for (const id of pauses?.keys() ?? []) {
53
75
  if (context.oauthAccountKeys.has(`${instance}\0${id}`)) continue;
54
76
  pauses!.delete(id); removed++;
55
77
  }
78
+ for (const id of recent?.keys() ?? []) if (!context.oauthAccountKeys.has(`${instance}\0${id}`)) recent!.delete(id);
56
79
  return removed;
57
80
  }
58
81
  function sweepExpiredAnthropicRatePauses(now = Date.now()): number {
59
82
  let removed = 0;
60
83
  for (const [id, pause] of pauses ?? []) if (pause.until <= now) { pauses!.delete(id); removed++; }
84
+ for (const [id, mark] of recent ?? []) if (now - mark.at > ANTHROPIC_DETOUR_GRACE_MS) recent!.delete(id);
61
85
  return removed;
62
86
  }
63
- return Object.freeze({ instance, pauseAnthropicRateAdmission, anthropicRatePauseUntil,
87
+ return Object.freeze({ instance, pauseAnthropicRateAdmission, anthropicRatePauseUntil, anthropicRatePausedRecently,
64
88
  clearAnthropicRatePauses, reconcileAnthropicRatePauses, sweepExpiredAnthropicRatePauses });
65
89
  }
66
90
  export type AnthropicRatePolicy = ReturnType<typeof createAnthropicRatePolicy>;