@bitkyc08/opencodex 2.96.0 → 2.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-bwugJRKn.js → App-DuNhggE1.js} +15 -15
  3. package/gui/dist/assets/{Tray-BOPQyDbH.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-6HsrHQAy.js → quota-summary-VHFSlUuM.js} +1 -1
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/command-code.ts +15 -16
  9. package/src/adapters/cursor/transport-retry.ts +2 -2
  10. package/src/adapters/devin/cloud-direct/chat.ts +15 -6
  11. package/src/adapters/kiro/stream.ts +63 -4
  12. package/src/adapters/kiro-constants.ts +15 -1
  13. package/src/adapters/kiro-events.ts +31 -1
  14. package/src/adapters/kiro-retry.ts +3 -3
  15. package/src/adapters/ollama-native.ts +11 -1
  16. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  17. package/src/adapters/openai-responses/passthrough.ts +5 -4
  18. package/src/adapters/openai-responses/reasoning.ts +9 -4
  19. package/src/adapters/openai-responses/request-strips.ts +1 -1
  20. package/src/adapters/physical-send.ts +3 -3
  21. package/src/adapters/zed-openai-stream.ts +2 -1
  22. package/src/bridge/errors.ts +11 -2
  23. package/src/bridge/response-json.ts +2 -1
  24. package/src/bridge/sse.ts +14 -6
  25. package/src/chat/failure-verdict.ts +21 -0
  26. package/src/chat/outbound.ts +139 -21
  27. package/src/claude/outbound.ts +49 -2
  28. package/src/cli/capabilities-base.ts +25 -3
  29. package/src/cli/capabilities-command.ts +12 -3
  30. package/src/cli/capability-contracts.ts +2 -0
  31. package/src/cli/codex-launch-auth.ts +30 -1
  32. package/src/cli/codex-launcher.ts +12 -5
  33. package/src/cli/codex-shim-autorestore.ts +5 -4
  34. package/src/cli/dispatch.ts +11 -176
  35. package/src/cli/help.ts +2 -2
  36. package/src/cli/index.ts +5 -1
  37. package/src/cli/link.ts +1 -1
  38. package/src/cli/registry.ts +11 -3
  39. package/src/cli/root.ts +8 -0
  40. package/src/cli/sync-command.ts +243 -0
  41. package/src/cli/sync-fanout-process.ts +92 -0
  42. package/src/cli/sync-fanout.ts +150 -0
  43. package/src/cli/sync-flags.ts +10 -0
  44. package/src/cli/sync-link-status.ts +39 -0
  45. package/src/cli/sync-update-guard.ts +18 -0
  46. package/src/client/connect.ts +31 -14
  47. package/src/client/link-home.ts +3 -2
  48. package/src/client/machine-listener.ts +3 -0
  49. package/src/client/restore-ownership.ts +19 -1
  50. package/src/client/runtime-restart.ts +12 -4
  51. package/src/client/runtime.ts +40 -11
  52. package/src/client/stop-routing.ts +62 -0
  53. package/src/client/sync-runtime.ts +65 -0
  54. package/src/clients/config-export.ts +32 -3
  55. package/src/codex/auth-context.ts +49 -103
  56. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  57. package/src/codex/catalog/provider-models.ts +6 -8
  58. package/src/codex/forward-transport-headers.ts +35 -6
  59. package/src/codex/inject/config-toml.ts +88 -0
  60. package/src/codex/inject/multi-agent-v2.ts +30 -4
  61. package/src/codex/inject/plan.ts +34 -7
  62. package/src/codex/inject-coordination.ts +11 -0
  63. package/src/codex/inject.ts +18 -7
  64. package/src/codex/lineage.ts +13 -7
  65. package/src/codex/quota.ts +22 -6
  66. package/src/codex/request-owned-affinity-key.ts +11 -0
  67. package/src/codex/request-owned-affinity.ts +118 -0
  68. package/src/codex/request-owned-main-pin.ts +86 -0
  69. package/src/codex/role-capability.ts +52 -41
  70. package/src/codex/routing/active-account.ts +13 -5
  71. package/src/codex/routing/selection.ts +40 -1
  72. package/src/codex/routing/thread-affinity-store.ts +916 -0
  73. package/src/codex/routing/thread-affinity.ts +90 -12
  74. package/src/codex/toml-source-lines.ts +72 -13
  75. package/src/combos/failover.ts +6 -109
  76. package/src/combos/request.ts +2 -2
  77. package/src/combos/resolve.ts +29 -11
  78. package/src/config/process-state.ts +5 -0
  79. package/src/config/schema/leaf-validators.ts +1 -0
  80. package/src/generated/compatibility-version.json +433 -165
  81. package/src/images/loop.ts +2 -1
  82. package/src/lib/client-error-body.ts +184 -0
  83. package/src/lib/client-retry-after.ts +66 -0
  84. package/src/lib/config-ownership.ts +4 -0
  85. package/src/lib/context-overflow-verdict.ts +113 -0
  86. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  87. package/src/lib/desktop-cli-handoff.mjs +11 -1
  88. package/src/lib/empty-tool-catalog.ts +25 -3
  89. package/src/lib/error-destination.ts +47 -0
  90. package/src/lib/failure-detail.ts +66 -0
  91. package/src/lib/model-identity.ts +44 -0
  92. package/src/lib/private-sqlite-path.ts +124 -0
  93. package/src/lib/response-service-tier.ts +17 -0
  94. package/src/lib/retry-after.ts +3 -0
  95. package/src/lib/spend-ledger-owner.ts +43 -4
  96. package/src/lib/upstream-condition.ts +142 -0
  97. package/src/lib/upstream-retry.ts +14 -11
  98. package/src/lib/windows-owner-acl.ts +13 -6
  99. package/src/link/remote-platform.ts +14 -0
  100. package/src/link/remote-windows.ts +51 -9
  101. package/src/link/ssh-argv.ts +63 -10
  102. package/src/oauth/generic-account-failover.ts +13 -11
  103. package/src/oauth/index.ts +36 -74
  104. package/src/oauth/oauth-errors.ts +67 -0
  105. package/src/oauth/store.ts +1 -1
  106. package/src/protocols/codecs/ollama.ts +197 -0
  107. package/src/protocols/encoders/adapter-events.ts +4 -0
  108. package/src/protocols/encoders/chat.ts +18 -10
  109. package/src/protocols/trace.ts +18 -0
  110. package/src/providers/fastwire.ts +3 -2
  111. package/src/providers/quota/anthropic-usage-windows.ts +13 -3
  112. package/src/providers/quota/vendor-probes-key.ts +60 -24
  113. package/src/providers/request-pacing.ts +3 -2
  114. package/src/responses/apply-patch-envelope.ts +45 -19
  115. package/src/responses/compaction-history-framing.ts +5 -1
  116. package/src/responses/freeform-wrapper-scan.ts +5 -3
  117. package/src/responses/progressive-freeform-input.ts +354 -45
  118. package/src/routing/fallback-policy.ts +3 -1
  119. package/src/server/admission-model-scope.ts +17 -6
  120. package/src/server/admitted-http-turn.ts +56 -0
  121. package/src/server/auth-cors.ts +5 -0
  122. package/src/server/chat-completions.ts +45 -20
  123. package/src/server/chat-native-sse.ts +52 -7
  124. package/src/server/chat-native.ts +60 -35
  125. package/src/server/claude-bridge-pool-session.ts +59 -0
  126. package/src/server/claude-messages.ts +51 -24
  127. package/src/server/context-history.ts +5 -1
  128. package/src/server/inbound-body-admission.ts +11 -4
  129. package/src/server/index/ollama-routes.ts +89 -0
  130. package/src/server/index/serve-options.ts +21 -4
  131. package/src/server/index/websocket-handler.ts +4 -2
  132. package/src/server/index.ts +6 -36
  133. package/src/server/inference/client-encoder-delivery.ts +4 -2
  134. package/src/server/json-serialized-bytes.ts +44 -0
  135. package/src/server/management/agent-settings-routes.ts +24 -21
  136. package/src/server/management/codex-cli-update-routes.ts +2 -1
  137. package/src/server/management/route-registry.ts +1 -1
  138. package/src/server/messages-native-scope.ts +2 -1
  139. package/src/server/messages-native-tool-guard.ts +1 -1
  140. package/src/server/messages-native.ts +12 -7
  141. package/src/server/messages-shared.ts +6 -2
  142. package/src/server/native-final-log.ts +93 -0
  143. package/src/server/ollama-inbound.ts +349 -0
  144. package/src/server/ollama-native-paths.ts +21 -0
  145. package/src/server/ollama-route-policy.ts +73 -0
  146. package/src/server/relay.ts +22 -3
  147. package/src/server/request-decompress.ts +4 -2
  148. package/src/server/request-log-failure-attribution.ts +22 -0
  149. package/src/server/request-log-failure-detail.ts +80 -0
  150. package/src/server/request-log-terminal-status.ts +4 -2
  151. package/src/server/request-log.ts +79 -42
  152. package/src/server/response-log-body.ts +6 -1
  153. package/src/server/responses/account-change-state.ts +17 -6
  154. package/src/server/responses/adapter-continuation.ts +9 -4
  155. package/src/server/responses/adapter-delivery.ts +5 -4
  156. package/src/server/responses/adapter-dispatch.ts +31 -30
  157. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  158. package/src/server/responses/codex-auth-error.ts +19 -18
  159. package/src/server/responses/codex-ws-exchange.ts +11 -8
  160. package/src/server/responses/codex-ws-metadata.ts +94 -21
  161. package/src/server/responses/codex-ws-request.ts +3 -1
  162. package/src/server/responses/compact.ts +53 -23
  163. package/src/server/responses/compaction-recovery.ts +4 -2
  164. package/src/server/responses/compaction-routing.ts +9 -4
  165. package/src/server/responses/core-auth.ts +32 -14
  166. package/src/server/responses/core-codex-account.ts +17 -6
  167. package/src/server/responses/core-combo-failure.ts +5 -1
  168. package/src/server/responses/core-combo-native.ts +2 -1
  169. package/src/server/responses/core-combo.ts +41 -27
  170. package/src/server/responses/core-errors.ts +22 -20
  171. package/src/server/responses/core-lifetime.ts +6 -3
  172. package/src/server/responses/core-normalize.ts +1 -0
  173. package/src/server/responses/core-options.ts +7 -0
  174. package/src/server/responses/core-pipeline.ts +4 -3
  175. package/src/server/responses/fetch-helpers.ts +7 -1
  176. package/src/server/responses/input-admission.ts +28 -2
  177. package/src/server/responses/native-injection.ts +1 -1
  178. package/src/server/responses/native-response-json.ts +13 -4
  179. package/src/server/responses/native-response-output.ts +1 -2
  180. package/src/server/responses/non-replayable-error.ts +2 -1
  181. package/src/server/responses/pacing-overload.ts +3 -2
  182. package/src/server/responses/passthrough-delivery.ts +55 -14
  183. package/src/server/responses/passthrough-dispatch.ts +19 -17
  184. package/src/server/responses/passthrough-error.ts +9 -9
  185. package/src/server/responses/policy-fallback.ts +2 -1
  186. package/src/server/responses/request-prepare.ts +67 -48
  187. package/src/server/responses/request-transport.ts +35 -31
  188. package/src/server/responses/run-turn-execution.ts +6 -6
  189. package/src/server/responses/sidecar-execution.ts +16 -12
  190. package/src/server/responses/spend-storage-error.ts +2 -1
  191. package/src/server/responses/ws-upstream.ts +9 -0
  192. package/src/server/responses-custom-tool-repair.ts +14 -3
  193. package/src/server/responses-terminal-repair.ts +5 -2
  194. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  195. package/src/server/safe-response-headers.ts +162 -13
  196. package/src/server/turn-state-handles.ts +164 -0
  197. package/src/server/workflow-refusal.ts +2 -1
  198. package/src/service/ownership-mutation-lease.d.mts +11 -2
  199. package/src/service/ownership-mutation-lease.mjs +53 -11
  200. package/src/types/config.ts +2 -0
  201. package/src/update/index.ts +133 -25
  202. package/src/update/npm-install.d.mts +8 -0
  203. package/src/update/npm-install.mjs +20 -1
  204. package/src/update/orchestrated-admission.d.mts +4 -0
  205. package/src/update/orchestrated-admission.mjs +12 -0
  206. package/src/update/orchestrated-arguments.d.mts +12 -0
  207. package/src/update/orchestrated-arguments.mjs +64 -0
  208. package/src/update/orchestrated-child.d.mts +12 -0
  209. package/src/update/orchestrated-child.mjs +70 -0
  210. package/src/update/orchestrated-entry.ts +234 -0
  211. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  212. package/src/update/orchestrated-identity.ts +53 -0
  213. package/src/update/orchestrated-live-identity.ts +48 -0
  214. package/src/update/orchestrated-node-driver.mjs +99 -0
  215. package/src/update/orchestrated-outcome.d.mts +21 -0
  216. package/src/update/orchestrated-outcome.mjs +40 -0
  217. package/src/update/orchestrated-plan.ts +49 -0
  218. package/src/update/orchestrated-pnpm.d.mts +8 -0
  219. package/src/update/orchestrated-pnpm.mjs +33 -0
  220. package/src/update/orchestrated-session.d.mts +37 -0
  221. package/src/update/orchestrated-session.mjs +264 -0
  222. package/src/update/orchestrated-token.d.mts +10 -0
  223. package/src/update/orchestrated-token.mjs +21 -0
  224. package/src/update/orchestrated-token.ts +3 -0
  225. package/src/update/orchestrated-tree.d.mts +1 -0
  226. package/src/update/orchestrated-tree.mjs +14 -0
  227. package/src/update/pnpm-global-install.d.mts +6 -0
  228. package/src/update/pnpm-global-install.mjs +9 -2
  229. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  230. package/src/update/posix-install-supervisor.d.mts +10 -0
  231. package/src/update/posix-install-supervisor.mjs +88 -0
  232. package/src/update/sync-update-mutex.d.mts +10 -0
  233. package/src/update/sync-update-mutex.mjs +164 -0
  234. package/src/update/sync-update-mutex.ts +1 -0
  235. package/src/update/test-home-guard.mjs +33 -0
  236. package/src/update/transactional-install.mjs +2 -2
  237. package/src/usage/error-detail.ts +225 -0
  238. package/src/usage/log.ts +60 -27
  239. package/src/web-search/loop.ts +31 -5
  240. package/gui/dist/assets/index-ebuVUtB7.js +0 -94
@@ -2,19 +2,21 @@
2
2
  * Measured capability per task domain, so role auto-assign can tier candidates by what they score
3
3
  * instead of what they cost. Artificial Analysis is read live when configured:
4
4
  *
5
- * - Artificial Analysis (https://artificialanalysis.ai/api-reference), when the user configures
5
+ * - Artificial Analysis (https://artificialanalysis.ai/data-api/docs), when the user configures
6
6
  * their own API key. Its terms allow that user's internal use with attribution and forbid
7
7
  * redistributing the raw data, so its scores never leave this process.
8
8
  *
9
- * Each domain maps to one published index. The source names a model by display name
10
- * with one row per reasoning setting ("Claude Opus 5.5 (High)"); capabilityModelKey drops the
11
- * setting and folds the rest to a slug, which matches a catalog id once its provider prefix is
12
- * gone ("cpa/claude-opus-5-5"). The best setting's score stands for the model, since a role can
13
- * be given that setting. A candidate with no row is unmeasured, never guessed.
9
+ * Every domain reads the Intelligence Index: Artificial Analysis no longer publishes a Coding or
10
+ * an Agentic Index (both are always null) and its free model list carries no math index. The
11
+ * source names a model by display name with one row per reasoning setting ("Claude Opus 5.5
12
+ * (High)"); capabilityModelKey drops the setting and folds the rest to a slug, which matches a
13
+ * catalog id once its provider prefix is gone ("cpa/claude-opus-5-5"). The best setting's score
14
+ * stands for the model, since a role can be given that setting. A candidate with no row is
15
+ * unmeasured, never guessed.
14
16
  */
15
17
  import { resolveProviderApiKey } from "../providers/api-key-resolve";
16
18
  import type { OcxConfig } from "../types";
17
- import type { SizingDomain } from "./role-sizing";
19
+ import { SIZING_DOMAINS, type SizingDomain } from "./role-sizing";
18
20
 
19
21
  export interface CapabilitySource {
20
22
  readonly name: string;
@@ -31,21 +33,23 @@ export const ARTIFICIAL_ANALYSIS_SOURCE: CapabilitySource = {
31
33
  redistributable: false,
32
34
  };
33
35
 
34
- const ARTIFICIAL_ANALYSIS_URL = "https://artificialanalysis.ai/api/v2/data/llms/models";
36
+ /**
37
+ * The free-tier language model list, which any key may read. It replaced
38
+ * /api/v2/data/llms/models, retired at 2026-11-04 23:59 UTC with 410 Gone afterwards
39
+ * (https://artificialanalysis.ai/data-api/migrate-v2-data).
40
+ */
41
+ export const ARTIFICIAL_ANALYSIS_URL = "https://artificialanalysis.ai/api/v2/language/models/free";
35
42
 
36
- /** Per domain, the indexes to read in order; the first one the response carries is used. */
37
43
  const INTELLIGENCE_INDEX = "artificial_analysis_intelligence_index";
38
- const ARTIFICIAL_ANALYSIS_INDEXES: Record<SizingDomain, readonly string[]> = {
39
- coding: ["artificial_analysis_coding_index", INTELLIGENCE_INDEX],
40
- agentic: ["artificial_analysis_agentic_index", INTELLIGENCE_INDEX],
41
- reasoning: ["artificial_analysis_math_index", INTELLIGENCE_INDEX],
42
- writing: [INTELLIGENCE_INDEX],
43
- knowledge: [INTELLIGENCE_INDEX],
44
- general: [INTELLIGENCE_INDEX],
45
- };
44
+
45
+ /**
46
+ * Pages read per refresh. The list is paginated (200 rows a page in the published example, two
47
+ * pages); ten pages bound one daily refresh to a tenth of the free tier's 100 requests a day.
48
+ */
49
+ export const MAX_TABLE_PAGES = 10;
46
50
 
47
51
  const FETCH_TIMEOUT_MS = 30_000;
48
- /** Each published table is under 1 MB today; 16 MB leaves room to grow and still bounds memory. */
52
+ /** The bytes all pages of one refresh may total; the list is under 1 MB today, 16 MB still bounds memory. */
49
53
  export const MAX_TABLE_BYTES = 16 * 1024 * 1024;
50
54
 
51
55
  export interface CapabilityTable {
@@ -74,22 +78,15 @@ function keepBest(scores: Map<string, number>, key: string, value: number) {
74
78
  export function capabilityTableFromArtificialAnalysis(body: unknown): CapabilityTable {
75
79
  const rows = (body as { data?: unknown } | null)?.data;
76
80
  if (!Array.isArray(rows)) throw new Error("Artificial Analysis returned no model list");
77
- const domains: Partial<Record<SizingDomain, Map<string, number>>> = {};
78
- for (const [domain, indexes] of Object.entries(ARTIFICIAL_ANALYSIS_INDEXES) as [SizingDomain, readonly string[]][]) {
79
- for (const index of indexes) {
80
- const scores = new Map<string, number>();
81
- for (const row of rows as Record<string, unknown>[]) {
82
- const value = (row?.evaluations as Record<string, unknown> | undefined)?.[index];
83
- if (typeof value !== "number" || !Number.isFinite(value)) continue;
84
- if (typeof row.name === "string") keepBest(scores, capabilityModelKey(row.name), value);
85
- if (typeof row.slug === "string") keepBest(scores, capabilityModelKey(row.slug), value);
86
- }
87
- if (scores.size > 0) {
88
- domains[domain] = scores;
89
- break;
90
- }
91
- }
81
+ const scores = new Map<string, number>();
82
+ for (const row of rows as Record<string, unknown>[]) {
83
+ const value = (row?.evaluations as Record<string, unknown> | undefined)?.[INTELLIGENCE_INDEX];
84
+ if (typeof value !== "number" || !Number.isFinite(value)) continue;
85
+ if (typeof row.name === "string") keepBest(scores, capabilityModelKey(row.name), value);
86
+ if (typeof row.slug === "string") keepBest(scores, capabilityModelKey(row.slug), value);
92
87
  }
88
+ const domains: Partial<Record<SizingDomain, ReadonlyMap<string, number>>> = {};
89
+ if (scores.size > 0) for (const domain of SIZING_DOMAINS) domains[domain] = scores;
93
90
  return { source: ARTIFICIAL_ANALYSIS_SOURCE, publishedAt: null, domains };
94
91
  }
95
92
 
@@ -118,15 +115,29 @@ export async function readBoundedBytes(response: Response, maxBytes: number): Pr
118
115
  return out.buffer;
119
116
  }
120
117
 
118
+ /** A list past either bound fails whole, so price ranking takes over rather than tiering on part of it. */
121
119
  export async function fetchArtificialAnalysisTable(apiKey: string, fetchImpl: typeof fetch = fetch): Promise<CapabilityTable> {
122
- const response = await fetchImpl(ARTIFICIAL_ANALYSIS_URL, {
123
- redirect: "error",
124
- headers: { "x-api-key": apiKey },
125
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
126
- });
127
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
128
- const bytes = await readBoundedBytes(response, MAX_TABLE_BYTES);
129
- return capabilityTableFromArtificialAnalysis(JSON.parse(new TextDecoder().decode(bytes)));
120
+ const rows: unknown[] = [];
121
+ let budget = MAX_TABLE_BYTES;
122
+ for (let page = 1; page <= MAX_TABLE_PAGES; page++) {
123
+ const url = new URL(ARTIFICIAL_ANALYSIS_URL);
124
+ url.searchParams.set("page", String(page));
125
+ const response = await fetchImpl(url.href, {
126
+ redirect: "error",
127
+ headers: { "x-api-key": apiKey },
128
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
129
+ });
130
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
131
+ const bytes = await readBoundedBytes(response, budget);
132
+ budget -= bytes.byteLength;
133
+ const body = JSON.parse(new TextDecoder().decode(bytes)) as { data?: unknown; pagination?: { has_more?: unknown } } | null;
134
+ if (!Array.isArray(body?.data)) throw new Error("Artificial Analysis returned no model list");
135
+ const hasMore = body.pagination?.has_more;
136
+ if (typeof hasMore !== "boolean") throw new Error("Artificial Analysis returned no pagination.has_more");
137
+ rows.push(...body.data);
138
+ if (!hasMore) return capabilityTableFromArtificialAnalysis({ data: rows });
139
+ }
140
+ throw new Error(`Artificial Analysis listed more than ${MAX_TABLE_PAGES} pages`);
130
141
  }
131
142
 
132
143
  /** One fetch per period key; a failed fetch is forgotten so the next request retries. */
@@ -32,13 +32,14 @@ let runtimeActiveCodexAccountId: string | undefined;
32
32
 
33
33
  /** Manual selection resets transient routing evidence without bypassing a real 429 cooldown. */
34
34
  export function resetCodexRoutingForManualSelection(accountId: string): void {
35
- clearThreadAccountMap();
35
+ clearThreadAccountMap({ preserveConversationStateIssuers: true });
36
36
  // Manual selection is the operator source of truth — drop any automatic runtime cursor.
37
37
  runtimeActiveCodexAccountId = undefined;
38
- // Record the pick as an unspent one-shot on the SHARED scope only. An independent scope
39
- // gets no entry on purpose: every write site the guard protects is already skipped for
40
- // independent scopes, so an entry there would be state nothing reads — and state nothing
41
- // reads is what the next reader mistakes for a rule.
38
+ // Record the pick as an unspent one-shot on the shared scope and on each independent scope
39
+ // whose ring is seeded below. The cursor guard (`manualPreferenceBlocks`) still only acts on
40
+ // the shared scope: every write site it protects skips independent scopes. The independent
41
+ // entries have exactly one reader, round-robin placement, which keeps the selected account
42
+ // among its candidates until a dispatch in that scope spends the entry.
42
43
  //
43
44
  // Seeding happens ONLY here. A pool-driven promote must never create or move a preference,
44
45
  // or the pool would manufacture an operator intent nobody expressed.
@@ -50,6 +51,7 @@ export function resetCodexRoutingForManualSelection(accountId: string): void {
50
51
  for (const scope of new Set(Object.values(NATIVE_MODEL_QUOTA_SCOPES))) {
51
52
  if (isIndependentCodexQuotaScope(scope)) {
52
53
  seedPoolRotationAccount(codexPoolKeyForScope(scope), accountId);
54
+ manualPreference.set(codexPoolKeyForScope(scope), accountId);
53
55
  }
54
56
  }
55
57
  // Quota avoidance is a preference, like the soft avoid dropped above, and an operator naming
@@ -91,6 +93,7 @@ export function resetCodexRoutingForClearedSelection(): void {
91
93
  for (const scope of new Set(Object.values(NATIVE_MODEL_QUOTA_SCOPES))) {
92
94
  if (isIndependentCodexQuotaScope(scope)) {
93
95
  clearPoolRotationState(codexPoolKeyForScope(scope));
96
+ manualPreference.delete(codexPoolKeyForScope(scope));
94
97
  }
95
98
  }
96
99
  }
@@ -143,6 +146,11 @@ export function manualPreferenceBlocks(poolKey: string, accountId: string): bool
143
146
  return preferred !== undefined && preferred !== accountId;
144
147
  }
145
148
 
149
+ /** The unspent operator selection for this pool scope, if any. Read-only. */
150
+ export function unspentManualPreference(poolKey: string): string | undefined {
151
+ return manualPreference.get(poolKey);
152
+ }
153
+
146
154
  export function getEffectiveActiveCodexAccountId(config: OcxConfig): string | undefined {
147
155
  return runtimeActiveCodexAccountId ?? config.activeCodexAccountId;
148
156
  }
@@ -39,6 +39,7 @@ import {
39
39
  promoteActiveCodexAccount,
40
40
  rememberActiveCodexAccount,
41
41
  setActiveCodexAccount,
42
+ unspentManualPreference,
42
43
  } from "./active-account";
43
44
 
44
45
  /**
@@ -302,6 +303,38 @@ export function hasCodexQuotaHeadroom(
302
303
  return usage < threshold;
303
304
  }
304
305
 
306
+ /**
307
+ * Where round-robin may place a NEW conversation: the eligible accounts that still have headroom
308
+ * under their own threshold, or the whole eligible list when none does.
309
+ *
310
+ * Rotation by count alone put a fresh conversation on an account already at 95%. The conversation
311
+ * binds there, and when the account runs out it has to move to another account with a cold prompt
312
+ * cache. Preferring headroom at placement avoids that hop without touching anything already bound:
313
+ * live bindings never reach this function, and failover ({@link pickAlternateCodexAccount}) keeps
314
+ * plain ring order because leaving a failing account is not a placement.
315
+ *
316
+ * The score is {@link hasCodexQuotaHeadroom}, the one fill-first and the priority tier already use,
317
+ * so a threshold of 0 or unknown usage counts as headroom. It is a preference, never eligibility:
318
+ * when every account is at or over its threshold the ring sees the full list, exactly as before.
319
+ *
320
+ * An operator's unspent manual selection for this scope stays in the list whatever its usage.
321
+ * Manual selection seeds the ring so the next placement lands on the chosen account, and a
322
+ * preference must not overrule a person's explicit choice: dropping it here would clear that seed.
323
+ * Once a dispatch on it succeeds the selection is spent and the account is treated like any other.
324
+ */
325
+ function roundRobinPlacementCandidates(
326
+ config: OcxConfig,
327
+ eligible: readonly string[],
328
+ now: number,
329
+ quotaScope?: CodexQuotaScope,
330
+ selectionOptions?: CodexAccountUsabilityOptions,
331
+ ): readonly string[] {
332
+ const operatorChoice = unspentManualPreference(codexPoolKeyForScope(quotaScope));
333
+ const withHeadroom = eligible.filter(id =>
334
+ id === operatorChoice || hasCodexQuotaHeadroom(config, id, selectionOptions, now));
335
+ return withHeadroom.length > 0 ? withHeadroom : eligible;
336
+ }
337
+
305
338
  /**
306
339
  * Is a live binding held for its prompt cache?
307
340
  *
@@ -475,7 +508,13 @@ export function pickUnboundStrategyAccount(
475
508
 
476
509
  let picked: string | null = null;
477
510
  if (strategy === "round-robin") {
478
- const eligible = listEligibleCodexAccountIds(config, now, quotaScope, selectionOptions);
511
+ const eligible = roundRobinPlacementCandidates(
512
+ config,
513
+ listEligibleCodexAccountIds(config, now, quotaScope, selectionOptions),
514
+ now,
515
+ quotaScope,
516
+ selectionOptions,
517
+ );
479
518
  const limit = stickyLimitForConfig(config);
480
519
  if (!commit) {
481
520
  return peekRoundRobinAccount(poolKey, eligible, limit);