codex-copilot-dx 1.3.20 → 1.3.22

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.
@@ -0,0 +1,320 @@
1
+ import { createHash } from "node:crypto";
2
+ import { imageModelCatalog, imageModelSelection } from "./image-models.mjs";
3
+ import { CLIENT_IDS, CLIENT_NAMES } from "./access-settings.mjs";
4
+ import { publicModelCatalog } from "./provider-metadata.mjs";
5
+ import { sourceModels, clientModelExclusion } from "./client-model-plan.mjs";
6
+ import { deploymentModelId, resolveModelCapabilities, deploymentRevision } from "./model-capabilities.mjs";
7
+
8
+ export function createConnectionView({ legacy, env, binding, plan, getSource, enabled, editable, modelDisplay, discoveries,
9
+ setup, credentialStates, lastClients, memoryModel, capabilitySupport, sharedSync, isManaged, getSettings, corePort, permitted }) {
10
+ const summaries = new WeakMap();
11
+ function summary(api) {
12
+ if (!summaries.has(api))
13
+ summaries.set(api, {
14
+ model_count: api.models.length,
15
+ codex_model_count: api.models.filter(model => model.protocols.includes("responses")).length,
16
+ protocols: Object.keys(api.endpoints),
17
+ });
18
+ return summaries.get(api);
19
+ }
20
+ function imageModels() {
21
+ const c = binding("codex");
22
+ return imageModelSelection(enabled("github") && c.allowed.includes("github")
23
+ ? imageModelCatalog(legacy.github?.registry?.models) : [], c.image_model);
24
+ }
25
+ function clientSnapshot(id, config, compact, readPlan) {
26
+ const base = {
27
+ id,
28
+ name: CLIENT_NAMES[id],
29
+ ...config.clients[id],
30
+ setup: setup[id] || null,
31
+ ...(credentialStates[id] ? { credential_state: credentialStates[id] } : {}),
32
+ ...(id === "codex" ? { memory_model: memoryModel.snapshot() } : {}),
33
+ observed_at: lastClients[id] || null,
34
+ };
35
+ if (compact) return base;
36
+ const revision = clientRevision(id),
37
+ compiled = readPlan(id);
38
+ return {
39
+ ...base,
40
+ revision,
41
+ model_plan: {
42
+ ...(id === "codex" ? { image: imageModels() } : {}),
43
+ default_model: compiled.defaultModel,
44
+ default_unavailable: compiled.defaultUnavailable,
45
+ models: compiled.models.map(model => ({
46
+ source: model.source_id,
47
+ id: model.id,
48
+ display_name: model.display_name,
49
+ public_id: model.public_id,
50
+ route_id: model.route_id,
51
+ capability: model.capability,
52
+ })),
53
+ unavailable: (config.clients[id].deployments || [])
54
+ .filter(
55
+ item => !compiled.models.some(model => model.source_id === item.source && model.id === item.model)
56
+ )
57
+ .map(item => ({
58
+ source: item.source,
59
+ id: item.model,
60
+ route_id: deploymentModelId(item.source, item.model),
61
+ reason: modelExclusion(id, item.source, item.model),
62
+ })),
63
+ available: config.clients[id].allowed
64
+ .filter(enabled)
65
+ .flatMap(source =>
66
+ sourceModels(getSource(source), id).map(model => ({
67
+ source,
68
+ id: model.id,
69
+ display_name: model.display_name || model.name || model.id,
70
+ route_id: deploymentModelId(source, model.id),
71
+ capability: model.capability || resolveModelCapabilities(model, { builtin: true }),
72
+ }))
73
+ ),
74
+ sync: sharedSync(),
75
+ support: capabilitySupport,
76
+ },
77
+ };
78
+ }
79
+ function modelExclusion(id, sourceId, modelId, model, selected = false) {
80
+ if (!model) {
81
+ const source = getSource(sourceId), raw = source?.catalog?.() || source?.registry?.models?.data || [];
82
+ model = publicModelCatalog(raw.filter(value => value.id === modelId))[0];
83
+ }
84
+ return clientModelExclusion({ client: id, binding: binding(id), sourceId, sourceEnabled: enabled(sourceId), model, selected });
85
+ }
86
+ function catalogVisibility(catalog, sourceId) {
87
+ if (!catalog || !Array.isArray(catalog.models)) return catalog;
88
+ const selected = new Map(CLIENT_IDS.map(id => [id, new Set(plan(id).models.filter(model => model.source_id === sourceId).map(model => model.id))]));
89
+ return { ...catalog, models: catalog.models.map(model => ({ ...model,
90
+ client_visibility: CLIENT_IDS.map(id => ({ client: id,
91
+ reason: modelExclusion(id, sourceId, model.id, model, selected.get(id).has(model.id) || id === "codex" && sourceId === "github" && model.kind === "image" && imageModels().selected_model === model.id) })) })) };
92
+ }
93
+ function snapshot(compact = false) {
94
+ const state = legacy.snapshot(),
95
+ config = isManaged() ? getSettings() : editable();
96
+ const localPlans = new Map();
97
+ const readPlan = id => {
98
+ if (!localPlans.has(id)) localPlans.set(id, plan(id));
99
+ return localPlans.get(id);
100
+ };
101
+ return structuredClone({
102
+ source: "connections",
103
+ providers: [
104
+ {
105
+ id: "github",
106
+ name: "GitHub Copilot",
107
+ enabled: config.providers.github,
108
+ builtin: true,
109
+ protocols: ["responses"],
110
+ },
111
+ {
112
+ id: "m365",
113
+ name: "Microsoft 365",
114
+ enabled: config.providers.m365,
115
+ builtin: true,
116
+ protocols: ["messages", "responses"],
117
+ },
118
+ ...config.apis.map(api => {
119
+ const { secret_ref, ...publicApi } = api,
120
+ revision = compact ? null : deploymentRevision(api, env);
121
+ return {
122
+ ...(compact ? { id: api.id, name: api.name, enabled: api.enabled } : publicApi),
123
+ ...summary(api),
124
+ ...(compact
125
+ ? {}
126
+ : {
127
+ deployment_revision: revision,
128
+ model_display: Object.fromEntries(
129
+ api.models.map(model => [model.id, modelDisplay.get(api.id, revision, model.id)])
130
+ ),
131
+ }),
132
+ discovery: discoveries.get(api.id) || null,
133
+ builtin: false,
134
+ key_saved: api.key_env ? Boolean(env[api.key_env]) : Boolean(secret_ref),
135
+ };
136
+ }),
137
+ ],
138
+ clients: CLIENT_IDS.map(id => clientSnapshot(id, config, compact, readPlan)),
139
+ ...(!compact
140
+ ? {
141
+ source_impacts: Object.fromEntries(
142
+ ["github", "m365", ...config.apis.map(api => api.id)].map(id => [
143
+ id,
144
+ sourceImpact(id, readPlan),
145
+ ])
146
+ ),
147
+ }
148
+ : {}),
149
+ managed: isManaged(),
150
+ ...(!compact ? { management_version: 1 } : {}),
151
+ m365_state: state.m365.state,
152
+ });
153
+ }
154
+ const clientRevision = id =>
155
+ createHash("sha256")
156
+ .update(JSON.stringify(binding(id)))
157
+ .digest("hex");
158
+ function sourceImpact(source, readPlan = plan) {
159
+ const clients = CLIENT_IDS.flatMap(id => {
160
+ const c = binding(id);
161
+ if (!c.enabled) return [];
162
+ const explicit = Array.isArray(c.deployments),
163
+ removed = explicit ? c.deployments.filter(item => item.source === source) : [];
164
+ if (explicit ? !removed.length : c.source !== source) return [];
165
+ const remaining = explicit ? c.deployments.length - removed.length : 0;
166
+ const defaultSource =
167
+ readPlan(id).routes.get(c.default_model)?.source ||
168
+ removed.find(item => deploymentModelId(source, item.model) === c.default_model)?.source ||
169
+ c.source;
170
+ const default_affected = defaultSource === source;
171
+ return [
172
+ {
173
+ id,
174
+ removed: explicit ? removed.length : sourceModels(getSource(source), id).length,
175
+ remaining,
176
+ default_affected,
177
+ needs_replacement: default_affected || remaining === 0,
178
+ },
179
+ ];
180
+ });
181
+ const api = getSettings().apis.find(item => item.id === source),
182
+ profile = api ? deploymentRevision(api, env) : getSource(source)?.profileId();
183
+ return {
184
+ clients,
185
+ revision: createHash("sha256")
186
+ .update(JSON.stringify([source, enabled(source), profile, CLIENT_IDS.map(id => binding(id))]))
187
+ .digest("hex"),
188
+ };
189
+ }
190
+ const methods = {
191
+ snapshot() {
192
+ const result = legacy.snapshot();
193
+ if (!isManaged()) return result;
194
+ const performance = legacy.claudePerformance.snapshot(),
195
+ totals = performance.by_route.messages.terminal_outcomes.totals;
196
+ const ms = performance.by_route.messages.by_provider.m365;
197
+ const m365Requests = ms
198
+ ? {
199
+ ...ms.terminal_outcomes.totals,
200
+ active: ms.active,
201
+ total: ms.requests,
202
+ performance: {
203
+ by_route: { messages: { by_provider: { m365: ms }, terminal_outcomes: ms.terminal_outcomes } },
204
+ active_total: ms.active,
205
+ active_requests: performance.active_requests.filter(row => row.provider === "m365"),
206
+ recent_requests: performance.recent_requests.filter(row => row.provider === "m365"),
207
+ },
208
+ }
209
+ : null;
210
+ return {
211
+ ...result,
212
+ codex_provider: this.selection().codex,
213
+ connections: snapshot(true),
214
+ m365: {
215
+ ...result.m365,
216
+ ...(binding("codex").source === "m365"
217
+ ? { preference: this.providerPreference(binding("codex").source) }
218
+ : {}),
219
+ claude: {
220
+ ...result.m365.claude,
221
+ requests: m365Requests,
222
+ clients: Object.fromEntries(
223
+ [
224
+ ["app", "claude_app"],
225
+ ["code", "claude_code"],
226
+ ].map(([short, id]) => [
227
+ short,
228
+ binding(id).enabled && binding(id).source === "m365"
229
+ ? setup[id] || result.m365.claude.clients[short]
230
+ : "not_selected",
231
+ ])
232
+ ),
233
+ },
234
+ },
235
+ claude: {
236
+ base_url: `http://127.0.0.1:${corePort}/anthropic`,
237
+ gateway: CLIENT_IDS.some(
238
+ id => id !== "codex" && binding(id).enabled && permitted(id, binding(id).source)
239
+ )
240
+ ? "running"
241
+ : "unavailable",
242
+ clients: { app: setup.claude_app || "not_configured", code: setup.claude_code || "not_configured" },
243
+ requests: {
244
+ ...totals,
245
+ active: performance.active_total,
246
+ total: Object.values(totals).reduce((sum, value) => sum + value, 0) + performance.active_total,
247
+ performance,
248
+ },
249
+ },
250
+ ...Object.fromEntries(
251
+ getSettings().apis.map(api => [api.id, { preference: this.providerPreference(binding("codex").source) }])
252
+ ),
253
+ };
254
+ },
255
+ dashboardProviders() {
256
+ const builtins = legacy.dashboardProviders();
257
+ if (!isManaged()) return builtins.filter(source => source.enabled);
258
+ const definitions = snapshot(true).providers,
259
+ performance = legacy.claudePerformance.snapshot();
260
+ return definitions
261
+ .filter(item => item.enabled)
262
+ .map(item => {
263
+ const old = builtins.find(source => source.id === item.id),
264
+ source = item.builtin ? null : getSource(item.id);
265
+ const clients = CLIENT_IDS.filter(
266
+ id =>
267
+ binding(id).enabled &&
268
+ binding(id).allowed.includes(item.id) &&
269
+ (id === "codex" ? item.protocols.includes("responses") : item.protocols.includes("messages"))
270
+ ).map(id => ({
271
+ id,
272
+ name: CLIENT_NAMES[id],
273
+ selected:
274
+ binding(id).deployments?.some(model => model.source === item.id) ||
275
+ binding(id).source === item.id,
276
+ state: setup[id] || old?.clients?.find(client => client.id === id)?.state || "unknown",
277
+ gateway:
278
+ binding(id).deployments?.some(model => model.source === item.id) ||
279
+ binding(id).source === item.id
280
+ ? "running"
281
+ : "standby",
282
+ last_request_at: lastClients[id] || null,
283
+ }));
284
+ return {
285
+ ...old,
286
+ id: item.id,
287
+ name: item.name,
288
+ enabled: true,
289
+ generation: old?.generation || source?.registry.generation || 1,
290
+ state: old?.state || "configured",
291
+ auth: old?.auth || { state: "saved", token_cached: false },
292
+ selection: {
293
+ codex: clients.some(client => client.id === "codex"),
294
+ models_required: item.id !== "github",
295
+ },
296
+ clients,
297
+ models: old?.models || { count: item.model_count, source: "configured" },
298
+ requests: performance.by_route.messages.by_provider[item.id]
299
+ ? {
300
+ ...performance.by_route.messages.by_provider[item.id].terminal_outcomes.totals,
301
+ active: performance.by_route.messages.by_provider[item.id].active,
302
+ total: performance.by_route.messages.by_provider[item.id].requests,
303
+ }
304
+ : null,
305
+ };
306
+ });
307
+ },
308
+ dashboardCatalog(input = {}) {
309
+ if (!input.provider?.startsWith("api_")) {
310
+ const value = legacy.dashboardCatalog(input), source = input.provider || this.selection().codex;
311
+ return value?.then ? value.then(catalog => catalogVisibility(catalog, source)) : catalogVisibility(value, source);
312
+ }
313
+ if (!enabled(input.provider)) throw accessError("ccdx_client_source_disabled", 503);
314
+ return catalogVisibility(getSource(input.provider).publicCatalog(
315
+ CLIENT_IDS.filter(id => binding(id).enabled && binding(id).allowed.includes(input.provider))
316
+ ), input.provider);
317
+ },
318
+ };
319
+ return { imageModels, snapshot, sourceImpact, clientRevision, catalogVisibility, methods };
320
+ }
@@ -18,6 +18,7 @@ import {
18
18
  import { responseFailureDetails } from "./response-failures.mjs";
19
19
  import { status } from "./status.mjs";
20
20
  import { markUpstreamHeaders } from "./stream-performance.mjs";
21
+ import { adaptCallLessContext, isMissingCallIdError } from "./responses-tool-output.mjs";
21
22
 
22
23
  // Ordered Copilot-only fallbacks. Each policy is single-use and must be gated
23
24
  // by an exact upstream failure plus a request transformation that changes the
@@ -98,7 +99,7 @@ export async function openCopilotResponse(reqContext, upstream = copilotResponse
98
99
  let payloadPrepared = false;
99
100
  let releaseRecovery;
100
101
  try {
101
- for (let attempt = 0; attempt <= RETRY_POLICIES.length; attempt += 1) {
102
+ for (let attempt = 0; attempt <= RETRY_POLICIES.length + 1; attempt += 1) {
102
103
  let resp;
103
104
  try {
104
105
  options.assertPrepareActive?.();
@@ -123,6 +124,13 @@ export async function openCopilotResponse(reqContext, upstream = copilotResponse
123
124
  label: "Copilot Responses error body",
124
125
  });
125
126
  options.assertPrepareActive?.();
127
+ if (reqContext.surface !== "responses_compact" && !usedPolicies.has("call-less-tool-output") && isMissingCallIdError(resp.status, errorText)) {
128
+ const adapted = adaptCallLessContext(reqContext);
129
+ if (adapted) {
130
+ usedPolicies.add("call-less-tool-output");reqContext = adapted;payloadPrepared = false;
131
+ continue;
132
+ }
133
+ }
126
134
  let retry;
127
135
  try { retry = await selectCopilotResponseRetryWithHistory(reqContext, resp.status, errorText, usedPolicies, options); }
128
136
  catch (error) {
@@ -0,0 +1,155 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+
3
+ export const MESSAGES_TOOL_GUARD = Symbol("messages-tool-schema-guard");
4
+ const combiners = ["oneOf", "anyOf", "allOf"];
5
+ const unsafeKeywords = new Set(["pattern", "patternProperties", "format", "uniqueItems", "$ref", "$dynamicRef", "$recursiveRef"]);
6
+ const object = value => value && typeof value === "object" && !Array.isArray(value);
7
+
8
+ export function hasRootToolSchema(body) {
9
+ return Array.isArray(body?.tools) && body.tools.some(tool => object(tool?.input_schema)
10
+ && combiners.some(key => Object.hasOwn(tool.input_schema, key)));
11
+ }
12
+
13
+ export function isRootToolSchemaError(status, text) {
14
+ if (![400, 422].includes(status) || typeof text !== "string") return false;
15
+ let message = text;
16
+ try { const parsed = JSON.parse(text);message = parsed?.error?.message ?? parsed?.message ?? ""; } catch {}
17
+ return typeof message === "string" && /^(?:tools\.\d+\.(?:custom\.)?input_schema:\s*)?input_schema does not support oneOf, allOf, or anyOf at the top level\.?\s*$/i.test(message);
18
+ }
19
+
20
+ function safeSchema(schema) {
21
+ if (Buffer.byteLength(JSON.stringify(schema)) > 64 * 1024) return false;
22
+ let nodes = 0;
23
+ const visit = (value, depth) => {
24
+ if (++nodes > 2048 || depth > 32) return false;
25
+ if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value)) return false;
26
+ if (!value || typeof value !== "object") return true;
27
+ if (Array.isArray(value)) return value.every(item => visit(item, depth + 1));
28
+ return Object.entries(value).every(([key, child]) => !unsafeKeywords.has(key) && visit(child, depth + 1));
29
+ };
30
+ return visit(schema, 0);
31
+ }
32
+
33
+ function modelFacingSchema(schema, strict) {
34
+ const keys = combiners.filter(key => Object.hasOwn(schema, key));
35
+ if (keys.length !== 1 || schema.type != null && schema.type !== "object") return null;
36
+ const key = keys[0], variants = schema[key];
37
+ if (!Array.isArray(variants) || !variants.length || variants.some(variant => !object(variant)
38
+ || variant.type != null && variant.type !== "object" || combiners.some(name => Object.hasOwn(variant, name)))) return null;
39
+ if (schema.properties != null && !object(schema.properties) || variants.some(variant => variant.properties != null && !object(variant.properties))) return null;
40
+ const properties = Object.create(null), names = new Set(Object.keys(schema.properties || {}));
41
+ for (const variant of variants) for (const name of Object.keys(variant.properties || {})) names.add(name);
42
+ for (const name of names) {
43
+ if (Object.hasOwn(schema.properties || {}, name)) { properties[name] = schema.properties[name];continue; }
44
+ const choices = [];
45
+ for (const variant of variants) {
46
+ const property = variant.properties?.[name];
47
+ if (property === undefined) {
48
+ if (variant.additionalProperties !== false) { choices.splice(0, choices.length, {});break; }
49
+ } else if (!choices.some(value => isDeepStrictEqual(value, property))) choices.push(property);
50
+ }
51
+ properties[name] = choices.length === 1 ? choices[0] : choices.length ? { anyOf: choices } : {};
52
+ }
53
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
54
+ const lists = variants.map(variant => new Set(Array.isArray(variant.required) ? variant.required : []));
55
+ for (const name of lists[0]) if (key === "allOf" || lists.every(list => list.has(name))) required.add(name);
56
+ if (key === "allOf") for (const list of lists) for (const name of list) required.add(name);
57
+ for (const name of required) if (!Object.hasOwn(properties, name)) properties[name] = {};
58
+ const closed = schema.additionalProperties === false || variants.every(variant => variant.additionalProperties === false);
59
+ if (strict && !closed) return null;
60
+ return { type: "object", properties, ...(required.size ? { required: [...required] } : {}),
61
+ ...(closed ? { additionalProperties: false } : {}),
62
+ ...Object.fromEntries(["title", "description", "minProperties", "maxProperties"].filter(name => schema[name] !== undefined).map(name => [name, schema[name]])) };
63
+ }
64
+
65
+ function lossyNumber(value, source) {
66
+ if (typeof value !== "number") return false;
67
+ if (!Number.isFinite(value) || Number.isInteger(value) && !Number.isSafeInteger(value)) return true;
68
+ return typeof source === "string" && String(value) !== source && source.replace(/\D/g, "").replace(/^0+/, "").length > 15;
69
+ }
70
+
71
+ function parseCheckedJson(text) {
72
+ const unsafe = new WeakSet();
73
+ const value = JSON.parse(text, function(_key, child, context) {
74
+ if (lossyNumber(child, context?.source) || child && typeof child === "object" && unsafe.has(child)) unsafe.add(this);
75
+ return child;
76
+ });
77
+ return { value, unsafe };
78
+ }
79
+
80
+ function invalidToolInput() {
81
+ return Object.assign(new Error("Upstream tool input did not satisfy its original schema."), { code: "ccdx_tool_input_invalid", statusCode: 502 });
82
+ }
83
+
84
+ function makeGuard(validators, maxBytes) {
85
+ const pending = new Map(), buffered = [];let bytes = 0;
86
+ const check = (name, value, unsafe, restore) => {
87
+ const validate = validators.get(name);
88
+ if (!validate) return;
89
+ if (unsafe || !validate(restore ? restore(value) : value)) throw invalidToolInput();
90
+ };
91
+ return {
92
+ validateMessage(text, restore) {
93
+ let parsed;try { parsed = parseCheckedJson(text); } catch { throw invalidToolInput(); }
94
+ if (parsed.value?.content !== undefined && !Array.isArray(parsed.value.content)) throw invalidToolInput();
95
+ for (const block of parsed.value?.content || []) if (block?.type === "tool_use" && validators.has(block.name)) {
96
+ check(block.name, block.input, block.input && typeof block.input === "object" && parsed.unsafe.has(block.input), restore);
97
+ }
98
+ return parsed.value;
99
+ },
100
+ frame(event, chunk, raw, restore) {
101
+ const block = event?.content_block;
102
+ if (event?.type === "content_block_start" && block?.type === "tool_use" && validators.has(block.name)) {
103
+ if (pending.has(event.index)) throw invalidToolInput();
104
+ const parsed = parseCheckedJson(raw), initial = parsed.value?.content_block?.input;
105
+ pending.set(event.index, { name: block.name, initial, unsafe: initial && typeof initial === "object" && parsed.unsafe.has(initial), parts: [] });
106
+ }
107
+ if (!pending.size) return [{ event, chunk }];
108
+ if (event?.type === "error") { pending.clear();buffered.length = 0;bytes = 0;return [{ event, chunk }]; }
109
+ buffered.push({ event, chunk });bytes += chunk.length;
110
+ if (bytes > maxBytes) throw invalidToolInput();
111
+ const state = pending.get(event?.index);
112
+ if (state && event.type === "content_block_delta") {
113
+ if (event.delta?.type !== "input_json_delta" || typeof event.delta.partial_json !== "string") throw invalidToolInput();
114
+ state.parts.push(event.delta.partial_json);
115
+ }
116
+ if (state && event.type === "content_block_stop") {
117
+ let value = state.initial, unsafe = state.unsafe;
118
+ if (state.parts.length) {
119
+ let parsed;try { parsed = parseCheckedJson(state.parts.join("")); } catch { throw invalidToolInput(); }
120
+ value = parsed.value;unsafe = value && typeof value === "object" && parsed.unsafe.has(value);
121
+ }
122
+ check(state.name, value, unsafe, restore);pending.delete(event.index);
123
+ if (!pending.size) { const result = buffered.splice(0);bytes = 0;return result; }
124
+ }
125
+ if (event?.type === "message_stop") throw invalidToolInput();
126
+ return [];
127
+ },
128
+ };
129
+ }
130
+
131
+ export async function adaptMessagesToolSchemas(body, { maxBytes = 8 * 1024 * 1024 } = {}) {
132
+ if (!hasRootToolSchema(body)) return null;
133
+ const names = new Set(), validators = new Map(), tools = [];
134
+ let Ajv, Ajv2020;
135
+ try {
136
+ for (const tool of body.tools) {
137
+ if (typeof tool?.name === "string") { if (names.has(tool.name)) return null;names.add(tool.name); }
138
+ const schema = tool?.input_schema;
139
+ if (!object(schema) || !combiners.some(key => Object.hasOwn(schema, key))) { tools.push(tool);continue; }
140
+ if (typeof tool.name !== "string" || !tool.name || !safeSchema(schema)) return null;
141
+ if (validators.size >= 32) return null;
142
+ const modelSchema = modelFacingSchema(schema, tool.strict === true);
143
+ if (!modelSchema) return null;
144
+ const dialect = schema.$schema;
145
+ if (dialect && !["http://json-schema.org/draft-07/schema#", "https://json-schema.org/draft/2020-12/schema"].includes(dialect)) return null;
146
+ if (dialect?.includes("2020-12")) Ajv2020 ||= (await import("ajv/dist/2020.js")).default;
147
+ else Ajv ||= (await import("ajv")).default;
148
+ const Validator = dialect?.includes("2020-12") ? Ajv2020 : Ajv;
149
+ const validator = new Validator({ strict: true, strictTypes: false, strictRequired: false, allowUnionTypes: true, allErrors: false, addUsedSchema: false });
150
+ validators.set(tool.name, validator.compile(schema));
151
+ tools.push({ ...tool, input_schema: modelSchema });
152
+ }
153
+ } catch { return null; }
154
+ return validators.size ? { body: { ...body, tools }, guard: makeGuard(validators, maxBytes) } : null;
155
+ }
@@ -13,21 +13,38 @@ const secretPatterns = [
13
13
  ];
14
14
  const secretField = /(?:["']?\b(?:password|passwd|api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password)\b["']?\s*[:=]\s*)(?:"((?:\\.|[^"\\\r\n])+)"|'((?:\\.|[^'\\\r\n])+)'|([^\s,;\r\n}]+))/gdi;
15
15
  const personalKinds = new Set(["email", "phone", "account", "payment_card", "private_address", "private_date", "private_person"]);
16
+ const secretKeyPattern = /^(?:password|passwd|api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password|credential|secret|token)$/i;
16
17
  const kept = new Set(["model", "id", "type", "role", "name", "namespace", "server_label", "server_name", "call_id", "tool_use_id", "item_id", "signature", "encrypted_content", "thought_signature", "thoughtSignature", "data", "url", "file_id", "previous_response_id", "prompt_cache_key", "media_type", "mime_type", "stop_reason", "finish_reason", "status", "object", "event"]);
18
+ function parseToolArguments(text) {
19
+ return JSON.parse(text, (_key, value, context) => typeof value === "number" && String(value) !== context.source
20
+ ? JSON.rawJSON(context.source) : value);
21
+ }
22
+ // Integers under 16 digits and ordinary short decimals round-trip as JSON text.
23
+ // Preserve longer values and cases where JSON.stringify changes their spelling.
24
+ const possibleLossyNumber = /(?:\d{16}|(?=\d+\.\d)(?=(?:\d|\.){17})\d+\.\d+|\d+\.\d*0(?=[,\]}\s]|$)|\b0\.0{6,}[1-9]|\d[eE][+-]?\d|-0(?=[,\]}\s]|$))/;
25
+ function overlayToolStrings(target, source) {
26
+ if (typeof source === "string") return source;
27
+ if (!source || typeof source !== "object") return target;
28
+ for (const [key, value] of Object.entries(source)) {
29
+ if (typeof value === "string") target[key] = value;
30
+ else if (value && typeof value === "object") overlayToolStrings(target[key], value);
31
+ }
32
+ return target;
33
+ }
17
34
  function leaves(value, add, inArguments = false) {
18
35
  if (typeof value === "string") return;
19
- if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) typeof value[i] === "string" ? add(value, i, value[i], inArguments) : leaves(value[i], add, inArguments);return; }
36
+ if (Array.isArray(value)) { for (let i = 0; i < value.length; i++) typeof value[i] === "string" ? add(value, i, value[i]) : leaves(value[i], add, inArguments);return; }
20
37
  if (!value || typeof value !== "object") return;
21
38
  if (!inArguments && (value.encrypted_content || ["thinking", "redacted_thinking", "reasoning"].includes(value.type))) return;
22
39
  for (const [key, item] of Object.entries(value)) {
23
40
  if (!inArguments && kept.has(key)) continue;
24
- if (typeof item === "string") add(value, key, item, inArguments);
41
+ if (typeof item === "string") add(value, key, item);
25
42
  else leaves(item, add, inArguments);
26
43
  }
27
44
  }
28
45
  function requestTexts(body, protocol) {
29
46
  const items = [], nested = [];
30
- const add = (parent, key, text) => { if (text && !text.startsWith("data:")) items.push({ parent, key, text, secret: /^(?:password|passwd|api_key|apikey|access_token|refresh_token|client_secret|secret_key|auth_token|db_password|credential|secret|token)$/i.test(String(key)) }); };
47
+ const add = (parent, key, text) => { if (text && !text.startsWith("data:")) items.push({ parent, key, text, secret: secretKeyPattern.test(String(key)) }); };
31
48
  const text = (parent, key) => { if (typeof parent?.[key] === "string") add(parent, key, parent[key]);else if (Array.isArray(parent?.[key])) for (const block of parent[key]) if (["text", "input_text", "output_text"].includes(block?.type)) add(block, "text", block.text); };
32
49
  const args = (parent, key) => {
33
50
  if (typeof parent[key] === "string") {
@@ -121,9 +138,10 @@ export async function maskPrivacyRequest(body, { protocol, client = "api", perso
121
138
  const found = texts.length ? await find(texts, { signal, onPlan }) : [], values = new Map(), kinds = {}, total = { count: 0, bytes: 0 };
122
139
  if (!Array.isArray(found) || found.length !== texts.length) throw privacyFailure("engine_invalid");
123
140
  for (let i = 0; i < items.length; i++) {
124
- const item = items[i], bytes = Buffer.from(item.text), spans = rules(item.text, personal);
141
+ const item = items[i], spans = rules(item.text, personal);let bytes;
125
142
  if (item.secret) spans.push({ start: 0, end: item.text.length, kind: "secret" });
126
143
  for (const span of found[i] || []) {
144
+ bytes ||= Buffer.from(item.text);
127
145
  if (!Number.isInteger(span.start) || !Number.isInteger(span.end) || span.start < 0 || span.end <= span.start || span.end > bytes.length || !Number.isFinite(span.score)) throw privacyFailure("engine_invalid");
128
146
  if (span.score < 0.8 || span.label !== "common_secret" && !(personal && personalKinds.has(span.label))) continue;
129
147
  const start = bytes.subarray(0, span.start).toString("utf8").length, end = bytes.subarray(0, span.end).toString("utf8").length;
@@ -143,18 +161,25 @@ export async function maskPrivacyRequest(body, { protocol, client = "api", perso
143
161
  }
144
162
  if (end) item.parent[item.key] = output + item.text.slice(end);
145
163
  }
146
- if (total.count) for (const item of nested) item.parent[item.key] = JSON.stringify(item.value);
164
+ if (total.count) for (const item of nested) {
165
+ const ordinary = JSON.stringify(item.value), original = item.parent[item.key];
166
+ item.parent[item.key] = ordinary !== original && possibleLossyNumber.test(original)
167
+ ? JSON.stringify(overlayToolStrings(parseToolArguments(original), item.value)) : ordinary;
168
+ }
147
169
  const restoreText = text => text.replace(tokenPattern, token => values.get(token) ?? token);
148
170
  function restoreValue(value, inToolData = false) {
149
171
  if (typeof value === "string") return restoreText(value);
150
172
  if (Array.isArray(value)) return value.map(item => restoreValue(item, inToolData));
151
- if (!value || typeof value !== "object") return value;
173
+ if (!value || typeof value !== "object" || JSON.isRawJSON(value)) return value;
152
174
  if (!inToolData && (value.encrypted_content || ["thinking", "redacted_thinking", "reasoning"].includes(value.type))) return value;
153
175
  return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, !inToolData && kept.has(key) ? item
154
176
  : !inToolData && key === "arguments" && typeof item === "string" && item ? restoreArguments(item)
155
177
  : restoreValue(item, inToolData || key === "input" && ["tool_use", "server_tool_use", "mcp_tool_use"].includes(value.type))]));
156
178
  }
157
- function restoreArguments(text) { try { return JSON.stringify(restoreValue(JSON.parse(text), true)); } catch { return restoreText(text); } }
179
+ function restoreArguments(text) {
180
+ if (!text.includes(TOKEN_START) && !text.includes("\\u")) return text;
181
+ try { return JSON.stringify(restoreValue(parseToolArguments(text), true)); } catch { return restoreText(text); }
182
+ }
158
183
  return { body: total.count ? copy : body, count: total.count, kinds, restoreText, restoreValue,
159
184
  restoreToolValue: value => restoreValue(value, true), release: () => values.clear() };
160
185
  }
@@ -24,7 +24,7 @@ export async function createApiNetwork({ targets, env = process.env, platform =
24
24
  requestImpl = worker.requestImpl;
25
25
  }
26
26
  }
27
- const agent = worker ? undefined : createProxyAgent(plan);let closed = false, broken = false, retiring = false, active = 0, finishRetiring;
27
+ const agent = worker ? undefined : createProxyAgent(plan, { freeSocketTimeoutMs: 60_000 });let closed = false, broken = false, retiring = false, active = 0, finishRetiring;
28
28
  const close = () => { if (closed) return;closed = true;agent?.destroy();worker?.close();finishRetiring?.(); };
29
29
  return {
30
30
  healthy: () => !closed && !broken && !retiring && (!worker || worker.healthy()),
@@ -17,6 +17,9 @@ import { markRequestObservation, markUpstreamStarted } from "../stream-performan
17
17
  import { createAbortAwareSingleflight } from "../bounded-result-cache.mjs";
18
18
  import { createApiTokenCounter } from "./api-token-count.mjs";
19
19
  import { apiModelDisplay } from "../api-model-display.mjs";
20
+ import { adaptCallLessContext, CALL_LESS_TOOL_RETRIED, normalizeCallLessToolOutputs } from "../responses-tool-output.mjs";
21
+ import { adaptMessagesToolSchemas, hasRootToolSchema, MESSAGES_TOOL_GUARD } from "../messages-tool-schema.mjs";
22
+ import { loadRuntimeConfig } from "../runtime-config.mjs";
20
23
 
21
24
  const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
22
25
  export function apiCatalog(config, env = process.env) {
@@ -86,8 +89,28 @@ export function createApiProvider({ config, secrets, env = process.env, platform
86
89
  const result = await transport.fetch(url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal });
87
90
  if (result.status >= 300 && result.status < 400) { await result.body?.cancel();throw accessError("ccdx_api_redirect_refused", 502); }
88
91
  if (!result.ok) {
89
- try { options.onUpstreamErrorHeaders?.(result.status); } catch { /* Optional admission release cannot hide the upstream response. */ }
90
- const reason = await readSafeUpstreamReason(result, { signal: options.signal });const code = `ccdx_api_http_${result.status}`;
92
+ const adapted = api === "responses" && [400, 422].includes(result.status) && !options.compatibilityRetried && !options.skipCallLessRetry
93
+ ? normalizeCallLessToolOutputs(body) : null;
94
+ const schemaCandidate = api === "messages" && !options.countTokens && [400, 422].includes(result.status)
95
+ && !options.compatibilityRetried && hasRootToolSchema(body);
96
+ if (!adapted && !schemaCandidate) try { options.onUpstreamErrorHeaders?.(result.status); } catch { /* Optional admission release cannot hide the upstream response. */ }
97
+ const reason = await readSafeUpstreamReason(result, { signal: options.signal, missingCallId: Boolean(adapted), rootToolSchema: schemaCandidate });
98
+ if (adapted && reason?.code === "ccdx_missing_call_id") {
99
+ const recovered = await request(url, adapted, { ...options, bodyText: undefined, compatibilityRetried: true }, api);
100
+ if (recovered.ok) Object.defineProperty(recovered, CALL_LESS_TOOL_RETRIED, { value: true });
101
+ return recovered;
102
+ }
103
+ if (schemaCandidate && reason?.code === "ccdx_tool_schema_root_unsupported") {
104
+ const compatibility = await adaptMessagesToolSchemas(body, { maxBytes: loadRuntimeConfig(env).maxSseBufferBytes });
105
+ options.signal?.throwIfAborted();
106
+ if (compatibility) {
107
+ const recovered = await request(url, compatibility.body, { ...options, bodyText: undefined, compatibilityRetried: true }, api);
108
+ if (recovered.ok) Object.defineProperty(recovered, MESSAGES_TOOL_GUARD, { value: compatibility.guard });
109
+ return recovered;
110
+ }
111
+ }
112
+ if (adapted || schemaCandidate) try { options.onUpstreamErrorHeaders?.(result.status); } catch { /* Preserve the original upstream failure. */ }
113
+ const code = `ccdx_api_http_${result.status}`;
91
114
  const safeHeaders = { "Content-Type": "application/json" }, retry = result.headers.get("retry-after");
92
115
  if (/^\d{1,8}$/.test(retry || "")) safeHeaders["Retry-After"] = retry;
93
116
  else if (retry && Number.isFinite(Date.parse(retry))) safeHeaders["Retry-After"] = new Date(retry).toUTCString();
@@ -116,7 +139,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
116
139
  const final = enforceResponsesPayloadByteBudget(body, prepared, { assertActive: options.assertActive });
117
140
  return request(config.endpoints.responses, body, { ...options, bodyText: final.bodyText });
118
141
  },
119
- responsesCompact(body, options = {}) { selected(body.model, "responses");return request(config.endpoints.responses.replace(/\/+$/, "") + "/compact", body, options); },
142
+ responsesCompact(body, options = {}) { selected(body.model, "responses");return request(config.endpoints.responses.replace(/\/+$/, "") + "/compact", body, { ...options, skipCallLessRetry: true }); },
120
143
  chatCompletions(body, options = {}) { selected(body.model, "chat");return request(config.endpoints.chat, body, options, "chat"); },
121
144
  messages(body, options = {}) {
122
145
  const model = selected(body.model, "messages");
@@ -167,6 +190,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
167
190
  const resp = await upstream(context.body, { assertActive: options.assertPrepareActive, signal: options.signal, currentInputStart: context.currentInputStart, onUpstreamStart: options.onUpstreamStart,
168
191
  onUpstreamErrorHeaders(status) { headersObserved = true;markUpstreamHeaders(status);options.releaseRequest?.(context); } });
169
192
  if (!headersObserved) markUpstreamHeaders(resp.status);
193
+ if (resp[CALL_LESS_TOOL_RETRIED]) context = adaptCallLessContext(context) || context;
170
194
  // request() already discarded the vendor body and projected a safe error.
171
195
  if (!resp.ok) {
172
196
  const errorText = await readBoundedResponseText(resp, { maxBytes: MAX_UPSTREAM_ERROR_BODY_BYTES, signal: options.signal, label: "API error response" });