@bitkyc08/opencodex 2.95.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 (276) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-8yedBkhm.js → App-DuNhggE1.js} +18 -18
  3. package/gui/dist/assets/{Tray-erSMzxPG.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-BK4VuQNc.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 +21 -7
  16. package/src/adapters/openai-responses/canonical-forward.ts +50 -13
  17. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  18. package/src/adapters/openai-responses/passthrough.ts +8 -8
  19. package/src/adapters/openai-responses/reasoning.ts +9 -4
  20. package/src/adapters/openai-responses/request-strips.ts +1 -1
  21. package/src/adapters/openai-responses/transport.ts +17 -26
  22. package/src/adapters/physical-send.ts +3 -3
  23. package/src/adapters/qoder/adapter.ts +1 -1
  24. package/src/adapters/qoder/image-input.ts +5 -2
  25. package/src/adapters/zed-openai-stream.ts +2 -1
  26. package/src/bridge/errors.ts +11 -2
  27. package/src/bridge/response-json.ts +2 -1
  28. package/src/bridge/sse.ts +14 -6
  29. package/src/chat/failure-verdict.ts +21 -0
  30. package/src/chat/outbound.ts +139 -21
  31. package/src/claude/outbound.ts +49 -2
  32. package/src/cli/agent.ts +44 -15
  33. package/src/cli/capabilities-agents-routing.ts +9 -0
  34. package/src/cli/capabilities-base.ts +25 -3
  35. package/src/cli/capabilities-command.ts +12 -3
  36. package/src/cli/capability-contracts.ts +2 -0
  37. package/src/cli/codex-launch-auth.ts +30 -1
  38. package/src/cli/codex-launcher.ts +12 -5
  39. package/src/cli/codex-shim-autorestore.ts +5 -4
  40. package/src/cli/dispatch.ts +11 -176
  41. package/src/cli/ensure-desired-integrations.ts +4 -3
  42. package/src/cli/help.ts +2 -2
  43. package/src/cli/index.ts +9 -2
  44. package/src/cli/link.ts +1 -1
  45. package/src/cli/message-command.ts +2 -1
  46. package/src/cli/message-mcp-command.ts +29 -0
  47. package/src/cli/registry.ts +12 -4
  48. package/src/cli/root.ts +8 -0
  49. package/src/cli/sync-command.ts +243 -0
  50. package/src/cli/sync-fanout-process.ts +92 -0
  51. package/src/cli/sync-fanout.ts +150 -0
  52. package/src/cli/sync-flags.ts +10 -0
  53. package/src/cli/sync-link-status.ts +39 -0
  54. package/src/cli/sync-update-guard.ts +18 -0
  55. package/src/client/connect.ts +31 -14
  56. package/src/client/link-home.ts +3 -2
  57. package/src/client/machine-listener.ts +3 -0
  58. package/src/client/restore-ownership.ts +19 -1
  59. package/src/client/runtime-restart.ts +12 -4
  60. package/src/client/runtime.ts +40 -11
  61. package/src/client/stop-routing.ts +62 -0
  62. package/src/client/sync-runtime.ts +65 -0
  63. package/src/clients/config-export.ts +32 -3
  64. package/src/codex/account-store.ts +1 -0
  65. package/src/codex/auth-context-provider.ts +15 -0
  66. package/src/codex/auth-context.ts +59 -122
  67. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  68. package/src/codex/catalog/provider-models.ts +6 -8
  69. package/src/codex/forward-transport-headers.ts +65 -36
  70. package/src/codex/inject/config-toml.ts +88 -0
  71. package/src/codex/inject/multi-agent-v2.ts +30 -4
  72. package/src/codex/inject/plan.ts +34 -7
  73. package/src/codex/inject-coordination.ts +11 -0
  74. package/src/codex/inject.ts +18 -7
  75. package/src/codex/installation-id.ts +72 -0
  76. package/src/codex/lineage.ts +13 -7
  77. package/src/codex/quota.ts +22 -6
  78. package/src/codex/request-owned-affinity-key.ts +11 -0
  79. package/src/codex/request-owned-affinity.ts +118 -0
  80. package/src/codex/request-owned-main-pin.ts +86 -0
  81. package/src/codex/role-capability.ts +52 -41
  82. package/src/codex/routing/active-account.ts +13 -5
  83. package/src/codex/routing/selection.ts +40 -1
  84. package/src/codex/routing/thread-affinity-store.ts +916 -0
  85. package/src/codex/routing/thread-affinity.ts +90 -12
  86. package/src/codex/toml-source-lines.ts +72 -13
  87. package/src/combos/failover.ts +6 -109
  88. package/src/combos/request.ts +2 -2
  89. package/src/combos/resolve.ts +29 -11
  90. package/src/config/process-state.ts +5 -0
  91. package/src/config/schema/leaf-validators.ts +1 -0
  92. package/src/generated/compatibility-version.json +496 -192
  93. package/src/grok/sync.ts +10 -1
  94. package/src/images/loop.ts +2 -1
  95. package/src/lib/client-error-body.ts +184 -0
  96. package/src/lib/client-retry-after.ts +66 -0
  97. package/src/lib/config-ownership.ts +4 -0
  98. package/src/lib/context-overflow-verdict.ts +113 -0
  99. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  100. package/src/lib/desktop-cli-handoff.mjs +11 -1
  101. package/src/lib/empty-tool-catalog.ts +25 -3
  102. package/src/lib/error-destination.ts +47 -0
  103. package/src/lib/failure-detail.ts +66 -0
  104. package/src/lib/model-identity.ts +44 -0
  105. package/src/lib/private-sqlite-path.ts +124 -0
  106. package/src/lib/response-service-tier.ts +17 -0
  107. package/src/lib/retry-after.ts +3 -0
  108. package/src/lib/spend-ledger-owner.ts +43 -4
  109. package/src/lib/upstream-condition.ts +142 -0
  110. package/src/lib/upstream-retry.ts +14 -11
  111. package/src/lib/windows-owner-acl.ts +13 -6
  112. package/src/lib/windows-secret-acl.ts +2 -2
  113. package/src/link/remote-platform.ts +14 -0
  114. package/src/link/remote-windows.ts +51 -9
  115. package/src/link/ssh-argv.ts +63 -10
  116. package/src/messaging/mcp-queue-rpc.ts +102 -0
  117. package/src/messaging/mcp-queue-server.ts +42 -0
  118. package/src/messaging/mcp-queue-tools.ts +39 -0
  119. package/src/oauth/anthropic-identity.ts +2 -6
  120. package/src/oauth/generic-account-failover.ts +13 -11
  121. package/src/oauth/index.ts +41 -74
  122. package/src/oauth/oauth-errors.ts +67 -0
  123. package/src/oauth/store.ts +1 -1
  124. package/src/protocols/codecs/ollama.ts +197 -0
  125. package/src/protocols/encoders/adapter-events.ts +4 -0
  126. package/src/protocols/encoders/chat.ts +18 -10
  127. package/src/protocols/trace.ts +18 -0
  128. package/src/providers/anthropic-subscription.ts +25 -0
  129. package/src/providers/claude-cli-usage.ts +15 -67
  130. package/src/providers/fastwire.ts +3 -2
  131. package/src/providers/quota/anthropic-decision-windows.ts +5 -19
  132. package/src/providers/quota/anthropic-usage-windows.ts +65 -0
  133. package/src/providers/quota/vendor-probes-key.ts +60 -24
  134. package/src/providers/request-pacing.ts +3 -2
  135. package/src/responses/apply-patch-envelope.ts +45 -19
  136. package/src/responses/compaction-history-framing.ts +5 -1
  137. package/src/responses/freeform-wrapper-scan.ts +5 -3
  138. package/src/responses/parser-tools.ts +1 -0
  139. package/src/responses/progressive-freeform-input.ts +354 -45
  140. package/src/responses/schema.ts +5 -2
  141. package/src/routing/fallback-policy.ts +3 -1
  142. package/src/server/admission-model-scope.ts +17 -6
  143. package/src/server/admitted-http-turn.ts +56 -0
  144. package/src/server/audio-dictation.ts +3 -0
  145. package/src/server/audio-live.ts +8 -2
  146. package/src/server/audio-upstream.ts +2 -0
  147. package/src/server/auth-cors.ts +5 -0
  148. package/src/server/chat-completions.ts +45 -20
  149. package/src/server/chat-native-sse.ts +52 -7
  150. package/src/server/chat-native.ts +60 -35
  151. package/src/server/claude-bridge-pool-session.ts +59 -0
  152. package/src/server/claude-messages.ts +57 -27
  153. package/src/server/context-history.ts +14 -7
  154. package/src/server/images.ts +14 -5
  155. package/src/server/inbound-body-admission.ts +11 -4
  156. package/src/server/index/live-sideband.ts +16 -2
  157. package/src/server/index/ollama-routes.ts +89 -0
  158. package/src/server/index/serve-options.ts +22 -4
  159. package/src/server/index/websocket-handler.ts +5 -3
  160. package/src/server/index.ts +6 -36
  161. package/src/server/inference/client-encoder-delivery.ts +4 -2
  162. package/src/server/json-serialized-bytes.ts +44 -0
  163. package/src/server/live.ts +30 -5
  164. package/src/server/management/agent-settings-routes.ts +24 -21
  165. package/src/server/management/codex-cli-update-routes.ts +2 -1
  166. package/src/server/management/route-registry.ts +1 -1
  167. package/src/server/messages-native-scope.ts +2 -1
  168. package/src/server/messages-native-tool-guard.ts +1 -1
  169. package/src/server/messages-native.ts +12 -7
  170. package/src/server/messages-shared.ts +6 -2
  171. package/src/server/native-final-log.ts +93 -0
  172. package/src/server/ollama-inbound.ts +349 -0
  173. package/src/server/ollama-native-paths.ts +21 -0
  174. package/src/server/ollama-route-policy.ts +73 -0
  175. package/src/server/relay.ts +22 -3
  176. package/src/server/request-decompress.ts +4 -2
  177. package/src/server/request-log-failure-attribution.ts +22 -0
  178. package/src/server/request-log-failure-detail.ts +80 -0
  179. package/src/server/request-log-terminal-status.ts +4 -2
  180. package/src/server/request-log.ts +79 -42
  181. package/src/server/response-log-body.ts +6 -1
  182. package/src/server/responses/account-change-state.ts +17 -6
  183. package/src/server/responses/adapter-continuation.ts +9 -4
  184. package/src/server/responses/adapter-delivery.ts +5 -4
  185. package/src/server/responses/adapter-dispatch.ts +36 -30
  186. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  187. package/src/server/responses/codex-auth-error.ts +22 -17
  188. package/src/server/responses/codex-ws-exchange.ts +11 -8
  189. package/src/server/responses/codex-ws-metadata.ts +94 -21
  190. package/src/server/responses/codex-ws-request.ts +3 -1
  191. package/src/server/responses/combo-required-tool-contract.ts +24 -12
  192. package/src/server/responses/compact.ts +89 -41
  193. package/src/server/responses/compaction-recovery.ts +4 -2
  194. package/src/server/responses/compaction-routing.ts +9 -4
  195. package/src/server/responses/core-auth.ts +32 -14
  196. package/src/server/responses/core-codex-account.ts +34 -12
  197. package/src/server/responses/core-combo-failure.ts +5 -1
  198. package/src/server/responses/core-combo-native.ts +2 -1
  199. package/src/server/responses/core-combo.ts +51 -33
  200. package/src/server/responses/core-errors.ts +22 -20
  201. package/src/server/responses/core-lifetime.ts +6 -3
  202. package/src/server/responses/core-normalize.ts +8 -1
  203. package/src/server/responses/core-options.ts +7 -0
  204. package/src/server/responses/core-pipeline.ts +4 -3
  205. package/src/server/responses/fetch-helpers.ts +7 -1
  206. package/src/server/responses/input-admission.ts +28 -2
  207. package/src/server/responses/native-injection.ts +1 -1
  208. package/src/server/responses/native-response-json.ts +13 -4
  209. package/src/server/responses/native-response-output.ts +1 -2
  210. package/src/server/responses/non-replayable-error.ts +2 -1
  211. package/src/server/responses/pacing-overload.ts +3 -2
  212. package/src/server/responses/passthrough-build-error.ts +36 -0
  213. package/src/server/responses/passthrough-delivery.ts +55 -14
  214. package/src/server/responses/passthrough-dispatch.ts +26 -39
  215. package/src/server/responses/passthrough-error.ts +9 -9
  216. package/src/server/responses/policy-fallback.ts +2 -1
  217. package/src/server/responses/request-prepare.ts +67 -48
  218. package/src/server/responses/request-sidecar-auth.ts +3 -1
  219. package/src/server/responses/request-transport.ts +35 -31
  220. package/src/server/responses/run-turn-execution.ts +6 -6
  221. package/src/server/responses/sidecar-execution.ts +16 -12
  222. package/src/server/responses/spend-storage-error.ts +2 -1
  223. package/src/server/responses/ws-upstream.ts +9 -0
  224. package/src/server/responses-custom-tool-repair.ts +14 -3
  225. package/src/server/responses-terminal-repair.ts +5 -2
  226. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  227. package/src/server/safe-response-headers.ts +162 -13
  228. package/src/server/search.ts +13 -4
  229. package/src/server/turn-state-handles.ts +164 -0
  230. package/src/server/workflow-refusal.ts +2 -1
  231. package/src/server/ws-bridge.ts +5 -2
  232. package/src/service/ownership-mutation-lease.d.mts +11 -2
  233. package/src/service/ownership-mutation-lease.mjs +53 -11
  234. package/src/types/config.ts +2 -0
  235. package/src/update/index.ts +133 -25
  236. package/src/update/npm-install.d.mts +8 -0
  237. package/src/update/npm-install.mjs +20 -1
  238. package/src/update/orchestrated-admission.d.mts +4 -0
  239. package/src/update/orchestrated-admission.mjs +12 -0
  240. package/src/update/orchestrated-arguments.d.mts +12 -0
  241. package/src/update/orchestrated-arguments.mjs +64 -0
  242. package/src/update/orchestrated-child.d.mts +12 -0
  243. package/src/update/orchestrated-child.mjs +70 -0
  244. package/src/update/orchestrated-entry.ts +234 -0
  245. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  246. package/src/update/orchestrated-identity.ts +53 -0
  247. package/src/update/orchestrated-live-identity.ts +48 -0
  248. package/src/update/orchestrated-node-driver.mjs +99 -0
  249. package/src/update/orchestrated-outcome.d.mts +21 -0
  250. package/src/update/orchestrated-outcome.mjs +40 -0
  251. package/src/update/orchestrated-plan.ts +49 -0
  252. package/src/update/orchestrated-pnpm.d.mts +8 -0
  253. package/src/update/orchestrated-pnpm.mjs +33 -0
  254. package/src/update/orchestrated-session.d.mts +37 -0
  255. package/src/update/orchestrated-session.mjs +264 -0
  256. package/src/update/orchestrated-token.d.mts +10 -0
  257. package/src/update/orchestrated-token.mjs +21 -0
  258. package/src/update/orchestrated-token.ts +3 -0
  259. package/src/update/orchestrated-tree.d.mts +1 -0
  260. package/src/update/orchestrated-tree.mjs +14 -0
  261. package/src/update/pnpm-global-install.d.mts +6 -0
  262. package/src/update/pnpm-global-install.mjs +9 -2
  263. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  264. package/src/update/posix-install-supervisor.d.mts +10 -0
  265. package/src/update/posix-install-supervisor.mjs +88 -0
  266. package/src/update/sync-update-mutex.d.mts +10 -0
  267. package/src/update/sync-update-mutex.mjs +164 -0
  268. package/src/update/sync-update-mutex.ts +1 -0
  269. package/src/update/test-home-guard.mjs +33 -0
  270. package/src/update/transactional-install.mjs +2 -2
  271. package/src/usage/error-detail.ts +225 -0
  272. package/src/usage/log.ts +60 -27
  273. package/src/vision/describe.ts +4 -7
  274. package/src/web-search/executor.ts +4 -7
  275. package/src/web-search/loop.ts +31 -5
  276. package/gui/dist/assets/index-D7DCm5eQ.js +0 -94
package/src/grok/sync.ts CHANGED
@@ -32,9 +32,15 @@ async function defaultFetchAllModels(config: OcxConfig): Promise<CatalogModel[]>
32
32
  export async function syncGrokConfig(
33
33
  port: number,
34
34
  config: OcxConfig,
35
- opts: { hostname?: string; probeHostname?: string; grokHome?: string; refreshOnly?: { admit: () => boolean } } = {},
35
+ opts: { hostname?: string; probeHostname?: string; grokHome?: string; refreshOnly?: { admit: () => boolean };
36
+ /** Recheck caller-owned desired state/lifecycle after asynchronous catalog work. */
37
+ admit?: () => boolean } = {},
36
38
  deps: GrokSyncDeps = { fetchAllModels: defaultFetchAllModels, injectGrokConfig },
37
39
  ): Promise<GrokInjectResult> {
40
+ const skipped = (): GrokInjectResult => ({
41
+ ok: true, changed: false, message: "Grok config sync skipped: caller admission is no longer current.",
42
+ });
43
+ if (opts.admit && !opts.admit()) return skipped();
38
44
  let projection: ReturnType<typeof projectGrokCatalog>;
39
45
  try {
40
46
  const allRouted = await deps.fetchAllModels(config);
@@ -54,6 +60,9 @@ export async function syncGrokConfig(
54
60
  unauthenticatedLoopbackListener: config.unauthenticatedLoopbackListener,
55
61
  });
56
62
  const targetUrl = new URL(target.baseUrl);
63
+ // Admission and the synchronous writer share one event-loop turn. A toggle or
64
+ // shutdown that landed while catalog discovery awaited must win over this snapshot.
65
+ if (opts.admit && !opts.admit()) return skipped();
57
66
  return deps.injectGrokConfig(Number(targetUrl.port), projection.models, {
58
67
  hostname: target.requiresAdmissionToken
59
68
  ? (opts.hostname ?? config.hostname)
@@ -348,6 +348,7 @@ export interface ImageBridgeDeps {
348
348
  waitForRequestSlot?: (signal?: AbortSignal) => Promise<ProviderRequestSlot | void>;
349
349
  /** Raw adapter usage at the terminal event, pre wire-normalization (see bridgeToResponsesSSE onUsage). */
350
350
  onUsage?: (usage: OcxUsage | undefined) => void;
351
+ proxyErrorContext?: object;
351
352
  /**
352
353
  * After an `on429` rotation, offered the usage of the hidden iterations the left credential
353
354
  * served. Returning true means it was billed to that credential's attempt, so `onUsage` will not
@@ -1215,7 +1216,7 @@ export async function runWithImageBridge(deps: ImageBridgeDeps): Promise<Respons
1215
1216
  internalAbort.abort("client closed responses stream");
1216
1217
  }, 2_000,
1217
1218
  {
1218
- translatorBudget,
1219
+ translatorBudget, proxyErrorContext: deps.proxyErrorContext,
1219
1220
  replayCacheScope: parsed._reasoningReplayScope,
1220
1221
  ...(deps.clientToolCatalogRestriction ? { ...deps.clientToolCatalogRestriction, enforceDeclaredToolNames: false } : {}),
1221
1222
  ...(deps.forceEmptyResponseId ? { responseId: "" } : {}),
@@ -0,0 +1,184 @@
1
+ import { CYBER_POLICY_FALLBACK_MESSAGE, classifyError } from "./errors";
2
+ import { classifyUpstreamCondition, upstreamConditionMessage, type UpstreamConditionEvidence } from "./upstream-condition";
3
+
4
+ const openaiTypes = ["invalid_request_error", "authentication_error", "permission_error", "not_found_error", "rate_limit_error", "server_error", "upstream_error", "insufficient_quota", "client_cancelled", "cyber_policy", "model_not_allowed_for_key", "api_error", "overloaded_error"] as const;
5
+ const openaiCodes = [
6
+ "spend_ledger_storage_unavailable", "previous_response_not_found", "client_cancelled", "client_closed_request",
7
+ "cyber_policy", "input_admission_refused", "inbound_body_too_large", "context_length_exceeded", "tool_catalog_too_large",
8
+ "rate_limit_exceeded", "insufficient_quota", "request_send_budget_exhausted", "origin_rejected", "upstream_server_error",
9
+ "invalid_api_key", "permission_denied", "location_not_supported", "subscription_required", "server_is_overloaded", "invalid_request_error",
10
+ "usage_limit_reached", "slow_down", "misalignment_policy_violation", "invalid_prompt", "bio_policy", "model_not_in_plan",
11
+ "upstream_reset_replay_refused", "upstream_no_response", "upstream_closed_before_response", "claude_subscription_cooldown",
12
+ "model_not_found", "model_not_allowed_for_key", "undeclared_tool_call", "required_tool_contract_unsatisfied",
13
+ "translation_buffer_limit", "invalid_refusal", "unsupported_feature", "agent_assertion_unsupported", "upstream_error",
14
+ "upstream_sse_truncated", "upstream_sse_error", "upstream_sse_unterminated", "upstream_sse_invalid", "upstream_stream_incomplete", "upstream_stream_error", "upstream_stall_timeout",
15
+ "upstream_incomplete", "server_busy", "outbound_body_too_large", "codex_no_account", "memory_model_target_unavailable", "intercept_target_unavailable",
16
+ "observation_barrier_timeout", "claude_thread_unsupported", "claude_compatibility_configuration", "claude_compatibility_unsupported",
17
+ "unsupported_credential_domain", "unsupported_synthetic_selector", "unsupported_shadow_rewrite",
18
+ "workflow_sends_exhausted", "workflow_children_exhausted", "workflow_concurrency_exhausted", "workflow_spend_exhausted",
19
+ "workflow_tracking_exhausted", "workflow_send_replayed", "workflow_pool_history_unresolved", "workflow_spend_undurable",
20
+ ] as const;
21
+ function literalMap<const T extends readonly string[]>(values: T): ReadonlyMap<string, T[number]> {
22
+ return new Map(values.map(value => [value, value]));
23
+ }
24
+ export const OPENAI_ERROR_TYPES = literalMap(openaiTypes);
25
+ export const OPENAI_ERROR_CODES = literalMap(openaiCodes);
26
+ export const ANTHROPIC_ERROR_TYPES = literalMap(["invalid_request_error", "authentication_error", "permission_error", "not_found_error", "request_too_large", "rate_limit_error", "api_error", "overloaded_error", "billing_error", "timeout_error", "conflict_error"] as const);
27
+ export const ANTHROPIC_ERROR_CODES = literalMap([...ANTHROPIC_ERROR_TYPES.values(), ...openaiCodes] as const);
28
+ export const CLAUDE_CONTEXT_OVERFLOW_MESSAGE = "prompt is too long: The request exceeds the model's context window.";
29
+ export const CLIENT_ERROR_CONTRACTS = {
30
+ context_overflow: "The request exceeds the model's context window.",
31
+ cyber_policy: CYBER_POLICY_FALLBACK_MESSAGE,
32
+ invalid_prompt: "The provider refused this request.",
33
+ misalignment_policy_violation: "The provider refused this request under its policy.",
34
+ bio_policy: "The provider refused this request under its policy.",
35
+ model_not_in_plan: "The selected model is not included in your provider plan (MODEL_NOT_IN_PLAN). Choose a model the plan includes or change the plan; retrying this request will not succeed.",
36
+ replay_refused: "The provider connection closed after the request was sent. This proxy refused to replay the request automatically.",
37
+ translation_buffer_limit: "upstream translation buffer exceeded the safe limit",
38
+ invalid_refusal: "upstream refusal representations are inconsistent",
39
+ undeclared_tool_call: "Upstream emitted a client tool call outside this request's declared tool catalog.",
40
+ required_tool_contract_unsatisfied: "The provider did not return the tool call required by this request.",
41
+ transport_failed: "The proxy could not reach or read the provider.",
42
+ stream_incomplete: "The provider stream ended before the request completed.",
43
+ } as const;
44
+ export type ClientErrorContract = keyof typeof CLIENT_ERROR_CONTRACTS;
45
+ export const UNDECLARED_TOOL_CALL_MESSAGE = "routed provider emitted undeclared client tool; only request-declared tools may be called";
46
+ /** Only producers of synthetic incomplete events register these process-local origins. */
47
+ type ProxyIncompleteReason = "adapter_eof" | "upstream_stall_timeout" | "missing_terminal_event";
48
+ const proxyIncompletes = new WeakMap<object, Set<string>>();
49
+ export function rememberProxyIncomplete(context: object, reason: ProxyIncompleteReason): void {
50
+ let reasons = proxyIncompletes.get(context);
51
+ if (!reasons) { reasons = new Set(); proxyIncompletes.set(context, reasons); }
52
+ reasons.add(reason);
53
+ }
54
+ export function hasProxyIncomplete(context: object | undefined, reason: unknown, message?: unknown): boolean {
55
+ return message === undefined && context !== undefined && typeof reason === "string" && proxyIncompletes.get(context)?.has(reason) === true;
56
+ }
57
+ export function carryProxyIncompleteContext<T extends object>(source: object, target: T): T {
58
+ let reasons = proxyIncompletes.get(source);
59
+ if (!reasons) { reasons = new Set(); proxyIncompletes.set(source, reasons); }
60
+ proxyIncompletes.set(target, reasons);
61
+ return target;
62
+ }
63
+ const CODE_MESSAGES: ReadonlyMap<string, string> = new Map([
64
+ ["context_length_exceeded", CLIENT_ERROR_CONTRACTS.context_overflow],
65
+ ["upstream_incomplete", CLIENT_ERROR_CONTRACTS.stream_incomplete],
66
+ ["upstream_stream_incomplete", CLIENT_ERROR_CONTRACTS.stream_incomplete],
67
+ ["upstream_reset_replay_refused", CLIENT_ERROR_CONTRACTS.replay_refused],
68
+ ...["cyber_policy", "invalid_prompt", "misalignment_policy_violation", "bio_policy", "model_not_in_plan", "translation_buffer_limit", "invalid_refusal", "undeclared_tool_call", "required_tool_contract_unsatisfied"].map(code => [code, CLIENT_ERROR_CONTRACTS[code as ClientErrorContract]] as const),
69
+ ]);
70
+ /** Local guidance is selected only by a closed reason supplied by the owning proxy call site. */
71
+ export const LOCAL_CHAT_ERROR_MESSAGES: ReadonlyMap<string, string> = new Map([
72
+ ["credentials_paused", "The configured credentials are paused. Resume an account or key in account settings before retrying."],
73
+ ["request_send_budget_exhausted", "This request reached the proxy's send budget. Start a new request or adjust the configured budget."],
74
+ ["spend_ledger_storage_unavailable", "The proxy cannot record spending. Restore spend-ledger storage before retrying."],
75
+ ["model_not_allowed_for_key", "This model is not allowed for the configured key. Choose an allowed model."],
76
+ ["usage_limit_reached", "The configured usage limit was reached. Review the proxy's usage limits before retrying."],
77
+ ["workflow_sends_exhausted", "The task reached its send ceiling. Wait for the workflow window or adjust its budget."],
78
+ ["workflow_children_exhausted", "The task reached its child limit. Wait for the workflow window or adjust its budget."],
79
+ ["workflow_concurrency_exhausted", "The task has no free concurrency slot. Wait for an active child to finish."],
80
+ ["workflow_spend_exhausted", "The configured token ceiling was reached. Review the task, account and pool budgets."],
81
+ ["workflow_tracking_exhausted", "The proxy reached its tracked-task limit. Wait for an active task to finish."],
82
+ ["workflow_send_replayed", "The proxy refused a send that was already reserved."],
83
+ ["workflow_pool_history_unresolved", "Provider pool spending history must be resolved before sending."],
84
+ ["workflow_spend_undurable", "The proxy cannot record the token reservation. Restore spend-ledger storage before retrying."],
85
+ ]);
86
+ export interface OwnedChatErrorOptions {
87
+ status: number; type?: string; code?: string | null; evidence: UpstreamConditionEvidence;
88
+ contract?: ClientErrorContract; providerId?: string; localReason?: string;
89
+ }
90
+ export function ownedChatErrorPayload(options: OwnedChatErrorOptions) {
91
+ const { status, evidence } = options;
92
+ const type = OPENAI_ERROR_TYPES.get(options.type ?? "") ?? (status === 401 ? "authentication_error" : status === 403 ? "permission_error" : status === 429 ? "rate_limit_error" : status >= 500 ? "server_error" : "invalid_request_error");
93
+ const code = OPENAI_ERROR_CODES.get(options.code ?? "") ?? (status === 401 ? "invalid_api_key" : status === 404 ? "model_not_found" : status === 429 ? "rate_limit_exceeded" : null);
94
+ const fixedMessage = options.contract === undefined
95
+ && code !== "cyber_policy" && code !== "context_length_exceeded" ? fixedProxyErrorMessage(evidence.message) : undefined;
96
+ const message = actionableRefusalMessage(evidence, code, options.contract)
97
+ ?? (options.contract ? CLIENT_ERROR_CONTRACTS[options.contract] : undefined) ?? fixedMessage
98
+ ?? LOCAL_CHAT_ERROR_MESSAGES.get(options.localReason ?? "") ?? CODE_MESSAGES.get(code ?? "")
99
+ ?? upstreamConditionMessage(classifyUpstreamCondition(evidence) ?? "upstream_failed", options.providerId);
100
+ return { error: { message, type, param: null, code } };
101
+ }
102
+ /**
103
+ * Provider refusals the user acts on by changing the request (model or plan). The key is the exact
104
+ * token; the value is the proxy's own message, which carries the proxy's copy of that token.
105
+ */
106
+ const ACTIONABLE_REFUSALS: ReadonlyMap<string, string> = new Map([
107
+ ["MODEL_NOT_IN_PLAN", CLIENT_ERROR_CONTRACTS.model_not_in_plan],
108
+ ]);
109
+ /** Codes a plan refusal travels under: the buffered code, and the stream code that ends the turn. */
110
+ const REFUSAL_CARRIER_CODES: ReadonlySet<string> = new Set(["model_not_in_plan", "invalid_prompt"]);
111
+ const REFUSAL_TOKEN_SCAN = 4096;
112
+ /**
113
+ * The fixed message for a known actionable refusal, or undefined. A structured code matches when it
114
+ * equals a listed token after case and hyphen folding. The message is read only for a refusal-carrying
115
+ * code, and only for a listed token standing as a whole word; nothing from it is returned.
116
+ */
117
+ export function actionableRefusalMessage(
118
+ evidence: UpstreamConditionEvidence, code: string | null, contract?: ClientErrorContract,
119
+ ): string | undefined {
120
+ if (contract !== undefined && !REFUSAL_CARRIER_CODES.has(contract)) return undefined;
121
+ const structured = typeof evidence.code === "string" && evidence.code.length <= 64
122
+ ? evidence.code.trim().toUpperCase().replaceAll("-", "_") : undefined;
123
+ if (structured !== undefined && ACTIONABLE_REFUSALS.has(structured)) return ACTIONABLE_REFUSALS.get(structured);
124
+ if (code === null || !REFUSAL_CARRIER_CODES.has(code) || typeof evidence.message !== "string") return undefined;
125
+ const scanned = evidence.message.slice(0, REFUSAL_TOKEN_SCAN);
126
+ for (const [token, message] of ACTIONABLE_REFUSALS) {
127
+ if (new RegExp(`(^|[^A-Za-z0-9_])${token}(?![A-Za-z0-9_])`).test(scanned)) return message;
128
+ }
129
+ return undefined;
130
+ }
131
+ export function canonicalSseErrorBlock(payload: unknown): string { return `data: ${JSON.stringify(payload)}\n\n`; }
132
+ const comboEvidence = new WeakMap<Response, string>();
133
+ export function attachComboFailureEvidence(response: Response, legacyBodyText: string): Response {
134
+ comboEvidence.set(response, legacyBodyText); return response;
135
+ }
136
+ export function comboFailureEvidence(response: Response): string | undefined { return comboEvidence.get(response); }
137
+
138
+ /** Identity belongs to the locally constructed object, never to serialized fields. */
139
+ const proxyErrors = new WeakSet<object>();
140
+ export function markProxyError<T extends object>(value: T): T { proxyErrors.add(value); return value; }
141
+ export function isProxyError(value: object): boolean { return proxyErrors.has(value); }
142
+ export function carryProxyError<T extends object>(source: object, target: T): T {
143
+ return isProxyError(source) ? markProxyError(target) : target;
144
+ }
145
+ /** The tool guard records only messages it constructs for this response's request context. */
146
+ export interface ProxyErrorMessageFields { type?: string; code?: string | null }
147
+ const proxyMessages = new WeakMap<object, Map<string, Set<string>>>();
148
+ const errorFields = (fields: ProxyErrorMessageFields) => JSON.stringify([fields.type ?? null, fields.code ?? null]);
149
+ export function rememberProxyErrorMessage(context: object, message: string, fields: ProxyErrorMessageFields & { status: number }): void {
150
+ let messages = proxyMessages.get(context);
151
+ if (!messages) { messages = new Map(); proxyMessages.set(context, messages); }
152
+ let allowed = messages.get(message);
153
+ if (!allowed) { allowed = new Set(); messages.set(message, allowed); }
154
+ const classified = classifyError(fields.status, fields.type ?? "upstream_error", message);
155
+ // The bridge may classify a field while preserving the other field's explicit local verdict.
156
+ for (const type of [fields.type, classified.type]) for (const code of [fields.code, classified.code]) allowed.add(errorFields({ type, code }));
157
+ }
158
+ export function carryProxyErrorContext(source: object, target: object): void {
159
+ carryProxyIncompleteContext(source, target);
160
+ let messages = proxyMessages.get(source);
161
+ if (!messages) { messages = new Map(); proxyMessages.set(source, messages); }
162
+ proxyMessages.set(target, messages);
163
+ }
164
+ export function hasProxyErrorMessage(context: object | undefined, message: string, fields: ProxyErrorMessageFields): boolean {
165
+ return context !== undefined && proxyMessages.get(context)?.get(message)?.has(errorFields(fields)) === true;
166
+ }
167
+ // These complete sentences contain only proxy literals, including each recognized reason.
168
+ const PROXY_FIXED_MESSAGES: ReadonlyMap<string, string> = literalMap([
169
+ "internal replay returned a non-JSON response",
170
+ "upstream returned malformed Chat Completions JSON",
171
+ "upstream response contained no choices",
172
+ "upstream response ended without a supported completion boundary",
173
+ "upstream returned malformed SSE JSON",
174
+ "upstream returned an invalid SSE event",
175
+ "upstream SSE ended with an unterminated event",
176
+ "upstream SSE ended mid tool call without a terminal signal — possible truncation",
177
+ "upstream SSE ended before a terminal event",
178
+ "upstream stream stalled without meaningful progress",
179
+ "routed provider emitted a client tool call outside the current request's explicit tool catalog",
180
+ "upstream stream ended before a terminal frame (truncated response)",
181
+ ] as const);
182
+ export function fixedProxyErrorMessage(message: unknown): string | undefined {
183
+ return typeof message === "string" ? PROXY_FIXED_MESSAGES.get(message) : undefined;
184
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Client-facing Retry-After formatting, dependency-free so leaf header modules can use it.
3
+ */
4
+
5
+ /**
6
+ * Longest wait this proxy advertises to a client: eight days, so a weekly usage window's reset
7
+ * (a local Codex account cooldown, for example) still reaches the client intact. Internal cooldowns
8
+ * keep their own parsed values.
9
+ */
10
+ export const MAX_CLIENT_RETRY_AFTER_SECONDS = 8 * 24 * 60 * 60;
11
+
12
+ // RFC 9110 HTTP-date forms: IMF-fixdate, obsolete RFC 850, and asctime. All are GMT; they are
13
+ // parsed field by field because Date.parse reads a zoneless asctime date in local time.
14
+ const IMF_FIXDATE = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/;
15
+ const RFC850_DATE = /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-([A-Za-z]{3})-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/;
16
+ const ASCTIME_DATE = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) ([A-Za-z]{3}) ([ \d]\d) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/;
17
+ const MONTHS = new Map(["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"].map((name, index) => [name, index]));
18
+
19
+ function utcMs(day: string, monthName: string, year: number, hour: string, minute: string, second: string): number | undefined {
20
+ const month = MONTHS.get(monthName.toLowerCase());
21
+ const [d, h, m, s] = [Number(day), Number(hour), Number(minute), Number(second)];
22
+ if (month === undefined || d < 1 || h > 23 || m > 59 || s > 60) return undefined;
23
+ const at = Date.UTC(year, month, d, h, m, s);
24
+ return new Date(at).getUTCDate() === d ? at : undefined;
25
+ }
26
+
27
+ /** Milliseconds since the epoch for an RFC 9110 HTTP-date, or undefined. */
28
+ function httpDateMs(value: string, now: number): number | undefined {
29
+ let match = IMF_FIXDATE.exec(value);
30
+ if (match) return utcMs(match[1]!, match[2]!, Number(match[3]), match[4]!, match[5]!, match[6]!);
31
+ match = RFC850_DATE.exec(value);
32
+ if (match) {
33
+ // A two-digit year more than 50 years ahead is read as the previous century (RFC 9110 5.6.7).
34
+ let year = 2000 + Number(match[3]);
35
+ if (year > new Date(now).getUTCFullYear() + 50) year -= 100;
36
+ return utcMs(match[1]!, match[2]!, year, match[4]!, match[5]!, match[6]!);
37
+ }
38
+ match = ASCTIME_DATE.exec(value);
39
+ if (match) return utcMs(match[2]!.trim(), match[1]!, Number(match[6]), match[3]!, match[4]!, match[5]!);
40
+ return undefined;
41
+ }
42
+
43
+ /**
44
+ * Retry advice as bytes this proxy writes: a non-negative integer number of seconds, clamped to
45
+ * {@link MAX_CLIENT_RETRY_AFTER_SECONDS}, or undefined. Accepts delay seconds (including "0" and
46
+ * fractions, rounded up) and HTTP dates in any RFC 9110 form (past or current -> "0"). The input
47
+ * string is never echoed. For client headers and bodies only; cooldown and retry scheduling read
48
+ * the parsed evidence.
49
+ */
50
+ export function formatClientRetryAfter(value: string | number | null | undefined, now = Date.now()): string | undefined {
51
+ let seconds: number | undefined;
52
+ if (typeof value === "number") {
53
+ seconds = Number.isFinite(value) && value >= 0 ? value : undefined;
54
+ } else if (typeof value === "string") {
55
+ const trimmed = value.trim();
56
+ if (!trimmed || trimmed.length > 128) return undefined;
57
+ if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
58
+ seconds = Number(trimmed);
59
+ } else {
60
+ const at = httpDateMs(trimmed, now);
61
+ if (at !== undefined) seconds = Math.max(0, (at - now) / 1000);
62
+ }
63
+ }
64
+ if (seconds === undefined || !Number.isFinite(seconds)) return undefined;
65
+ return String(Math.min(MAX_CLIENT_RETRY_AFTER_SECONDS, Math.ceil(seconds)));
66
+ }
@@ -53,6 +53,10 @@ const INITIAL_OWNED_PATHS = [
53
53
  "config-mutation.sqlite-journal",
54
54
  "config-mutation.sqlite-shm",
55
55
  "config-mutation.sqlite-wal",
56
+ "codex-affinity.sqlite",
57
+ "codex-affinity.sqlite-journal",
58
+ "codex-affinity.sqlite-shm",
59
+ "codex-affinity.sqlite-wal",
56
60
  "local-credentials.json",
57
61
  "local-credential-observers",
58
62
  "local-credential-publication.sqlite",
@@ -0,0 +1,113 @@
1
+ /**
2
+ * The definite context-window overflow verdict, shared by combo failover (src/combos/failover.ts,
3
+ * which re-exports it) and the presentation classifier (src/lib/upstream-condition.ts). It has no
4
+ * imports, so the dashboard's type-only use of the classifier never pulls in server modules.
5
+ */
6
+
7
+ /** A status can carry a verdict about the REQUEST; 401/403/429 speak about the credential. */
8
+ const CONTEXT_VERDICT_STATUSES: ReadonlySet<number> = new Set([400, 413, 422]);
9
+
10
+ /**
11
+ * Phrases a provider emits when the INPUT does not fit this model's context window. Matched
12
+ * against the innermost provider message only, so an unrelated refusal that merely quotes one
13
+ * of these tokens in a code field cannot authorize a replay.
14
+ */
15
+ const DEFINITE_CONTEXT_OVERFLOW_PHRASES = [
16
+ "exceeds the context window",
17
+ "exceed the context window",
18
+ "context window exceeded",
19
+ "context length exceeded",
20
+ "maximum context length",
21
+ "maximum context window",
22
+ "too many tokens",
23
+ ];
24
+
25
+ /**
26
+ * Short provider verdicts that a validation error could otherwise echo as the caller's own value
27
+ * (#7443). Each counts only at the very start of the provider's leaf message, after JSON envelopes
28
+ * are unwrapped, and Anthropic's only with its token counts. Text that merely contains one, including
29
+ * a serialized SDK exception or a quoted caller object, is not evidence: only the phrases dev already
30
+ * matched as substrings keep that wider reach.
31
+ */
32
+ const ANCHORED_CONTEXT_OVERFLOW_VERDICTS: readonly RegExp[] = [
33
+ /^prompt is too long: \d+ tokens > \d+ maximum/i,
34
+ /^input is too long for requested model\b/i,
35
+ /^please reduce the length of the messages or completion\b/i,
36
+ ];
37
+
38
+ /** Wrapper envelopes unwrapped before the leaf message is read. */
39
+ const MAX_CONTEXT_OVERFLOW_ENVELOPES = 4;
40
+
41
+ /**
42
+ * Parameter validation echoes the caller's own value, so its prose is not a context verdict even
43
+ * when the value reads like one: "Invalid 'tools[0].function.name': 'prompt is too long'". These
44
+ * markers are read anywhere in the text, so an SDK error wrapper that serializes such a record as a
45
+ * Python dict is refused too, while a quoted genuine verdict in the same wrapper stays evidence.
46
+ */
47
+ const CONTEXT_PARAM_NAMES = "messages|input|input_text|input_tokens|prompt|contents?|max_tokens|max_completion_tokens|max_output_tokens";
48
+ /** A `param` naming the conversation or a token budget is consistent with an overflow. */
49
+ const CONTEXT_PARAM = new RegExp(`^(?:${CONTEXT_PARAM_NAMES})(?:$|[.[])`, "i");
50
+ const PARAMETER_VALIDATION_CODES: ReadonlySet<string> = new Set(["invalid_value", "invalid_type"]);
51
+ const PARAMETER_VALIDATION_MARKERS: readonly RegExp[] = [
52
+ /\binvalid_(?:value|type)\b/i,
53
+ new RegExp(`['"]param['"]\\s*:\\s*['"](?!(?:${CONTEXT_PARAM_NAMES})(?:['".[]))`, "i"),
54
+ /\binvalid\s+(?:value\s+for\s+)?['"`\u2018\u201c]/i,
55
+ /\binvalid\s+(?:tool|function|parameter|argument|field|value)\b/i,
56
+ /\binput_value\s*=/i,
57
+ /\bvalidation errors? for\b/i,
58
+ ];
59
+
60
+ function isParameterValidationRecord(record: Record<string, unknown>): boolean {
61
+ if (typeof record.code === "string" && PARAMETER_VALIDATION_CODES.has(record.code.toLowerCase())) return true;
62
+ return typeof record.param === "string" && record.param.length > 0 && !CONTEXT_PARAM.test(record.param);
63
+ }
64
+
65
+ function isDefiniteContextOverflowMessage(text: string): boolean {
66
+ if (PARAMETER_VALIDATION_MARKERS.some(marker => marker.test(text))) return false;
67
+ const normalized = text.toLowerCase();
68
+ return normalized === "context_length_exceeded"
69
+ || DEFINITE_CONTEXT_OVERFLOW_PHRASES.some(phrase => normalized.includes(phrase))
70
+ || ANCHORED_CONTEXT_OVERFLOW_VERDICTS.some(verdict => verdict.test(text.trim()));
71
+ }
72
+
73
+ /**
74
+ * Confirm a context overflow from the provider MESSAGE rather than from a code token that
75
+ * merely appears somewhere in the envelope. An upstream controls both fields and can emit a
76
+ * contradictory pair -- `context_length_exceeded` beside `Unsupported parameter: user` -- and
77
+ * that is not evidence the turn is too large for this model. `classifyError` reads the whole
78
+ * blob, which is exactly the looseness this must not inherit.
79
+ *
80
+ * A JSON-shaped body that fails to parse is truncated or corrupt, not prose: `classificationText`
81
+ * is capped at 500 characters by `normalizeUpstreamErrorText` before it reaches this function, so
82
+ * a long envelope arrives here as a JSON prefix. Reading that prefix as plain text would let an
83
+ * arbitrary field that happens to sit in the first 500 bytes authorize a hop, so it fails closed.
84
+ *
85
+ * Only the exact proxy wrapper is unwrapped, within a fixed envelope budget and 16,384 characters.
86
+ * Exported for the sidecar loops, which classify their own provider failures with the same rule.
87
+ */
88
+ export function isDefiniteContextOverflow(status: number, message: string): boolean {
89
+ if (!CONTEXT_VERDICT_STATUSES.has(status) && status < 500) return false;
90
+ if (message.length > 16_384) return false;
91
+ let text = message.trim();
92
+ // One pass per unwrapped envelope, plus one for the leaf the last envelope yields.
93
+ for (let unwrapped = 0; unwrapped <= MAX_CONTEXT_OVERFLOW_ENVELOPES; unwrapped += 1) {
94
+ const providerPrefix = /^Provider error \d{3}:\s*/.exec(text);
95
+ if (providerPrefix) text = text.slice(providerPrefix[0].length).trim();
96
+ if (!text.startsWith("{")) return isDefiniteContextOverflowMessage(text);
97
+ if (unwrapped === MAX_CONTEXT_OVERFLOW_ENVELOPES) return false;
98
+ let payload: unknown;
99
+ try { payload = JSON.parse(text); } catch { return false; }
100
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false;
101
+ const record = payload as Record<string, unknown>;
102
+ const response = record.response && typeof record.response === "object" && !Array.isArray(record.response)
103
+ ? record.response as Record<string, unknown>
104
+ : undefined;
105
+ const source = [record.error, response?.error, response?.last_error, record.last_error, record]
106
+ .find((candidate): candidate is Record<string, unknown> =>
107
+ !!candidate && typeof candidate === "object" && !Array.isArray(candidate)
108
+ && typeof (candidate as Record<string, unknown>).message === "string");
109
+ if (!source || isParameterValidationRecord(source)) return false;
110
+ text = (source.message as string).trim();
111
+ }
112
+ return false;
113
+ }
@@ -16,5 +16,5 @@ export function planDesktopCliHandoff(input?: {
16
16
  recordRead?: DesktopCliRecordRead; selfPaths?: (string | undefined)[];
17
17
  }, deps?: { stat?: typeof statSync; access?: typeof accessSync; realpath?: (path: string) => string }): DesktopCliHandoffPlan;
18
18
  export function runDesktopCliHandoff(plan: Extract<DesktopCliHandoffPlan, { kind: "handoff" }>, launch: {
19
- argv: string[]; env: NodeJS.ProcessEnv; proof: string; context: string;
19
+ argv: string[]; env: NodeJS.ProcessEnv; proof: string; context: string; onSpawn?: (pid: number) => void;
20
20
  }, deps?: { spawn?: typeof spawn; lstat?: typeof lstatSync; parent?: Pick<NodeJS.Process, "on" | "removeListener">; platform?: NodeJS.Platform }): Promise<DesktopCliHandoffExit>;
@@ -10,6 +10,7 @@ export function desktopHandoffExcluded(argv, env = process.env) {
10
10
  const args = argv.filter(arg => !arg.startsWith(PROOF_PREFIX));
11
11
  return env.OCX_NO_DESKTOP_HANDOFF === "1"
12
12
  || ["update", "uninstall", "remove"].includes(args[0])
13
+ || (args[0] === "capabilities" && args.includes("--contracts"))
13
14
  || (args[0] ?? "").startsWith("__")
14
15
  || isCodexCliUpdateInspectionArgv(["node", "ocx.mjs", ...args]);
15
16
  }
@@ -87,6 +88,15 @@ export function runDesktopCliHandoff(plan, launch, deps = {}) {
87
88
  let done = false;
88
89
  const finish = result => { if (done) return; done = true; clear(); resolveExit(result); };
89
90
  child.once("error", error => finish(spawnFailure(error)));
90
- child.once("exit", (code, signal) => finish({ kind: "exit", code: code ?? 1, signal }));
91
+ let delegateError = false;
92
+ child.once("exit", (code, signal) => finish(delegateError ? { kind: "error", issue: "spawn-failed" } : { kind: "exit", code: code ?? 1, signal }));
93
+ if (child.pid && launch.onSpawn) {
94
+ try { launch.onSpawn(child.pid); }
95
+ catch (error) {
96
+ delegateError = true;
97
+ console.error(`opencodex: sync mutex delegate publication failed: ${error.message}`);
98
+ try { child.kill(); } catch (killError) { console.error(`opencodex: failed to stop sync child: ${killError.message}`); }
99
+ }
100
+ }
91
101
  });
92
102
  }
@@ -1,19 +1,41 @@
1
- import { normalizeDeclaredToolName, type AdapterEvent } from "../types";
1
+ import { namespacedToolName, normalizeDeclaredToolName, type AdapterEvent } from "../types";
2
2
  import { UNDECLARED_TOOL_CALL_ERROR_CODE } from "./errors";
3
3
  import { releaseTranslatedEvent, type TranslatorBudget } from "./translator-budget";
4
4
  import { releaseCompactionCiphertextLease } from "../responses/compaction";
5
5
 
6
- /** Snapshot of current-turn declarations when an explicit empty catalog activates enforcement. */
6
+ /** Current-turn names for normalization, with wire-specific membership enforcement. */
7
7
  export interface ClientToolCatalogRestriction {
8
8
  declaredToolNames: ReadonlySet<string>;
9
9
  bareCustomToolNames: ReadonlySet<string>;
10
+ canonicalToolNames?: ReadonlySet<string>;
11
+ enforceDeclaredToolNames?: boolean;
12
+ }
13
+
14
+ /** Current declarations may narrow the selection-filtered bridge names, never widen them. */
15
+ export function currentTurnToolBridgeMaps<T extends Pick<ClientToolCatalogRestriction, "declaredToolNames" | "bareCustomToolNames"> & {
16
+ toolNsMap: ReadonlyMap<string, { namespace: string; name: string }>;
17
+ }>(
18
+ maps: T,
19
+ catalog: ClientToolCatalogRestriction | undefined,
20
+ ): T {
21
+ if (!catalog) return maps;
22
+ const currentIdentity = (name: string): boolean => {
23
+ const mapped = maps.toolNsMap.get(name);
24
+ // An ambiguous historical bare alias may lack a mapping. Keep only current identities.
25
+ return catalog.canonicalToolNames?.has(mapped ? namespacedToolName(mapped.namespace, mapped.name) : name) ?? true;
26
+ };
27
+ return {
28
+ ...maps,
29
+ declaredToolNames: new Set([...catalog.declaredToolNames].filter(name => maps.declaredToolNames.has(name) && currentIdentity(name))),
30
+ bareCustomToolNames: new Set([...catalog.bareCustomToolNames].filter(name => maps.bareCustomToolNames.has(name) && currentIdentity(name))),
31
+ };
10
32
  }
11
33
 
12
34
  export function emptyToolCatalogRefusal(
13
35
  event: AdapterEvent,
14
36
  catalog: ClientToolCatalogRestriction | undefined,
15
37
  ): Extract<AdapterEvent, { type: "error" }> | undefined {
16
- if (!catalog) return;
38
+ if (!catalog || catalog.enforceDeclaredToolNames === false) return;
17
39
  if (event.type === "tool_call_start") {
18
40
  const name = normalizeDeclaredToolName(event.name, catalog.declaredToolNames, undefined, catalog.bareCustomToolNames);
19
41
  if (catalog.declaredToolNames.has(name)) return;
@@ -0,0 +1,47 @@
1
+ /** Destination labels are minted locally and revalidated by the error constructor. */
2
+ declare const errorDestinationBrand: unique symbol;
3
+ export type ErrorDestinationLabel = { readonly [errorDestinationBrand]: true };
4
+ const labels = new WeakMap<object, { kind: "origin" | "provider"; value: string }>();
5
+ const fallback = "the provider";
6
+ const providerId = /^[A-Za-z0-9._-]{1,64}$/;
7
+ const schemes = new Set(["http:", "https:", "ws:", "wss:", "socks5:", "socks5h:"]);
8
+ function origin(value: unknown): string {
9
+ if (typeof value !== "string") return fallback;
10
+ try {
11
+ const url = new URL(value);
12
+ return schemes.has(url.protocol) && url.hostname.length > 0 && url.hostname.length <= 253
13
+ ? `${url.protocol}//${url.host}` : fallback;
14
+ } catch { return fallback; }
15
+ }
16
+ function mint(kind: "origin" | "provider", value: string): ErrorDestinationLabel {
17
+ const label = Object.freeze({}) as ErrorDestinationLabel;
18
+ labels.set(label, { kind, value });
19
+ return label;
20
+ }
21
+ export function errorDestinationLabel(url: string): ErrorDestinationLabel { return mint("origin", origin(url)); }
22
+ export function providerErrorDestinationLabel(id: string): ErrorDestinationLabel {
23
+ return mint("provider", typeof id === "string" && providerId.test(id) ? id : fallback);
24
+ }
25
+ export function errorDestinationText(label: ErrorDestinationLabel): string {
26
+ // Runtime validation also handles callers that supply a value without the branded type.
27
+ const input: unknown = label;
28
+ if (typeof input === "string") return origin(input);
29
+ const owned = input !== null && typeof input === "object" ? labels.get(input) : undefined;
30
+ if (!owned) return fallback;
31
+ return owned.kind === "origin" ? origin(owned.value) : providerId.test(owned.value) ? owned.value : fallback;
32
+ }
33
+
34
+ /** A client selector captured before any route or helper-model rewrite. */
35
+ declare const clientModelBrand: unique symbol;
36
+ export type ClientFacingModelLabel = { readonly [clientModelBrand]: true };
37
+ const clientModels = new WeakMap<object, string>();
38
+ const clientModelId = /^[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*){0,3}$/;
39
+ export function clientFacingModelLabel(requestedModel: unknown, placeholder: "requested" | "unnamed" = "requested"): ClientFacingModelLabel {
40
+ const label = Object.freeze({}) as ClientFacingModelLabel;
41
+ clientModels.set(label, typeof requestedModel === "string" && requestedModel.length <= 128
42
+ && clientModelId.test(requestedModel) ? requestedModel : placeholder === "unnamed" ? "(unnamed)" : "the requested model");
43
+ return label;
44
+ }
45
+ export function clientFacingModelText(label: ClientFacingModelLabel | undefined): string {
46
+ return label && clientModels.get(label) || "the requested model";
47
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Failure detail a request-log row may carry: a closed code plus bounded numeric or closed parameters.
3
+ * The dashboard renders each code as localized text; rows never hold free-form failure text.
4
+ */
5
+ export const FAILURE_DETAIL_CODES = [
6
+ "provider_error",
7
+ "header_timeout",
8
+ "connect_timeout",
9
+ "connect_failed",
10
+ "client_closed",
11
+ "body_stall",
12
+ "body_overflow",
13
+ "stream_error_stop",
14
+ "stream_ended_early",
15
+ "stream_failed",
16
+ "output_limit",
17
+ "stall_timeout",
18
+ "adapter_eof",
19
+ "generation_timeout",
20
+ "turn_inactivity",
21
+ ] as const;
22
+
23
+ export type FailureDetailCode = typeof FAILURE_DETAIL_CODES[number];
24
+
25
+ /** Closed provider error classes a provider_error detail may name (the Anthropic error envelope types). */
26
+ export const FAILURE_DETAIL_PROVIDER_TYPES = [
27
+ "invalid_request_error", "authentication_error", "permission_error", "not_found_error",
28
+ "rate_limit_error", "api_error", "overloaded_error", "request_too_large",
29
+ ] as const;
30
+
31
+ export type FailureDetailProviderType = typeof FAILURE_DETAIL_PROVIDER_TYPES[number];
32
+
33
+ export interface FailureDetail {
34
+ code: FailureDetailCode;
35
+ /** Milliseconds for timeouts and stalls, bytes for an overflow. */
36
+ value?: number;
37
+ type?: FailureDetailProviderType;
38
+ }
39
+
40
+ const CODES: ReadonlySet<string> = new Set(FAILURE_DETAIL_CODES);
41
+ const TYPES: ReadonlySet<string> = new Set(FAILURE_DETAIL_PROVIDER_TYPES);
42
+ const MAX_VALUE = 1e12;
43
+
44
+ /** Codes whose value parameter carries meaning; the value is dropped for any other code. */
45
+ const VALUED: ReadonlySet<FailureDetailCode> = new Set([
46
+ "header_timeout", "connect_timeout", "body_stall", "body_overflow", "generation_timeout", "turn_inactivity",
47
+ ]);
48
+
49
+ /**
50
+ * The detail when it is a closed code with valid parameters, else undefined. Free text (a legacy or
51
+ * edited row) is never accepted. Returns the same object when it is already exactly valid.
52
+ */
53
+ export function boundedFailureDetail(value: unknown): FailureDetail | undefined {
54
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
55
+ const record = value as Record<string, unknown>;
56
+ if (typeof record.code !== "string" || !CODES.has(record.code)) return undefined;
57
+ const code = record.code as FailureDetailCode;
58
+ const number = record.value;
59
+ const valid = typeof number === "number" && Number.isSafeInteger(number) && number >= 0 && number <= MAX_VALUE && VALUED.has(code);
60
+ const type = code === "provider_error" && typeof record.type === "string" && TYPES.has(record.type)
61
+ ? record.type as FailureDetailProviderType : undefined;
62
+ const keys = Object.keys(record);
63
+ const exact = keys.every(key => key === "code" || (key === "value" && valid) || (key === "type" && type !== undefined));
64
+ if (exact) return record as unknown as FailureDetail;
65
+ return { code, ...(valid ? { value: number as number } : {}), ...(type ? { type } : {}) };
66
+ }