@bitkyc08/opencodex 2.100.3 → 2.100.5-preview.20261118.1

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 (249) hide show
  1. package/AGENTS_INSTALL.md +23 -1
  2. package/bin/ocx.mjs +8 -1
  3. package/gui/dist/assets/{App-Dnb6VMsP.js → App-BiOGtxDS.js} +21 -20
  4. package/gui/dist/assets/{Tray-BV4ms9U9.js → Tray-BwsMejUO.js} +1 -1
  5. package/gui/dist/assets/brand-mark-BY1dgACL.js +1 -0
  6. package/gui/dist/assets/{index-DCdXsMyZ.js → index-CwHSKMdG.js} +46 -13
  7. package/gui/dist/assets/index-DJxM-imn.css +2 -0
  8. package/gui/dist/assets/{segment-thumb-features-DXSidY6D.js → segment-thumb-features-Bds9Hb_7.js} +1 -1
  9. package/gui/dist/classic/assets/{App-DA-scMPq.js → App-CGLOiqQL.js} +20 -19
  10. package/gui/dist/classic/assets/{Tray-BrHaVRAq.js → Tray-Da4r2O70.js} +1 -1
  11. package/gui/dist/classic/assets/{index-BqOaGLf5.js → index-CvoKXKL9.js} +46 -13
  12. package/gui/dist/classic/assets/quota-summary-DvqzfCmr.js +1 -0
  13. package/gui/dist/classic/index.html +1 -1
  14. package/gui/dist/index.html +2 -2
  15. package/native/ocx-child/src/cli.rs +5 -3
  16. package/native/ocx-child/src/codex_home.rs +1 -0
  17. package/native/ocx-child/src/link_ws.rs +24 -19
  18. package/native/ocx-child/src/link_ws_frame.rs +136 -50
  19. package/package.json +3 -3
  20. package/src/adapters/anthropic/per-message-effort.ts +296 -0
  21. package/src/adapters/anthropic-input-schema.ts +270 -0
  22. package/src/adapters/anthropic.ts +4 -63
  23. package/src/adapters/claude-cli/adapter.ts +1 -0
  24. package/src/adapters/command-code-tool-text.ts +9 -1
  25. package/src/adapters/command-code.ts +18 -2
  26. package/src/adapters/devin/cloud-direct/chat.ts +95 -14
  27. package/src/adapters/devin/live-models.ts +11 -1
  28. package/src/adapters/google-errors.ts +14 -2
  29. package/src/adapters/kiro/reasoning.ts +3 -0
  30. package/src/adapters/kiro-tools.ts +14 -9
  31. package/src/adapters/openai-responses/passthrough.ts +3 -1
  32. package/src/adapters/openai-responses/request-strips.ts +1 -0
  33. package/src/adapters/qoder/adapter.ts +9 -1
  34. package/src/adapters/tool-catalog-nudge.ts +1 -1
  35. package/src/adapters/zed.ts +4 -2
  36. package/src/claude/chat-tool-dispatch.ts +4 -1
  37. package/src/claude/desktop-remote-store.ts +60 -10
  38. package/src/cli/account-api.ts +4 -0
  39. package/src/cli/account-auth.ts +30 -2
  40. package/src/cli/account-extended.ts +33 -2
  41. package/src/cli/capabilities-access-remote.ts +3 -3
  42. package/src/cli/capabilities-accounts.ts +3 -3
  43. package/src/cli/capabilities-base.ts +11 -6
  44. package/src/cli/capabilities-observe-system.ts +2 -2
  45. package/src/cli/claude.ts +3 -3
  46. package/src/cli/disconnect-runtime.ts +16 -6
  47. package/src/cli/dispatch.ts +7 -1
  48. package/src/cli/index.ts +2 -2
  49. package/src/cli/link-apply-restart.ts +4 -2
  50. package/src/cli/link-routes.ts +4 -1
  51. package/src/cli/link.ts +5 -4
  52. package/src/cli/logout-command.ts +23 -4
  53. package/src/cli/preflight-exemptions.ts +3 -0
  54. package/src/cli/provider.ts +3 -2
  55. package/src/cli/registry.ts +5 -2
  56. package/src/cli/resolve.ts +23 -8
  57. package/src/cli/restart-failure.ts +11 -1
  58. package/src/cli/runtime-api.ts +4 -0
  59. package/src/cli/status.ts +4 -1
  60. package/src/cli/system-command.ts +1 -1
  61. package/src/cli/system-restart-client.ts +9 -3
  62. package/src/cli/system-settings-parity.ts +2 -1
  63. package/src/client/connect.ts +73 -11
  64. package/src/client/desktop-refusal.ts +38 -0
  65. package/src/client/lifecycle-lock.ts +29 -4
  66. package/src/client/runtime-restart.ts +27 -15
  67. package/src/client/runtime.ts +4 -2
  68. package/src/client/state.ts +14 -0
  69. package/src/clients/config-export.ts +12 -7
  70. package/src/codex/account-lifecycle.ts +3 -1
  71. package/src/codex/account-pause.ts +4 -0
  72. package/src/codex/account-runtime-state.ts +4 -0
  73. package/src/codex/auth-api/main-account-probe.ts +3 -1
  74. package/src/codex/auth-api/main-hard-lock-refusal-read.ts +172 -0
  75. package/src/codex/auth-context.ts +40 -2
  76. package/src/codex/catalog/build-entries.ts +10 -0
  77. package/src/codex/catalog/derive-entry.ts +7 -0
  78. package/src/codex/catalog/metadata.ts +8 -0
  79. package/src/codex/catalog/native-models.ts +16 -6
  80. package/src/codex/catalog/pinned-models.ts +1 -0
  81. package/src/codex/catalog/provider-models.ts +5 -5
  82. package/src/codex/catalog/reserve-warn.ts +7 -5
  83. package/src/codex/catalog/reserve.ts +4 -3
  84. package/src/codex/catalog/retained-sync.ts +2 -0
  85. package/src/codex/catalog/routed-defaults.ts +35 -0
  86. package/src/codex/catalog-auto-refresh.ts +13 -2
  87. package/src/codex/config-drift-heal.ts +40 -12
  88. package/src/codex/config-write-lock.ts +39 -1
  89. package/src/codex/convergence.ts +2 -0
  90. package/src/codex/data/roster-pinned-models.json +346 -1
  91. package/src/codex/inject/config-write-section.ts +39 -1
  92. package/src/codex/inject/plan.ts +10 -8
  93. package/src/codex/inject/remove.ts +21 -19
  94. package/src/codex/inject/restore.ts +5 -1
  95. package/src/codex/inject-coordination.ts +58 -7
  96. package/src/codex/inject.ts +10 -12
  97. package/src/codex/journal-config-restore.ts +42 -0
  98. package/src/codex/journal.ts +62 -8
  99. package/src/codex/loopback-target.ts +22 -8
  100. package/src/codex/main-account.ts +94 -30
  101. package/src/codex/native-main-auth-file.ts +14 -0
  102. package/src/codex/native-main-credentials.ts +276 -0
  103. package/src/codex/native-main-owner.ts +3 -0
  104. package/src/codex/native-main-refresh-mode.ts +14 -1
  105. package/src/codex/quota.ts +63 -14
  106. package/src/combos/failover.ts +195 -1
  107. package/src/combos/index.ts +5 -0
  108. package/src/combos/resolve.ts +115 -19
  109. package/src/config/diagnostics.ts +3 -0
  110. package/src/config/live-reconcile.ts +6 -3
  111. package/src/config/load-degrade.ts +2 -0
  112. package/src/config/persisted-mutation.ts +2 -2
  113. package/src/config/persisted-projections.ts +18 -0
  114. package/src/config/process-state.ts +4 -3
  115. package/src/config/reserve-capability.ts +96 -0
  116. package/src/config/schema/config-schema.ts +6 -0
  117. package/src/config/schema/leaf-validators.ts +2 -0
  118. package/src/config/schema/routed-catalog-defaults.ts +49 -0
  119. package/src/config/subagent-models.ts +20 -12
  120. package/src/config.ts +7 -7
  121. package/src/desktop-update/acquire.ts +202 -0
  122. package/src/desktop-update/cli.ts +168 -0
  123. package/src/desktop-update/drain.ts +40 -0
  124. package/src/desktop-update/headless.ts +285 -0
  125. package/src/desktop-update/image.ts +85 -0
  126. package/src/desktop-update/install.ts +53 -0
  127. package/src/desktop-update/msi.ts +72 -0
  128. package/src/desktop-update/release.ts +128 -0
  129. package/src/desktop-update/runtime.ts +155 -0
  130. package/src/desktop-update/staging.ts +118 -0
  131. package/src/desktop-update/trust.ts +45 -0
  132. package/src/generated/compatibility-version.json +327 -195
  133. package/src/generated/model-metadata.ts +3 -3
  134. package/src/images/fulfill-video.ts +3 -3
  135. package/src/images/loop.ts +6 -2
  136. package/src/images/plan.ts +147 -11
  137. package/src/images/types.ts +13 -4
  138. package/src/images/xai-video-client.ts +72 -10
  139. package/src/lib/client-error-body.ts +6 -0
  140. package/src/lib/developer-role-rejection.ts +15 -0
  141. package/src/lib/gcp-adc.ts +48 -4
  142. package/src/lib/offline-resend.ts +150 -0
  143. package/src/lib/paced-stream.ts +3 -3
  144. package/src/lib/provider-outbound.ts +17 -6
  145. package/src/lib/request-failure-model.ts +2 -0
  146. package/src/lib/response-body-inactivity.ts +23 -1
  147. package/src/lib/upstream-retry.ts +39 -6
  148. package/src/link/explicit-route.ts +4 -4
  149. package/src/link/remote-windows.ts +79 -31
  150. package/src/link/residual-recovery.ts +20 -8
  151. package/src/messaging/budget.ts +23 -5
  152. package/src/messaging/remote-ports.ts +22 -10
  153. package/src/messaging/rpc.ts +4 -4
  154. package/src/oauth/antigravity-risk.ts +126 -0
  155. package/src/oauth/credential-siblings.ts +32 -0
  156. package/src/oauth/generic-account-failover.ts +113 -30
  157. package/src/oauth/generic-session-affinity.ts +10 -3
  158. package/src/oauth/index.ts +22 -14
  159. package/src/oauth/login-cli.ts +35 -1
  160. package/src/oauth/pool-kernel.ts +3 -3
  161. package/src/oauth/store.ts +38 -7
  162. package/src/providers/anthropic-billing-refusal.ts +27 -3
  163. package/src/providers/anthropic-reset-grants.ts +4 -0
  164. package/src/providers/claude-cli-usage.ts +2 -0
  165. package/src/providers/codebuddy-models.ts +11 -0
  166. package/src/providers/google-vertex-model-discovery.ts +49 -15
  167. package/src/providers/kiro-models.ts +5 -0
  168. package/src/providers/model-rename-fields.ts +2 -0
  169. package/src/providers/quota/workbuddy.ts +6 -2
  170. package/src/providers/registry/entries-core.ts +9 -3
  171. package/src/providers/registry/entries-extended.ts +20 -9
  172. package/src/providers/registry/model-seeds.ts +4 -1
  173. package/src/providers/stale-context-window-migration.ts +2 -0
  174. package/src/providers/workbuddy-credit-balance.ts +125 -16
  175. package/src/responses/citation-markers.ts +26 -23
  176. package/src/responses/effort-history.ts +732 -0
  177. package/src/routing/history/integrity.ts +41 -4
  178. package/src/server/auth-cors.ts +13 -3
  179. package/src/server/codex-model-list.ts +2 -1
  180. package/src/server/direct-local-http.ts +26 -3
  181. package/src/server/index/link-listener.ts +20 -14
  182. package/src/server/index/serve-options.ts +1 -0
  183. package/src/server/index.ts +3 -2
  184. package/src/server/link-turn.ts +17 -5
  185. package/src/server/management/config-routes.ts +39 -3
  186. package/src/server/management/link-child-preflight.ts +1 -1
  187. package/src/server/management/link-enrollment.ts +3 -3
  188. package/src/server/management/link-route-edit.ts +20 -1
  189. package/src/server/management/link-route-request.ts +11 -5
  190. package/src/server/management/oauth-account-routes.ts +43 -13
  191. package/src/server/management/provider-credential-release.ts +44 -0
  192. package/src/server/management/provider-overwrite-carry.ts +3 -0
  193. package/src/server/management/provider-routes.ts +12 -12
  194. package/src/server/management/static-catalog-probe.ts +33 -0
  195. package/src/server/management/usage-aggregate-cache.ts +6 -3
  196. package/src/server/messages-native.ts +16 -2
  197. package/src/server/proxy-liveness.ts +54 -9
  198. package/src/server/relay.ts +6 -1
  199. package/src/server/request-log-conversation.ts +8 -4
  200. package/src/server/request-log-failure-detail.ts +26 -9
  201. package/src/server/request-log.ts +5 -1
  202. package/src/server/reserve-capability-startup.ts +32 -0
  203. package/src/server/responses/adapter-continuation.ts +59 -25
  204. package/src/server/responses/adapter-delivery.ts +2 -0
  205. package/src/server/responses/adapter-dispatch.ts +39 -18
  206. package/src/server/responses/antigravity-fault-rotation.ts +24 -0
  207. package/src/server/responses/antigravity-validation-refusal.ts +43 -6
  208. package/src/server/responses/codex-tool-catalog.ts +47 -10
  209. package/src/server/responses/combo-selection-keepalive.ts +254 -0
  210. package/src/server/responses/combo-session-recall.ts +26 -1
  211. package/src/server/responses/combo-stream-preflight.ts +35 -26
  212. package/src/server/responses/core-combo-failure.ts +6 -0
  213. package/src/server/responses/core-combo-native.ts +2 -1
  214. package/src/server/responses/core-combo.ts +67 -28
  215. package/src/server/responses/core-errors.ts +9 -6
  216. package/src/server/responses/core-options.ts +10 -0
  217. package/src/server/responses/core.ts +21 -0
  218. package/src/server/responses/estimated-usage.ts +115 -0
  219. package/src/server/responses/input-admission.ts +41 -3
  220. package/src/server/responses/jev-model-invoke.ts +7 -2
  221. package/src/server/responses/passthrough-completion.ts +6 -3
  222. package/src/server/responses/passthrough-delivery.ts +47 -8
  223. package/src/server/responses/passthrough-dispatch.ts +3 -0
  224. package/src/server/responses/request-prepare.ts +9 -5
  225. package/src/server/responses/request-send-budget.ts +1 -1
  226. package/src/server/responses/request-transport.ts +10 -2
  227. package/src/server/responses/sidecar-execution.ts +11 -4
  228. package/src/service/desktop-supervision.d.mts +2 -0
  229. package/src/service/desktop-supervision.mjs +5 -0
  230. package/src/service/windows-checked-stop-live.ts +28 -5
  231. package/src/stall-timeout.ts +11 -0
  232. package/src/types/config.ts +15 -92
  233. package/src/types/provider.ts +13 -0
  234. package/src/types/request.ts +23 -3
  235. package/src/types/routed-catalog-defaults.ts +17 -0
  236. package/src/types/routing-profile.ts +90 -0
  237. package/src/types.ts +1 -0
  238. package/src/update/index.ts +1 -1
  239. package/src/usage/expected-prices.ts +35 -0
  240. package/src/usage/ledger-scanner.ts +44 -10
  241. package/src/usage/log.ts +14 -4
  242. package/src/usage/telemetry-contract.ts +1 -0
  243. package/src/web-search/loop.ts +20 -2
  244. package/src/web-search/parse.ts +2 -12
  245. package/src/web-search/passthrough-bridge.ts +7 -0
  246. package/src/web-search/sources.ts +13 -0
  247. package/gui/dist/assets/brand-mark-XOLJbomA.js +0 -1
  248. package/gui/dist/assets/index-DQtCRNAw.css +0 -2
  249. package/gui/dist/classic/assets/quota-summary-Dy5_wfTT.js +0 -1
@@ -1,6 +1,7 @@
1
1
  import { currentTurnWireToolCatalogBody } from "../responses-undeclared-tool-guard";
2
2
  import { sessionLaneIdFromRequest } from "../request-log-conversation";
3
3
  import { codeModeRenderedToolNames } from "./code-mode-collab-surface";
4
+ import { CODE_MODE_EXEC_TOOL_NAME } from "../../types";
4
5
 
5
6
  /**
6
7
  * Eager MCP definitions at which a Codex request is diagnosed as carrying an expanded catalog.
@@ -21,6 +22,17 @@ const warnedSessions = new Map<string, true>();
21
22
  /** Logical requests already warned without a session identity; weak so completed requests leave no trace. */
22
23
  const warnedAnonymousRequests = new WeakSet<object>();
23
24
  const CODEX_CLIENT_IDENTITY = /^(?:codex|codex_cli_rs|codex_app|codex_work_desktop|codexless_agent|Codex Desktop)(?:\/|$)/i;
25
+ // This optional diagnostic has a request-wide work/storage budget, not an admission limit.
26
+ const MAX_DIAGNOSTIC_ITEMS = 4_096;
27
+ const MAX_DIAGNOSTIC_CHARACTERS = 1 << 20;
28
+ interface DiagnosticBudget { items: number; characters: number }
29
+
30
+ function reserveDiagnosticBudget(budget: DiagnosticBudget, items: number, characters = 0): boolean {
31
+ if (items > budget.items || characters > budget.characters) return false;
32
+ budget.items -= items;
33
+ budget.characters -= characters;
34
+ return true;
35
+ }
24
36
 
25
37
  function isRecord(value: unknown): value is Record<string, unknown> {
26
38
  return value !== null && typeof value === "object" && !Array.isArray(value);
@@ -36,32 +48,48 @@ export function eagerCodexToolCatalogSurface(
36
48
  ): "responses" | "compact" {
37
49
  if (compactionRecoveryKind === "compaction-v1") return "compact";
38
50
  const input = isRecord(body) && Array.isArray(body.input) ? body.input : [];
51
+ // An oversized unknown surface is skipped by the count's input budget too.
52
+ if (input.length > MAX_DIAGNOSTIC_ITEMS) return "responses";
39
53
  return input.some(item => isRecord(item) && item.type === "compaction_trigger") ? "compact" : "responses";
40
54
  }
41
55
 
42
- function collectEagerMcpTools(specs: unknown[], names: Set<string>, namespace?: string): void {
56
+ function collectEagerMcpTools(specs: unknown[], names: Set<string>, budget: DiagnosticBudget, namespace?: string): boolean {
57
+ if (!reserveDiagnosticBudget(budget, specs.length)) return false;
43
58
  for (const spec of specs) {
44
59
  if (!isRecord(spec) || spec.defer_loading === true) continue;
45
60
  // Codex namespaces are one level deep. A namespace nested inside another is not a Codex
46
61
  // declaration, and recursing into caller-shaped depth could exhaust the stack.
47
62
  if (spec.type === "namespace" && typeof spec.name === "string" && Array.isArray(spec.tools)) {
48
- if (namespace === undefined) collectEagerMcpTools(spec.tools, names, spec.name);
63
+ if (namespace === undefined && !collectEagerMcpTools(spec.tools, names, budget, spec.name)) return false;
49
64
  continue;
50
65
  }
51
66
  const tool = isRecord(spec.function) ? spec.function : spec;
52
67
  if (tool.defer_loading === true || typeof tool.name !== "string") continue;
53
68
  // `functions` is the reserved unnamespaced group (as in the undeclared-tool guard and parser),
54
69
  // so an MCP tool declared inside it keeps its own `mcp__` name.
55
- const name = namespace && namespace !== "functions" ? `${namespace}__${tool.name}` : tool.name;
56
- if (name.startsWith("mcp__")) names.add(name);
70
+ const prefix = namespace && namespace !== "functions" ? namespace : undefined;
71
+ const isMcp = prefix === undefined ? tool.name.startsWith("mcp__")
72
+ : prefix === "mcp" || prefix === "mcp_" || prefix.startsWith("mcp__");
73
+ if (isMcp) {
74
+ // Charge every occurrence, including duplicates, before concatenation or Set hashing.
75
+ const length = tool.name.length + (prefix === undefined ? 0 : prefix.length + 2);
76
+ if (!reserveDiagnosticBudget(budget, 0, length)) return false;
77
+ names.add(prefix === undefined ? tool.name : `${prefix}__${tool.name}`);
78
+ }
57
79
  // Code Mode renders each enabled, non-deferred nested tool into the exec description. Codex
58
80
  // sends exec bare or, on Responses Lite, inside its `functions` namespace.
59
- if ((namespace === undefined || namespace === "functions") && spec.type === "custom") {
60
- for (const nested of codeModeRenderedToolNames(tool.name, tool.description)) {
81
+ if ((namespace === undefined || namespace === "functions") && spec.type === "custom"
82
+ && tool.name === CODE_MODE_EXEC_TOOL_NAME && typeof tool.description === "string") {
83
+ // Reserving the complete description bounds parsing, copies and all names it can render.
84
+ if (!reserveDiagnosticBudget(budget, 0, tool.description.length)) return false;
85
+ const rendered = codeModeRenderedToolNames(tool.name, tool.description);
86
+ if (!reserveDiagnosticBudget(budget, rendered.length)) return false;
87
+ for (const nested of rendered) {
61
88
  if (nested.startsWith("mcp__")) names.add(nested);
62
89
  }
63
90
  }
64
91
  }
92
+ return true;
65
93
  }
66
94
 
67
95
  /**
@@ -86,7 +114,8 @@ function clientSentAdditionalTools(input: unknown[]): unknown[][] {
86
114
  * Eager MCP definitions a canonical Codex client declared for this request, or 0 for any other
87
115
  * client. `replayPrefixLength` is the leading input the proxy restored from stored continuation
88
116
  * state; those items are history and grant no declaration for this turn. Compaction reads only
89
- * top-level `tools`: its `input` is history.
117
+ * top-level `tools`: its `input` is history. Exceeding the diagnostic budget returns 0 rather
118
+ * than a partial count; it neither rejects nor rewrites the request.
90
119
  */
91
120
  export function eagerCodexMcpToolCount(
92
121
  body: unknown,
@@ -97,12 +126,20 @@ export function eagerCodexMcpToolCount(
97
126
  if (!headers.has("x-codex-turn-metadata")
98
127
  && !CODEX_CLIENT_IDENTITY.test(headers.get("originator") ?? "")
99
128
  && !CODEX_CLIENT_IDENTITY.test(headers.get("user-agent") ?? "")) return 0;
100
- const current = currentTurnWireToolCatalogBody(body, replayPrefixLength);
129
+ if (!isRecord(body)) return 0;
130
+ const budget = { items: MAX_DIAGNOSTIC_ITEMS, characters: MAX_DIAGNOSTIC_CHARACTERS };
131
+ const input = surface === "responses" && Array.isArray(body.input) ? body.input : undefined;
132
+ if (input !== undefined && !reserveDiagnosticBudget(budget, input.length)) return 0;
133
+ // Bound replay scans/copies before invoking the shared helper, and never spread unrelated
134
+ // request fields or inspect compaction history just to compute an optional diagnostic.
135
+ const current = currentTurnWireToolCatalogBody({ tools: body.tools, input }, replayPrefixLength);
101
136
  if (!isRecord(current)) return 0;
102
137
  const names = new Set<string>();
103
- if (Array.isArray(current.tools)) collectEagerMcpTools(current.tools, names);
138
+ if (Array.isArray(current.tools) && !collectEagerMcpTools(current.tools, names, budget)) return 0;
104
139
  if (surface === "responses" && Array.isArray(current.input)) {
105
- for (const tools of clientSentAdditionalTools(current.input)) collectEagerMcpTools(tools, names);
140
+ for (const tools of clientSentAdditionalTools(current.input)) {
141
+ if (!collectEagerMcpTools(tools, names, budget)) return 0;
142
+ }
106
143
  }
107
144
  return names.size;
108
145
  }
@@ -0,0 +1,254 @@
1
+ import type { RequestLogContext } from "../request-log";
2
+ import type { HandleResponsesOptions } from "./core-options";
3
+ import { hasResponseMediaType } from "../../lib/http-response-semantics";
4
+ import { readDisplaySafeErrorText } from "./core-errors";
5
+
6
+ /**
7
+ * How long a streaming combo may spend choosing a child before the client gets a response head
8
+ * (#8326). Below it nothing changes: the selected child's own head is returned, zero-output
9
+ * failover stays invisible and an all-targets failure keeps its real HTTP status. Once it passes,
10
+ * a 200 SSE head is committed so an idle-limited intermediary sees bytes, and the eventual
11
+ * outcome is delivered inside that stream. It matches the native reset-selection heartbeat.
12
+ */
13
+ export const COMBO_SELECTION_KEEPALIVE_THRESHOLD_MS = 15_000;
14
+ /** Gap between keepalive comments while selection continues behind a committed head. */
15
+ export const COMBO_SELECTION_KEEPALIVE_INTERVAL_MS = 15_000;
16
+
17
+ const KEEPALIVE = new TextEncoder().encode(": keepalive\n\n");
18
+ /** Proxy-owned copy for a ladder that threw after the head was committed; never the error text. */
19
+ const THROWN_SELECTION_MESSAGE = "opencodex could not complete this combo request";
20
+
21
+ /** Timer seam: production uses the global timers, tests advance a manual clock. */
22
+ export type ComboSelectionKeepaliveClock = NonNullable<NonNullable<HandleResponsesOptions["comboSelectionKeepalive"]>["clock"]>;
23
+
24
+ export interface ComboSelectionKeepaliveHooks {
25
+ /** The request's abort signal, also aborted when the client cancels the committed stream. */
26
+ signal: AbortSignal;
27
+ /** True once the keepalive head has been handed to the client. */
28
+ headCommitted(): boolean;
29
+ }
30
+
31
+ const systemClock: ComboSelectionKeepaliveClock = {
32
+ setTimeout: (callback, ms) => setTimeout(callback, ms),
33
+ clearTimeout: handle => clearTimeout(handle as ReturnType<typeof setTimeout>),
34
+ };
35
+
36
+ /**
37
+ * Only a streaming Responses turn from the HTTP ingress opts in. WebSocket frames carry their own
38
+ * status, Chat and Messages ingresses consume a different failure vocabulary, and internal
39
+ * decision calls read the HTTP status themselves.
40
+ */
41
+ export function comboSelectionKeepaliveApplies(
42
+ rawBody: unknown,
43
+ options: Pick<HandleResponsesOptions, "comboSelectionKeepalive" | "inboundTransport" | "inboundWire" | "internalDecisionCall">,
44
+ ): boolean {
45
+ return options.comboSelectionKeepalive !== undefined
46
+ && (rawBody as { stream?: unknown } | null)?.stream === true
47
+ && options.inboundTransport === undefined
48
+ && (options.inboundWire === undefined || options.inboundWire === "responses")
49
+ && options.internalDecisionCall !== true;
50
+ }
51
+
52
+ /**
53
+ * The ladder's options behind a possible keepalive head. A committed head is an unmarked SSE
54
+ * response, so the ingress request-log tap records its terminal; the native passthrough log
55
+ * callbacks are dropped from then on so one request is never logged twice.
56
+ */
57
+ export function comboSelectionKeepaliveLadderOptions<T extends HandleResponsesOptions>(
58
+ options: T,
59
+ hooks: ComboSelectionKeepaliveHooks,
60
+ ): T {
61
+ const { comboSelectionKeepalive: _optIn, ...rest } = options;
62
+ const onTerminal = options.onNativePassthroughTerminal;
63
+ const onCancel = options.onNativePassthroughCancel;
64
+ return {
65
+ ...rest,
66
+ abortSignal: hooks.signal,
67
+ ...(onTerminal ? { onNativePassthroughTerminal: status => { if (!hooks.headCommitted()) onTerminal(status); } } : {}),
68
+ ...(onCancel ? { onNativePassthroughCancel: () => { if (!hooks.headCommitted()) onCancel(); } } : {}),
69
+ } as T;
70
+ }
71
+
72
+ function isRecord(value: unknown): value is Record<string, unknown> {
73
+ return value !== null && typeof value === "object" && !Array.isArray(value);
74
+ }
75
+
76
+ function failedFrame(model: string, error: { type?: string; code: string; message: string }): Uint8Array {
77
+ const failure = { ...(error.type ? { type: error.type } : {}), code: error.code, message: error.message };
78
+ const payload = {
79
+ type: "response.failed",
80
+ sequence_number: 0,
81
+ response: {
82
+ id: `resp_${crypto.randomUUID().replaceAll("-", "")}`,
83
+ object: "response",
84
+ created_at: Math.floor(Date.now() / 1000),
85
+ status: "failed",
86
+ model,
87
+ output: [],
88
+ error: failure,
89
+ last_error: failure,
90
+ },
91
+ };
92
+ return new TextEncoder().encode(`event: response.failed\ndata: ${JSON.stringify(payload)}\n\n`);
93
+ }
94
+
95
+ /** Restate a non-streamable selection (an error envelope) as the in-stream failure terminal. */
96
+ async function failureFromResponse(response: Response, signal: AbortSignal): Promise<{ type?: string; code: string; message: string }> {
97
+ const fallback = `opencodex combo request failed with HTTP ${response.status}`;
98
+ const text = await readDisplaySafeErrorText(response, signal, "");
99
+ let record: Record<string, unknown> | undefined;
100
+ try {
101
+ const parsed: unknown = JSON.parse(text);
102
+ if (isRecord(parsed)) record = isRecord(parsed.error) ? parsed.error : parsed;
103
+ } catch { /* not JSON: the status-only fallback below applies */ }
104
+ const type = typeof record?.type === "string" && record.type ? record.type : undefined;
105
+ const code = typeof record?.code === "string" && record.code ? record.code
106
+ : typeof record?.code === "number" && Number.isFinite(record.code) ? String(record.code)
107
+ : type ?? (response.ok ? "invalid_response" : "upstream_error");
108
+ const message = typeof record?.message === "string" && record.message.trim() ? record.message : fallback;
109
+ return { ...(type ? { type } : {}), code, message };
110
+ }
111
+
112
+ /**
113
+ * Run combo selection and return its response, or a keepalive SSE response once selection has
114
+ * waited past the threshold. Behind the keepalive head, an accepted SSE child is streamed as is and
115
+ * any other outcome becomes one `response.failed` with the same error code.
116
+ */
117
+ export function selectComboWithKeepalive(
118
+ select: (hooks: ComboSelectionKeepaliveHooks) => Promise<Response>,
119
+ context: { model: string; logCtx: RequestLogContext; signal?: AbortSignal; clock?: ComboSelectionKeepaliveClock },
120
+ ): Promise<Response> {
121
+ const clock = context.clock ?? systemClock;
122
+ const cancel = new AbortController();
123
+ const signal = context.signal ? AbortSignal.any([context.signal, cancel.signal]) : cancel.signal;
124
+ let committed = false;
125
+ let settled = false;
126
+ let closed = false;
127
+ let keepaliveOwed = true;
128
+ let source: ReadableStreamDefaultReader<Uint8Array> | undefined;
129
+ let wake: (() => void) | undefined;
130
+ let timer: unknown;
131
+ const stopTimer = (): void => {
132
+ if (timer !== undefined) clock.clearTimeout(timer);
133
+ timer = undefined;
134
+ };
135
+ const notify = (): void => { const next = wake; wake = undefined; next?.(); };
136
+ const setSource = (stream: ReadableStream<Uint8Array> | null): void => {
137
+ if (closed) {
138
+ void stream?.cancel("client cancelled the committed combo stream").catch(() => {});
139
+ return;
140
+ }
141
+ source = (stream ?? new ReadableStream<Uint8Array>({ start: controller => controller.close() })).getReader();
142
+ notify();
143
+ };
144
+ const deliverFailure = (status: number, failure: { type?: string; code: string; message: string }): void => {
145
+ context.logCtx.terminalHttpStatus = status;
146
+ const frame = failedFrame(context.model, failure);
147
+ setSource(new ReadableStream<Uint8Array>({ start(controller) { controller.enqueue(frame); controller.close(); } }));
148
+ };
149
+ const deliver = async (response: Response): Promise<void> => {
150
+ if (closed) {
151
+ void response.body?.cancel("client cancelled the committed combo stream").catch(() => {});
152
+ return;
153
+ }
154
+ if (response.ok && hasResponseMediaType(response.headers, "text/event-stream")) {
155
+ setSource(response.body);
156
+ return;
157
+ }
158
+ if (response.status === 499) {
159
+ void response.body?.cancel().catch(() => {});
160
+ setSource(null);
161
+ return;
162
+ }
163
+ const failure = await failureFromResponse(response, signal);
164
+ deliverFailure(response.ok ? 502 : response.status, failure);
165
+ };
166
+
167
+ const body = new ReadableStream<Uint8Array>({
168
+ async pull(controller) {
169
+ try {
170
+ for (;;) {
171
+ if (closed) return;
172
+ if (source) {
173
+ const next = await source.read();
174
+ if (closed) return;
175
+ if (next.done) {
176
+ closed = true;
177
+ controller.close();
178
+ } else {
179
+ controller.enqueue(next.value);
180
+ }
181
+ return;
182
+ }
183
+ if (keepaliveOwed) {
184
+ keepaliveOwed = false;
185
+ controller.enqueue(KEEPALIVE);
186
+ return;
187
+ }
188
+ await new Promise<void>(resolve => { wake = resolve; });
189
+ }
190
+ } catch (error) {
191
+ if (closed) return;
192
+ closed = true;
193
+ controller.error(error);
194
+ }
195
+ },
196
+ cancel(reason) {
197
+ closed = true;
198
+ stopTimer();
199
+ cancel.abort(reason);
200
+ notify();
201
+ if (source) void source.cancel(reason).catch(() => {});
202
+ },
203
+ }, { highWaterMark: 0 });
204
+
205
+ const scheduleKeepalive = (): void => {
206
+ timer = clock.setTimeout(() => {
207
+ timer = undefined;
208
+ if (closed || settled) return;
209
+ keepaliveOwed = true;
210
+ notify();
211
+ scheduleKeepalive();
212
+ }, COMBO_SELECTION_KEEPALIVE_INTERVAL_MS);
213
+ };
214
+
215
+ return new Promise<Response>((resolve, reject) => {
216
+ const selection = select({ signal, headCommitted: () => committed });
217
+ timer = clock.setTimeout(() => {
218
+ timer = undefined;
219
+ // A cancelled request is about to settle as a client cancellation; it needs no head.
220
+ if (settled || signal.aborted) return;
221
+ committed = true;
222
+ scheduleKeepalive();
223
+ resolve(new Response(body, {
224
+ status: 200,
225
+ headers: {
226
+ "Content-Type": "text/event-stream",
227
+ "Cache-Control": "no-cache",
228
+ Connection: "keep-alive",
229
+ "X-Accel-Buffering": "no",
230
+ },
231
+ }));
232
+ }, COMBO_SELECTION_KEEPALIVE_THRESHOLD_MS);
233
+ selection.then(response => {
234
+ settled = true;
235
+ stopTimer();
236
+ if (!committed) {
237
+ resolve(response);
238
+ return;
239
+ }
240
+ deliver(response).catch(() => {
241
+ deliverFailure(502, { type: "server_error", code: "server_error", message: THROWN_SELECTION_MESSAGE });
242
+ });
243
+ }, error => {
244
+ settled = true;
245
+ stopTimer();
246
+ if (!committed) {
247
+ reject(error);
248
+ return;
249
+ }
250
+ console.warn(`[combo] selection failed after its keepalive head: ${error instanceof Error ? error.name : typeof error}`);
251
+ deliverFailure(502, { type: "server_error", code: "server_error", message: THROWN_SELECTION_MESSAGE });
252
+ });
253
+ });
254
+ }
@@ -1,7 +1,12 @@
1
1
  /** Process-local recall of the last completed combo response on an explicit session lane. */
2
2
  import { getCombo, targetKey } from "../../combos/types";
3
3
  import { captureConfigGeneration, type GenerationContext } from "../../lib/state-store-sweeper";
4
- import type { OcxConfig, OcxComboTarget } from "../../types";
4
+ import type { OcxComboDefaultEffort, OcxConfig, OcxComboTarget } from "../../types";
5
+
6
+ /** The effort a JEV decision set for a lane's turn; `null` is its explicit no-effort choice. */
7
+ export interface ComboTurnEffort {
8
+ effort: OcxComboDefaultEffort | null;
9
+ }
5
10
 
6
11
  interface ComboRecallEntry {
7
12
  comboId: string;
@@ -10,6 +15,8 @@ interface ComboRecallEntry {
10
15
  at: number;
11
16
  /** UTF-8 size of `responseModel`, the only client-influenced field of unbounded length. */
12
17
  bytes: number;
18
+ /** Present only when a JEV decision, not ordinary Combo policy, set the completed request's effort. */
19
+ turnEffort?: ComboTurnEffort;
13
20
  }
14
21
 
15
22
  const RECALL_CAPACITY = 256;
@@ -60,6 +67,7 @@ export function rememberComboForLane(
60
67
  target: Pick<OcxComboTarget, "provider" | "model">,
61
68
  responseModel: string,
62
69
  writerGeneration: number,
70
+ turnEffort?: ComboTurnEffort,
63
71
  ): void {
64
72
  if (!lane || !comboId || !responseModel.trim()) return;
65
73
  // Reject even a same-named recreated owner: its previous in-flight turn is obsolete.
@@ -75,6 +83,7 @@ export function rememberComboForLane(
75
83
  responseModel,
76
84
  at: Date.now(),
77
85
  bytes,
86
+ ...(turnEffort ? { turnEffort: { effort: turnEffort.effort } } : {}),
78
87
  };
79
88
  if (liveOwners && !ownsEntry(liveOwners, entry)) return;
80
89
  deleteEntry(lane);
@@ -135,6 +144,22 @@ export function recallComboTargetForLane(
135
144
  return { provider: entry.target.provider, model: entry.target.model };
136
145
  }
137
146
 
147
+ /**
148
+ * The effort a JEV decision set for the lane's turn, when `target` is the one that completed it.
149
+ * Freshness and ownership are `recallComboTargetForLane`'s job: a tool-loop pin reads this only
150
+ * for the target that call just returned, in the same synchronous turn.
151
+ */
152
+ export function recallComboTurnEffortForLane(
153
+ lane: string | undefined,
154
+ comboId: string,
155
+ target: Pick<OcxComboTarget, "provider" | "model">,
156
+ ): ComboTurnEffort | undefined {
157
+ if (!lane || !comboId) return undefined;
158
+ const entry = recall.get(lane);
159
+ if (!entry || entry.comboId !== comboId || targetKey(entry.target) !== targetKey(target)) return undefined;
160
+ return entry.turnEffort ? { effort: entry.turnEffort.effort } : undefined;
161
+ }
162
+
138
163
  /**
139
164
  * Periodic expiry. Without it a lane that is never read again and never touched by a config
140
165
  * reconciliation holds its entry for the life of the process: the existing TTL is only
@@ -138,7 +138,8 @@ function snapshotMetadataIsSafe(snapshot: Record<string, unknown>): boolean {
138
138
  if (typeof snapshot.tool_choice === "string" && !["none", "auto", "required"].includes(snapshot.tool_choice)) return false;
139
139
  if (snapshot.tool_choice != null && typeof snapshot.tool_choice !== "string") {
140
140
  if (!recordWithOnly(snapshot.tool_choice, ["type", "name", "namespace", "function"])
141
- || !["function", "custom", "tool_search"].includes(String(snapshot.tool_choice.type))
141
+ || typeof snapshot.tool_choice.type !== "string"
142
+ || !["function", "custom", "tool_search"].includes(snapshot.tool_choice.type)
142
143
  || (snapshot.tool_choice.name != null && typeof snapshot.tool_choice.name !== "string")
143
144
  || (snapshot.tool_choice.namespace != null && typeof snapshot.tool_choice.namespace !== "string")) return false;
144
145
  const selected = snapshot.tool_choice.function;
@@ -160,7 +161,8 @@ function snapshotMetadataIsSafe(snapshot: Record<string, unknown>): boolean {
160
161
  || (snapshot.text.verbosity != null && typeof snapshot.text.verbosity !== "string")) return false;
161
162
  const format = snapshot.text.format;
162
163
  if (format != null && (!recordWithOnly(format, ["type", "name", "description", "schema", "strict"])
163
- || !["text", "json_object", "json_schema"].includes(String(format.type))
164
+ || typeof format.type !== "string"
165
+ || !["text", "json_object", "json_schema"].includes(format.type)
164
166
  || (format.name != null && typeof format.name !== "string")
165
167
  || (format.description != null && typeof format.description !== "string")
166
168
  || (format.schema != null && !isRecord(format.schema))
@@ -665,31 +667,38 @@ export async function preflightComboStreamResponse(
665
667
  onOpaquePayload: () => { outputCommitted = true; },
666
668
  onParsedPayload: payload => {
667
669
  if (terminalStatus !== undefined || outputCommitted || retryableTerminalPayload) return;
668
- if (payload !== null && typeof payload === "object" && !Array.isArray(payload)
669
- && (payload as { type?: unknown }).type === "response.created") responseCreated = true;
670
- const retryable = retryableTerminalFor(payload);
671
- const matchedBareError = retryable && payload !== null && typeof payload === "object"
672
- && !Array.isArray(payload) && (payload as { type?: unknown }).type === "error";
673
- // A zero-output bare error is terminal evidence. Explicit client errors stay
674
- // committed; unknown and retryable upstream failures may advance the combo.
675
- const heldReasoning = options?.requiredToolPrelude && requiredToolReasoningPrelude(payload);
676
- if (heldReasoning) holdDeadline ??= new Promise(resolve => {
677
- holdTimer = setTimeout(() => resolve("hold-expired"), COMBO_REQUIRED_TOOL_REASONING_HOLD_MS);
678
- });
679
- if (comboStreamPayloadCommitsOutput(payload) && !matchedBareError && !heldReasoning) outputCommitted = true;
680
- if (options?.requiredToolPrelude && payload && typeof payload === "object") {
681
- const event = payload as { type?: unknown; response?: { output?: unknown; error?: { code?: unknown; retryable?: unknown } } };
682
- const output = event.response?.output;
683
- const contractFailure = event.type === "response.failed" && event.response?.error?.code === REQUIRED_TOOL_CONTRACT_CODE
684
- && event.response.error.retryable !== false && Array.isArray(output) && output.every(item =>
685
- item !== null && typeof item === "object" && !Array.isArray(item)
686
- && ["message", "reasoning"].includes((item as { type: string }).type));
687
- // Other lifecycle/terminal snapshots can hide effects too. Only our checked contract
688
- // failure may discard a terminal-only text snapshot that was held in its entirety.
689
- if (output !== undefined && (!Array.isArray(output) || output.length > 0) && !contractFailure) outputCommitted = true;
670
+ try {
671
+ if (payload !== null && typeof payload === "object" && !Array.isArray(payload)
672
+ && (payload as { type?: unknown }).type === "response.created") responseCreated = true;
673
+ const retryable = retryableTerminalFor(payload);
674
+ const matchedBareError = retryable && payload !== null && typeof payload === "object"
675
+ && !Array.isArray(payload) && (payload as { type?: unknown }).type === "error";
676
+ // A zero-output bare error is terminal evidence. Explicit client errors stay
677
+ // committed; unknown and retryable upstream failures may advance the combo.
678
+ const heldReasoning = options?.requiredToolPrelude && requiredToolReasoningPrelude(payload);
679
+ if (heldReasoning) holdDeadline ??= new Promise(resolve => {
680
+ holdTimer = setTimeout(() => resolve("hold-expired"), COMBO_REQUIRED_TOOL_REASONING_HOLD_MS);
681
+ });
682
+ if (comboStreamPayloadCommitsOutput(payload) && !matchedBareError && !heldReasoning) outputCommitted = true;
683
+ if (options?.requiredToolPrelude && payload && typeof payload === "object") {
684
+ const event = payload as { type?: unknown; response?: { output?: unknown; error?: { code?: unknown; retryable?: unknown } } };
685
+ const output = event.response?.output;
686
+ const contractFailure = event.type === "response.failed" && event.response?.error?.code === REQUIRED_TOOL_CONTRACT_CODE
687
+ && event.response.error.retryable !== false && Array.isArray(output) && output.every(item =>
688
+ item !== null && typeof item === "object" && !Array.isArray(item)
689
+ && ["message", "reasoning"].includes((item as { type: string }).type));
690
+ // Other lifecycle/terminal snapshots can hide effects too. Only our checked contract
691
+ // failure may discard a terminal-only text snapshot that was held in its entirety.
692
+ if (output !== undefined && (!Array.isArray(output) || output.length > 0) && !contractFailure) outputCommitted = true;
693
+ }
694
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return;
695
+ if (retryable) retryableTerminalPayload = payload as Record<string, unknown>;
696
+ } catch {
697
+ // The generic inspector swallows observer errors. Replay requires a successful proof
698
+ // of no effects, so a failed classification keeps this attempt and its original bytes.
699
+ outputCommitted = true;
700
+ retryableTerminalPayload = undefined;
690
701
  }
691
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) return;
692
- if (retryable) retryableTerminalPayload = payload as Record<string, unknown>;
693
702
  },
694
703
  onTerminal: status => { terminalStatus = status; },
695
704
  });
@@ -8,6 +8,7 @@ import {
8
8
  codexAccountModelRefusalHardStopCode,
9
9
  isMalformedResponseFormatRequest,
10
10
  isOpenRouterOpaque400Envelope,
11
+ isUnofferedToolCallRefusal,
11
12
  isProviderModerationRefusal,
12
13
  upstreamEnvelopeRootCode,
13
14
  type CodexAccountModelRefusal,
@@ -67,6 +68,7 @@ export async function consumeComboFailure(
67
68
  let codexModelRefusal: CodexAccountModelRefusal | undefined;
68
69
  let malformedResponseFormat: boolean | undefined;
69
70
  let openRouterOpaque400: boolean | undefined;
71
+ let unofferedToolCallRefusal: boolean | undefined;
70
72
  let providerModerationRefusal: boolean | undefined;
71
73
  let usage: OcxUsage | undefined;
72
74
  let upstreamCode: string | undefined;
@@ -108,6 +110,9 @@ export async function consumeComboFailure(
108
110
  codexModelRefusal = codexAccountModelRefusal(response.status, body.text);
109
111
  malformedResponseFormat = isMalformedResponseFormatRequest(response.status, body.text);
110
112
  openRouterOpaque400 = isOpenRouterOpaque400Envelope(body.text);
113
+ // The intact bounded body, not the 500-char display prefix: a long refusal envelope
114
+ // would fail the classifier's JSON parse on truncated text and stop the combo.
115
+ unofferedToolCallRefusal = isUnofferedToolCallRefusal(response.status, body.text);
111
116
  }
112
117
  // Judged on the whole body: the classification text below is cut at 500 characters, and a
113
118
  // hard refusal after the cut must still veto a moderation hop.
@@ -196,6 +201,7 @@ export async function consumeComboFailure(
196
201
  ...(codexModelRefusal !== undefined ? { codexModelRefusal } : {}),
197
202
  ...(malformedResponseFormat !== undefined ? { malformedResponseFormat } : {}),
198
203
  ...(openRouterOpaque400 !== undefined ? { openRouterOpaque400 } : {}),
204
+ ...(unofferedToolCallRefusal !== undefined ? { unofferedToolCallRefusal } : {}),
199
205
  ...(providerModerationRefusal !== undefined ? { providerModerationRefusal } : {}),
200
206
  ...(normalizedUpstreamCode !== undefined ? { upstreamCode: normalizedUpstreamCode } : {}),
201
207
  // A rewritten identity (policy, replay refusal) is the whole verdict; the root's own code
@@ -426,7 +426,8 @@ export async function dispatchNativeComboChild(input: {
426
426
  attempt,
427
427
  startedAt,
428
428
  seal: label => sealRequestAttemptIdentity(attempt, childLog.provider, childLog.providerAdapter ?? attempt.adapter, label),
429
- finish: (status, usage) => finishRequestAttempt(attempt, status, Date.now() - startedAt, usage),
429
+ // A rotation inside the child seals the earlier account and moves the segment start forward.
430
+ finish: (status, usage) => finishRequestAttempt(attempt, status, Date.now() - (childLog.activeAttemptStartedAt ?? startedAt), usage),
430
431
  };
431
432
  const child = {
432
433
  route: plan.route,