@bitkyc08/opencodex 2.55.0-preview.20260914 → 2.56.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 (167) hide show
  1. package/gui/dist/assets/{index-DH2PUHqr.js → index-D4zuyIxQ.js} +1 -1
  2. package/gui/dist/index.html +1 -1
  3. package/package.json +2 -1
  4. package/src/adapters/base.ts +21 -0
  5. package/src/adapters/cursor/transport-retry.ts +46 -1
  6. package/src/adapters/cursor.ts +4 -0
  7. package/src/adapters/kiro/adapter.ts +42 -1
  8. package/src/adapters/kiro-retry.ts +23 -4
  9. package/src/adapters/openai-chat/errors.ts +116 -0
  10. package/src/adapters/openai-chat/messages.ts +346 -0
  11. package/src/adapters/openai-chat/passthrough.ts +146 -0
  12. package/src/adapters/openai-chat/response-events.ts +117 -0
  13. package/src/adapters/openai-chat/tool-call-validation.ts +200 -0
  14. package/src/adapters/openai-chat/tool-schema.ts +477 -0
  15. package/src/adapters/openai-chat/wire.ts +50 -0
  16. package/src/adapters/openai-chat.ts +33 -1445
  17. package/src/adapters/openai-responses/canonical-forward.ts +202 -0
  18. package/src/adapters/openai-responses/image-gen.ts +406 -0
  19. package/src/adapters/openai-responses/internal.ts +3 -0
  20. package/src/adapters/openai-responses/passthrough.ts +611 -0
  21. package/src/adapters/openai-responses/prompt-cache.ts +83 -0
  22. package/src/adapters/openai-responses/reasoning.ts +220 -0
  23. package/src/adapters/openai-responses/request-strips.ts +185 -0
  24. package/src/adapters/openai-responses/tool-output-recovery.ts +509 -0
  25. package/src/adapters/openai-responses/tool-schema.ts +293 -0
  26. package/src/adapters/openai-responses/web-search.ts +156 -0
  27. package/src/adapters/openai-responses.ts +4 -2625
  28. package/src/bridge/errors.ts +34 -0
  29. package/src/bridge/internal.ts +174 -0
  30. package/src/bridge/response-json.ts +624 -0
  31. package/src/bridge/sse.ts +1444 -0
  32. package/src/bridge.ts +5 -2204
  33. package/src/chat/inbound.ts +12 -1
  34. package/src/codex/account-lifecycle.ts +3 -0
  35. package/src/codex/account-store.ts +71 -9
  36. package/src/codex/auth-api/account-list.ts +507 -0
  37. package/src/codex/auth-api/http.ts +32 -0
  38. package/src/codex/auth-api/login-flow.ts +554 -0
  39. package/src/codex/auth-api/login-state.ts +64 -0
  40. package/src/codex/auth-api/main-account-probe.ts +331 -0
  41. package/src/codex/auth-api/pool-mode-gate.ts +274 -0
  42. package/src/codex/auth-api/pool-quota-probe.ts +512 -0
  43. package/src/codex/auth-api/reset-credit-service.ts +422 -0
  44. package/src/codex/auth-api/routes.ts +425 -0
  45. package/src/codex/auth-api/runtime-config.ts +48 -0
  46. package/src/codex/auth-api.ts +27 -3118
  47. package/src/codex/auth-context.ts +95 -28
  48. package/src/codex/catalog/auto-review.ts +507 -0
  49. package/src/codex/catalog/build-entries.ts +981 -0
  50. package/src/codex/catalog/combo-member.ts +375 -0
  51. package/src/codex/catalog/derive-entry.ts +229 -0
  52. package/src/codex/catalog/effort.ts +0 -1
  53. package/src/codex/catalog/gated-native-warn.ts +63 -0
  54. package/src/codex/catalog/gather-capture.ts +533 -0
  55. package/src/codex/catalog/model-hints.ts +691 -0
  56. package/src/codex/catalog/model-visibility.ts +304 -0
  57. package/src/codex/catalog/provider-fetch.ts +52 -2942
  58. package/src/codex/catalog/provider-models.ts +685 -0
  59. package/src/codex/catalog/restore.ts +132 -0
  60. package/src/codex/catalog/retained-sync.ts +706 -0
  61. package/src/codex/catalog/routed-gather.ts +858 -0
  62. package/src/codex/catalog/subagent-roster.ts +176 -0
  63. package/src/codex/catalog/sync.ts +52 -2698
  64. package/src/codex/inject/config-toml.ts +563 -0
  65. package/src/codex/inject/remove.ts +192 -0
  66. package/src/codex/inject/restore.ts +540 -0
  67. package/src/codex/inject/routing-classify.ts +109 -0
  68. package/src/codex/inject/routing-target.ts +125 -0
  69. package/src/codex/inject.ts +81 -1436
  70. package/src/codex/lineage.ts +458 -0
  71. package/src/codex/pool-refresh-backoff.ts +152 -0
  72. package/src/codex/routing/active-account.ts +194 -0
  73. package/src/codex/routing/cooldown-math.ts +275 -0
  74. package/src/codex/routing/health-store.ts +402 -0
  75. package/src/codex/routing/probe-lease.ts +358 -0
  76. package/src/codex/routing/selection.ts +703 -0
  77. package/src/codex/routing/thread-affinity.ts +538 -0
  78. package/src/codex/routing.ts +353 -2234
  79. package/src/codex/shim-fingerprint.ts +223 -0
  80. package/src/codex/shim-inspect.ts +175 -0
  81. package/src/codex/shim-probe.ts +367 -0
  82. package/src/codex/shim-restore-lock.ts +169 -0
  83. package/src/codex/shim-state-file.ts +151 -0
  84. package/src/codex/shim-templates.ts +265 -0
  85. package/src/codex/shim.ts +48 -1268
  86. package/src/config/diagnostics.ts +705 -0
  87. package/src/config/feature-flags.ts +55 -0
  88. package/src/config/live-reconcile.ts +403 -0
  89. package/src/config/load-degrade.ts +880 -0
  90. package/src/config/mutation-lock.ts +244 -0
  91. package/src/config/openai-tier-backup.ts +268 -0
  92. package/src/config/persist-unlocked.ts +92 -0
  93. package/src/config/proxy-env.ts +188 -0
  94. package/src/config/salvage.ts +244 -0
  95. package/src/config/schema/config-schema.ts +640 -0
  96. package/src/config/schema/leaf-validators.ts +855 -0
  97. package/src/config/warn-memo.ts +28 -0
  98. package/src/config.ts +234 -4481
  99. package/src/generated/compatibility-version.json +539 -39
  100. package/src/lib/request-execution-budget.ts +69 -20
  101. package/src/lib/spend-reservation-ledger.ts +940 -0
  102. package/src/lib/upstream-retry.ts +55 -11
  103. package/src/lib/workflow-budget.ts +553 -30
  104. package/src/providers/quota/account-cache.ts +441 -0
  105. package/src/providers/quota/antigravity.ts +295 -0
  106. package/src/providers/quota/report-cache.ts +320 -0
  107. package/src/providers/quota/vendor-probes-key.ts +1243 -0
  108. package/src/providers/quota/vendor-probes-oauth.ts +590 -0
  109. package/src/providers/quota.ts +324 -3079
  110. package/src/providers/registry/entries-core.ts +1221 -0
  111. package/src/providers/registry/entries-extended.ts +1204 -0
  112. package/src/providers/registry/model-seeds.ts +908 -0
  113. package/src/providers/registry/types.ts +352 -0
  114. package/src/providers/registry.ts +24 -3536
  115. package/src/responses/continuation-ownership.ts +29 -0
  116. package/src/responses/state/replay-fingerprint.ts +80 -0
  117. package/src/responses/state/snapshot-codec.ts +104 -0
  118. package/src/responses/state/spill-failure.ts +118 -0
  119. package/src/responses/state/spill-queue.ts +665 -0
  120. package/src/responses/state/temp-recovery.ts +257 -0
  121. package/src/responses/state.ts +82 -1143
  122. package/src/routing/identity-domains.ts +449 -0
  123. package/src/routing/probe-lease.ts +511 -0
  124. package/src/server/index/bounded-request.ts +88 -0
  125. package/src/server/index/live-sideband.ts +565 -0
  126. package/src/server/index/serve-options.ts +1766 -0
  127. package/src/server/index/startup-warnings.ts +213 -0
  128. package/src/server/index/websocket-handler.ts +335 -0
  129. package/src/server/index.ts +40 -2547
  130. package/src/server/management/route-registry.ts +26 -23
  131. package/src/server/management/shared.ts +8 -5
  132. package/src/server/management/workflow-budget-routes.ts +133 -0
  133. package/src/server/management-api.ts +12 -0
  134. package/src/server/request-log-conversation.ts +9 -7
  135. package/src/server/request-log.ts +245 -1
  136. package/src/server/responses/account-change-state.ts +233 -0
  137. package/src/server/responses/adapter-continuation.ts +514 -0
  138. package/src/server/responses/adapter-delivery.ts +214 -0
  139. package/src/server/responses/adapter-dispatch.ts +971 -0
  140. package/src/server/responses/compact.ts +59 -4
  141. package/src/server/responses/completion-policy.ts +33 -0
  142. package/src/server/responses/core-auth.ts +527 -0
  143. package/src/server/responses/core-codex-account.ts +859 -0
  144. package/src/server/responses/core-combo-failure.ts +210 -0
  145. package/src/server/responses/core-combo.ts +707 -0
  146. package/src/server/responses/core-errors.ts +152 -0
  147. package/src/server/responses/core-lifetime.ts +95 -0
  148. package/src/server/responses/core-normalize.ts +350 -0
  149. package/src/server/responses/core-opaque-recovery.ts +380 -0
  150. package/src/server/responses/core-options.ts +159 -0
  151. package/src/server/responses/core-replay.ts +225 -0
  152. package/src/server/responses/core.ts +192 -8893
  153. package/src/server/responses/passthrough-delivery.ts +856 -0
  154. package/src/server/responses/passthrough-dispatch.ts +1476 -0
  155. package/src/server/responses/passthrough-execution.ts +54 -0
  156. package/src/server/responses/request-prepare.ts +970 -0
  157. package/src/server/responses/request-send-budget.ts +164 -0
  158. package/src/server/responses/request-sidecar-auth.ts +149 -0
  159. package/src/server/responses/request-transport.ts +744 -0
  160. package/src/server/responses/response-effects.ts +157 -0
  161. package/src/server/responses/run-turn-execution.ts +448 -0
  162. package/src/server/responses/sidecar-execution.ts +469 -0
  163. package/src/server/responses-image-gen-repair.ts +1 -1
  164. package/src/server/workflow-refusal.ts +84 -0
  165. package/src/types/config.ts +30 -0
  166. package/src/usage/log.ts +146 -0
  167. package/src/usage/summary.ts +171 -21
@@ -0,0 +1,200 @@
1
+ import { debugProviderDiagnostic } from "../../lib/debug";
2
+ import { isDebugEnabled } from "../../lib/debug-settings";
3
+
4
+ export function isRecord(value: unknown): value is Record<string, unknown> {
5
+ return value !== null && typeof value === "object" && !Array.isArray(value);
6
+ }
7
+
8
+ type InvalidToolCallReason =
9
+ | "tool_calls_not_array"
10
+ | "tool_call_not_object"
11
+ | "tool_call_id_invalid"
12
+ | "tool_call_function_not_object"
13
+ | "tool_call_function_name_invalid"
14
+ | "tool_call_function_name_blank"
15
+ | "tool_call_function_arguments_invalid";
16
+
17
+ export type InvalidToolCallDiagnostic = {
18
+ reason: InvalidToolCallReason;
19
+ callIndex?: number;
20
+ valueType: string;
21
+ };
22
+
23
+ type InvalidFieldShape =
24
+ | {
25
+ kind: "object";
26
+ knownKeys: string[];
27
+ knownFieldTypes: Record<string, string>;
28
+ hasUnknownKeys: boolean;
29
+ }
30
+ | {
31
+ kind: "array";
32
+ length: number;
33
+ };
34
+
35
+ const SAFE_TOOL_CALL_SHAPE_KEYS = [
36
+ "name",
37
+ "type",
38
+ "value",
39
+ "function",
40
+ "arguments",
41
+ "id",
42
+ "index",
43
+ ] as const;
44
+ const SAFE_TOOL_CALL_SHAPE_KEY_SET = new Set<string>(SAFE_TOOL_CALL_SHAPE_KEYS);
45
+
46
+ function structuralValueType(value: unknown): string {
47
+ return value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
48
+ }
49
+
50
+ function invalidToolCallField(rawToolCalls: unknown, diagnostic: InvalidToolCallDiagnostic): unknown {
51
+ if (diagnostic.reason === "tool_calls_not_array") return rawToolCalls;
52
+ if (!Array.isArray(rawToolCalls) || diagnostic.callIndex === undefined) return undefined;
53
+
54
+ const rawToolCall = rawToolCalls[diagnostic.callIndex];
55
+ if (diagnostic.reason === "tool_call_not_object") return rawToolCall;
56
+ if (!isRecord(rawToolCall)) return undefined;
57
+ if (diagnostic.reason === "tool_call_function_not_object") return rawToolCall.function;
58
+
59
+ const rawFunction = rawToolCall.function;
60
+ switch (diagnostic.reason) {
61
+ case "tool_call_id_invalid":
62
+ return rawToolCall.id;
63
+ case "tool_call_function_name_invalid":
64
+ return isRecord(rawFunction) ? rawFunction.name : undefined;
65
+ case "tool_call_function_arguments_invalid":
66
+ return isRecord(rawFunction) ? rawFunction.arguments : undefined;
67
+ default:
68
+ return undefined;
69
+ }
70
+ }
71
+
72
+ function fingerprintInvalidField(value: unknown): InvalidFieldShape | undefined {
73
+ if (Array.isArray(value)) return { kind: "array", length: value.length };
74
+ if (!isRecord(value)) return undefined;
75
+
76
+ const knownKeys: string[] = [];
77
+ const knownFieldTypes: Record<string, string> = {};
78
+ for (const key of SAFE_TOOL_CALL_SHAPE_KEYS) {
79
+ if (!Object.hasOwn(value, key)) continue;
80
+ knownKeys.push(key);
81
+ knownFieldTypes[key] = structuralValueType(value[key]);
82
+ }
83
+
84
+ let hasUnknownKeys = false;
85
+ for (const key of Object.keys(value)) {
86
+ if (!SAFE_TOOL_CALL_SHAPE_KEY_SET.has(key)) {
87
+ hasUnknownKeys = true;
88
+ break;
89
+ }
90
+ }
91
+ return { kind: "object", knownKeys, knownFieldTypes, hasUnknownKeys };
92
+ }
93
+
94
+ /**
95
+ * Streamed string fields are absent when null or undefined (#1731): OpenAI-compatible
96
+ * streamers repeat already-sent `id`/`name`/`arguments` as null on continuation deltas.
97
+ * The accumulator and this diagnostic share this predicate so they cannot disagree about
98
+ * which delta was the invalid one.
99
+ */
100
+ export function isInvalidStreamStringField(value: unknown): boolean {
101
+ return value != null && typeof value !== "string";
102
+ }
103
+
104
+ /**
105
+ * Explain only the rejected wire shape, never its values. This diagnostic exists so provider
106
+ * compatibility can be tightened from evidence without retaining tool arguments or credentials.
107
+ */
108
+ export function diagnoseInvalidToolCalls(
109
+ rawToolCalls: unknown,
110
+ mode: "stream" | "response",
111
+ ): InvalidToolCallDiagnostic | undefined {
112
+ if (!Array.isArray(rawToolCalls)) {
113
+ return { reason: "tool_calls_not_array", valueType: rawToolCalls === null ? "null" : typeof rawToolCalls };
114
+ }
115
+ for (let callIndex = 0; callIndex < rawToolCalls.length; callIndex++) {
116
+ const rawToolCall = rawToolCalls[callIndex];
117
+ if (!isRecord(rawToolCall)) {
118
+ return {
119
+ reason: "tool_call_not_object",
120
+ callIndex,
121
+ valueType: rawToolCall === null ? "null" : Array.isArray(rawToolCall) ? "array" : typeof rawToolCall,
122
+ };
123
+ }
124
+ if (mode === "stream") {
125
+ // The streamed path validates the pieces it is about to store (#1531): a present
126
+ // `function` must be a record, and a present `name`/`arguments`/`id` must be a string.
127
+ // Blank names are caught later at flush, not here, so they are not diagnosed on this
128
+ // branch. Describe exactly that boundary rather than tightening compatibility in a
129
+ // diagnostic change.
130
+ // #1731: "present" means the same thing here as in the accumulator — null and undefined
131
+ // are both absent, because some OpenAI-compatible streamers repeat already-sent fields
132
+ // as null on continuation deltas. A separate predicate here would diagnose accepted
133
+ // padding as the failure and point compatibility work at the wrong delta.
134
+ const streamFunction = (rawToolCall as { function?: unknown }).function;
135
+ if (streamFunction !== undefined && streamFunction !== null) {
136
+ if (!isRecord(streamFunction)) {
137
+ return {
138
+ reason: "tool_call_function_not_object",
139
+ callIndex,
140
+ valueType: Array.isArray(streamFunction) ? "array" : typeof streamFunction,
141
+ };
142
+ }
143
+ if (isInvalidStreamStringField(streamFunction.name)) {
144
+ return { reason: "tool_call_function_name_invalid", callIndex, valueType: typeof streamFunction.name };
145
+ }
146
+ if (isInvalidStreamStringField(streamFunction.arguments)) {
147
+ return { reason: "tool_call_function_arguments_invalid", callIndex, valueType: typeof streamFunction.arguments };
148
+ }
149
+ }
150
+ if (isInvalidStreamStringField(rawToolCall.id)) {
151
+ return { reason: "tool_call_id_invalid", callIndex, valueType: typeof rawToolCall.id };
152
+ }
153
+ continue;
154
+ }
155
+ // Precedence must mirror the buffered validator below, or a payload with more than one
156
+ // problem is reported under the wrong reason and sends compatibility work after the wrong
157
+ // shape. That validator checks the `function` container first (`!isRecord(rawToolCall) ||
158
+ // !isRecord(rawToolCall.function)`), then id/name/arguments types together, and only then
159
+ // the blank name.
160
+ if (!isRecord(rawToolCall.function)) {
161
+ return {
162
+ reason: "tool_call_function_not_object",
163
+ callIndex,
164
+ valueType: rawToolCall.function === null ? "null" : Array.isArray(rawToolCall.function) ? "array" : typeof rawToolCall.function,
165
+ };
166
+ }
167
+ if (typeof rawToolCall.id !== "string") {
168
+ return { reason: "tool_call_id_invalid", callIndex, valueType: typeof rawToolCall.id };
169
+ }
170
+ if (typeof rawToolCall.function.name !== "string") {
171
+ return { reason: "tool_call_function_name_invalid", callIndex, valueType: typeof rawToolCall.function.name };
172
+ }
173
+ if (typeof rawToolCall.function.arguments !== "string") {
174
+ return { reason: "tool_call_function_arguments_invalid", callIndex, valueType: typeof rawToolCall.function.arguments };
175
+ }
176
+ // Last, matching the validator: #1531 also rejects a blank or whitespace-only name here,
177
+ // because such a call cannot select a dispatch target. Reporting it as `name_invalid`
178
+ // would claim a type problem for a correctly-typed value, so it gets its own code.
179
+ if (rawToolCall.function.name.trim().length === 0) {
180
+ return { reason: "tool_call_function_name_blank", callIndex, valueType: "string" };
181
+ }
182
+ }
183
+ return undefined;
184
+ }
185
+
186
+ export function logInvalidToolCalls(
187
+ mode: "stream" | "response",
188
+ rawToolCalls: unknown,
189
+ diagnosticOverride?: InvalidToolCallDiagnostic,
190
+ ): void {
191
+ if (!isDebugEnabled()) return;
192
+ const diagnostic = diagnosticOverride ?? diagnoseInvalidToolCalls(rawToolCalls, mode);
193
+ if (!diagnostic) return;
194
+ const fieldShape = fingerprintInvalidField(invalidToolCallField(rawToolCalls, diagnostic));
195
+ debugProviderDiagnostic("openai-chat", "invalid-tool-calls", {
196
+ mode,
197
+ ...diagnostic,
198
+ ...(fieldShape ? { fieldShape } : {}),
199
+ });
200
+ }
@@ -0,0 +1,477 @@
1
+ import { isNativeOpenAIChatTarget } from "./wire";
2
+ import { isXaiSchemaTarget, lookupLocalJsonPointer, normalizeXaiToolParameters } from "../xai-tool-schema";
3
+ import { stripResponsesOnlyEncryptedMarker, stripUnicodePropertyPatterns } from "../responses-tool-schema";
4
+ import { isAllowedToolChoice, namespacedToolName, resolveToolChoiceWireName, toolChoiceToolPredicate } from "../../types";
5
+ import type { OcxParsedRequest, OcxProviderConfig } from "../../types";
6
+
7
+ const ZEN_SCHEMA_MAP_KEYS = new Set(["properties", "$defs", "definitions"]);
8
+ const ZEN_DROPPED_SCHEMA_KEYS = new Set(["encrypted"]);
9
+
10
+ function sanitizeZenSchemaMap(value: unknown): unknown {
11
+ if (!value || typeof value !== "object" || Array.isArray(value)) return sanitizeZenToolParameters(value);
12
+ const out: Record<string, unknown> = {};
13
+ for (const [name, child] of Object.entries(value as Record<string, unknown>)) {
14
+ out[name] = sanitizeZenToolParameters(child);
15
+ }
16
+ return out;
17
+ }
18
+
19
+ function sanitizeZenToolParameters(value: unknown): unknown {
20
+ if (Array.isArray(value)) return value.map(sanitizeZenToolParameters);
21
+ if (!value || typeof value !== "object") return value;
22
+ const input = value as Record<string, unknown>;
23
+ const out: Record<string, unknown> = {};
24
+ for (const [key, child] of Object.entries(input)) {
25
+ if (ZEN_DROPPED_SCHEMA_KEYS.has(key)) continue;
26
+ if (key === "required" && Array.isArray(child) && child.length === 0) continue;
27
+ if (key === "type" && Array.isArray(child)) {
28
+ const nonNull = child.filter(entry => entry !== "null");
29
+ if (child.includes("null")) out.nullable = true;
30
+ if (nonNull.length > 0) out.type = nonNull[0];
31
+ continue;
32
+ }
33
+ out[key] = ZEN_SCHEMA_MAP_KEYS.has(key) ? sanitizeZenSchemaMap(child) : sanitizeZenToolParameters(child);
34
+ }
35
+ return out;
36
+ }
37
+
38
+ function ensureZenRootObjectSchema(schema: unknown): Record<string, unknown> {
39
+ const obj = schema && typeof schema === "object" && !Array.isArray(schema)
40
+ ? schema as Record<string, unknown>
41
+ : {};
42
+ const compositionKeys = ["oneOf", "anyOf", "allOf"] as const;
43
+ const hasComposition = compositionKeys.some(key => Array.isArray(obj[key]));
44
+ const rootType = obj.type;
45
+ const rootObjectType = rootType === "object" || (Array.isArray(rootType) && rootType.includes("object"));
46
+ if (!hasComposition) {
47
+ const base = sanitizeZenToolParameters(obj) as Record<string, unknown>;
48
+ return rootObjectType && base.type === "object" ? base : { ...base, type: "object" };
49
+ }
50
+
51
+ const props: Record<string, unknown> = {};
52
+ const required = new Set<string>();
53
+ if (obj.properties && typeof obj.properties === "object") {
54
+ Object.assign(props, sanitizeZenSchemaMap(obj.properties) as Record<string, unknown>);
55
+ }
56
+ if (Array.isArray(obj.required)) {
57
+ for (const entry of obj.required) if (typeof entry === "string") required.add(entry);
58
+ }
59
+ for (const key of compositionKeys) {
60
+ const variants = obj[key];
61
+ if (!Array.isArray(variants)) continue;
62
+ const mergeRequired = key === "allOf";
63
+ for (const variant of variants) {
64
+ if (!variant || typeof variant !== "object" || Array.isArray(variant)) continue;
65
+ const rec = variant as Record<string, unknown>;
66
+ if (rec.properties && typeof rec.properties === "object") {
67
+ Object.assign(props, sanitizeZenSchemaMap(rec.properties) as Record<string, unknown>);
68
+ }
69
+ if (mergeRequired && Array.isArray(rec.required)) {
70
+ for (const entry of rec.required) if (typeof entry === "string") required.add(entry);
71
+ }
72
+ }
73
+ }
74
+
75
+ const merged = sanitizeZenToolParameters(obj) as Record<string, unknown>;
76
+ delete merged.oneOf;
77
+ delete merged.anyOf;
78
+ delete merged.allOf;
79
+ merged.type = "object";
80
+ if (Object.keys(props).length > 0) merged.properties = props;
81
+ if (required.size > 0) merged.required = [...required];
82
+ return merged;
83
+ }
84
+
85
+ function shouldSanitizeZenToolParameters(provider: OcxProviderConfig): boolean {
86
+ const baseUrl = provider.baseUrl.replace(/\/+$/, "");
87
+ return baseUrl === "https://opencode.ai/zen/v1"
88
+ || baseUrl === "https://opencode.ai/zen/go/v1";
89
+ }
90
+
91
+ /** Azure Model Router (and Gemini-in-the-pool) 400s Codex MCP schemas whose root is a union. */
92
+ const AZURE_CHAT_FORBIDDEN_ROOT_KEYS = ["oneOf", "anyOf", "allOf", "enum", "const", "not"] as const;
93
+
94
+ function isAzureOpenAiChatTarget(provider: OcxProviderConfig): boolean {
95
+ try {
96
+ const host = new URL(provider.baseUrl).hostname.toLowerCase();
97
+ return host.endsWith(".openai.azure.com")
98
+ || host.endsWith(".cognitiveservices.azure.com")
99
+ || host.endsWith(".services.ai.azure.com")
100
+ || host.endsWith(".ai.azure.com");
101
+ } catch {
102
+ return false;
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Azure Foundry Model Router validates every function schema against the strictest model in
108
+ * the pool (Gemini-shaped): root must be {type:"object"} with no oneOf/anyOf/allOf/enum/
109
+ * const/not. Codex App MCP tools such as mcp__codex_app__automation_update ship a root
110
+ * union, which 400s the whole turn. Flatten like Zen, then strip leftover forbidden keys.
111
+ */
112
+ function sanitizeAzureChatToolParameters(parameters: unknown): Record<string, unknown> {
113
+ const root = ensureZenRootObjectSchema(parameters);
114
+ for (const key of AZURE_CHAT_FORBIDDEN_ROOT_KEYS) delete root[key];
115
+ root.type = "object";
116
+ if (!root.properties || typeof root.properties !== "object" || Array.isArray(root.properties)) {
117
+ root.properties = {};
118
+ }
119
+ return root;
120
+ }
121
+
122
+ // Moonshot validates function schemas against a draft-07 reading of `$ref`, where the
123
+ // keyword stands alone and siblings are ignored. It rejects the whole request rather
124
+ // than ignoring them: "not a valid moonshot flavored json schema ... when using $ref,
125
+ // type should be defined in the referenced schema instead of the parent schema".
126
+ const MOONSHOT_SCHEMA_HOSTNAMES = new Set([
127
+ "api.kimi.com",
128
+ "api.moonshot.ai",
129
+ "api.moonshot.cn",
130
+ ]);
131
+
132
+ function isMoonshotSchemaTarget(provider: OcxProviderConfig): boolean {
133
+ try {
134
+ return MOONSHOT_SCHEMA_HOSTNAMES.has(new URL(provider.baseUrl).hostname);
135
+ } catch {
136
+ return false;
137
+ }
138
+ }
139
+
140
+ const VOLCENGINE_ARK_HOSTNAMES = new Set([
141
+ "ark.cn-beijing.volces.com",
142
+ "ark.ap-southeast.volces.com",
143
+ ]);
144
+
145
+ export function isVolcengineArkPaygChatTarget(provider: OcxProviderConfig): boolean {
146
+ try {
147
+ const url = new URL(provider.baseUrl);
148
+ const pathname = url.pathname.replace(/\/+$/, "") || "/";
149
+ return VOLCENGINE_ARK_HOSTNAMES.has(url.hostname) && pathname === "/api/v3";
150
+ } catch {
151
+ return false;
152
+ }
153
+ }
154
+
155
+ function ensureRootObjectType(parameters: unknown): Record<string, unknown> {
156
+ if (!parameters || typeof parameters !== "object" || Array.isArray(parameters)) {
157
+ return { type: "object", properties: {} };
158
+ }
159
+ const obj = parameters as Record<string, unknown>;
160
+ if (obj.type === "object") return obj;
161
+ return { ...obj, type: "object" };
162
+ }
163
+
164
+ function isXaiObjectSchema(value: unknown): value is Record<string, unknown> {
165
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
166
+ }
167
+
168
+ /**
169
+ * JSON Schema 2020-12 makes `$ref` an in-place applicator: siblings stay in force and are
170
+ * combined with the referenced schema. Moonshot enforces the older draft-07 reading where
171
+ * `$ref` must stand alone, and 400s the entire request when a node carries both. Codex's own
172
+ * deferred tool catalog emits exactly that shape (zod-to-json-schema deduplicates into
173
+ * `$defs.__schema*` nodes that keep `type`/`minLength`/`format` beside the `$ref`), so the
174
+ * schema is not something a user can fix from configuration — see issue #2673.
175
+ *
176
+ * Inline the referenced schema underneath the node's own keywords, which is what 2020-12 says
177
+ * the node means, then drop `$ref`. Constraints reach the model instead of being stripped.
178
+ * The `$defs` bag is preserved: a bare `$ref` (no siblings) is already legal for Moonshot and
179
+ * is left pointing at its definition rather than expanded, which keeps recursive schemas finite.
180
+ */
181
+ function moonshotRefTargetKeys(node: Record<string, unknown>): string[] {
182
+ return Object.keys(node).filter(key => key !== "$ref");
183
+ }
184
+
185
+ /**
186
+ * Inlining duplicates the target, so a schema referencing one large definition from many
187
+ * sibling-carrying nodes can multiply. Bound the total expansions and fall back to a bare
188
+ * `$ref` once the budget is spent: still valid for Moonshot, just without the node's own
189
+ * narrowing keywords. Mirrors the node budget in google-tool-schema.ts.
190
+ */
191
+ const MOONSHOT_MAX_REF_EXPANSIONS = 512;
192
+
193
+ /**
194
+ * Expansion count alone does not bound the walk: a deeply nested ref-free schema, or one
195
+ * large definition repeated across many nodes, still recurses to exhaustion or amplifies the
196
+ * emitted output. Depth and node budgets close both, and mirror google-tool-schema.ts.
197
+ */
198
+ const MOONSHOT_MAX_SCHEMA_DEPTH = 64;
199
+ const MOONSHOT_MAX_SCHEMA_NODES = 4_096;
200
+
201
+ /**
202
+ * Assertion keywords whose meaning under a `$ref` is CONJUNCTION, not replacement. A node
203
+ * carrying `required: ["b"]` beside a target requiring `["a"]` means both are required;
204
+ * letting the sibling win emitted a schema that no longer described the tool.
205
+ */
206
+ function unionRequired(target: unknown, sibling: unknown): unknown {
207
+ if (!Array.isArray(target) || !Array.isArray(sibling)) return sibling;
208
+ const seen = new Set<unknown>();
209
+ const out: unknown[] = [];
210
+ for (const name of [...target, ...sibling]) {
211
+ if (seen.has(name)) continue;
212
+ seen.add(name);
213
+ out.push(name);
214
+ }
215
+ return out;
216
+ }
217
+
218
+ /**
219
+ * Keywords whose values are DATA, not schemas.
220
+ *
221
+ * Recursing into them rewrote user data: an `enum` listing a literal object that happens
222
+ * to carry a `"$ref"` string had that key stripped as if it were a schema reference, so a
223
+ * value the tool declared as legal silently changed shape. These are copied through.
224
+ */
225
+ const MOONSHOT_DATA_VALUED_KEYWORDS = new Set(["enum", "const", "default", "examples"]);
226
+
227
+ /**
228
+ * Numeric assertions whose intersection is a bound, and which direction tightens.
229
+ *
230
+ * `$ref` under 2020-12 is an in-place applicator: the node and its target BOTH apply, so
231
+ * the emitted schema must be their INTERSECTION. The previous code overwrote the target
232
+ * with the node and called that "the narrower reading", which holds only when the node
233
+ * happens to be narrower. A node declaring `minLength: 1` beside a target declaring
234
+ * `minLength: 5` shipped `minLength: 1` - a contract weaker than either side asked for,
235
+ * emitted silently, which is the same failure mode the `required` composition fixed for
236
+ * set-valued keywords.
237
+ *
238
+ * "max" means the surviving value is the larger of the two (lower bounds), "min" the
239
+ * smaller (upper bounds). A keyword absent from this table keeps the overwrite: for
240
+ * `type`, `format`, `description` and friends there is no ordering to intersect along,
241
+ * and the node is the more specific statement.
242
+ */
243
+ const MOONSHOT_BOUND_KEYWORDS: Record<string, "max" | "min"> = {
244
+ minLength: "max",
245
+ minItems: "max",
246
+ minProperties: "max",
247
+ minimum: "max",
248
+ exclusiveMinimum: "max",
249
+ maxLength: "min",
250
+ maxItems: "min",
251
+ maxProperties: "min",
252
+ maximum: "min",
253
+ exclusiveMaximum: "min",
254
+ };
255
+
256
+ /**
257
+ * Intersect one numeric bound. Either side being absent or non-finite yields the other,
258
+ * because an unstated bound constrains nothing - returning `undefined` there would drop
259
+ * a constraint the remaining side genuinely made.
260
+ */
261
+ function intersectBound(target: unknown, sibling: unknown, direction: "max" | "min"): unknown {
262
+ const a = typeof target === "number" && Number.isFinite(target) ? target : null;
263
+ const b = typeof sibling === "number" && Number.isFinite(sibling) ? sibling : null;
264
+ if (a === null) return b === null ? sibling : sibling;
265
+ if (b === null) return target;
266
+ return direction === "max" ? Math.max(a, b) : Math.min(a, b);
267
+ }
268
+
269
+ /**
270
+ * Compose two `properties` maps. A property named in BOTH the referenced target and the
271
+ * node is the same conjunction problem `required` had: letting the sibling win discards
272
+ * the target's constraints for that member. Merge the two member schemas so neither side
273
+ * loses its keywords. Shared member bounds are the same conjunction one level down,
274
+ * and nested object members recurse through this helper instead of replacing the target.
275
+ */
276
+ function composeProperties(
277
+ target: Record<string, unknown>,
278
+ sibling: Record<string, unknown>,
279
+ ): Record<string, unknown> {
280
+ const combined: Record<string, unknown> = Object.create(null) as Record<string, unknown>;
281
+ for (const [name, sub] of Object.entries(target)) combined[name] = sub;
282
+ for (const [name, sub] of Object.entries(sibling)) {
283
+ const existing = combined[name];
284
+ if (isXaiObjectSchema(existing) && isXaiObjectSchema(sub)) {
285
+ const member: Record<string, unknown> = Object.create(null) as Record<string, unknown>;
286
+ for (const [k, v] of Object.entries(existing)) member[k] = v;
287
+ for (const [k, v] of Object.entries(sub)) {
288
+ if (k === "required") {
289
+ member[k] = unionRequired(member[k], v);
290
+ continue;
291
+ }
292
+ if (k === "properties" && isXaiObjectSchema(member[k]) && isXaiObjectSchema(v)) {
293
+ member[k] = composeProperties(member[k] as Record<string, unknown>, v);
294
+ continue;
295
+ }
296
+ const boundDirection = MOONSHOT_BOUND_KEYWORDS[k];
297
+ if (boundDirection && k in member) {
298
+ member[k] = intersectBound(member[k], v, boundDirection);
299
+ continue;
300
+ }
301
+ member[k] = v;
302
+ }
303
+ combined[name] = member;
304
+ continue;
305
+ }
306
+ combined[name] = sub;
307
+ }
308
+ return combined;
309
+ }
310
+
311
+ interface MoonshotNormalizeState {
312
+ activeRefs: Set<string>;
313
+ remainingExpansions: number;
314
+ remainingNodes: number;
315
+ }
316
+
317
+ function normalizeMoonshotSchemaNode(
318
+ node: unknown,
319
+ root: Record<string, unknown>,
320
+ state: MoonshotNormalizeState,
321
+ depth = 0,
322
+ ): unknown {
323
+ if (Array.isArray(node)) {
324
+ if (depth >= MOONSHOT_MAX_SCHEMA_DEPTH) return [];
325
+ return node.map(item => normalizeMoonshotSchemaNode(item, root, state, depth + 1));
326
+ }
327
+ if (!isXaiObjectSchema(node)) return node;
328
+
329
+ // Fail closed for this node rather than emitting a partially weakened schema: an empty
330
+ // object is the one shape that asserts nothing it cannot back up.
331
+ if (depth >= MOONSHOT_MAX_SCHEMA_DEPTH || state.remainingNodes <= 0) return {};
332
+ state.remainingNodes -= 1;
333
+
334
+ const ref = node.$ref;
335
+ const hasSiblings = moonshotRefTargetKeys(node).length > 0;
336
+
337
+ if (typeof ref === "string" && hasSiblings) {
338
+ // A cycle cannot be inlined. Keeping the bare `$ref` is the lossy-but-valid fallback:
339
+ // Moonshot accepts it, and the alternative (dropping the ref) would erase the recursion.
340
+ if (state.activeRefs.has(ref) || state.remainingExpansions <= 0) return { $ref: ref };
341
+
342
+ const target = lookupLocalJsonPointer(root, ref);
343
+ if (isXaiObjectSchema(target)) {
344
+ state.remainingExpansions -= 1;
345
+ state.activeRefs.add(ref);
346
+ const resolvedTarget = normalizeMoonshotSchemaNode(target, root, state, depth + 1);
347
+ state.activeRefs.delete(ref);
348
+ const merged: Record<string, unknown> = Object.create(null) as Record<string, unknown>;
349
+ if (isXaiObjectSchema(resolvedTarget)) {
350
+ for (const [key, value] of Object.entries(resolvedTarget)) merged[key] = value;
351
+ }
352
+ // "Alongside the target" is conjunction, not replacement. For most keywords the node
353
+ // narrows the target and overwriting is the narrower reading, but `required` and
354
+ // `properties` are set-valued: letting the sibling win DROPPED the target's own
355
+ // members, so a tool requiring `a` beside a node requiring `b` shipped requiring only
356
+ // `b`. Those two compose; everything else keeps the narrowing overwrite.
357
+ for (const [key, value] of Object.entries(node)) {
358
+ if (key === "$ref") continue;
359
+ if (MOONSHOT_DATA_VALUED_KEYWORDS.has(key)) {
360
+ merged[key] = value;
361
+ continue;
362
+ }
363
+ const normalized = normalizeMoonshotSchemaNode(value, root, state, depth + 1);
364
+ if (key === "required") {
365
+ merged[key] = unionRequired(merged[key], normalized);
366
+ continue;
367
+ }
368
+ if (key === "properties" && isXaiObjectSchema(merged[key]) && isXaiObjectSchema(normalized)) {
369
+ merged[key] = composeProperties(merged[key] as Record<string, unknown>, normalized);
370
+ continue;
371
+ }
372
+ // Numeric bounds intersect rather than overwrite: both the node and its target
373
+ // apply, so the surviving bound is the stricter of the two in whichever direction
374
+ // that keyword tightens.
375
+ const boundDirection = MOONSHOT_BOUND_KEYWORDS[key];
376
+ if (boundDirection && key in merged) {
377
+ merged[key] = intersectBound(merged[key], normalized, boundDirection);
378
+ continue;
379
+ }
380
+ merged[key] = normalized;
381
+ }
382
+ return merged;
383
+ }
384
+
385
+ // Unresolvable pointer: a remote ref, a malformed path, or a non-object target. Dropping
386
+ // the ref and keeping the siblings silently discards whatever the reference constrained,
387
+ // which is the one outcome we cannot detect downstream. A bare `$ref` is lossy in the
388
+ // other direction - it loses the node's own keywords - but it preserves the identity of
389
+ // what was asked for, and Moonshot accepts it.
390
+ return { $ref: ref };
391
+ }
392
+
393
+ const out: Record<string, unknown> = Object.create(null) as Record<string, unknown>;
394
+ for (const [key, value] of Object.entries(node)) {
395
+ out[key] = key === "$ref" || MOONSHOT_DATA_VALUED_KEYWORDS.has(key)
396
+ ? value
397
+ : normalizeMoonshotSchemaNode(value, root, state, depth + 1);
398
+ }
399
+ return out;
400
+ }
401
+
402
+ function normalizeMoonshotToolParameters(parameters: unknown): Record<string, unknown> {
403
+ const rooted = ensureRootObjectType(parameters);
404
+ const normalized = normalizeMoonshotSchemaNode(rooted, rooted, {
405
+ activeRefs: new Set<string>(),
406
+ remainingExpansions: MOONSHOT_MAX_REF_EXPANSIONS,
407
+ remainingNodes: MOONSHOT_MAX_SCHEMA_NODES,
408
+ });
409
+ return isXaiObjectSchema(normalized) ? normalized : rooted;
410
+ }
411
+
412
+ export function toolsToChatFormat(parsed: OcxParsedRequest, provider: OcxProviderConfig): unknown[] | undefined {
413
+ if (!parsed.context.tools || parsed.context.tools.length === 0) return undefined;
414
+ const tools = parsed.context.tools.filter(toolChoiceToolPredicate(parsed.options.toolChoice, parsed.context.tools));
415
+ if (tools.length === 0) return undefined;
416
+ const xaiTarget = isXaiSchemaTarget(provider);
417
+ const moonshotTarget = !xaiTarget && isMoonshotSchemaTarget(provider);
418
+ const formatted = tools.flatMap(t => {
419
+ const normalized = xaiTarget
420
+ ? normalizeXaiToolParameters(t.parameters)
421
+ : moonshotTarget
422
+ ? normalizeMoonshotToolParameters(t.parameters)
423
+ : ensureRootObjectType(t.parameters);
424
+ const parameters = stripUnicodePropertyPatterns(stripResponsesOnlyEncryptedMarker(normalized));
425
+
426
+ if (parameters === undefined) return [];
427
+ return [{
428
+ type: "function",
429
+ function: {
430
+ name: namespacedToolName(t.namespace, t.name),
431
+ ...(t.description ? { description: t.description } : {}),
432
+ parameters,
433
+ ...(t.strict !== undefined ? { strict: t.strict } : {}),
434
+ },
435
+ }];
436
+ });
437
+ return formatted.length > 0 ? formatted : undefined;
438
+ }
439
+
440
+ export function toolsToChatFormatForProvider(parsed: OcxParsedRequest, provider: OcxProviderConfig): unknown[] | undefined {
441
+ const base = toolsToChatFormat(parsed, provider);
442
+ const azureChat = isAzureOpenAiChatTarget(provider);
443
+ const zenChat = shouldSanitizeZenToolParameters(provider);
444
+ if (!base || (!zenChat && !azureChat)) return base;
445
+ return base.map(tool => {
446
+ if (!tool || typeof tool !== "object") return tool;
447
+ const functionDef = (tool as { function?: Record<string, unknown> }).function;
448
+ if (!functionDef || typeof functionDef !== "object") return tool;
449
+ const parameters = azureChat
450
+ ? sanitizeAzureChatToolParameters(functionDef.parameters ?? {})
451
+ : ensureZenRootObjectSchema(functionDef.parameters ?? {});
452
+ const nextFunction: Record<string, unknown> = { ...functionDef, parameters };
453
+ // strict: true plus a flattened schema is rejected by Gemini-in-the-pool routers.
454
+ if (azureChat) delete nextFunction.strict;
455
+ return {
456
+ ...tool,
457
+ function: nextFunction,
458
+ };
459
+ });
460
+ }
461
+
462
+ export function toolChoiceToChatFormat(
463
+ tc: OcxParsedRequest["options"]["toolChoice"],
464
+ tools: OcxParsedRequest["context"]["tools"],
465
+ provider: OcxProviderConfig,
466
+ ): unknown {
467
+ if (!tc) return undefined;
468
+ if (isAllowedToolChoice(tc)) {
469
+ if (tc.mode === "required" && tc.allowedTools.length === 1 && isNativeOpenAIChatTarget(provider)) {
470
+ return { type: "function", function: { name: resolveToolChoiceWireName(tools, tc.allowedTools[0]) } };
471
+ }
472
+ return tc.mode === "required" ? "required" : "auto";
473
+ }
474
+ if (tc === "auto" || tc === "none" || tc === "required") return tc;
475
+ if ("name" in tc) return { type: "function", function: { name: resolveToolChoiceWireName(tools, tc.name) } };
476
+ return undefined;
477
+ }