@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
@@ -9,16 +9,17 @@
9
9
  *
10
10
  * The one thing an app-server restart cannot refresh is the picker: the renderer builds
11
11
  * the roster once when the shell launches, and `model_catalog_json` is startup-only. So
12
- * the shell has to restart only when it launched before the catalog it should show was
13
- * written. The catalog writer skips byte-identical rewrites to keep this mtime honest
14
- * (`src/codex/catalog/retained-sync.ts`), which is what makes the comparison usable.
12
+ * a running shell has to restart unless there is affirmative evidence that it loaded the
13
+ * current binding. The catalog writer skips byte-identical rewrites
14
+ * (`src/codex/catalog/retained-sync.ts`), so a file timestamp alone is not that evidence.
15
15
  *
16
16
  * The mtime only means something for the catalog `config.toml` actually binds. With no
17
17
  * `model_catalog_json` the shell shows Codex's own roster, which no local file dates, so
18
18
  * an unbound config is `unknown`. `config.toml`'s own mtime is no substitute: injection
19
19
  * rewrites it on every sync even when the bytes are identical. A binding changed by THIS
20
- * request's sync is caught by the caller comparing it across the sync; one changed by an
21
- * earlier sync over a byte-identical catalog file is not observable here.
20
+ * request's sync is caught by the caller comparing it across the sync. If the shell is
21
+ * newer than the catalog, however, its launch time cannot prove which binding it loaded:
22
+ * an earlier sync may have rebound an already-existing, byte-identical catalog.
22
23
  *
23
24
  * Anything we cannot read answers `unknown`, and the caller falls back to the full
24
25
  * desktop restart: a stale picker the operator asked us to fix is the failure this
@@ -38,8 +39,8 @@ export type DesktopPickerState = CodexDesktopPickerState;
38
39
  * Pure decision. `shellStartsMs === null` means the shells could not be listed; a null
39
40
  * entry means one shell's start time was unreadable.
40
41
  *
41
- * Strictly later, never equal: macOS `ps lstart` has one-second granularity, so a shell
42
- * that started in the same second as the catalog write may predate it.
42
+ * A shell no newer than the catalog is definitely stale. A newer shell is `unknown`, not
43
+ * current, because timestamps carry no evidence of which catalog binding it loaded.
43
44
  */
44
45
  export function classifyDesktopPicker(
45
46
  shellStartsMs: readonly (number | null)[] | null,
@@ -48,8 +49,9 @@ export function classifyDesktopPicker(
48
49
  if (shellStartsMs === null) return "unknown";
49
50
  if (shellStartsMs.length === 0) return "not_running";
50
51
  if (catalogMtimeMs === null) return "unknown";
52
+ if (shellStartsMs.some(start => start !== null && start <= catalogMtimeMs)) return "stale";
51
53
  if (shellStartsMs.some(start => start === null)) return "unknown";
52
- return shellStartsMs.every(start => start! > catalogMtimeMs) ? "current" : "stale";
54
+ return "unknown";
53
55
  }
54
56
 
55
57
  export interface DesktopPickerIo extends DesktopAppRestartIo {
@@ -1,13 +1,61 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { win32 } from "node:path";
3
+ import { createHash } from "node:crypto";
3
4
  import { isTestHomeGuardArmed } from "../../lib/test-home-guard";
4
5
  import { resolveTrustedWindowsPowerShellExe } from "../../lib/windows-elevation";
5
- import { parseWindowsDesktopPackage, WINDOWS_PACKAGE_DISCOVERY_SCRIPT } from "../desktop-app/windows";
6
6
  import type { DesktopAppInstall } from "../desktop-app/types";
7
7
 
8
8
  export const DESKTOP_COMPATIBILITY_ASSESSED_VERSION = "26.924.2738.0";
9
9
  export const DESKTOP_COMPATIBILITY_ASSESSED_FAMILY = "OpenAI.Codex_2p2nqsd0c76g0";
10
10
 
11
+ /** Internal observation only; never returned by management status. */
12
+ export interface DesktopPackageObservation extends DesktopAppInstall {
13
+ proof?: { packageFullName: string; publisherId: string; publisher: string; manifestName: string;
14
+ manifestPublisher: string; manifestVersion: string; appId: string; executable: string;
15
+ canonicalExecutable: string; manifestDigest: string; executableIdentity: string; ancestryIdentity: string };
16
+ }
17
+
18
+ /** Shared only with owned-path fixtures. Metadata walk, not handle-bound final-path attestation. */
19
+ export const DESKTOP_PACKAGE_PATH_GUARD_SCRIPT = [
20
+ "function Assert-DesktopPackagePath([string]$Path){",
21
+ String.raw`if($Path.Length -gt 8192 -or $Path -notmatch '^[A-Za-z]:\\' -or [IO.Path]::GetFullPath($Path) -ine $Path){throw 'Noncanonical package path'}`,
22
+ "$volume=[IO.Path]::GetPathRoot($Path); $current=$volume; $parts=@($Path.Substring($volume.Length).Split('\\')|Where-Object {$_ -ne ''})",
23
+ "if($parts.Count -gt 128){throw 'Package ancestry too deep'}; $seen=[Collections.Generic.List[string]]::new()",
24
+ "for($i=-1;$i -lt $parts.Count;$i++){",
25
+ "if($i -ge 0){$current=Join-Path $current $parts[$i]}; $item=Get-Item -LiteralPath $current -Force",
26
+ "if(($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -or ($i -lt $parts.Count-1 -and -not $item.PSIsContainer)){throw 'Reparse package ancestry'}",
27
+ "$seen.Add($item.FullName.ToLowerInvariant()+':'+$item.CreationTimeUtc.Ticks)",
28
+ "}; return ($seen -join '|')",
29
+ "}",
30
+ ].join("; ");
31
+
32
+ // Compatibility-only read: do not alter general discovery or execute/activate the application.
33
+ export const DESKTOP_PACKAGE_PROOF_SCRIPT = [
34
+ "$ErrorActionPreference='Stop'; Import-Module Appx -ErrorAction Stop",
35
+ DESKTOP_PACKAGE_PATH_GUARD_SCRIPT,
36
+ "$packages=@(Get-AppxPackage -Name OpenAI.Codex)",
37
+ "if($packages.Count -ne 1){throw 'Package not unique'}; $p=$packages[0]",
38
+ // Walk from volume root down, rejecting junctions before reading the manifest/executable.
39
+ "$exePath=Join-Path $p.InstallLocation 'app\\ChatGPT.exe'; $manifestPath=Join-Path $p.InstallLocation 'AppxManifest.xml'",
40
+ "$exeChain=Assert-DesktopPackagePath $exePath; $manifestChain=Assert-DesktopPackagePath $manifestPath",
41
+ "$root=Get-Item -LiteralPath $p.InstallLocation; $app=Get-Item -LiteralPath (Join-Path $root.FullName 'app')",
42
+ "$exe=Get-Item -LiteralPath (Join-Path $app.FullName 'ChatGPT.exe')",
43
+ "foreach($item in @($root,$app,$exe)){if($item.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Reparse identity'}}",
44
+ "if(-not $root.PSIsContainer -or -not $app.PSIsContainer -or $exe.PSIsContainer){throw 'Wrong file kind'}",
45
+ "$manifest=Get-AppxPackageManifest -Package $p.PackageFullName",
46
+ "$entry=@($manifest.Package.Applications.Application|Where-Object {$_.Id -eq 'App'})",
47
+ "if($entry.Count -ne 1){throw 'App not unique'}; $entry=$entry[0]",
48
+ "$xml=[Text.Encoding]::UTF8.GetBytes($manifest.OuterXml); if($xml.Length -gt 1048576){throw 'Manifest too large'}",
49
+ "$sha=[Security.Cryptography.SHA256]::Create(); try{$digest=([BitConverter]::ToString($sha.ComputeHash($xml))).Replace('-','').ToLowerInvariant()}finally{$sha.Dispose()}",
50
+ // Revalidate the whole chain before further file reads and immediately before publication.
51
+ "if((Assert-DesktopPackagePath $exePath) -cne $exeChain -or (Assert-DesktopPackagePath $manifestPath) -cne $manifestChain){throw 'Package ancestry changed'}",
52
+ "$again=@(Get-AppxPackage -Name OpenAI.Codex); $exeAgain=Get-Item -LiteralPath $exe.FullName",
53
+ "if($again.Count -ne 1 -or $again[0].PackageFullName -cne $p.PackageFullName -or $again[0].Publisher -cne $p.Publisher -or $again[0].InstallLocation -ine $p.InstallLocation -or ($exeAgain.Attributes -band [IO.FileAttributes]::ReparsePoint) -or $exeAgain.Length -ne $exe.Length -or $exeAgain.CreationTimeUtc.Ticks -ne $exe.CreationTimeUtc.Ticks -or $exeAgain.LastWriteTimeUtc.Ticks -ne $exe.LastWriteTimeUtc.Ticks){throw 'Package changed during proof'}",
54
+ "if((Assert-DesktopPackagePath $exePath) -cne $exeChain -or (Assert-DesktopPackagePath $manifestPath) -cne $manifestChain){throw 'Package ancestry changed'}",
55
+ "$sha=[Security.Cryptography.SHA256]::Create(); try{$ancestry=([BitConverter]::ToString($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($exeChain+'|'+$manifestChain)))).Replace('-','').ToLowerInvariant()}finally{$sha.Dispose()}",
56
+ "[pscustomobject]@{id=$p.PackageFamilyName;root=$root.FullName;relaunch=$p.PackageFamilyName+'!App';proof=@{packageFullName=$p.PackageFullName;publisherId=$p.PublisherId;publisher=$p.Publisher;manifestName=[string]$manifest.Package.Identity.Name;manifestPublisher=[string]$manifest.Package.Identity.Publisher;manifestVersion=[string]$manifest.Package.Identity.Version;appId=[string]$entry.Id;executable=[string]$entry.Executable;canonicalExecutable=$exe.FullName;manifestDigest=$digest;executableIdentity=([string]$exe.Length+':'+$exe.CreationTimeUtc.Ticks+':'+$exe.LastWriteTimeUtc.Ticks);ancestryIdentity=$ancestry}}|ConvertTo-Json -Depth 3 -Compress",
57
+ ].join("; ");
58
+
11
59
  /** Last completed probe outcome. Only public package facts: never paths, keys or account data. */
12
60
  export interface DesktopBuildAssessment {
13
61
  assessedVersion: string;
@@ -16,24 +64,47 @@ export interface DesktopBuildAssessment {
16
64
  completedAt: number;
17
65
  }
18
66
 
19
- function assessInstalledPackage(install: DesktopAppInstall): { observedVersion: string | null; verified: boolean } {
67
+ function assessInstalledPackage(install: DesktopPackageObservation): { observedVersion: string | null; verified: boolean; identity: string | null } {
20
68
  const name = win32.basename(install.root);
21
69
  const parts = /^OpenAI\.Codex_(\d+\.\d+\.\d+\.\d+)_(x64|arm64|x86|neutral)_([A-Za-z0-9.-]*)_([A-Za-z0-9]+)$/.exec(name);
22
70
  const identified = install.id === DESKTOP_COMPATIBILITY_ASSESSED_FAMILY && install.relaunch === `${install.id}!App`
23
71
  && !!parts && `OpenAI.Codex_${parts[4]}` === install.id;
24
72
  const observedVersion = identified ? parts![1] : null;
25
- return { observedVersion, verified: identified && observedVersion === DESKTOP_COMPATIBILITY_ASSESSED_VERSION };
73
+ const proof = install.proof;
74
+ const verified = identified && observedVersion === DESKTOP_COMPATIBILITY_ASSESSED_VERSION && !!proof
75
+ && /^[A-Za-z]:\\/.test(install.root) && win32.normalize(install.root) === install.root
76
+ && proof.packageFullName === name && proof.publisherId === "2p2nqsd0c76g0"
77
+ && typeof proof.publisher === "string" && proof.publisher.length > 0 && proof.publisher.length <= 1024
78
+ && proof.manifestName === "OpenAI.Codex" && proof.manifestPublisher === proof.publisher
79
+ && proof.manifestVersion === observedVersion && proof.appId === "App"
80
+ && typeof proof.executable === "string" && proof.executable.replaceAll("/", "\\").toLowerCase() === "app\\chatgpt.exe"
81
+ && proof.canonicalExecutable === win32.join(install.root, "app", "ChatGPT.exe")
82
+ && /^[a-f0-9]{64}$/.test(proof.manifestDigest) && /^[a-f0-9]{64}$/.test(proof.ancestryIdentity)
83
+ && /^\d{1,16}:\d{1,20}:\d{1,20}$/.test(proof.executableIdentity);
84
+ const identity = verified && proof ? createHash("sha256").update(JSON.stringify([install.id, install.root, install.relaunch,
85
+ proof.packageFullName, proof.publisherId, proof.publisher, proof.manifestName, proof.manifestPublisher,
86
+ proof.manifestVersion, proof.appId, proof.executable, proof.canonicalExecutable, proof.manifestDigest,
87
+ proof.executableIdentity, proof.ancestryIdentity])).digest("hex") : null;
88
+ return { observedVersion, verified, identity };
26
89
  }
27
90
 
28
91
  /** Resolve only after the exact asynchronous child has closed, including abort/timeout. */
29
- function queryInstalledPackage(signal: AbortSignal): Promise<DesktopAppInstall | null> {
92
+ function queryInstalledPackage(signal: AbortSignal): Promise<DesktopPackageObservation | null> {
30
93
  if (process.platform !== "win32" || isTestHomeGuardArmed() || signal.aborted) return Promise.resolve(null);
31
94
  return new Promise(resolve => {
32
- let completed = false, closed = false, result: DesktopAppInstall | null = null;
95
+ let completed = false, closed = false, result: DesktopPackageObservation | null = null;
33
96
  const finish = () => { if (completed && closed) { signal.removeEventListener("abort", abort); resolve(result); } };
34
- const child = execFile(resolveTrustedWindowsPowerShellExe(), ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_PACKAGE_DISCOVERY_SCRIPT], {
97
+ const child = execFile(resolveTrustedWindowsPowerShellExe(), ["-NoProfile", "-NonInteractive", "-Command", DESKTOP_PACKAGE_PROOF_SCRIPT], {
35
98
  timeout: 10000, maxBuffer: 65536, encoding: "utf8", windowsHide: true,
36
- }, (error, stdout) => { result = error ? null : parseWindowsDesktopPackage(stdout); completed = true; finish(); });
99
+ }, (error, stdout) => {
100
+ try {
101
+ const value = error ? null : JSON.parse(stdout);
102
+ if (value && typeof value === "object" && !Array.isArray(value) && typeof value.id === "string"
103
+ && typeof value.root === "string" && typeof value.relaunch === "string"
104
+ && value.proof && typeof value.proof === "object" && !Array.isArray(value.proof)) result = value;
105
+ } catch { /* An unverifiable package never inherits a completed success. */ }
106
+ completed = true; finish();
107
+ });
37
108
  const abort = () => { try { child.kill(); } catch { /* Keep ownership until execFile reports close. */ } };
38
109
  child.once("close", () => { closed = true; finish(); });
39
110
  signal.addEventListener("abort", abort, { once: true });
@@ -42,12 +113,15 @@ function queryInstalledPackage(signal: AbortSignal): Promise<DesktopAppInstall |
42
113
  }
43
114
 
44
115
  /** Coalesce concurrent fresh probes; never cache a positive verdict across requests. */
45
- export function createInstalledBuildProbe(query: (signal: AbortSignal) => Promise<DesktopAppInstall | null> = queryInstalledPackage) {
116
+ export function createInstalledBuildProbe(query: (signal: AbortSignal) => Promise<DesktopPackageObservation | null> = queryInstalledPackage) {
46
117
  let pending: Promise<boolean> | null = null, controller: AbortController | null = null, closed = false;
47
118
  let lastResult: DesktopBuildAssessment | null = null;
48
- const record = (install: DesktopAppInstall | null) => {
49
- const outcome = install ? assessInstalledPackage(install) : { observedVersion: null, verified: false };
50
- lastResult = { assessedVersion: DESKTOP_COMPATIBILITY_ASSESSED_VERSION, ...outcome, completedAt: Date.now() };
119
+ let identity: string | null = null, revision = 0;
120
+ const record = (install: DesktopPackageObservation | null) => {
121
+ const outcome = install ? assessInstalledPackage(install) : { observedVersion: null, verified: false, identity: null };
122
+ if (outcome.identity !== identity) { identity = outcome.identity; revision++; }
123
+ lastResult = { assessedVersion: DESKTOP_COMPATIBILITY_ASSESSED_VERSION, observedVersion: outcome.observedVersion,
124
+ verified: outcome.verified, completedAt: Date.now() };
51
125
  return outcome.verified;
52
126
  };
53
127
  return {
@@ -63,7 +137,9 @@ export function createInstalledBuildProbe(query: (signal: AbortSignal) => Promis
63
137
  },
64
138
  /** Last completed check only: an aborted or in-flight query never rewrites it. */
65
139
  lastResult(): DesktopBuildAssessment | null { return lastResult ? { ...lastResult } : null; },
66
- async close(): Promise<void> { closed = true; controller?.abort(); await pending; },
140
+ /** Private consent fence: a completed A->B->A proof is distinct from unchanged A. */
141
+ binding() { return { identity, revision }; },
142
+ async close(): Promise<void> { closed = true; identity = null; revision++; controller?.abort(); await pending; },
67
143
  };
68
144
  }
69
145
 
@@ -39,16 +39,34 @@ export function createDesktopCompatibilityRuntime(io: DesktopRuntimeIo = {}) {
39
39
  const platform = io.platform ?? process.platform;
40
40
  let buildProbe: ReturnType<typeof createInstalledBuildProbe> | undefined;
41
41
  let previousBuildAssessment: DesktopBuildAssessment | null = null;
42
+ let boundBuild: { probe: ReturnType<typeof createInstalledBuildProbe>; revision: number } | null = null;
43
+ let invalidateTrial: (() => void) | undefined;
44
+ let contextEpoch = 0;
42
45
  const buildSupported = io.buildSupported ?? (() => buildProbe?.check() ?? Promise.resolve(false));
43
46
  let routingSupported = io.routingSupported ?? (() => false);
44
47
  let contextFailure: "build_unverified" | "native_routing_unverified" | null = null;
45
48
  const contextValid = async () => {
49
+ const epoch = contextEpoch, probe = buildProbe;
46
50
  try {
47
- if (!routingSupported()) { contextFailure = "native_routing_unverified"; return false; }
51
+ if (!routingSupported()) { contextFailure = "native_routing_unverified"; invalidateTrial?.(); return false; }
48
52
  const supported = await buildSupported();
53
+ // An old probe completion must not invalidate a replacement runtime's consent.
54
+ if (epoch !== contextEpoch || probe !== buildProbe) return false;
55
+ if (!io.buildSupported && probe) {
56
+ const binding = probe.binding();
57
+ const changed = boundBuild?.probe === probe && boundBuild.revision !== binding.revision;
58
+ boundBuild = { probe, revision: binding.revision };
59
+ if (!supported || !binding.identity || changed) {
60
+ contextFailure = "build_unverified"; invalidateTrial?.(); return false;
61
+ }
62
+ }
49
63
  contextFailure = !routingSupported() ? "native_routing_unverified" : !supported ? "build_unverified" : null;
50
64
  }
51
- catch { contextFailure = "build_unverified"; }
65
+ catch {
66
+ if (epoch !== contextEpoch || probe !== buildProbe) return false;
67
+ contextFailure = "build_unverified";
68
+ }
69
+ if (contextFailure) invalidateTrial?.();
52
70
  return contextFailure === null;
53
71
  };
54
72
  let phase: "off" | "starting" | "running" | "stopping" | "cleanup-required" = "off";
@@ -63,14 +81,17 @@ export function createDesktopCompatibilityRuntime(io: DesktopRuntimeIo = {}) {
63
81
  if (phase === "starting") throw new Error("desktop_compatibility_busy");
64
82
  if (closing) { await closing; return status(); }
65
83
  if (!pendingCleanup) return status();
84
+ contextEpoch++; invalidateTrial?.();
66
85
  phase = "stopping";
67
- closing = pendingCleanup().then(() => { owned = null; pendingCleanup = null; phase = "off"; releaseOwner?.(); releaseOwner = null; })
86
+ closing = pendingCleanup().then(() => { owned = null; pendingCleanup = null; invalidateTrial = undefined; boundBuild = null;
87
+ phase = "off"; releaseOwner?.(); releaseOwner = null; })
68
88
  .catch(error => { phase = "cleanup-required"; throw error; }).finally(() => { closing = null; });
69
89
  await closing; return status();
70
90
  }
71
91
  async function start() {
72
92
  if (phase !== "off") throw new Error("desktop_compatibility_busy");
73
93
  if (platform !== "win32") throw new Error("desktop_compatibility_unsupported");
94
+ contextEpoch++; boundBuild = null; invalidateTrial = undefined;
74
95
  if (io.testOnlyBuildProbe && (!io.testOnly || io.buildSupported)) throw new Error("desktop_compatibility_test_environment");
75
96
  if ((isTestHomeGuardArmed() || io.testOnlyBuildProbe) && !(io.testOnly && io.identity && io.loadAuthority && io.trust && (io.buildSupported || io.testOnlyBuildProbe) && io.connectionStore && io.routingSupported)) throw new Error("desktop_compatibility_test_environment");
76
97
  if (didRunOptionalShutdownHooks()) throw new Error("desktop_compatibility_stopping");
@@ -114,6 +135,8 @@ export function createDesktopCompatibilityRuntime(io: DesktopRuntimeIo = {}) {
114
135
  if (!account) throw new Error("desktop_compatibility_native_identity_unverified");
115
136
  if (didRunOptionalShutdownHooks()) throw new Error("desktop_compatibility_stopping");
116
137
  controller = new UsageRelayController(account, identity.readCurrentIdentity, identity.verifyFreshIdentity, Date.now, deadline, 180000, contextValid);
138
+ const trialController = controller;
139
+ invalidateTrial = () => trialController.invalidateContext();
117
140
  relay = await startDesktopRelay({ leaf: issueServerLeaf(authority.authority, authority.commonName, ["chatgpt.com"]),
118
141
  fetchImpl: createUsageControlledFetch(controller, io.upstreamFetch ?? desktopOutboundFetch as typeof fetch) });
119
142
  try { proxy = await startConnectProxy(previousConnection?.connectPort ?? 0, { interceptPort: relay.port, interceptHosts: ["chatgpt.com"], allowedTargets: ["chatgpt.com:443"] }); }
@@ -150,7 +173,8 @@ export function createDesktopCompatibilityRuntime(io: DesktopRuntimeIo = {}) {
150
173
  detach = registerOptionalShutdownHook("codex-desktop-compatibility", () => { void stop().catch(() => {}); });
151
174
  return status();
152
175
  } catch (error) {
153
- try { await cleanup(); pendingCleanup = null; phase = "off"; releaseOwner?.(); releaseOwner = null; }
176
+ try { await cleanup(); pendingCleanup = null; invalidateTrial = undefined; boundBuild = null;
177
+ phase = "off"; releaseOwner?.(); releaseOwner = null; }
154
178
  catch { phase = "cleanup-required"; throw new Error("desktop_compatibility_cleanup_incomplete"); }
155
179
  throw error;
156
180
  }
@@ -160,8 +184,8 @@ export function createDesktopCompatibilityRuntime(io: DesktopRuntimeIo = {}) {
160
184
  if (!current || phase !== "running") throw new Error("desktop_compatibility_not_running");
161
185
  const generation = current.controller.snapshot().generation, valid = await contextValid();
162
186
  if (owned !== current || phase !== "running") throw new Error("desktop_compatibility_not_running");
163
- if (generation !== current.controller.snapshot().generation) return { accepted: false, reason: "superseded", ...current.controller.snapshot() };
164
187
  if (!valid) { await current.controller.observeOnly(); throw new Error(`desktop_compatibility_${contextFailure}`); }
188
+ if (generation !== current.controller.snapshot().generation) return { accepted: false, reason: "superseded", ...current.controller.snapshot() };
165
189
  const result = await current.controller.activate({ scope: "account-ui-compatibility", accountWideConsent });
166
190
  if (owned !== current || phase !== "running") { await current.controller.observeOnly(); return { ...result, accepted: false, reason: "runtime-stopped" }; }
167
191
  return result;
@@ -40,7 +40,8 @@ export class UsageActivation {
40
40
  const beforeVerification=this.generation,binding=this.binding;
41
41
  let verified:string|null;
42
42
  try{verified=await this.verifyIdentity();}catch{verified=null;}
43
- if(verified!==binding||this.binding!==binding||this.generation!==beforeVerification)return{accepted:false,reason:'identity-not-verified',...this.snapshot()};
43
+ if(this.binding!==binding||this.generation!==beforeVerification)return{accepted:false,reason:'identity-not-verified',...this.snapshot()};
44
+ if(verified!==binding){this.invalidateIdentity();return{accepted:false,reason:'identity-not-verified',...this.snapshot()};}
44
45
  if(this.mode==='apply')return{accepted:false,reason:'activation-already-pending',...this.snapshot()};
45
46
  const age=this.latest?this.clock()-this.latest.at:Infinity;
46
47
  if(!this.latest||this.latest.kind!=='exhausted'||age<0||age>300000)return{accepted:false,reason:'no-fresh-eligible-exhaustion',...this.snapshot()};
@@ -46,6 +46,8 @@ export class UsageRelayController {
46
46
  return this.activation.activate(options);
47
47
  }
48
48
  observeOnly() { return this.activation.observeOnly(); }
49
+ /** Internal package-proof revocation; synchronous so pending output loses its generation first. */
50
+ invalidateContext() { this.activation.invalidateIdentity(); }
49
51
  expireIfNeeded() { return this.activation.expireIfNeeded(); }
50
52
  registerStream(exchange: Exchange, close: () => Promise<void>): Registration | null {
51
53
  if (exchange.status !== 200) return null;
@@ -72,7 +74,13 @@ export class UsageRelayController {
72
74
  || !Number.isSafeInteger(envelope.sequence) || Number(envelope.sequence) <= 0))) { stream?.exclude(); return null; }
73
75
  const original = envelope ? envelope.usage : parsed;
74
76
  if (!object(original) || original.account_id !== this.account.id || original.user_id !== this.account.userId
75
- || original.plan_type !== this.account.plan) { stream?.exclude(); return null; }
77
+ || original.plan_type !== this.account.plan) {
78
+ if (object(original) && [[original.account_id, this.account.id], [original.user_id, this.account.userId],
79
+ [original.plan_type, this.account.plan]].some(([actual, expected]) => typeof actual === 'string' && actual.length > 0 && actual !== expected)) {
80
+ this.activation.invalidateIdentity();
81
+ }
82
+ stream?.exclude(); return null;
83
+ }
76
84
  const rate = original.rate_limit;
77
85
  if (!object(rate) || typeof rate.allowed !== 'boolean' || typeof rate.limit_reached !== 'boolean') {
78
86
  stream?.exclude(); return null;
@@ -9,6 +9,26 @@ export type DesktopCertificateTrust = "trusted" | "not-trusted" | "unknown";
9
9
  export type TrustOperation = "inspect" | "trust" | "remove";
10
10
  export type CertificateTrustRunner = (operation: TrustOperation, certificateDer: string, fingerprint: string) => Promise<DesktopCertificateTrust>;
11
11
 
12
+ /** Public status is an interactive read; a store that cannot answer within it reports `unknown`. */
13
+ export const TRUST_INSPECT_DEADLINE_MS = 10_000;
14
+ /** A mutation may wait on the user's certificate prompt. */
15
+ export const TRUST_CHANGE_DEADLINE_MS = 120_000;
16
+
17
+ /** The slice of `child_process.execFile` the runner uses, so a deadline breach can be driven without a real store. */
18
+ export type TrustCommandExec = (
19
+ file: string,
20
+ args: string[],
21
+ options: { timeout: number; maxBuffer: number; windowsHide: boolean; encoding: "utf8" },
22
+ callback: (error: Error | null, stdout: string) => void,
23
+ ) => { stdin?: { on(event: "error", listener: () => void): unknown; end(chunk: string): unknown } | null };
24
+
25
+ export type PowerShellTrustRunnerOptions = {
26
+ inspectDeadlineMs?: number;
27
+ platform?: NodeJS.Platform;
28
+ exec?: TrustCommandExec;
29
+ resolvePowerShell?: () => string;
30
+ };
31
+
12
32
  const SCRIPT = [
13
33
  "$ErrorActionPreference='Stop'",
14
34
  "$inputData=[Console]::In.ReadToEnd()|ConvertFrom-Json",
@@ -31,18 +51,32 @@ const SCRIPT = [
31
51
  "}finally{$store.Close();$store.Dispose();$cert.Dispose()}",
32
52
  ].join("\n");
33
53
 
34
- const run: CertificateTrustRunner = (operation, certificateDer, fingerprint) => {
35
- if (process.platform !== "win32") return Promise.resolve("unknown");
36
- if (operation !== "inspect" && isTestHomeGuardArmed()) return Promise.resolve("unknown");
37
- return new Promise(resolve => {
38
- const child = execFile(resolveTrustedWindowsPowerShellExe(), ["-NoProfile", "-NonInteractive", "-Command", SCRIPT], {
39
- timeout: operation === "inspect" ? 10_000 : 120_000, maxBuffer: 4096, windowsHide: true, encoding: "utf8",
40
- }, (error, stdout) => resolve(!error && (stdout.trim() === "trusted" || stdout.trim() === "not-trusted")
41
- ? stdout.trim() as DesktopCertificateTrust : "unknown"));
42
- child.stdin?.on("error", () => { /* completion and readback decide the result */ });
43
- child.stdin?.end(JSON.stringify({ operation, certificate: certificateDer, fingerprint }));
44
- });
45
- };
54
+ /**
55
+ * The real CurrentUser Root runner. Any failure, including a deadline breach, is `unknown`, which
56
+ * never authorizes a write. The options exist so a test can replay this exact call with a cold-start
57
+ * deadline and can drive a breach deterministically; production uses the defaults.
58
+ */
59
+ export function createPowerShellCertificateTrustRunner({
60
+ inspectDeadlineMs = TRUST_INSPECT_DEADLINE_MS,
61
+ platform = process.platform,
62
+ exec = execFile as unknown as TrustCommandExec,
63
+ resolvePowerShell = resolveTrustedWindowsPowerShellExe,
64
+ }: PowerShellTrustRunnerOptions = {}): CertificateTrustRunner {
65
+ return (operation, certificateDer, fingerprint) => {
66
+ if (platform !== "win32") return Promise.resolve("unknown");
67
+ if (operation !== "inspect" && isTestHomeGuardArmed()) return Promise.resolve("unknown");
68
+ return new Promise(resolve => {
69
+ const child = exec(resolvePowerShell(), ["-NoProfile", "-NonInteractive", "-Command", SCRIPT], {
70
+ timeout: operation === "inspect" ? inspectDeadlineMs : TRUST_CHANGE_DEADLINE_MS, maxBuffer: 4096, windowsHide: true, encoding: "utf8",
71
+ }, (error, stdout) => resolve(!error && (stdout.trim() === "trusted" || stdout.trim() === "not-trusted")
72
+ ? stdout.trim() as DesktopCertificateTrust : "unknown"));
73
+ child.stdin?.on("error", () => { /* completion and readback decide the result */ });
74
+ child.stdin?.end(JSON.stringify({ operation, certificate: certificateDer, fingerprint }));
75
+ });
76
+ };
77
+ }
78
+
79
+ const run = createPowerShellCertificateTrustRunner();
46
80
 
47
81
  /** Public status cannot create a certificate, decrypt a key or alter OS trust. */
48
82
  export async function inspectWindowsCertificateTrust(certPem: string, expectedFingerprint: string, runner: CertificateTrustRunner = run): Promise<DesktopCertificateTrust> {
@@ -479,24 +479,6 @@ export function stripExistingModelProvider(content: string): string {
479
479
  return bom + sourceText(lines.filter((_, index) => !drop.has(index)));
480
480
  }
481
481
 
482
- /**
483
- * Drop ROOT-level `model_context_window` overrides (keys before the first table header). Codex
484
- * treats this root key as a global override that wins over the per-model catalog values, so a stale
485
- * `model_context_window = 1000000` makes every model (e.g. gpt-5.5) report a 1M window. User-owned
486
- * compaction limits do not alter the advertised context window and must survive reinjection.
487
- */
488
- export function stripRootContextWindowOverrides(content: string): string {
489
- const { bom, lines, rootEnd } = rootSourceLines(content);
490
- const drop = new Set<number>();
491
- for (let index = 0; index < rootEnd; index++) {
492
- if (!lines[index]!.structural || rootAssignmentKey(lines[index]!.text) !== "model_context_window") continue;
493
- const assignment = sourceAssignmentSpan(lines, index, rootEnd);
494
- if (!assignment) throw new Error("Cannot safely rewrite an incomplete model_context_window assignment.");
495
- for (let at = index; at < assignment.end; at++) drop.add(at);
496
- }
497
- return bom + sourceText(lines.filter((_, index) => !drop.has(index)));
498
- }
499
-
500
482
  export function stripRootRoutedModel(content: string): string {
501
483
  const { bom, lines, rootEnd } = rootSourceLines(content);
502
484
  return bom + sourceText(lines.filter((line, index) => index >= rootEnd || !line.structural
@@ -18,11 +18,12 @@ import {
18
18
  journaledInjectedOpenaiBaseUrl,
19
19
  journaledInjectedRealtimeWsBaseUrl,
20
20
  journaledInjectedRootWebSearch,
21
+ journaledInjectedSubagentDefaults,
21
22
  journaledReplacedRootWebSearch,
22
23
  } from "../journal";
23
24
  import { stripJournaledOpenaiBaseUrl } from "../injected-marker";
24
25
  import { CODEX_CONFIG_PATH, resolveCodexStateDbPath } from "../paths";
25
- import { transformManagedSubagentDefaults } from "../subagent-defaults";
26
+ import { transformManagedSubagentDefaults, type WrittenSubagentDefaults } from "../subagent-defaults";
26
27
  import type { OcxConfig } from "../../types";
27
28
  import type { CodexWriteCandidate } from "../write-coordination";
28
29
  import {
@@ -42,7 +43,6 @@ import {
42
43
  stripExistingModelProvider,
43
44
  stripInjectedOpenaiBaseUrl,
44
45
  stripOpencodexCatalogPath,
45
- stripRootContextWindowOverrides,
46
46
  } from "./config-toml";
47
47
  import { hasOcxProviderTable, removeOcxSection } from "./remove";
48
48
  import {
@@ -81,6 +81,8 @@ export interface CodexInjectionPlanOk {
81
81
  injectedRootWebSearch: string | null;
82
82
  /** The user-owned root `web_search` line this plan removed, for the journal to carry. */
83
83
  replacedRootWebSearch: string | null;
84
+ /** The marker-owned `[agents]` defaults this plan writes, for the journal to carry; null when none. */
85
+ injectedSubagentDefaults: WrittenSubagentDefaults | null;
84
86
  nativeSubagentDefaultsWarning: string | undefined;
85
87
  managedDefaultsMessage: string;
86
88
  /**
@@ -130,9 +132,12 @@ export function deriveCodexInjectionPlan(
130
132
  // root routing key: inserting that key ahead of a marker-owned first table
131
133
  // would otherwise separate the table marker from its header. Ambiguous
132
134
  // markers fail closed without writing config, profile, or journal state.
135
+ // A marked value that no longer matches the journaled write was edited by the
136
+ // user (#7425); it is adopted into the baseline instead of being cleaned.
133
137
  const nativeDefaultsBaseline = transformManagedSubagentDefaults(
134
138
  source,
135
139
  null,
140
+ journaledInjectedSubagentDefaults({ readOnly: ctx.journalReadOnly }),
136
141
  );
137
142
  if (!nativeDefaultsBaseline.ok) {
138
143
  return {
@@ -186,7 +191,8 @@ export function deriveCodexInjectionPlan(
186
191
  }
187
192
  content = removeProfileSection(content);
188
193
  content = stripExistingModelProvider(content);
189
- content = stripRootContextWindowOverrides(content);
194
+ // A root `model_context_window` is never written by OpenCodex, so it is the user's choice and
195
+ // survives injection (#7425). Codex applies it to every model ahead of the catalog's windows.
190
196
  content = normalizeServiceTier(content);
191
197
  content = ensureFastModeFeature(content, config?.fastMode);
192
198
  // Codex's own web-search switch follows the sidecar's master switch. While the sidecar is off,
@@ -291,6 +297,7 @@ export function deriveCodexInjectionPlan(
291
297
  let managedDefaultsMessage = routingOwnershipWarning
292
298
  ? ` ⚠️ ${routingOwnershipWarning}\n`
293
299
  : "";
300
+ let injectedSubagentDefaults: WrittenSubagentDefaults | null = null;
294
301
  if (managedDefaults.ok) {
295
302
  content = managedDefaults.content;
296
303
  if (desiredSubagentDefaults && managedDefaults.conflicts.length > 0) {
@@ -299,6 +306,13 @@ export function deriveCodexInjectionPlan(
299
306
  .join(", ");
300
307
  nativeSubagentDefaultsWarning = `Native Codex sub-agent defaults were not injected: user-owned ${keys} preserved.`;
301
308
  managedDefaultsMessage = ` ⚠️ ${nativeSubagentDefaultsWarning}\n`;
309
+ } else if (desiredSubagentDefaults && !keptUserBaseUrl) {
310
+ injectedSubagentDefaults = {
311
+ default_subagent_model: desiredSubagentDefaults.model,
312
+ ...(desiredSubagentDefaults.reasoningEffort !== undefined
313
+ ? { default_subagent_reasoning_effort: desiredSubagentDefaults.reasoningEffort }
314
+ : {}),
315
+ };
302
316
  }
303
317
  } else {
304
318
  const action =
@@ -388,6 +402,7 @@ export function deriveCodexInjectionPlan(
388
402
  keptUserRealtimeWsBaseUrl,
389
403
  injectedRootWebSearch: webSearch.wroteValue,
390
404
  replacedRootWebSearch: webSearch.replacedUserLine,
405
+ injectedSubagentDefaults,
391
406
  nativeSubagentDefaultsWarning,
392
407
  managedDefaultsMessage,
393
408
  historyRelabelRefusal: observedHistoryRefusal,
@@ -15,12 +15,13 @@ import {
15
15
  journaledInjectedOpenaiBaseUrl,
16
16
  journaledInjectedRealtimeWsBaseUrl,
17
17
  journaledInjectedRootWebSearch,
18
+ journaledInjectedSubagentDefaults,
18
19
  journaledReplacedRootWebSearch,
19
20
  } from "../journal";
20
21
  import { CODEX_CONFIG_PATH, CODEX_PROFILE_PATH } from "../paths";
21
22
  import { getCodexHome } from "../paths";
22
23
  import { codexHomeIsAbsent } from "../codex-home-owner";
23
- import { transformManagedSubagentDefaults } from "../subagent-defaults";
24
+ import { transformManagedSubagentDefaults, type WrittenSubagentDefaults } from "../subagent-defaults";
24
25
  import {
25
26
  applyEol,
26
27
  dominantEol,
@@ -93,6 +94,7 @@ function stripOpencodexConfigResult(
93
94
  journaledRealtimeWsBaseUrl: string | null = null,
94
95
  journaledRootWebSearch: string | null = null,
95
96
  journaledReplacedWebSearch: string | null = null,
97
+ journaledSubagentDefaults: WrittenSubagentDefaults | null = null,
96
98
  ): StripOpencodexConfigResult {
97
99
  let out = content;
98
100
  const hadRootOcxProvider =
@@ -129,7 +131,8 @@ function stripOpencodexConfigResult(
129
131
  // Routed root model ids (`model = "provider/slug"`) only make sense while the proxy serves
130
132
  // them — strip on both the legacy re-tag form and the Design B injected-base-url form.
131
133
  if (hadRootOcxProvider || hadInjectedBaseUrl) out = stripRootRoutedModel(out);
132
- const managedDefaults = transformManagedSubagentDefaults(out, null);
134
+ // A marked value the user edited after injection is theirs (#7425) and survives restore.
135
+ const managedDefaults = transformManagedSubagentDefaults(out, null, journaledSubagentDefaults);
133
136
  if (managedDefaults.ok) out = managedDefaults.content;
134
137
  out = stripOpencodexCatalogPath(out);
135
138
  return {
@@ -246,6 +249,7 @@ export function removeCodexConfig(
246
249
  journaledRealtimeWsBaseUrl,
247
250
  journaledRootWebSearch,
248
251
  journaledReplaced,
252
+ journaledInjectedSubagentDefaults(),
249
253
  );
250
254
  // Captured from the pre-strip bytes: the strip is what removes the table, so reading it
251
255
  // afterwards would find nothing.
@@ -512,6 +512,7 @@ async function injectCodexConfigImpl(
512
512
  // not durable) and the line we removed (so re-enabling the sidecar can return it).
513
513
  injectedRootWebSearch: plan.injectedRootWebSearch,
514
514
  replacedRootWebSearch: plan.replacedRootWebSearch,
515
+ injectedSubagentDefaults: plan.injectedSubagentDefaults,
515
516
  // This is the catalog artifact selected for this injection, even when config.toml
516
517
  // already points at that path and therefore needs no textual rewrite.
517
518
  injectedCatalogPath: plan.catalogPath,
@@ -896,7 +897,6 @@ export {
896
897
  setRootOpenaiBaseUrl,
897
898
  setRootRealtimeWsBaseUrl,
898
899
  stripInjectedOpenaiBaseUrl,
899
- stripRootContextWindowOverrides,
900
900
  } from "./inject/config-toml";
901
901
 
902
902
  export {