@bitkyc08/opencodex 2.92.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 (259) hide show
  1. package/bin/ocx.mjs +10 -5
  2. package/gui/dist/assets/App-CJZoq-uF.js +58 -0
  3. package/gui/dist/assets/{Tray-BSsxznDm.js → Tray-BWQPcgZn.js} +1 -1
  4. package/gui/dist/assets/index-DRe8Hhfz.css +1 -0
  5. package/gui/dist/assets/{index-BlFE_VB_.js → index-Xfct8owH.js} +12 -12
  6. package/gui/dist/assets/{quota-summary-BRlbXgw0.js → quota-summary-DxToX1rV.js} +1 -1
  7. package/gui/dist/index.html +2 -2
  8. package/package.json +5 -5
  9. package/src/adapters/anthropic.ts +28 -5
  10. package/src/adapters/coding-agent/batch-dispatcher.ts +122 -0
  11. package/src/adapters/coding-agent/profile.ts +54 -16
  12. package/src/adapters/coding-agent/turn.ts +30 -2
  13. package/src/adapters/command-code.ts +114 -7
  14. package/src/adapters/cursor/native-exec-fs.ts +11 -9
  15. package/src/adapters/devin/live-models.ts +4 -0
  16. package/src/adapters/google-wire-compiler.ts +1 -2
  17. package/src/adapters/kiro/reasoning.ts +2 -0
  18. package/src/adapters/kiro-refusal.ts +6 -1
  19. package/src/adapters/kiro-wire.ts +1 -1
  20. package/src/adapters/openai-chat/messages.ts +8 -2
  21. package/src/adapters/openai-chat/passthrough.ts +35 -14
  22. package/src/adapters/openai-chat/reasoning-replay.ts +27 -16
  23. package/src/adapters/openai-chat/reasoning-wire.ts +117 -8
  24. package/src/adapters/openai-chat/required-tool-result.ts +64 -0
  25. package/src/adapters/openai-chat.ts +7 -8
  26. package/src/adapters/openai-responses/passthrough.ts +7 -4
  27. package/src/adapters/openai-responses/reasoning.ts +13 -0
  28. package/src/adapters/openai-responses/request-strips.ts +1 -1
  29. package/src/adapters/qoder/adapter.ts +129 -8
  30. package/src/adapters/qoder/scaffold-guard.ts +5 -0
  31. package/src/adapters/reasoning-controls.ts +16 -0
  32. package/src/adapters/tool-call-id.ts +1 -3
  33. package/src/bridge/errors.ts +27 -0
  34. package/src/bridge.ts +1 -1
  35. package/src/chat/inbound.ts +4 -1
  36. package/src/chat/outbound.ts +9 -2
  37. package/src/chat/reasoning-details.ts +28 -5
  38. package/src/claude/desktop-first-party.ts +54 -4
  39. package/src/claude/desktop-picker.ts +11 -8
  40. package/src/claude/first-party-settings.ts +3 -1
  41. package/src/claude/inbound.ts +2 -1
  42. package/src/claude/intercept/local-ca.ts +2 -1
  43. package/src/claude/intercept/picker-ca-cleanup.ts +4 -2
  44. package/src/claude/intercept/picker-ca-startup.ts +3 -1
  45. package/src/claude/intercept/picker-models.ts +6 -3
  46. package/src/claude/intercept/picker-runtime.ts +3 -2
  47. package/src/claude/intercept/runtime.ts +6 -3
  48. package/src/claude/model-info.ts +31 -8
  49. package/src/cli/account-api.ts +11 -0
  50. package/src/cli/capabilities-agents-routing.ts +2 -2
  51. package/src/cli/capabilities-base.ts +7 -1
  52. package/src/cli/capabilities-observe-system.ts +10 -0
  53. package/src/cli/claude-desktop.ts +9 -8
  54. package/src/cli/claude.ts +3 -2
  55. package/src/cli/codex-shim-autorestore.ts +9 -0
  56. package/src/cli/combo-result.ts +7 -0
  57. package/src/cli/combo.ts +18 -0
  58. package/src/cli/cross-home-owner.ts +13 -1
  59. package/src/cli/dispatch.ts +25 -6
  60. package/src/cli/ensure-desired-integrations.ts +8 -6
  61. package/src/cli/export-command.ts +4 -1
  62. package/src/cli/help.ts +2 -1
  63. package/src/cli/index.ts +45 -45
  64. package/src/cli/integration-plan-dto.ts +4 -0
  65. package/src/cli/opencode.ts +20 -9
  66. package/src/cli/registry.ts +6 -4
  67. package/src/cli/root.ts +9 -0
  68. package/src/cli/status.ts +59 -1
  69. package/src/cli/stop-restore.ts +113 -0
  70. package/src/cli/sync-expectation.ts +60 -0
  71. package/src/cli/uninstall-integrations.ts +41 -7
  72. package/src/client/connect.ts +40 -3
  73. package/src/client/link-home.ts +10 -1
  74. package/src/client/machine-api.ts +3 -1
  75. package/src/client/sync-expectation.ts +118 -0
  76. package/src/clients/config-export/agent-clients.ts +96 -0
  77. package/src/clients/config-export/contracts.ts +25 -7
  78. package/src/clients/config-export/qoder.ts +38 -23
  79. package/src/clients/config-export/reasoning-metadata.ts +55 -8
  80. package/src/clients/config-export.ts +12 -0
  81. package/src/clients/lazycodex.ts +7 -2
  82. package/src/clients/reasoning-controls.ts +49 -0
  83. package/src/codex/auth-api/account-identity.ts +14 -0
  84. package/src/codex/auth-api/account-list.ts +29 -2
  85. package/src/codex/auth-api/http.ts +13 -0
  86. package/src/codex/auth-api/main-account-probe.ts +2 -2
  87. package/src/codex/auth-api/pool-mode-gate.ts +16 -3
  88. package/src/codex/auth-api/pool-quota-probe.ts +15 -0
  89. package/src/codex/auth-context.ts +15 -12
  90. package/src/codex/catalog/build-entries.ts +22 -0
  91. package/src/codex/catalog/configured-tiers.ts +70 -0
  92. package/src/codex/catalog/effort.ts +44 -10
  93. package/src/codex/catalog/gather-capture.ts +1 -0
  94. package/src/codex/catalog/heal-observation.ts +155 -13
  95. package/src/codex/catalog/metadata.ts +6 -0
  96. package/src/codex/catalog/model-hints.ts +60 -11
  97. package/src/codex/catalog/model-visibility.ts +3 -2
  98. package/src/codex/catalog/native-models.ts +18 -3
  99. package/src/codex/catalog/parsing.ts +10 -8
  100. package/src/codex/catalog/pinned-models.ts +2 -1
  101. package/src/codex/catalog/provider-models.ts +4 -5
  102. package/src/codex/catalog/retained-sync.ts +2 -1
  103. package/src/codex/catalog/routed-gather.ts +19 -20
  104. package/src/codex/catalog/write-audit.ts +3 -2
  105. package/src/codex/catalog-self-heal.ts +43 -23
  106. package/src/codex/collision-identity.ts +30 -5
  107. package/src/codex/convergence.ts +4 -3
  108. package/src/codex/data/roster-pinned-models.json +177 -1
  109. package/src/codex/desired-state.ts +6 -1
  110. package/src/codex/desktop-compatibility/installed-build.ts +88 -12
  111. package/src/codex/desktop-compatibility/runtime.ts +29 -5
  112. package/src/codex/desktop-compatibility/usage-controller.ts +2 -0
  113. package/src/codex/desktop-compatibility/windows-certificate-trust.ts +46 -12
  114. package/src/codex/inject/config-toml.ts +0 -18
  115. package/src/codex/inject/plan.ts +18 -3
  116. package/src/codex/inject/remove.ts +6 -2
  117. package/src/codex/inject.ts +1 -1
  118. package/src/codex/journal.ts +61 -1
  119. package/src/codex/model-entitlements.ts +1 -1
  120. package/src/codex/native-main-owner.ts +27 -1
  121. package/src/codex/native-profile-store.ts +2 -1
  122. package/src/codex/pool-credit-policy.ts +35 -1
  123. package/src/codex/quota-types.ts +3 -0
  124. package/src/codex/quota.ts +24 -4
  125. package/src/codex/role-auto-assign.ts +6 -2
  126. package/src/codex/subagent-defaults.ts +49 -4
  127. package/src/combos/failover.ts +17 -2
  128. package/src/combos/jev-decision-contract.ts +22 -1
  129. package/src/combos/jev-service-exchange.ts +3 -1
  130. package/src/combos/jev.ts +95 -9
  131. package/src/combos/resolve.ts +45 -1
  132. package/src/combos/types.ts +24 -0
  133. package/src/config/load-degrade.ts +5 -0
  134. package/src/config/paths.ts +19 -3
  135. package/src/config/pending-teardown.ts +22 -1
  136. package/src/config/provider-validation.ts +15 -4
  137. package/src/config/removed-opencode-free.ts +11 -0
  138. package/src/config/schema/leaf-validators.ts +5 -0
  139. package/src/generated/compatibility-version.json +314 -230
  140. package/src/generated/model-metadata.ts +5 -5
  141. package/src/images/loop.ts +16 -2
  142. package/src/integrations/catalog-refresh.ts +1 -1
  143. package/src/integrations/hermes-profiles.ts +251 -0
  144. package/src/integrations/merge.ts +8 -0
  145. package/src/integrations/mutation-plan.ts +19 -4
  146. package/src/integrations/registry.ts +5 -0
  147. package/src/integrations/state.ts +36 -1
  148. package/src/integrations/writer.ts +18 -4
  149. package/src/lib/bun-path-runtime.mjs +2 -1
  150. package/src/lib/errors.ts +62 -0
  151. package/src/lib/eventstream-decoder.ts +81 -37
  152. package/src/lib/opaque-proxy-tunnel.ts +32 -8
  153. package/src/lib/pinned-http.ts +35 -2
  154. package/src/lib/process-control.ts +13 -1
  155. package/src/lib/socks5-fetch.ts +59 -64
  156. package/src/lib/socks5-upload-waiter.ts +50 -0
  157. package/src/lib/sse-decoder.ts +7 -2
  158. package/src/lib/state-store-sweeper.ts +40 -14
  159. package/src/lib/windows-native-principal-worker.ts +14 -0
  160. package/src/lib/windows-native-principal.ts +188 -0
  161. package/src/lib/windows-secret-acl.ts +39 -3
  162. package/src/lib/windows-user-principal.ts +62 -18
  163. package/src/link/ssh-config.ts +35 -3
  164. package/src/providers/account-quota-disk.ts +12 -4
  165. package/src/providers/codebuddy-models.ts +6 -0
  166. package/src/providers/codex-capacity.ts +3 -1
  167. package/src/providers/derive.ts +28 -0
  168. package/src/providers/kiro-models.ts +3 -0
  169. package/src/providers/mimo-thinking.ts +12 -0
  170. package/src/providers/model-rename-fields.ts +1 -0
  171. package/src/providers/model-rename-migration.ts +10 -0
  172. package/src/providers/openai-sidecar-credit.ts +2 -2
  173. package/src/providers/reasoning-capabilities.ts +76 -0
  174. package/src/providers/registry/entries-core.ts +14 -12
  175. package/src/providers/registry/entries-extended.ts +63 -20
  176. package/src/providers/registry/model-ids.ts +2 -0
  177. package/src/providers/registry/model-seeds.ts +93 -28
  178. package/src/providers/registry/types.ts +10 -1
  179. package/src/providers/resolved-model-policy.ts +26 -6
  180. package/src/providers/routed-config.ts +9 -1
  181. package/src/providers/stale-model-roster-migration.ts +44 -7
  182. package/src/remote-control/workspace-pi-runtime.ts +11 -6
  183. package/src/responses/compaction-summary.ts +45 -0
  184. package/src/responses/muse-tool-name-alias.ts +1 -2
  185. package/src/responses/parser.ts +3 -2
  186. package/src/responses/schema.ts +1 -0
  187. package/src/responses/thought-signature-replay.ts +10 -2
  188. package/src/routing/capability.ts +8 -2
  189. package/src/routing/history/ingest.ts +28 -3
  190. package/src/server/auth-cors.ts +3 -2
  191. package/src/server/chat-completions.ts +7 -0
  192. package/src/server/chat-native-eligibility.ts +7 -0
  193. package/src/server/chat-native-reasoning.ts +14 -4
  194. package/src/server/direct-local-http.ts +5 -2
  195. package/src/server/effort-policy.ts +5 -1
  196. package/src/server/index/live-sideband.ts +18 -15
  197. package/src/server/index/serve-options.ts +5 -4
  198. package/src/server/management/agent-settings-routes.ts +27 -15
  199. package/src/server/management/combo-routes.ts +4 -0
  200. package/src/server/management/config-routes.ts +2 -2
  201. package/src/server/management/decision-discovery.ts +12 -2
  202. package/src/server/management/hermes-profile-routes.ts +156 -0
  203. package/src/server/management/integration-routes.ts +85 -24
  204. package/src/server/management/model-routes.ts +2 -2
  205. package/src/server/management/model-row-export-metadata.ts +25 -6
  206. package/src/server/management/model-rows.ts +15 -20
  207. package/src/server/management/native-integration-routes.ts +11 -8
  208. package/src/server/management/route-registry.ts +4 -0
  209. package/src/server/management-api.ts +5 -0
  210. package/src/server/models-capabilities.ts +21 -3
  211. package/src/server/responses/adapter-delivery.ts +11 -1
  212. package/src/server/responses/adapter-dispatch.ts +2 -2
  213. package/src/server/responses/codex-ws-exchange.ts +39 -9
  214. package/src/server/responses/codex-ws-session.ts +38 -4
  215. package/src/server/responses/codex-ws-wire.ts +6 -1
  216. package/src/server/responses/combo-required-tool-contract.ts +103 -0
  217. package/src/server/responses/combo-stream-preflight.ts +8 -1
  218. package/src/server/responses/compact.ts +4 -3
  219. package/src/server/responses/context-overflow.ts +8 -1
  220. package/src/server/responses/core-combo-failure.ts +10 -0
  221. package/src/server/responses/core-combo.ts +23 -15
  222. package/src/server/responses/core-lifetime.ts +3 -0
  223. package/src/server/responses/core-normalize.ts +11 -1
  224. package/src/server/responses/core-options.ts +2 -0
  225. package/src/server/responses/main-hard-lock-routing.ts +60 -44
  226. package/src/server/responses/passthrough-delivery.ts +40 -2
  227. package/src/server/responses/policy-fallback.ts +6 -1
  228. package/src/server/responses/request-compression.ts +12 -7
  229. package/src/server/responses/request-prepare.ts +22 -2
  230. package/src/server/responses/request-sidecar-auth.ts +2 -0
  231. package/src/server/responses/response-effects.ts +22 -10
  232. package/src/server/responses/sidecar-execution.ts +11 -3
  233. package/src/server/stop-teardown.ts +36 -1
  234. package/src/server/ws-bridge.ts +1 -1
  235. package/src/service/desktop-supervision.d.mts +7 -4
  236. package/src/service/desktop-supervision.mjs +90 -13
  237. package/src/service/ownership-mutation-lease.mjs +21 -7
  238. package/src/types/config.ts +8 -2
  239. package/src/types/provider.ts +20 -6
  240. package/src/types/request.ts +10 -0
  241. package/src/types.ts +1 -0
  242. package/src/update/bind-probe.ts +29 -0
  243. package/src/update/job.ts +10 -29
  244. package/src/update/npm-install-job.ps1 +173 -0
  245. package/src/update/npm-install.mjs +70 -0
  246. package/src/update/stop-contract.d.mts +1 -0
  247. package/src/update/stop-contract.mjs +14 -0
  248. package/src/update/stop-decision.d.mts +1 -1
  249. package/src/update/stop-decision.mjs +13 -3
  250. package/src/update/teardown-handover.ts +166 -0
  251. package/src/update/transactional-install.d.mts +14 -3
  252. package/src/update/transactional-install.mjs +33 -7
  253. package/src/usage/expected-prices.ts +64 -31
  254. package/src/usage/timeline.ts +19 -9
  255. package/src/vision/eligibility.ts +15 -5
  256. package/src/vision/plan.ts +2 -2
  257. package/src/web-search/loop.ts +16 -2
  258. package/gui/dist/assets/App-sUf_8afJ.js +0 -58
  259. package/gui/dist/assets/index-DPeB9HpV.css +0 -1
@@ -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 {
@@ -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
+ }
@@ -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 {