@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,6 +9,7 @@ import { hasInjectedCodexRouting } from "./injected-marker";
9
9
  import { configWriteLockFailureMessage, withConfigWriteLockHeld } from "./config-write-lock";
10
10
  import type { LockHandle } from "./config-write-lock";
11
11
  import { CODEX_HOME, CODEX_CONFIG_PATH, CODEX_PROFILE_PATH } from "./paths";
12
+ import { transformManagedSubagentDefaults, type WrittenSubagentDefaults } from "./subagent-defaults";
12
13
 
13
14
  /**
14
15
  * Exported so that anything reasoning ABOUT the journal points at the journal.
@@ -76,6 +77,15 @@ interface Journal {
76
77
  * file we actually touched.
77
78
  */
78
79
  injectedCatalogPath?: string | null;
80
+ /**
81
+ * The marker-owned `[agents]` default values this injection wrote, keyed by TOML key.
82
+ *
83
+ * #7425: the marker comment proves OpenCodex wrote a line once, not that the value is still
84
+ * ours. A user (or a comment-preserving Codex settings writer) can change the value and keep
85
+ * the comment, and the next sync used to revert it. The recorded value is what tells an
86
+ * untouched managed line apart from an edited one. Null when no managed default was written.
87
+ */
88
+ injectedSubagentDefaults?: WrittenSubagentDefaults | null;
79
89
  /** Injection binding survives native snapshot replacement and is released by native restore. */
80
90
  opencodexHome?: string;
81
91
  pid: number;
@@ -106,6 +116,17 @@ function sha256(content: string | null): string | null {
106
116
  return content === null ? null : createHash("sha256").update(content).digest("hex");
107
117
  }
108
118
 
119
+ function defaultOwnershipAllowsSnapshot(journal: Journal, config: string | null): boolean {
120
+ const written = parseInjectedSubagentDefaults(journal.injectedSubagentDefaults);
121
+ if (!written || config === null) return true;
122
+ // A first-injection hash may match after a later managed write. If the newer ownership
123
+ // evidence preserves a value that bare markers would remove, use field-level restore.
124
+ // An ambiguous transform likewise cannot authorize replaying the whole snapshot.
125
+ const byRecord = transformManagedSubagentDefaults(config, null, written);
126
+ const byMarker = transformManagedSubagentDefaults(config, null);
127
+ return byRecord.ok && byMarker.ok && byRecord.content === byMarker.content;
128
+ }
129
+
109
130
  function compareJournalState(journal: Journal, config: string | null, profile: string | null) {
110
131
  const originalConfig = Buffer.from(journal.originalConfig, "base64").toString("utf-8");
111
132
  const originalProfile = journal.originalProfile === null
@@ -120,7 +141,10 @@ function compareJournalState(journal: Journal, config: string | null, profile: s
120
141
  originalProfile,
121
142
  configAlreadyOriginal,
122
143
  profileAlreadyOriginal,
123
- configUnchanged: configAlreadyOriginal || (configHashKnown && sha256(config) === journal.injectedConfigHash),
144
+ configUnchanged: configAlreadyOriginal || (
145
+ configHashKnown && sha256(config) === journal.injectedConfigHash
146
+ && defaultOwnershipAllowsSnapshot(journal, config)
147
+ ),
124
148
  profileUnchanged: profileAlreadyOriginal || (profileHashKnown && sha256(profile) === (journal.injectedProfileHash ?? null)),
125
149
  unverified: (!configHashKnown && !configAlreadyOriginal) || (!profileHashKnown && !profileAlreadyOriginal),
126
150
  };
@@ -203,6 +227,8 @@ export interface InjectedJournalOwnership {
203
227
  injectedRootWebSearch?: string | null;
204
228
  /** Omitted by callers that removed no user `web_search` line. */
205
229
  replacedRootWebSearch?: string | null;
230
+ /** Omitted by callers that wrote no managed `[agents]` default, which is the value it then records. */
231
+ injectedSubagentDefaults?: WrittenSubagentDefaults | null;
206
232
  }
207
233
 
208
234
  export function markJournalInjectedState(
@@ -230,6 +256,7 @@ export function markJournalInjectedState(
230
256
  journal.injectedRealtimeWsBaseUrl = ownership.injectedRealtimeWsBaseUrl;
231
257
  journal.injectedRootWebSearch = ownership.injectedRootWebSearch ?? null;
232
258
  journal.replacedRootWebSearch = ownership.replacedRootWebSearch ?? null;
259
+ journal.injectedSubagentDefaults = ownership.injectedSubagentDefaults ?? null;
233
260
  journal.injectedCatalogPath = ownership.injectedCatalogPath;
234
261
  journal.opencodexHome = opencodexHomeForInjection(journal.opencodexHome);
235
262
  atomicWriteFile(JOURNAL_PATH, JSON.stringify(journal), undefined, hooks);
@@ -267,6 +294,24 @@ export function journaledInjectedCatalogPath(): string | null {
267
294
  return readJournal()?.injectedCatalogPath ?? null;
268
295
  }
269
296
 
297
+ /**
298
+ * The managed `[agents]` default values the last injection wrote, or null when there is no
299
+ * record. The journal is read from disk, so only string values for the two known keys count.
300
+ */
301
+ export function journaledInjectedSubagentDefaults(options: { readOnly?: boolean } = {}): WrittenSubagentDefaults | null {
302
+ return parseInjectedSubagentDefaults(readJournal(options.readOnly !== true)?.injectedSubagentDefaults);
303
+ }
304
+
305
+ function parseInjectedSubagentDefaults(recorded: unknown): WrittenSubagentDefaults | null {
306
+ if (typeof recorded !== "object" || recorded === null) return null;
307
+ const written: WrittenSubagentDefaults = {};
308
+ for (const key of ["default_subagent_model", "default_subagent_reasoning_effort"] as const) {
309
+ const value = (recorded as Record<string, unknown>)[key];
310
+ if (typeof value === "string") written[key] = value;
311
+ }
312
+ return Object.keys(written).length > 0 ? written : null;
313
+ }
314
+
270
315
  export function removeJournal(hooks: AtomicWriteHooks = {}): void {
271
316
  assertCodexHomeOwner(CODEX_HOME);
272
317
  hooks.validateBeforeRename?.(JOURNAL_PATH);
@@ -441,6 +486,12 @@ function warnIfJournalRetained(): void {
441
486
 
442
487
  export interface ReconcileJournalOptions {
443
488
  activeClientApiKeyId?: string;
489
+ /**
490
+ * #7423: an update stopped the previous proxy and handed its Codex routing to this one.
491
+ * A process-owned journal whose owner is gone is then adopted rather than replayed, so
492
+ * startup does not restore native config in the seconds before its own sync re-injects.
493
+ */
494
+ adoptUpdateHandover?: boolean;
444
495
  }
445
496
 
446
497
  export function reconcileJournal(options: ReconcileJournalOptions = {}): boolean {
@@ -482,6 +533,15 @@ export function reconcileJournal(options: ReconcileJournalOptions = {}): boolean
482
533
  return false;
483
534
  }
484
535
  }
536
+ if (options.adoptUpdateHandover) {
537
+ // The original baseline and injected-state hashes stay as written; only ownership moves.
538
+ // Published like every other journal write, so a replaced Codex home is refused rather
539
+ // than overwritten; a refusal preserves both the journal and the config.
540
+ const adopted = JSON.stringify({ ...journal, pid: process.pid, owner: { kind: "process", pid: process.pid } });
541
+ try { publishCodexArtifact(JOURNAL_PATH, handle, (path, hooks) => atomicWriteFile(path, adopted, undefined, hooks)); }
542
+ catch { console.error("⚠️ The Codex journal handed over by an update could not be adopted; the journal and configuration were preserved."); }
543
+ return false;
544
+ }
485
545
  const restored = restoreJournalState({ heldConfigWriteLock: handle });
486
546
  if (restored.unverified) {
487
547
  console.error("⚠️ Codex journal recovery was not verified; current configuration files and the journal were preserved.");
@@ -151,7 +151,7 @@ function composeGatedClientVersionFloor(
151
151
 
152
152
  // Reads every pinned row (codex-rs snapshot plus roster-captured rows), so a gated slug whose row
153
153
  // arrives through roster-pinned-models.json still contributes its floor. None does today:
154
- // gpt-6-sol/luna and gpt-6.1-sol are ungated, and gpt-6-astra-minor has no row and no measured minimum.
154
+ // GPT-6 Sol/Luna and GPT-6.1 Sol/Terra are ungated; Astra Minor has no row or measured minimum.
155
155
  export const GATED_MODEL_CLIENT_VERSION_FLOOR: string = composeGatedClientVersionFloor(
156
156
  pinnedNativeModelRows(),
157
157
  );
@@ -1,4 +1,4 @@
1
- import { join } from "node:path";
1
+ import { isAbsolute, join, relative, resolve, sep } from "node:path";
2
2
 
3
3
  import { Database } from "bun:sqlite";
4
4
 
@@ -299,6 +299,32 @@ export function nativeMainOwnerSnapshot(context: NativeProfileContext): NativeMa
299
299
  return entry ? { ...entry.snapshot } : null;
300
300
  }
301
301
 
302
+ /**
303
+ * Homes at or below `root` whose owner entry may still hold or reopen handles there.
304
+ *
305
+ * Conservative on purpose: besides a published database or side descriptor, an
306
+ * acquisition in flight (`drive`) holds its descriptor and database in locals until
307
+ * hardening returns, a pending retry timer will reopen them, and a detached entry is
308
+ * still closing. Removal code asks this before deleting a home. Windows refuses to
309
+ * delete a file SQLite holds open, so a removal that starts early fails with EBUSY
310
+ * only after its whole retry budget, without naming the owner.
311
+ */
312
+ export function nativeMainOwnerHomesOpenAtOrBelow(root: string): string[] {
313
+ const fold = (path: string) => (process.platform === "win32" ? resolve(path).toLowerCase() : resolve(path));
314
+ const base = fold(root);
315
+ const open: string[] = [];
316
+ const candidates = [
317
+ ...[...entries.values()].filter(entry => entry.database || entry.file || entry.drive || entry.timer),
318
+ ...detachedEntries,
319
+ ];
320
+ for (const entry of candidates) {
321
+ const suffix = relative(base, fold(entry.context.codexHome));
322
+ if (suffix === ".." || suffix.startsWith(`..${sep}`) || isAbsolute(suffix)) continue;
323
+ open.push(entry.context.codexHome);
324
+ }
325
+ return open;
326
+ }
327
+
302
328
  export function assertNativeMainOwner(context: NativeProfileContext): void {
303
329
  const entry = entries.get(context.homeId);
304
330
  if (entry?.snapshot.status === "held" && entry.database && !entry.closing) return;
@@ -353,8 +353,9 @@ export function assertNativeProfileLockPath(context: NativeProfileContext): void
353
353
  }
354
354
 
355
355
  export function resolveNativeProfileContext(options: { codexHome?: string; configDir?: string } = {}): NativeProfileContext {
356
- const codexHome = canonicalExistingDirectory(options.codexHome ?? getCodexHome(), "The effective CODEX_HOME");
356
+ // Read-only callers may tolerate an absent native home, but never unsafe OpenCodex storage.
357
357
  const configDir = canonicalizeDirectoryPath(options.configDir ?? getConfigDir());
358
+ const codexHome = canonicalExistingDirectory(options.codexHome ?? getCodexHome(), "The effective CODEX_HOME");
358
359
  const homeId = nativeProfileHomeId(codexHome);
359
360
  const foldedHomeId = process.platform === "win32" ? legacyWindowsNativeProfileHomeId(codexHome) : homeId;
360
361
  const instanceId = createHash("sha256").update(DOMAIN_INSTANCE).update(configDir).digest("hex");
@@ -1,8 +1,11 @@
1
1
  import type { OcxConfig } from "../types";
2
- import { codexUsageLimitResetAt, isCodexAccountHeldForCredits } from "./account-credit-use";
2
+ import { codexAccountUsesCreditsAfterLimit, codexUsageLimitResetAt, isCodexAccountHeldForCredits } from "./account-credit-use";
3
3
  import { MAIN_CODEX_ACCOUNT_ID } from "./main-account";
4
4
  import { isSelectableCodexPoolAccount } from "./account-id";
5
5
  import { getAccountQuota } from "./quota";
6
+ import { hasSpendableCodexCredits } from "./quota-types";
7
+ import { getCodexAccountCooldownUntil, scopedHealthFor, type CodexQuotaScope } from "./routing/health-store";
8
+ import { nextQuotaQueryDelay } from "./quota-query-backoff";
6
9
 
7
10
  export type PoolCreditPolicyConfig = Readonly<Pick<OcxConfig, "creditCodexAccountIds" | "codexAccounts">>;
8
11
  type PoolContext = { kind: "pool"; accountId: string };
@@ -65,3 +68,34 @@ export function poolContextCreditHoldResetAt(
65
68
  const catalog = override?.codexAccounts ? override : bound?.config ?? policy;
66
69
  return poolCreditHoldResetAt(policy, context.accountId, catalog, now);
67
70
  }
71
+
72
+ /** Retry advice only: absent/uncertain evidence can be re-observed, never spent. */
73
+ export function poolCreditRecoveryNeeded(policy: PoolCreditPolicyConfig, accountId: string, now = Date.now()): boolean {
74
+ if (!codexAccountUsesCreditsAfterLimit(policy, accountId)) return false;
75
+ const quota = getAccountQuota(accountId);
76
+ const credits = quota?.credits;
77
+ // Only parser-proven unavailable null is re-observable. Legacy null and known
78
+ // vetoes remain conservative; unlimited overrides balance, never an explicit veto.
79
+ if (credits === null) return quota?.creditObservationUnavailable === true;
80
+ if (credits?.allowed === false || credits?.overageLimitReached === true
81
+ || credits?.hasCredits === false || (credits?.unlimited !== true && typeof credits?.balance === "number"
82
+ && Number.isFinite(credits.balance) && credits.balance <= 0)) return false;
83
+ return !hasSpendableCodexCredits({ credits }, now);
84
+ }
85
+
86
+ /** Use the same live policy/override as the context's admission check. */
87
+ export function poolContextCreditRecoveryNeeded(context: PoolContext, override?: PoolCreditPolicyConfig): boolean {
88
+ const policy = override ?? policies.get(context)?.policy;
89
+ return !!policy && poolCreditRecoveryNeeded(policy, context.accountId);
90
+ }
91
+
92
+ /** Retry advice observes both applicable holds without changing routing's health precedence. */
93
+ export function poolCreditRecoveryRetryAt(
94
+ accountId: string, resetAt: number, quotaScope?: CodexQuotaScope, now = Date.now(),
95
+ ): number {
96
+ const scopedUntil = quotaScope ? scopedHealthFor(accountId, quotaScope)?.cooldownUntil : undefined;
97
+ const liveScopedUntil = typeof scopedUntil === "number" && Number.isFinite(scopedUntil) && scopedUntil > now
98
+ ? scopedUntil : 0;
99
+ return Math.max(Math.min(resetAt, now + nextQuotaQueryDelay()),
100
+ getCodexAccountCooldownUntil(accountId, now) ?? 0, liveScopedUntil);
101
+ }
@@ -125,6 +125,8 @@ export function noteCodexPoolRefreshFailure(
125
125
  reason: string,
126
126
  now = currentNow(),
127
127
  fence?: string,
128
+ // Resolved only when a line is actually written; the caller knows the account's durable label.
129
+ logLabel: (accountId: string) => string = fallbackCodexAccountLogLabel,
128
130
  ): { consecutiveFailures: number; cooldownUntil: number; openedWindow: boolean } {
129
131
  const existing = backoffByAccount.get(accountId);
130
132
  // A flight that started before the account's failures were cleared is speaking for a grant
@@ -153,7 +155,7 @@ export function noteCodexPoolRefreshFailure(
153
155
  const consecutiveFailures = (existing?.consecutiveFailures ?? 0) + 1;
154
156
  const cooldownUntil = now + delayFor(consecutiveFailures);
155
157
  backoffByAccount.set(accountId, { consecutiveFailures, cooldownUntil, reason });
156
- const label = fallbackCodexAccountLogLabel(accountId);
158
+ const label = logLabel(accountId);
157
159
  console.warn(
158
160
  `[codex-auth] Codex pool account ${label} credential refresh failed (${reason})`,
159
161
  );
@@ -108,6 +108,9 @@ export type StoredAccountQuota = {
108
108
  resetCredits?: number;
109
109
  /** Spendable usage credits; resetCredits are separate, manually redeemed reset tickets. */
110
110
  credits?: CodexSpendableCredits | null;
111
+ /** Only with null: provider evidence was unavailable, not a proven spending veto.
112
+ * Affects retry advice only; legacy null remains conservative. */
113
+ creditObservationUnavailable?: true;
111
114
  /** Monthly usage came from an explicitly monthly PRIMARY, not supplementary tertiary, window. */
112
115
  monthlyIsPrimaryWindow?: boolean;
113
116
  updatedAt: number;
@@ -25,6 +25,8 @@ const QUOTA_CACHE_FILENAME = "codex-quota-cache.json";
25
25
  /** Keep last-known bars across restarts; WHAM still refreshes on TTL in live/prime paths. */
26
26
  const QUOTA_DISK_MAX_AGE_MS = 6 * 60 * 60_000;
27
27
  const QUOTA_PERSIST_DEBOUNCE_MS = 250;
28
+ /** Match the reset ledger's maximum deferral under sustained quota observations. */
29
+ const QUOTA_PERSIST_MAX_DEFERRAL_MS = 1_000;
28
30
 
29
31
  type QuotaDiskFile = {
30
32
  version: 1;
@@ -39,6 +41,7 @@ type MainPolicyQuotaObservation = Omit<StoredAccountQuota, "updatedAt"> & { shor
39
41
  let mainPolicyQuota: MainPolicyQuota | null = null;
40
42
  let diskHydrated = false;
41
43
  let persistTimer: ReturnType<typeof setTimeout> | null = null;
44
+ let persistStartedAt: number | null = null;
42
45
 
43
46
  const MONTHLY_WINDOW_MIN_SECONDS = 28 * 24 * 60 * 60;
44
47
  /**
@@ -386,8 +389,11 @@ function mergeAccountQuota(
386
389
  const creditsOnly = snapshotHasCredits(quota) && !snapshotHasUsage(quota);
387
390
  // An explicit empty/invalid credits summary retracts the old balance. Partial headers
388
391
  // retain the original observation clock instead of extending its spending authority.
389
- if (quota.credits !== undefined) next.credits = quota.credits;
390
- else if (existing?.credits !== undefined) next.credits = existing.credits;
392
+ const creditSource = quota.credits !== undefined ? quota : existing;
393
+ if (creditSource?.credits !== undefined) next.credits = creditSource.credits;
394
+ if (creditSource?.credits === null && creditSource.creditObservationUnavailable === true) {
395
+ next.creditObservationUnavailable = true;
396
+ }
391
397
 
392
398
  if (creditsOnly) {
393
399
  if (existing?.weeklyPercent !== undefined) next.weeklyPercent = existing.weeklyPercent;
@@ -677,6 +683,8 @@ export function updateAccountQuota(
677
683
  ...(existing?.customWindows !== undefined ? { customWindows: existing.customWindows } : {}),
678
684
  ...(existing?.resetCredits !== undefined ? { resetCredits: existing.resetCredits } : {}),
679
685
  ...(existing?.credits !== undefined ? { credits: existing.credits } : {}),
686
+ ...(existing?.credits === null && existing.creditObservationUnavailable === true
687
+ ? { creditObservationUnavailable: true as const } : {}),
680
688
  updatedAt: Date.now(),
681
689
  };
682
690
  assignCarriedShort(quota, existing, quota.updatedAt);
@@ -736,7 +744,10 @@ function readMainPolicyQuota(value: unknown): MainPolicyQuota | null {
736
744
  }
737
745
  if (quota.monthlyPercent !== undefined && raw.monthlyIsPrimaryWindow === true) quota.monthlyIsPrimaryWindow = true;
738
746
  // Retain the independent credit timestamp on restart; it still expires at its original deadline.
739
- if (raw.credits === null) quota.credits = null;
747
+ if (raw.credits === null) {
748
+ quota.credits = null;
749
+ if (raw.creditObservationUnavailable === true) quota.creditObservationUnavailable = true;
750
+ }
740
751
  else if (raw.credits && typeof raw.credits === "object" && !Array.isArray(raw.credits)) {
741
752
  const stored = raw.credits as Record<string, unknown>;
742
753
  if (typeof stored.observedAt === "number" && Number.isFinite(stored.observedAt) && stored.observedAt >= 0) {
@@ -778,9 +789,14 @@ function hydrateAccountQuotasFromDisk(): void {
778
789
  }
779
790
 
780
791
  function schedulePersistAccountQuotas(): void {
792
+ const now = performance.now();
793
+ persistStartedAt ??= now;
794
+ const delay = Math.max(0, Math.min(QUOTA_PERSIST_DEBOUNCE_MS,
795
+ QUOTA_PERSIST_MAX_DEFERRAL_MS - (now - persistStartedAt)));
781
796
  if (persistTimer) clearTimeout(persistTimer);
782
797
  persistTimer = setTimeout(() => {
783
798
  persistTimer = null;
799
+ persistStartedAt = null;
784
800
  try {
785
801
  const quotas: Record<string, StoredAccountQuota> = {};
786
802
  for (const [accountId, quota] of accountQuota.entries()) {
@@ -796,7 +812,7 @@ function schedulePersistAccountQuotas(): void {
796
812
  } catch {
797
813
  // Best-effort persistence only.
798
814
  }
799
- }, QUOTA_PERSIST_DEBOUNCE_MS);
815
+ }, delay);
800
816
  }
801
817
 
802
818
  export function getAccountQuota(accountId: string): StoredAccountQuota | null {
@@ -861,6 +877,7 @@ export function clearAccountQuota(accountId?: string): void {
861
877
  clearTimeout(persistTimer);
862
878
  persistTimer = null;
863
879
  }
880
+ persistStartedAt = null;
864
881
  try {
865
882
  const path = join(getConfigDir(), QUOTA_CACHE_FILENAME);
866
883
  if (existsSync(path)) unlinkSync(path);
@@ -967,6 +984,9 @@ export function parseUsageQuota(data: WhamUsageResponse): Omit<StoredAccountQuot
967
984
  };
968
985
  }
969
986
  } else if (data.rate_limit?.allowed === false || creditsAllowed === false) quota.credits = null;
987
+ // A missing/malformed summary retracts spending authority, but is re-observable.
988
+ // Explicit spending vetoes and legacy unmarked null retain conservative retry advice.
989
+ if (quota.credits === null && creditsAllowed !== false) quota.creditObservationUnavailable = true;
970
990
  if (!data.rate_limit) return snapshotHasCredits(quota) ? quota : null;
971
991
  const thirtyDayOnly = codexQuotaWindowForPlan(data.plan_type) === "monthly";
972
992
  const primaryWindow = data.rate_limit.primary_window;
@@ -14,7 +14,9 @@
14
14
  * 3. Otherwise it is unclassified and never proposed.
15
15
  *
16
16
  * A role gets the cheapest sufficient model: the lowest tier at or above what it was sized for,
17
- * then the lowest price, then the picker's own order.
17
+ * then the lowest price, then the model the role already uses when it is one of the tied models,
18
+ * then the picker's own order. The picker lists native models first, so without the current-model
19
+ * step a role on a routed model moved to a native one priced and tiered the same.
18
20
  *
19
21
  * Effort binds to positions on the chosen model's ladder: glance is the floor, measured is the
20
22
  * model's default or the middle rung, exhaustive is the ceiling, and thorough is the rung above
@@ -97,6 +99,7 @@ export function classifyRoleModelCandidates(
97
99
  export function cheapestSufficientCandidate(
98
100
  classified: readonly ClassifiedCandidate[],
99
101
  tier: SizingTier,
102
+ current: string | null = null,
100
103
  ): ClassifiedCandidate | null {
101
104
  const need = SIZING_TIERS.indexOf(tier);
102
105
  const ranked = classified
@@ -104,6 +107,7 @@ export function cheapestSufficientCandidate(
104
107
  .filter(entry => entry.rank >= need)
105
108
  .sort((a, b) => a.rank - b.rank
106
109
  || (a.candidate.unitPrice ?? Infinity) - (b.candidate.unitPrice ?? Infinity)
110
+ || Number(b.candidate.model === current) - Number(a.candidate.model === current)
107
111
  || a.order - b.order);
108
112
  return ranked[0]?.candidate ?? null;
109
113
  }
@@ -139,7 +143,7 @@ export function buildRoleProposals(
139
143
  const outcome = sizing.get(role.role) ?? { unsized: "the role was not sized" };
140
144
  if ("unsized" in outcome) return { ...role, status: "unsized", reason: outcome.unsized };
141
145
  const { tier, effort, rationale, moveUpIf, moveDownIf } = outcome.sizing;
142
- const pick = cheapestSufficientCandidate(classified, tier);
146
+ const pick = cheapestSufficientCandidate(classified, tier, role.model);
143
147
  const sized = { ...role, tier, effortIntent: effort, rationale, moveUpIf, moveDownIf };
144
148
  if (!pick) {
145
149
  return {
@@ -1,4 +1,4 @@
1
- import { splitSourceLines, type SourceLine } from "./toml-source-lines";
1
+ import { sourceAssignment, splitSourceLines, type SourceLine } from "./toml-source-lines";
2
2
 
3
3
  /**
4
4
  * Pure, ownership-aware edits for Codex's native `[agents]` defaults.
@@ -21,6 +21,16 @@ export interface ManagedSubagentDefaults {
21
21
  reasoningEffort?: string;
22
22
  }
23
23
 
24
+ /**
25
+ * The exact values the last injection wrote under a marker, as recorded in the
26
+ * injection journal. A marker proves only that OpenCodex once wrote the line;
27
+ * this record proves which value it wrote. A marked value that no longer
28
+ * matches it was edited by someone else — the user, or a Codex settings writer
29
+ * that keeps comments — and is adopted as user-owned instead of reverted.
30
+ * Absent (`null`/`undefined`) means no evidence, and the marker alone decides.
31
+ */
32
+ export type WrittenSubagentDefaults = Partial<Record<ManagedSubagentDefaultKey, string>>;
33
+
24
34
  export interface ManagedSubagentDefaultsConflict {
25
35
  key: ManagedSubagentDefaultKey;
26
36
  line: number;
@@ -303,15 +313,42 @@ function invalidInput(content: string, error: string): ManagedSubagentDefaultsTr
303
313
  return { ok: false, changed: false, content, conflicts: [], error };
304
314
  }
305
315
 
316
+ /**
317
+ * Marker lines whose value differs from what OpenCodex recorded writing. The
318
+ * marker is dropped so the line reads as what it now is: a user-owned value.
319
+ */
320
+ function userEditedMarkers(
321
+ lines: readonly SourceLine[],
322
+ shape: TomlShape,
323
+ written: WrittenSubagentDefaults | null | undefined,
324
+ ): number[] {
325
+ if (!written) return [];
326
+ const stale: number[] = [];
327
+ for (const definition of shape.definitions.values()) {
328
+ const recorded = written[definition.key];
329
+ if (!definition.owned || typeof recorded !== "string") continue;
330
+ // The whole assignment, so a value rewritten as a multiline string still decodes. An
331
+ // undecodable value is not edit evidence; the single-line replace step rejects it later.
332
+ const current = sourceAssignment(lines, definition.index, shape.agentsEnd ?? lines.length)?.value;
333
+ if (typeof current === "string" && current !== recorded) stale.push(definition.index - 1);
334
+ }
335
+ return stale;
336
+ }
337
+
306
338
  /**
307
339
  * Add/update opencodex-owned native subagent defaults, or remove them with
308
340
  * `defaults = null`. Unmarked target keys are user-owned: they are retained and
309
341
  * returned as conflicts rather than overwritten. Ambiguous TOML is rejected
310
342
  * byte-for-byte so callers never have to guess what was changed.
343
+ *
344
+ * `written` is the journal's record of the values the last injection wrote.
345
+ * When supplied, a marked value that differs from it is user-edited: its marker
346
+ * is dropped and the value is treated exactly like any other user-owned key.
311
347
  */
312
348
  export function transformManagedSubagentDefaults(
313
349
  content: string,
314
350
  defaults: ManagedSubagentDefaults | null,
351
+ written?: WrittenSubagentDefaults | null,
315
352
  ): ManagedSubagentDefaultsTransformResult {
316
353
  if (defaults !== null) {
317
354
  if (typeof defaults.model !== "string" || defaults.model.length === 0) {
@@ -329,14 +366,20 @@ export function transformManagedSubagentDefaults(
329
366
  }
330
367
  }
331
368
 
332
- const lines = splitSourceLines(content);
369
+ let lines = splitSourceLines(content);
333
370
  if (defaults === null && !lines.some(line =>
334
371
  markerLine(line, MANAGED_SUBAGENT_DEFAULT_MARKER)
335
372
  || markerLine(line, MANAGED_AGENTS_TABLE_MARKER))) {
336
373
  return { ok: true, changed: false, content, conflicts: [] };
337
374
  }
338
- const analysis = analyzeToml(lines);
375
+ let analysis = analyzeToml(lines);
339
376
  if ("error" in analysis) return invalidInput(content, analysis.error);
377
+ const stale = new Set(userEditedMarkers(lines, analysis.shape, written));
378
+ if (stale.size > 0) {
379
+ lines = lines.filter((_, index) => !stale.has(index));
380
+ analysis = analyzeToml(lines);
381
+ if ("error" in analysis) return invalidInput(content, analysis.error);
382
+ }
340
383
  const { shape } = analysis;
341
384
  const eol = dominantEol(lines);
342
385
  const desired = new Map<ManagedSubagentDefaultKey, string>();
@@ -361,8 +404,10 @@ export function transformManagedSubagentDefaults(
361
404
  // Model and effort are one effective native-default pair. A partial write
362
405
  // could apply a newly managed effort to a user's model (or vice versa), so
363
406
  // any desired-key ownership conflict makes the whole enable/update a no-op.
407
+ // Only an adopted user edit's stale marker is dropped from the result.
364
408
  if (conflicts.length > 0) {
365
- return { ok: true, changed: false, content, conflicts };
409
+ const adopted = joinSourceLines(lines);
410
+ return { ok: true, changed: adopted !== content, content: adopted, conflicts };
366
411
  }
367
412
  }
368
413
 
@@ -19,6 +19,7 @@ import { isAbsolute, join, resolve } from "node:path";
19
19
 
20
20
  import { resolveTrustedWindowsPowerShellExe } from "../lib/windows-elevation";
21
21
  import { WINDOWS_PRINCIPAL_LOOKUP_TIMEOUT_MS } from "../lib/windows-user-principal";
22
+ import { resolveWindowsCurrentSid } from "./windows-current-sid";
22
23
  import { resolveWindowsLocalAppData } from "./windows-local-appdata";
23
24
 
24
25
  import type {
@@ -213,8 +214,8 @@ export function decodeWindowsIdentityPowerShellOutputForTests(output: Uint8Array
213
214
  * Both helper values -- the effective token's SID and its known-folder local AppData --
214
215
  * are fixed for the lifetime of a process: neither can change without a new logon
215
216
  * token, and the lookups deliberately ignore the environment, so nothing a caller
216
- * does between two calls can alter the answer. The native x64 known-folder path
217
- * avoids this helper entirely. Each fallback call otherwise spawns a fresh
217
+ * does between two calls can alter the answer. The native x64 SID and known-folder
218
+ * paths avoid this helper entirely. Each fallback call otherwise spawns a fresh
218
219
  * PowerShell, roughly 150ms for the SID and 310ms for the folder, and the
219
220
  * coordinator asks for both on every config write and lock acquisition. That cost
220
221
  * pushed real multi-process injection tests past their budget while proving
@@ -259,14 +260,42 @@ function powershellValue(expression: string): string {
259
260
  return value;
260
261
  }
261
262
 
262
- function resolveWindowsSid(): string {
263
- const sid = powershellValue(
264
- "[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value",
265
- );
263
+ const WINDOWS_SID_EXPRESSION = "[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value";
264
+
265
+ /**
266
+ * Windows x64 reads the token SID in-process (`windows-current-sid.ts`, #7544);
267
+ * the PowerShell helper runs only where `bun:ffi` cannot. Every failure either
268
+ * path reports — a helper timeout, a native API error — refuses.
269
+ */
270
+ function resolveWindowsSidWith(
271
+ powershellLookup: () => string,
272
+ nativeLookup?: (() => string) | null,
273
+ ): string {
274
+ let sid: string;
275
+ try {
276
+ sid = nativeLookup === undefined
277
+ ? resolveWindowsCurrentSid(powershellLookup)
278
+ : resolveWindowsCurrentSid(powershellLookup, nativeLookup);
279
+ } catch (cause) {
280
+ if (cause instanceof CodexUserIdentityRefusal) throw cause;
281
+ refuse("Windows effective-account lookup failed.", cause);
282
+ }
266
283
  if (!SID_PATTERN.test(sid)) refuse("Windows effective-account lookup returned an invalid SID.");
267
284
  return sid.toUpperCase();
268
285
  }
269
286
 
287
+ function resolveWindowsSid(): string {
288
+ return resolveWindowsSidWith(() => powershellValue(WINDOWS_SID_EXPRESSION));
289
+ }
290
+
291
+ /** Test-only: the SID resolution and refusal mapping with both lookups injected. */
292
+ export function resolveWindowsSidForTests(
293
+ powershellLookup: () => string,
294
+ nativeLookup: (() => string) | null,
295
+ ): string {
296
+ return resolveWindowsSidWith(powershellLookup, nativeLookup);
297
+ }
298
+
270
299
  function windowsLocalAppData(): string {
271
300
  try {
272
301
  return resolveWindowsLocalAppData(() => powershellValue(windowsLocalAppDataExpression()));