@bitkyc08/opencodex 2.91.0 → 2.93.0-preview.20261027

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 (360) hide show
  1. package/bin/ocx.mjs +47 -8
  2. package/gui/dist/assets/App-CJZoq-uF.js +58 -0
  3. package/gui/dist/assets/{Tray-BuLy7hL1.js → Tray-BWQPcgZn.js} +1 -1
  4. package/gui/dist/assets/index-DRe8Hhfz.css +1 -0
  5. package/gui/dist/assets/index-Xfct8owH.js +94 -0
  6. package/gui/dist/assets/quota-summary-DxToX1rV.js +1 -0
  7. package/gui/dist/index.html +2 -2
  8. package/gui/dist/provider-icons/workbuddy-color.svg +29 -0
  9. package/package.json +8 -7
  10. package/src/adapters/anthropic.ts +28 -5
  11. package/src/adapters/coding-agent/batch-dispatcher.ts +122 -0
  12. package/src/adapters/coding-agent/profile.ts +54 -16
  13. package/src/adapters/coding-agent/turn.ts +30 -2
  14. package/src/adapters/command-code.ts +114 -7
  15. package/src/adapters/cursor/native-exec-fs.ts +11 -9
  16. package/src/adapters/devin/live-models.ts +4 -0
  17. package/src/adapters/google-vertex-endpoint.ts +9 -1
  18. package/src/adapters/google-vertex-key-project.ts +223 -0
  19. package/src/adapters/google-wire-compiler.ts +1 -2
  20. package/src/adapters/google.ts +13 -3
  21. package/src/adapters/kiro/reasoning.ts +2 -0
  22. package/src/adapters/kiro-refusal.ts +6 -1
  23. package/src/adapters/kiro-wire.ts +1 -1
  24. package/src/adapters/openai-chat/messages.ts +8 -2
  25. package/src/adapters/openai-chat/passthrough.ts +35 -14
  26. package/src/adapters/openai-chat/reasoning-replay.ts +27 -16
  27. package/src/adapters/openai-chat/reasoning-wire.ts +117 -8
  28. package/src/adapters/openai-chat/required-tool-result.ts +64 -0
  29. package/src/adapters/openai-chat/tool-name-registry.ts +3 -1
  30. package/src/adapters/openai-chat.ts +9 -10
  31. package/src/adapters/openai-responses/passthrough.ts +7 -4
  32. package/src/adapters/openai-responses/reasoning.ts +13 -0
  33. package/src/adapters/openai-responses/request-strips.ts +60 -0
  34. package/src/adapters/qoder/adapter.ts +129 -8
  35. package/src/adapters/qoder/scaffold-guard.ts +5 -0
  36. package/src/adapters/reasoning-controls.ts +16 -0
  37. package/src/adapters/registry.ts +5 -0
  38. package/src/adapters/tool-call-id.ts +1 -3
  39. package/src/adapters/workbuddy-schema.ts +61 -0
  40. package/src/adapters/workbuddy.ts +68 -0
  41. package/src/bridge/errors.ts +27 -0
  42. package/src/bridge/response-json.ts +1 -1
  43. package/src/bridge/sse.ts +1 -1
  44. package/src/bridge.ts +1 -1
  45. package/src/chat/inbound.ts +4 -1
  46. package/src/chat/outbound.ts +20 -6
  47. package/src/chat/reasoning-details.ts +28 -5
  48. package/src/claude/desktop-first-party.ts +54 -4
  49. package/src/claude/desktop-picker.ts +11 -8
  50. package/src/claude/first-party-settings.ts +3 -1
  51. package/src/claude/inbound.ts +2 -1
  52. package/src/claude/intercept/local-ca.ts +2 -1
  53. package/src/claude/intercept/picker-ca-cleanup.ts +4 -2
  54. package/src/claude/intercept/picker-ca-startup.ts +3 -1
  55. package/src/claude/intercept/picker-models.ts +6 -3
  56. package/src/claude/intercept/picker-runtime.ts +3 -2
  57. package/src/claude/intercept/runtime.ts +6 -3
  58. package/src/claude/model-info.ts +31 -8
  59. package/src/cli/account-api.ts +11 -0
  60. package/src/cli/capabilities-agents-routing.ts +3 -3
  61. package/src/cli/capabilities-base.ts +7 -1
  62. package/src/cli/capabilities-observe-system.ts +10 -0
  63. package/src/cli/claude-desktop.ts +9 -8
  64. package/src/cli/claude.ts +3 -2
  65. package/src/cli/codex-cli-update.ts +8 -0
  66. package/src/cli/codex-shim-autorestore.ts +9 -0
  67. package/src/cli/combo-result.ts +13 -0
  68. package/src/cli/combo-stats.ts +3 -0
  69. package/src/cli/combo.ts +83 -41
  70. package/src/cli/cross-home-owner.ts +13 -1
  71. package/src/cli/dispatch.ts +25 -6
  72. package/src/cli/ensure-desired-integrations.ts +8 -6
  73. package/src/cli/export-command.ts +4 -1
  74. package/src/cli/help.ts +2 -1
  75. package/src/cli/index.ts +45 -45
  76. package/src/cli/integration-plan-dto.ts +4 -0
  77. package/src/cli/launcher-context.ts +49 -2
  78. package/src/cli/link.ts +45 -32
  79. package/src/cli/opencode.ts +20 -9
  80. package/src/cli/provider.ts +2 -1
  81. package/src/cli/registry.ts +6 -4
  82. package/src/cli/root.ts +9 -0
  83. package/src/cli/status.ts +59 -1
  84. package/src/cli/stop-restore.ts +113 -0
  85. package/src/cli/sync-expectation.ts +60 -0
  86. package/src/cli/uninstall-integrations.ts +41 -7
  87. package/src/cli/usage-compare.ts +68 -12
  88. package/src/client/connect.ts +40 -3
  89. package/src/client/link-home.ts +10 -1
  90. package/src/client/link-ingress.ts +1 -1
  91. package/src/client/link-readiness.ts +97 -0
  92. package/src/client/link-relay-transport.ts +79 -11
  93. package/src/client/link-relay.ts +74 -15
  94. package/src/client/link-tunnel.ts +45 -18
  95. package/src/client/machine-api.ts +3 -1
  96. package/src/client/machine-listener.ts +20 -2
  97. package/src/client/runtime.ts +20 -2
  98. package/src/client/sync-expectation.ts +118 -0
  99. package/src/clients/config-export/agent-clients.ts +96 -0
  100. package/src/clients/config-export/contracts.ts +25 -7
  101. package/src/clients/config-export/qoder.ts +38 -23
  102. package/src/clients/config-export/reasoning-metadata.ts +55 -8
  103. package/src/clients/config-export.ts +12 -0
  104. package/src/clients/lazycodex.ts +7 -2
  105. package/src/clients/reasoning-controls.ts +49 -0
  106. package/src/codex/account-store.ts +17 -3
  107. package/src/codex/app-server-restart-service.ts +6 -5
  108. package/src/codex/auth-api/account-identity.ts +14 -0
  109. package/src/codex/auth-api/account-list.ts +29 -2
  110. package/src/codex/auth-api/http.ts +13 -0
  111. package/src/codex/auth-api/main-account-probe.ts +2 -2
  112. package/src/codex/auth-api/pool-mode-gate.ts +16 -3
  113. package/src/codex/auth-api/pool-quota-probe.ts +15 -0
  114. package/src/codex/auth-context.ts +15 -12
  115. package/src/codex/catalog/build-entries.ts +22 -0
  116. package/src/codex/catalog/configured-tiers.ts +70 -0
  117. package/src/codex/catalog/effort.ts +52 -11
  118. package/src/codex/catalog/gather-capture.ts +5 -2
  119. package/src/codex/catalog/heal-observation.ts +155 -13
  120. package/src/codex/catalog/metadata.ts +6 -0
  121. package/src/codex/catalog/model-hints.ts +60 -11
  122. package/src/codex/catalog/model-visibility.ts +3 -2
  123. package/src/codex/catalog/native-models.ts +18 -3
  124. package/src/codex/catalog/parsing.ts +10 -8
  125. package/src/codex/catalog/pinned-models.ts +2 -1
  126. package/src/codex/catalog/provider-models.ts +18 -13
  127. package/src/codex/catalog/retained-sync.ts +2 -1
  128. package/src/codex/catalog/routed-gather.ts +19 -20
  129. package/src/codex/catalog/write-audit.ts +3 -2
  130. package/src/codex/catalog-self-heal.ts +43 -23
  131. package/src/codex/chatgpt-refresh-failure.ts +6 -2
  132. package/src/codex/cli-install-provenance.ts +418 -0
  133. package/src/codex/cli-installation-targets.ts +5 -1
  134. package/src/codex/cli-update-plan.ts +43 -16
  135. package/src/codex/collision-identity.ts +30 -5
  136. package/src/codex/convergence.ts +4 -3
  137. package/src/codex/data/roster-pinned-models.json +177 -1
  138. package/src/codex/desired-state.ts +6 -1
  139. package/src/codex/desktop-app/picker-freshness.ts +10 -8
  140. package/src/codex/desktop-compatibility/installed-build.ts +88 -12
  141. package/src/codex/desktop-compatibility/runtime.ts +29 -5
  142. package/src/codex/desktop-compatibility/usage-activation.ts +2 -1
  143. package/src/codex/desktop-compatibility/usage-controller.ts +9 -1
  144. package/src/codex/desktop-compatibility/windows-certificate-trust.ts +46 -12
  145. package/src/codex/inject/config-toml.ts +0 -18
  146. package/src/codex/inject/plan.ts +18 -3
  147. package/src/codex/inject/remove.ts +6 -2
  148. package/src/codex/inject.ts +1 -1
  149. package/src/codex/journal.ts +61 -1
  150. package/src/codex/model-entitlements.ts +1 -1
  151. package/src/codex/native-main-owner.ts +27 -1
  152. package/src/codex/native-profile-store.ts +2 -1
  153. package/src/codex/pool-credit-policy.ts +35 -1
  154. package/src/codex/pool-refresh-backoff.ts +3 -1
  155. package/src/codex/quota-types.ts +3 -0
  156. package/src/codex/quota.ts +24 -4
  157. package/src/codex/role-auto-assign.ts +6 -2
  158. package/src/codex/subagent-defaults.ts +49 -4
  159. package/src/codex/user-identity.ts +35 -6
  160. package/src/codex/windows-current-sid.ts +162 -0
  161. package/src/combos/failover.ts +17 -2
  162. package/src/combos/jev-decision-contract.ts +22 -1
  163. package/src/combos/jev-quota-activation.ts +5 -1
  164. package/src/combos/jev-quota-route.ts +1 -1
  165. package/src/combos/jev-quota.ts +9 -1
  166. package/src/combos/jev-service-exchange.ts +3 -1
  167. package/src/combos/jev-session-pin-config.ts +51 -0
  168. package/src/combos/jev.ts +101 -9
  169. package/src/combos/resolve.ts +45 -1
  170. package/src/combos/types.ts +43 -0
  171. package/src/config/load-degrade.ts +5 -0
  172. package/src/config/paths.ts +19 -3
  173. package/src/config/pending-teardown.ts +22 -1
  174. package/src/config/provider-validation.ts +22 -4
  175. package/src/config/removed-opencode-free.ts +11 -0
  176. package/src/config/schema/leaf-validators.ts +6 -0
  177. package/src/generated/compatibility-version.json +467 -311
  178. package/src/generated/model-metadata.ts +5 -5
  179. package/src/images/loop.ts +16 -2
  180. package/src/integrations/catalog-refresh.ts +1 -1
  181. package/src/integrations/hermes-profiles.ts +251 -0
  182. package/src/integrations/merge.ts +8 -0
  183. package/src/integrations/mutation-plan.ts +19 -4
  184. package/src/integrations/registry.ts +5 -0
  185. package/src/integrations/state.ts +36 -1
  186. package/src/integrations/writer.ts +18 -4
  187. package/src/lib/bun-path-runtime.mjs +2 -1
  188. package/src/lib/decision-quota-sink.ts +10 -0
  189. package/src/lib/errors.ts +62 -0
  190. package/src/lib/eventstream-decoder.ts +81 -37
  191. package/src/lib/opaque-proxy-tunnel.ts +32 -8
  192. package/src/lib/pinned-http.ts +35 -2
  193. package/src/lib/process-control.ts +13 -1
  194. package/src/lib/socks5-fetch.ts +59 -64
  195. package/src/lib/socks5-upload-waiter.ts +50 -0
  196. package/src/lib/sse-decoder.ts +7 -2
  197. package/src/lib/state-store-sweeper.ts +40 -14
  198. package/src/lib/translator-budget.ts +4 -4
  199. package/src/lib/upstream-retry.ts +4 -1
  200. package/src/lib/windows-native-principal-worker.ts +14 -0
  201. package/src/lib/windows-native-principal.ts +188 -0
  202. package/src/lib/windows-secret-acl.ts +39 -3
  203. package/src/lib/windows-user-principal.ts +62 -18
  204. package/src/link/diagnostics.ts +193 -0
  205. package/src/link/relay-auth.ts +6 -0
  206. package/src/link/ssh-config.ts +35 -3
  207. package/src/link/status-projection.ts +39 -0
  208. package/src/link/supervisor.ts +45 -12
  209. package/src/link/tunnel-history.ts +109 -0
  210. package/src/link/tunnel-state.ts +80 -17
  211. package/src/messaging/remote-files.ts +24 -1
  212. package/src/oauth/generic-account-failover.ts +91 -7
  213. package/src/oauth/index.ts +15 -0
  214. package/src/oauth/model-discovery-auth.ts +5 -0
  215. package/src/oauth/store.ts +4 -1
  216. package/src/oauth/token-guardian.ts +7 -0
  217. package/src/oauth/types.ts +9 -0
  218. package/src/oauth/workbuddy.ts +139 -0
  219. package/src/providers/account-quota-disk.ts +12 -4
  220. package/src/providers/antigravity-quota-identity.ts +37 -0
  221. package/src/providers/base-url-choices.ts +8 -5
  222. package/src/providers/codebuddy-models.ts +6 -0
  223. package/src/providers/codex-capacity.ts +3 -1
  224. package/src/providers/derive.ts +51 -3
  225. package/src/providers/kiro-models.ts +3 -0
  226. package/src/providers/mimo-thinking.ts +12 -0
  227. package/src/providers/model-discovery.ts +2 -0
  228. package/src/providers/model-rename-fields.ts +2 -0
  229. package/src/providers/model-rename-migration.ts +10 -0
  230. package/src/providers/openai-sidecar-credit.ts +2 -2
  231. package/src/providers/quota/account-cache.ts +3 -2
  232. package/src/providers/quota/antigravity.ts +25 -14
  233. package/src/providers/quota/report-cache.ts +13 -4
  234. package/src/providers/quota/vendor-probes-key.ts +60 -0
  235. package/src/providers/quota/workbuddy.ts +83 -0
  236. package/src/providers/quota-decision-antigravity.ts +64 -0
  237. package/src/providers/quota-decision-publication.ts +11 -0
  238. package/src/providers/quota-decision-snapshot.ts +21 -4
  239. package/src/providers/quota-types.ts +2 -0
  240. package/src/providers/quota.ts +3 -1
  241. package/src/providers/reasoning-capabilities.ts +76 -0
  242. package/src/providers/registry/entries-core.ts +23 -12
  243. package/src/providers/registry/entries-extended.ts +83 -27
  244. package/src/providers/registry/model-ids.ts +5 -0
  245. package/src/providers/registry/model-seeds.ts +120 -56
  246. package/src/providers/registry/types.ts +29 -2
  247. package/src/providers/resolved-model-policy.ts +30 -10
  248. package/src/providers/routed-config.ts +24 -1
  249. package/src/providers/stale-model-roster-migration.ts +123 -18
  250. package/src/providers/workbuddy-credit-balance.ts +81 -0
  251. package/src/providers/workbuddy-models.ts +37 -0
  252. package/src/providers/workbuddy.ts +60 -0
  253. package/src/remote-control/workspace-pi-runtime.ts +11 -6
  254. package/src/responses/compaction-summary.ts +45 -0
  255. package/src/responses/muse-tool-name-alias.ts +1 -2
  256. package/src/responses/parser.ts +3 -2
  257. package/src/responses/reasoning-replay-cache.ts +18 -14
  258. package/src/responses/schema.ts +1 -0
  259. package/src/responses/thought-signature-replay.ts +10 -2
  260. package/src/router.ts +2 -0
  261. package/src/routing/analytics.ts +2 -3
  262. package/src/routing/capability.ts +8 -2
  263. package/src/routing/fallback-policy.ts +3 -3
  264. package/src/routing/history/ingest.ts +28 -3
  265. package/src/server/auth-cors.ts +4 -2
  266. package/src/server/chat-completions.ts +21 -1
  267. package/src/server/chat-native-eligibility.ts +7 -0
  268. package/src/server/chat-native-reasoning.ts +24 -7
  269. package/src/server/chat-native.ts +13 -2
  270. package/src/server/claude-messages.ts +3 -0
  271. package/src/server/direct-local-http.ts +5 -2
  272. package/src/server/effort-policy.ts +5 -1
  273. package/src/server/index/link-relay-sessions.ts +9 -5
  274. package/src/server/index/live-sideband.ts +18 -15
  275. package/src/server/index/optional-listeners.ts +4 -0
  276. package/src/server/index/serve-options.ts +5 -4
  277. package/src/server/local-management-read-client.ts +3 -1
  278. package/src/server/management/agent-settings-routes.ts +27 -15
  279. package/src/server/management/combo-routes.ts +14 -4
  280. package/src/server/management/config-routes.ts +2 -2
  281. package/src/server/management/decision-discovery.ts +12 -2
  282. package/src/server/management/hermes-profile-routes.ts +156 -0
  283. package/src/server/management/integration-routes.ts +85 -24
  284. package/src/server/management/link-routes.ts +5 -2
  285. package/src/server/management/model-routes.ts +2 -2
  286. package/src/server/management/model-row-export-metadata.ts +25 -6
  287. package/src/server/management/model-rows.ts +15 -20
  288. package/src/server/management/native-integration-routes.ts +11 -8
  289. package/src/server/management/provider-routes.ts +1 -1
  290. package/src/server/management/route-registry.ts +4 -0
  291. package/src/server/management-api.ts +5 -0
  292. package/src/server/models-capabilities.ts +21 -3
  293. package/src/server/port-reclaim.ts +51 -9
  294. package/src/server/request-log-conversation.ts +49 -0
  295. package/src/server/request-log.ts +2 -0
  296. package/src/server/responses/adapter-delivery.ts +11 -1
  297. package/src/server/responses/adapter-dispatch.ts +2 -2
  298. package/src/server/responses/anthropic-thinking-recovery.ts +1 -0
  299. package/src/server/responses/codex-ws-exchange.ts +39 -9
  300. package/src/server/responses/codex-ws-session.ts +38 -4
  301. package/src/server/responses/codex-ws-wire.ts +6 -1
  302. package/src/server/responses/combo-required-tool-contract.ts +103 -0
  303. package/src/server/responses/combo-stream-preflight.ts +8 -1
  304. package/src/server/responses/compact.ts +14 -5
  305. package/src/server/responses/context-overflow.ts +8 -1
  306. package/src/server/responses/core-combo-failure.ts +10 -0
  307. package/src/server/responses/core-combo.ts +74 -44
  308. package/src/server/responses/core-lifetime.ts +5 -2
  309. package/src/server/responses/core-normalize.ts +17 -4
  310. package/src/server/responses/core-opaque-recovery.ts +1 -0
  311. package/src/server/responses/core-options.ts +7 -0
  312. package/src/server/responses/core-replay.ts +2 -1
  313. package/src/server/responses/jev-combo-choice.ts +39 -0
  314. package/src/server/responses/jev-session-pin.ts +203 -0
  315. package/src/server/responses/main-hard-lock-routing.ts +60 -44
  316. package/src/server/responses/passthrough-delivery.ts +44 -2
  317. package/src/server/responses/policy-fallback.ts +6 -1
  318. package/src/server/responses/request-compression.ts +12 -7
  319. package/src/server/responses/request-prepare.ts +32 -7
  320. package/src/server/responses/request-sidecar-auth.ts +2 -0
  321. package/src/server/responses/request-transport.ts +25 -6
  322. package/src/server/responses/response-effects.ts +22 -10
  323. package/src/server/responses/run-turn-execution.ts +2 -4
  324. package/src/server/responses/sidecar-execution.ts +13 -7
  325. package/src/server/responses-phase-inference.ts +267 -0
  326. package/src/server/sse-payload-rewrite.ts +14 -1
  327. package/src/server/stop-teardown.ts +36 -1
  328. package/src/server/ws-bridge.ts +1 -1
  329. package/src/service/definition.ts +20 -8
  330. package/src/service/desktop-supervision.d.mts +7 -4
  331. package/src/service/desktop-supervision.mjs +90 -13
  332. package/src/service/ownership-mutation-lease.mjs +21 -7
  333. package/src/types/config.ts +14 -2
  334. package/src/types/provider.ts +29 -7
  335. package/src/types/request.ts +11 -0
  336. package/src/types/wire.ts +1 -0
  337. package/src/types.ts +1 -0
  338. package/src/update/bind-probe.ts +29 -0
  339. package/src/update/codex-cli-update-launch-policy.d.mts +9 -0
  340. package/src/update/codex-cli-update-launch-policy.mjs +30 -0
  341. package/src/update/job.ts +10 -29
  342. package/src/update/npm-install-job.ps1 +173 -0
  343. package/src/update/npm-install.mjs +70 -0
  344. package/src/update/stop-contract.d.mts +1 -0
  345. package/src/update/stop-contract.mjs +14 -0
  346. package/src/update/stop-decision.d.mts +1 -1
  347. package/src/update/stop-decision.mjs +13 -3
  348. package/src/update/teardown-handover.ts +166 -0
  349. package/src/update/transactional-install.d.mts +14 -3
  350. package/src/update/transactional-install.mjs +33 -7
  351. package/src/usage/expected-prices.ts +64 -31
  352. package/src/usage/jev-stats.ts +54 -14
  353. package/src/usage/timeline.ts +19 -9
  354. package/src/vision/eligibility.ts +15 -5
  355. package/src/vision/plan.ts +2 -2
  356. package/src/web-search/loop.ts +16 -2
  357. package/gui/dist/assets/App-nZ34cR5G.js +0 -58
  358. package/gui/dist/assets/index-DGXS51sp.js +0 -94
  359. package/gui/dist/assets/index-DPeB9HpV.css +0 -1
  360. package/gui/dist/assets/quota-summary-DO1Sx5TM.js +0 -1
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Hermes profiles: where each Hermes bot keeps its own config.yaml.
3
+ *
4
+ * Hermes gives every profile its own home. The default profile is the home
5
+ * OpenCodex has always written (`HERMES_HOME`, else `%LOCALAPPDATA%\hermes` on
6
+ * Windows, else `~/.hermes`); a named profile is `<root>/profiles/<name>/`, and
7
+ * Hermes selects it by running with `HERMES_HOME` pointed at that directory.
8
+ *
9
+ * The rules below mirror Hermes itself (NousResearch/hermes-agent
10
+ * `hermes_constants.py`: `PROFILE_ID_RE`, `_PROFILE_IDENTITY_MARKERS`,
11
+ * `profile_tombstone_path`, `_hermes_root_of`), so this lists exactly the
12
+ * profiles `hermes profile list` shows and never a cache or log directory that
13
+ * happens to sit under `profiles/`.
14
+ *
15
+ * Each named profile keeps its own ownership store under
16
+ * `<integrations>/hermes-profiles/<name>/`, so its records, journal and snapshots
17
+ * can never be confused with the default profile's.
18
+ */
19
+ import { lstatSync, readdirSync, type Stats } from "node:fs";
20
+ import { homedir } from "node:os";
21
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
22
+ import { hermesHomeDir } from "../clients/config-export";
23
+ import { createIntegrationStateStore, type IntegrationStateStore } from "./store";
24
+ import type { ResolvedIntegrationPaths } from "./registry";
25
+
26
+ export const HERMES_DEFAULT_PROFILE = "default";
27
+ /** Hermes `PROFILE_ID_RE`: the only names Hermes itself creates or lists. */
28
+ export const HERMES_PROFILE_ID_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/;
29
+ /** Hermes `_PROFILE_IDENTITY_MARKERS`: a directory without one is not a profile. */
30
+ const IDENTITY_MARKERS = ["config.yaml", ".env", "SOUL.md", "profile.yaml", "auth.json", "state.db"] as const;
31
+ const TOMBSTONE_DIR = ".deleted";
32
+ export const HERMES_PROFILE_STORE_DIR = "hermes-profiles";
33
+
34
+ export interface HermesProfile {
35
+ /** `default`, or the directory name under `<root>/profiles`. */
36
+ name: string;
37
+ /** The HERMES_HOME Hermes runs this profile with. */
38
+ home: string;
39
+ configPath: string;
40
+ }
41
+
42
+ export class HermesProfileError extends Error {
43
+ constructor(readonly code: string, readonly status: 400 | 404 | 409, message: string) {
44
+ super(message);
45
+ this.name = "HermesProfileError";
46
+ }
47
+ }
48
+
49
+ function lstatOrNull(path: string): Stats | null {
50
+ try { return lstatSync(path); }
51
+ catch (error) {
52
+ if ((error as NodeJS.ErrnoException).code === "ENOENT" || (error as NodeJS.ErrnoException).code === "ENOTDIR") return null;
53
+ throw new HermesProfileError("hermes_profiles_unavailable", 409, "Hermes profiles cannot be read");
54
+ }
55
+ }
56
+
57
+ function isWithin(base: string, target: string): boolean {
58
+ const rel = relative(resolve(base), resolve(target));
59
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
60
+ }
61
+
62
+ function samePath(a: string, b: string): boolean {
63
+ return relative(resolve(a), resolve(b)) === "";
64
+ }
65
+
66
+ /**
67
+ * The Hermes root that holds `profiles/`, as Hermes `_hermes_root_of` derives it:
68
+ * no override, or an override inside the platform home, means the platform home;
69
+ * `<root>/profiles/<name>` means `<root>`; any other override is its own root.
70
+ */
71
+ export function hermesRootDir(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string {
72
+ const { HERMES_HOME: _ignored, ...withoutOverride } = env;
73
+ const native = hermesHomeDir(withoutOverride, home);
74
+ const override = env.HERMES_HOME?.trim();
75
+ if (!override) return native;
76
+ if (isWithin(native, override)) return native;
77
+ return basename(dirname(override)) === "profiles" ? dirname(dirname(override)) : override;
78
+ }
79
+
80
+ function profileOf(name: string, profileHome: string): HermesProfile {
81
+ return { name, home: profileHome, configPath: join(profileHome, "config.yaml") };
82
+ }
83
+
84
+ /**
85
+ * The default profile first, then every live named profile, sorted by name.
86
+ *
87
+ * A named profile must be a real directory: a symbolic link or junction under
88
+ * `profiles/` is skipped, because writing through it would edit a file outside
89
+ * the Hermes root. A profile whose home IS the default home (HERMES_HOME pointed
90
+ * at a profile) is listed once, as the default.
91
+ */
92
+ export function listHermesProfiles(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): HermesProfile[] {
93
+ const defaultHome = hermesHomeDir(env, home);
94
+ const profiles = [profileOf(HERMES_DEFAULT_PROFILE, defaultHome)];
95
+ const profilesDir = join(hermesRootDir(env, home), "profiles");
96
+ const rootStat = lstatOrNull(profilesDir);
97
+ if (!rootStat?.isDirectory()) return profiles;
98
+ let names: string[];
99
+ try { names = readdirSync(profilesDir); }
100
+ catch { throw new HermesProfileError("hermes_profiles_unavailable", 409, "Hermes profiles cannot be read"); }
101
+ for (const name of names.sort()) {
102
+ if (name === HERMES_DEFAULT_PROFILE || !HERMES_PROFILE_ID_RE.test(name)) continue;
103
+ const profileHome = join(profilesDir, name);
104
+ const stat = lstatOrNull(profileHome);
105
+ if (!stat?.isDirectory() || stat.isSymbolicLink()) continue;
106
+ const hasIdentity = IDENTITY_MARKERS.some(marker => {
107
+ const markerStat = lstatOrNull(join(profileHome, marker));
108
+ return markerStat !== null && (markerStat.isFile() || markerStat.isSymbolicLink());
109
+ });
110
+ if (!hasIdentity || lstatOrNull(join(profilesDir, TOMBSTONE_DIR, name)) !== null) continue;
111
+ if (samePath(profileHome, defaultHome)) continue;
112
+ profiles.push(profileOf(name, profileHome));
113
+ }
114
+ return profiles;
115
+ }
116
+
117
+ /** An operator-selected profile, or a refusal that names why. */
118
+ export function resolveHermesProfile(
119
+ name: string,
120
+ env: NodeJS.ProcessEnv = process.env,
121
+ home: string = homedir(),
122
+ ): HermesProfile {
123
+ // The default profile is the home OpenCodex has always used; it never depends on its siblings.
124
+ if (name === HERMES_DEFAULT_PROFILE) return profileOf(HERMES_DEFAULT_PROFILE, hermesHomeDir(env, home));
125
+ if (!HERMES_PROFILE_ID_RE.test(name)) {
126
+ throw new HermesProfileError("invalid_hermes_profile", 400, "Hermes profile names use lowercase letters, digits, '-' and '_'");
127
+ }
128
+ const profile = listHermesProfiles(env, home).find(candidate => candidate.name === name);
129
+ if (!profile) throw new HermesProfileError("hermes_profile_not_found", 404, "Hermes profile is not present");
130
+ return profile;
131
+ }
132
+
133
+ /** The environment Hermes runs this profile with. The default profile changes nothing. */
134
+ export function hermesProfileEnv(profile: HermesProfile, env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
135
+ return profile.name === HERMES_DEFAULT_PROFILE ? env : { ...env, HERMES_HOME: profile.home };
136
+ }
137
+
138
+ export function hermesProfilePaths(profile: HermesProfile): ResolvedIntegrationPaths {
139
+ return { configPath: profile.configPath, detectDir: profile.home };
140
+ }
141
+
142
+ function unsafe(message: string): never {
143
+ throw new HermesProfileError("hermes_profile_unsafe", 409, message);
144
+ }
145
+
146
+ /** `dev:ino` of a real directory, null when it does not exist; a link or junction is refused. */
147
+ function realDirectoryKey(path: string): string | null {
148
+ const stat = lstatOrNull(path);
149
+ if (stat === null) return null;
150
+ if (stat.isSymbolicLink() || !stat.isDirectory()) unsafe("A Hermes profile path is a link or not a directory");
151
+ return `${stat.dev}:${stat.ino}`;
152
+ }
153
+
154
+ /**
155
+ * Pin a named profile's directories and owner, and return the check that proves
156
+ * they still hold.
157
+ *
158
+ * Discovery happens before the model roster loads, and the write happens after.
159
+ * The check runs again immediately before the write: the `profiles` directory and
160
+ * the profile home must be the same real directories (never a link or junction
161
+ * swapped in meanwhile), the profile must not have been deleted, the ownership
162
+ * store must not be a link, and an existing ownership record must name this
163
+ * profile's config.yaml. The last rule matters when HERMES_HOME moves: a profile
164
+ * of the same name under another Hermes root shares the store name, and must not
165
+ * inherit or overwrite the original profile's ownership.
166
+ */
167
+ export function hermesProfileBoundary(profile: HermesProfile, store: IntegrationStateStore): () => void {
168
+ const profilesDir = dirname(profile.home);
169
+ const pinned = [profilesDir, profile.home].map(path => ({ path, key: realDirectoryKey(path) }));
170
+ if (pinned.some(entry => entry.key === null)) {
171
+ throw new HermesProfileError("hermes_profile_not_found", 404, "Hermes profile is not present");
172
+ }
173
+ const check = () => {
174
+ for (const { path, key } of pinned) {
175
+ if (realDirectoryKey(path) !== key) unsafe("The Hermes profile directory changed while this change was prepared");
176
+ }
177
+ if (lstatOrNull(join(profilesDir, TOMBSTONE_DIR, profile.name)) !== null) {
178
+ throw new HermesProfileError("hermes_profile_not_found", 404, "Hermes profile was deleted");
179
+ }
180
+ realDirectoryKey(dirname(store.root));
181
+ realDirectoryKey(store.root);
182
+ const owner = store.readRecords().hermes;
183
+ if (owner && owner.configPath !== profile.configPath) {
184
+ throw new HermesProfileError("hermes_profile_owner_mismatch", 409,
185
+ "This profile's OpenCodex ownership names a Hermes file in another Hermes home; disconnect it there first");
186
+ }
187
+ };
188
+ check();
189
+ return check;
190
+ }
191
+
192
+ /**
193
+ * The store a request uses for a named profile: every method first proves the pinned boundary
194
+ * still holds, synchronously, at the moment it touches the store. A read that retries snapshot
195
+ * maintenance, a journal tombstone, a prune and a writer commit are all covered the same way, so no
196
+ * await between scope creation and use can leave a swapped directory unchecked.
197
+ */
198
+ export function guardedHermesProfileStore(store: IntegrationStateStore, holds: () => void): IntegrationStateStore {
199
+ const guarded: IntegrationStateStore = new Proxy(store, {
200
+ get(target, property, receiver) {
201
+ const value: unknown = Reflect.get(target, property, receiver);
202
+ if (typeof value !== "function") return value;
203
+ // io() closes over the raw store; route its bookkeeping back through this facade.
204
+ if (property === "io") {
205
+ return () => {
206
+ holds();
207
+ return {
208
+ ...target.io(),
209
+ appendJournal: (entry: Parameters<IntegrationStateStore["appendJournal"]>[0]) => guarded.appendJournal(entry),
210
+ putRecord: (record: Parameters<IntegrationStateStore["putRecord"]>[0]) => guarded.putRecord(record),
211
+ dropRecord: (clientId: Parameters<IntegrationStateStore["dropRecord"]>[0]) => guarded.dropRecord(clientId),
212
+ };
213
+ };
214
+ }
215
+ return (...args: unknown[]) => {
216
+ holds();
217
+ return Reflect.apply(value, target, args);
218
+ };
219
+ },
220
+ });
221
+ return guarded;
222
+ }
223
+
224
+ /** A named profile's ownership store; the default profile keeps the root store. */
225
+ export function hermesProfileStore(root: IntegrationStateStore, name: string): IntegrationStateStore {
226
+ if (name === HERMES_DEFAULT_PROFILE) return root;
227
+ if (!HERMES_PROFILE_ID_RE.test(name)) {
228
+ throw new HermesProfileError("invalid_hermes_profile", 400, "Hermes profile names use lowercase letters, digits, '-' and '_'");
229
+ }
230
+ return createIntegrationStateStore(join(root.root, HERMES_PROFILE_STORE_DIR, name));
231
+ }
232
+
233
+ /**
234
+ * Every persisted named-profile store, whether or not the profile still exists.
235
+ * Uninstall needs the orphans too: a deleted profile's record is still proof of
236
+ * what we wrote.
237
+ */
238
+ export function listHermesProfileStores(root: IntegrationStateStore): Array<{ name: string; store: IntegrationStateStore }> {
239
+ const directory = join(root.root, HERMES_PROFILE_STORE_DIR);
240
+ if (realDirectoryKey(directory) === null) return [];
241
+ let names: string[];
242
+ try { names = readdirSync(directory); }
243
+ catch { throw new HermesProfileError("hermes_profile_store_unsafe", 409, "Hermes profile ownership storage cannot be read"); }
244
+ return names.sort().map(name => {
245
+ if (name === HERMES_DEFAULT_PROFILE || !HERMES_PROFILE_ID_RE.test(name)) {
246
+ throw new HermesProfileError("hermes_profile_store_unsafe", 409, "Hermes profile ownership storage names an invalid profile");
247
+ }
248
+ realDirectoryKey(join(directory, name));
249
+ return { name, store: createIntegrationStateStore(join(directory, name)) };
250
+ });
251
+ }
@@ -62,6 +62,14 @@ export class InvalidSelectorError extends Error {
62
62
  }
63
63
  }
64
64
 
65
+ /** A generated contribution cannot name its exact owned array element. */
66
+ export class UnrepresentableSelectorError extends Error {
67
+ constructor(message: string) {
68
+ super(message);
69
+ this.name = "UnrepresentableSelectorError";
70
+ }
71
+ }
72
+
65
73
  function validConjunctionCriteria(criteria: readonly SelectorCriterion[]): boolean {
66
74
  return criteria.length >= 2 && criteria.every(criterion => (
67
75
  SELECTOR_FIELD.test(criterion.field)
@@ -38,9 +38,9 @@ import {
38
38
  } from "./registry";
39
39
  import { declaredIntegrationTarget, resolveIntegrationTarget, type IneffectiveWrite, type IneffectiveWriteReason, type IntegrationTarget } from "./target";
40
40
  import { shouldInjectApiAuthHeader } from "../codex/inject";
41
- import { buildIntegrationContribution, classifyIntegration, exportContextOf, readPath, type IntegrationState, type StateReason } from "./state";
41
+ import { buildIntegrationContribution, classifyIntegration, exportContextOf, qoderLegacyCatalogConflict, readPath, type IntegrationState, type StateReason } from "./state";
42
42
  import { inspectKiloCandidates } from "./kilo-candidates";
43
- import { InvalidSelectorError } from "./merge";
43
+ import { InvalidSelectorError, UnrepresentableSelectorError } from "./merge";
44
44
  import { createIntegrationStateStore, type IntegrationStateStore } from "./store";
45
45
  import type { OcxConfig } from "../types";
46
46
  import { matchesOperationResult, type JournalEntry } from "./journal";
@@ -132,6 +132,9 @@ export const DYNAMIC_SEGMENT = "*";
132
132
  */
133
133
  const CLIENT_MANAGED_PATHS = {
134
134
  qoder: [["providers", OPENCODE_PROVIDER_ID], ["modelConfigs", "customModels", DYNAMIC_SEGMENT]],
135
+ "qoder-cn": [["providers", OPENCODE_PROVIDER_ID], ["modelConfigs", "customModels", DYNAMIC_SEGMENT]],
136
+ workbuddy: [["models", DYNAMIC_SEGMENT], [DYNAMIC_SEGMENT]],
137
+ "workbuddy-ai": [["models", DYNAMIC_SEGMENT], [DYNAMIC_SEGMENT]],
135
138
  opencode: [["provider", OPENCODE_PROVIDER_ID], ["providers", OPENCODE_PROVIDER_ID]],
136
139
  pi: [["providers", OPENCODE_PROVIDER_ID]],
137
140
  "gentle-shell": [["providers", OPENCODE_PROVIDER_ID]],
@@ -378,7 +381,9 @@ function applyOutcome(input: PlanInput): PlanOutcome {
378
381
  */
379
382
  if (input.ineffectiveWrite !== null) return deny("superseded_store");
380
383
  // Overwrite exists precisely to proceed through a conflict the operator has been shown.
381
- if (input.classified.state === "conflict" && input.operation !== "overwrite") return deny("conflict");
384
+ // A Qoder legacy-catalog collision is not on a path overwrite replaces, so it still refuses.
385
+ if (input.classified.state === "conflict" && (input.operation !== "overwrite"
386
+ || qoderLegacyCatalogConflict(input.parsed, input.record, input.contribution))) return deny("conflict");
382
387
  if (input.classified.state === "unsafe") return deny("unsafe");
383
388
  if (input.classified.state === "current") return NOOP;
384
389
  return CHANGE;
@@ -1002,7 +1007,17 @@ export function observeIntegration(
1002
1007
  const record = stored && stored.clientId === clientId && stored.configPath === configPath
1003
1008
  ? stored
1004
1009
  : null;
1005
- const contribution = buildIntegrationContribution(input, effective, parsed, record);
1010
+ if (operation !== "disable") {
1011
+ const refusal = exportSpec.validateApply?.({ ...exportContextOf(input), document: parsed });
1012
+ if (refusal) return { failed: observationFailure("unsafe", "unsafe", refusal) } as const;
1013
+ }
1014
+ let contribution: ManagedContribution;
1015
+ try {
1016
+ contribution = buildIntegrationContribution(input, effective, parsed, record);
1017
+ } catch (error) {
1018
+ if (!(error instanceof UnrepresentableSelectorError)) throw error;
1019
+ return { failed: observationFailure("unsafe", "unsafe", error.message) } as const;
1020
+ }
1006
1021
  if (clientId === "droid" && input.models.length > 0 && contribution.fragments.length === 0 && !record) {
1007
1022
  return { failed: observationFailure("unsafe", "unsafe", "Factory Droid has no addressable models in the selected catalog") } as const;
1008
1023
  }
@@ -8,6 +8,7 @@
8
8
  *
9
9
  * Design of record: devlog/_fin/260802_client_toggle_api/021 §1.
10
10
  */
11
+ import { agentConfigPath, agentHomeDir } from "../clients/config-export/agent-clients";
11
12
  import { homedir } from "node:os";
12
13
  import { gentleShellPaths } from "../clients/gentle-shell-path";
13
14
  import { assertDroidSettingsUnambiguous } from "./droid-settings";
@@ -288,6 +289,10 @@ export const INTEGRATION_CLIENTS: Record<IntegrationClientId, IntegrationClientS
288
289
  configPath: qoderConfigPath,
289
290
  detectDir: (env = process.env, home = homedir()) => qoderHomeDir(env, home),
290
291
  },
292
+ ...Object.fromEntries((["qoder-cn", "workbuddy", "workbuddy-ai"] as const).map(id => [id, {
293
+ id, configPath: (env = process.env, home = homedir()) => agentConfigPath(id, env, home),
294
+ detectDir: (env = process.env, home = homedir()) => agentHomeDir(id, env, home),
295
+ }])) as Record<"qoder-cn" | "workbuddy" | "workbuddy-ai", IntegrationClientSpec>,
291
296
  opencode: {
292
297
  id: "opencode",
293
298
  // These take `home` explicitly. The export registry's `destination` reads
@@ -11,6 +11,7 @@
11
11
  import { createClineIO } from "./cline-io";
12
12
  import { parseClineDocument } from "./cline-document";
13
13
  import { ClientPathError, EXPORT_CLIENTS, opencodeProxyBaseUrl, droidDefaultsFromOwnedRows, type ExportModel, type ManagedContribution } from "../clients/config-export";
14
+ import { qoderLegacyCatalogCollision } from "../clients/config-export/qoder";
14
15
  import type { ConfigFormat } from "../clients/config-export";
15
16
  import type { OcxConfig } from "../types";
16
17
  import { PARSE_FAILED, loadTarget, parseConfig, type IntegrationIO } from "./config-io";
@@ -18,6 +19,7 @@ import { SNAPSHOT_RETENTION } from "./journal";
18
19
  import {
19
20
  AmbiguousSelectorError,
20
21
  InvalidSelectorError,
22
+ UnrepresentableSelectorError,
21
23
  parseSegment,
22
24
  readPath,
23
25
  selectIndex,
@@ -122,6 +124,24 @@ export function hasOurFragments(doc: unknown, contribution: ManagedContribution)
122
124
  return contribution.fragments.some(fragment => readPath(doc, fragment.path) !== undefined);
123
125
  }
124
126
 
127
+ /**
128
+ * A hand-written Qoder legacy row for one of our models makes Qoder reject the
129
+ * provider we would add. Rows a record still names are ours for refresh to
130
+ * drop. Overwrite cannot resolve this either, because the row is not on a path
131
+ * we write, so the writer and planner ask the same question before overwriting.
132
+ */
133
+ export function qoderLegacyCatalogConflict(
134
+ parsed: unknown,
135
+ record: OwnershipRecord | null,
136
+ contribution: ManagedContribution | null,
137
+ ): boolean {
138
+ if (contribution?.clientId !== "qoder" && contribution?.clientId !== "qoder-cn") return false;
139
+ const owned = new Set((record?.fragmentPaths ?? [])
140
+ .filter(path => Array.isArray(path) && path.every(key => typeof key === "string"))
141
+ .map(path => readPath(parsed, path)));
142
+ return qoderLegacyCatalogCollision(parsed, contribution, owned);
143
+ }
144
+
125
145
  /**
126
146
  * A container on one of our fragment paths that exists but is NOT an object.
127
147
  *
@@ -360,6 +380,10 @@ export function classifyIntegration(input: {
360
380
  }
361
381
  throw error;
362
382
  }
383
+ // Before `absent`: none of our paths is occupied, yet Qoder would reject the provider.
384
+ if (qoderLegacyCatalogConflict(input.parsed, input.record, input.contribution)) {
385
+ return { state: "conflict", reason: "unowned-key" };
386
+ }
363
387
  // A catalog can shrink to zero while the record still owns earlier rows.
364
388
  // Presence for disable must include those recorded paths, independent of the
365
389
  // current export roster; the ownership fingerprint is checked below.
@@ -678,7 +702,18 @@ export function readIntegrationState(input: IntegrationStateInput): IntegrationS
678
702
  const parsed = input.clientId === "cline"
679
703
  ? parseClineDocument(loaded.before)
680
704
  : parseConfig(loaded.before, effective.format, EXPORT_CLIENTS[input.clientId].jsonc ? { jsonc: true } : undefined);
681
- const contribution = buildIntegrationContribution(input, effective, parsed, record);
705
+ let contribution: ManagedContribution;
706
+ try {
707
+ contribution = buildIntegrationContribution(input, effective, parsed, record);
708
+ } catch (error) {
709
+ // One catalog row can make this client's ownership unaddressable. Keep its
710
+ // refusal visible without hiding every other client in a collection read.
711
+ if (!(error instanceof UnrepresentableSelectorError)) throw error;
712
+ return { clientId: input.clientId, state: "unsafe", installed, configPath,
713
+ reason: "unresolvable-path",
714
+ ...(record?.configPath === configPath ? { appliedAt: record.appliedAt, lastOpId: record.opId } : {}),
715
+ ...retention };
716
+ }
682
717
  if (input.clientId === "droid" && input.models.length > 0 && contribution.fragments.length === 0
683
718
  && (!record || record.configPath !== configPath)) {
684
719
  return { clientId: input.clientId, state: "unsafe", installed, configPath,
@@ -44,7 +44,7 @@ import {
44
44
  type IntegrationClientId,
45
45
  } from "./registry";
46
46
  import { declaredIntegrationTarget } from "./target";
47
- import { buildIntegrationContribution, exportContextOf } from "./state";
47
+ import { buildIntegrationContribution, exportContextOf, qoderLegacyCatalogConflict } from "./state";
48
48
  import type { IntegrationState } from "./state";
49
49
  import { serializeDocument, UnserializableValueError } from "./serialize";
50
50
  import { ClientPathError } from "../clients/config-export";
@@ -317,6 +317,10 @@ function applyOrRefreshIntegration(
317
317
  : `${clientId} now reads its providers from ${readsFrom}, whose schema opencodex does not recognise, so writing ${configPath} would change nothing it loads. ${fallback}`);
318
318
  }
319
319
  if (classified.state === "conflict") {
320
+ if (qoderLegacyCatalogConflict(parsed, record, contribution)) {
321
+ return refuse(clientId, "conflict", "conflict",
322
+ `${configPath} lists an opencodex model in modelConfigs.customModels that opencodex did not write; Qoder rejects the opencodex provider while that row exists, so remove or rename it first`);
323
+ }
320
324
  if (conflictPolicy === "refuse") {
321
325
  return refuse(clientId, "conflict", "conflict",
322
326
  classified.reason === "foreign-edit"
@@ -545,7 +549,7 @@ export function refreshIntegration(input: IntegrationWriteInput): WriteOutcome {
545
549
  export function disableIntegration(input: IntegrationWriteInput): WriteOutcome {
546
550
  const pre = preflight(input, "disable");
547
551
  if (pre.failed) return pre.failed;
548
- const { store, io, clientId, spec, target, configPath, before, parsed, record, classified } = pre;
552
+ const { store, io, clientId, spec, target, configPath, before, parsed, record, classified, contribution } = pre;
549
553
 
550
554
  if (classified.state === "absent") {
551
555
  return { ok: true, changed: false, state: "absent", clientId, message: "not applied" };
@@ -554,7 +558,9 @@ export function disableIntegration(input: IntegrationWriteInput): WriteOutcome {
554
558
  return refuse(clientId, "conflict", "conflict",
555
559
  classified.reason === "foreign-edit"
556
560
  ? `${configPath} changed after opencodex wrote it; disabling would discard that edit`
557
- : `${configPath} contains an opencodex block we did not write`);
561
+ : qoderLegacyCatalogConflict(parsed, record, contribution)
562
+ ? `${configPath} lists an opencodex model in modelConfigs.customModels that opencodex did not write; remove or rename that row, then disable again`
563
+ : `${configPath} contains an opencodex block we did not write`);
558
564
  }
559
565
  /*
560
566
  * `unsafe` reaches here the same way it reaches apply, and the code below
@@ -823,6 +829,12 @@ export interface CoordinatedIntegrationOptions {
823
829
  * `revalidate` and any lock acquisition). A non-null result refuses without writing.
824
830
  */
825
831
  guard?: (frozen: IntegrationWriteInput) => WriteOutcome | null;
832
+ /**
833
+ * Restore's own synchronous last word, evaluated immediately before the restore transaction
834
+ * with no await in between. Restore deliberately ignores `guard` (the background-refresh
835
+ * admission hook), so a caller that must re-prove a boundary at restore time uses this one.
836
+ */
837
+ restoreGuard?: (frozen: IntegrationWriteInput) => WriteOutcome | null;
826
838
  }
827
839
 
828
840
  /** Freeze all mutable resolution seams before the first lock await. */
@@ -1020,7 +1032,9 @@ export async function restoreIntegrationCoordinated(
1020
1032
  if (!prepared.ok) return prepared.refusal;
1021
1033
  const frozen = prepared.value;
1022
1034
  const spec = INTEGRATION_CLIENTS[frozen.clientId];
1023
- const run = () => restoreIntegration({ ...frozen, opId: input.opId, confirmDrift: input.confirmDrift });
1035
+ // Nothing awaits between restoreGuard and the restore transaction.
1036
+ const run = () => options?.restoreGuard?.(frozen)
1037
+ ?? restoreIntegration({ ...frozen, opId: input.opId, confirmDrift: input.confirmDrift });
1024
1038
  if (!spec.writerLock) {
1025
1039
  const refused = await options?.revalidate?.(frozen);
1026
1040
  return refused ?? run();
@@ -125,7 +125,8 @@ export function findPathBun({
125
125
  if (!validate(path)) continue;
126
126
  const version = probe(path, ["--version"]);
127
127
  const candidate = stableVersion(version);
128
- if (!candidate || candidate[0] !== pin[0] || candidate[1] < pin[1]) continue;
128
+ if (!candidate || candidate[0] !== pin[0] || candidate[1] < pin[1]
129
+ || (candidate[1] === pin[1] && candidate[2] < pin[2])) continue;
129
130
  if (probe(path, ["-e", IDENTITY_PROBE]) !== version) continue;
130
131
  return { path, version };
131
132
  } catch {
@@ -18,6 +18,10 @@ import type { CodexAccountCredentialRecord } from "../types";
18
18
 
19
19
  export type DecisionPoolRead = readonly { id: string; usable: boolean; windows?: readonly DecisionQuotaWindow[] }[];
20
20
  export interface MainDecisionRow { generation: number; usable: boolean }
21
+ /** Opaque, process-local producer receipt; only the active snapshot can validate it. */
22
+ export interface AntigravityQuotaReceipt { readonly kind: "antigravity" }
23
+ export interface AntigravityQuotaObservation { name: string; provider: OcxProviderConfig; receipt: AntigravityQuotaReceipt; windows: readonly DecisionQuotaWindow[] }
24
+ export interface DecisionKeyObservation { name: string; provider: OcxProviderConfig; windows: readonly DecisionQuotaWindow[] }
21
25
 
22
26
  export interface DecisionQuotaSink {
23
27
  observeKeyCredential(reference: string, resolved: string | undefined): void;
@@ -32,6 +36,8 @@ export interface DecisionQuotaSink {
32
36
  mainRosterChanged(row: MainDecisionRow | undefined): void;
33
37
  readKeyQuota(name: string, provider: OcxProviderConfig): readonly DecisionQuotaWindow[] | undefined;
34
38
  readPool(provider: string): DecisionPoolRead | undefined;
39
+ captureAntigravityReceipt(name: string, provider: OcxProviderConfig, id: string, generation: string): AntigravityQuotaReceipt | undefined;
40
+ replaceCollectedQuotas(keys: readonly DecisionKeyObservation[], oauth: readonly AntigravityQuotaObservation[]): void;
35
41
  }
36
42
 
37
43
  let sink: DecisionQuotaSink | undefined;
@@ -71,6 +77,10 @@ export function notifyCodexStoreLoaded(store: Readonly<Record<string, CodexAccou
71
77
  export function notifyMainRosterChanged(row: () => MainDecisionRow | undefined): void { forward(s => s.mainRosterChanged(row())); }
72
78
  export function readLoadedDecisionKeyQuota(name: string, provider: OcxProviderConfig): readonly DecisionQuotaWindow[] | undefined { return read(s => s.readKeyQuota(name, provider)); }
73
79
  export function readLoadedDecisionQuotaPool(provider: string): DecisionPoolRead | undefined { return read(s => s.readPool(provider)); }
80
+ /** Capture from the producer's already-loaded credential, never from a decision read. */
81
+ export function captureAntigravityQuotaReceipt(name: string, provider: OcxProviderConfig, id: string, generation: string): AntigravityQuotaReceipt | undefined { return read(s => s.captureAntigravityReceipt(name, provider, id, generation)); }
82
+ /** Accepted collector atomically replaces its key/instance evidence set. */
83
+ export function replaceCollectedDecisionQuotas(keys: readonly DecisionKeyObservation[], oauth: readonly AntigravityQuotaObservation[]): void { forward(s => s.replaceCollectedQuotas(keys, oauth)); }
74
84
 
75
85
  /** Test-only: drop any registration a previous test left behind. */
76
86
  export function resetDecisionQuotaSinkForTests(): void { sink = undefined; }
package/src/lib/errors.ts CHANGED
@@ -25,6 +25,68 @@ export const SPEND_LEDGER_STORAGE_UNAVAILABLE_CODE = "spend_ledger_storage_unava
25
25
  * envelope formatter decides whether the identity survives serialization.
26
26
  */
27
27
  export const UNDECLARED_TOOL_CALL_ERROR_CODE = "undeclared_tool_call";
28
+ /** A buffered combo child completed without the call explicitly required by tool_choice. */
29
+ export const REQUIRED_TOOL_CONTRACT_CODE = "required_tool_contract_unsatisfied";
30
+
31
+ /**
32
+ * Wire code for a provider's model-scoped plan refusal (#7684): the account's plan does not
33
+ * include the requested model. It travels as a 400 so Codex ends the turn instead of
34
+ * reconnecting through its retry budget on the upstream 403, and the shared formatter keeps it so
35
+ * combo and policy fallback can hop past the one refused target. Neither the body code nor the
36
+ * marker header is trusted: an upstream can send both. Only object identity is provenance.
37
+ */
38
+ export const MODEL_NOT_IN_PLAN_CODE = "model_not_in_plan";
39
+ /** Diagnostic `x-opencodex-refusal` value on the adapter's refusal; never read as provenance. */
40
+ export const MODEL_NOT_IN_PLAN_REFUSAL_MARKER = "model-not-in-plan";
41
+ /**
42
+ * The code a verified plan refusal carries once the response is already a 200 stream. The 400
43
+ * status can no longer stop Codex there, and it reconnects on any `response.failed` code outside
44
+ * {@link TERMINAL_REFUSAL_CODES}; `invalid_prompt` is the member that says "this request, as sent,
45
+ * cannot succeed" without naming a policy family. The message keeps `MODEL_NOT_IN_PLAN`.
46
+ */
47
+ export const MODEL_NOT_IN_PLAN_STREAM_CODE = "invalid_prompt";
48
+
49
+ /**
50
+ * Responses this process built as a verified plan refusal: the Command Code adapter's normalized
51
+ * refusal, and the client envelope `formatErrorResponse` built from one. Owned wrappers carry
52
+ * membership the way they carry non-replayability; a wrapper that drops it fails closed (no hop).
53
+ */
54
+ const verifiedPlanRefusalResponses = new WeakSet<Response>();
55
+
56
+ export function markVerifiedModelNotInPlanResponse(response: Response): void {
57
+ verifiedPlanRefusalResponses.add(response);
58
+ }
59
+
60
+ export function isVerifiedModelNotInPlanResponse(response: Response): boolean {
61
+ return verifiedPlanRefusalResponses.has(response);
62
+ }
63
+
64
+ /** True for a verified plan refusal that still carries the canonical code in its 400 body. */
65
+ export function isModelNotInPlanRefusal(response: Response, bodyCode: string | null | undefined): boolean {
66
+ return response.status === 400 && bodyCode === MODEL_NOT_IN_PLAN_CODE && verifiedPlanRefusalResponses.has(response);
67
+ }
68
+
69
+ /**
70
+ * The proxy's own fixed message from a verified plan refusal's body, or `undefined` for any other
71
+ * response. Sidecar loops rebuild a failed iteration as their own error envelope and use this to
72
+ * keep the actionable copy; the text is trusted only because the marked object is ours.
73
+ */
74
+ export function verifiedPlanRefusalMessage(response: Response, bodyText: string): string | undefined {
75
+ if (response.status !== 400 || !verifiedPlanRefusalResponses.has(response)) return undefined;
76
+ try {
77
+ const error = (JSON.parse(bodyText) as { error?: { code?: unknown; message?: unknown } }).error;
78
+ return error?.code === MODEL_NOT_IN_PLAN_CODE && typeof error.message === "string" ? error.message : undefined;
79
+ } catch { return undefined; }
80
+ }
81
+
82
+ /**
83
+ * Whether a code names the plan refusal in any spelling combo failover folds into it (case,
84
+ * surrounding space, hyphens). The trust gate has to match the same set, or an unmarked
85
+ * `MODEL_NOT_IN_PLAN` would pass the gate and still be read as the hop code downstream.
86
+ */
87
+ export function namesModelNotInPlanCode(code: string | null | undefined): boolean {
88
+ return typeof code === "string" && code.trim().toLowerCase().replaceAll("-", "_") === MODEL_NOT_IN_PLAN_CODE;
89
+ }
28
90
 
29
91
  /** First nonblank string across the canonical upstream error paths, in priority order. */
30
92
  export function upstreamErrorMessageFromPayload(payload: unknown): string | undefined {