codex-copilot-dx 1.3.21 → 1.3.23

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 (49) hide show
  1. package/README.md +3 -0
  2. package/docs/ARCHITECTURE.md +48 -1
  3. package/docs/REFERENCE.md +60 -2
  4. package/package.json +3 -2
  5. package/src/adapter.mjs +41 -10
  6. package/src/antigravity-chat-bridge.mjs +240 -0
  7. package/src/antigravity-handler.mjs +141 -0
  8. package/src/antigravity-images.mjs +28 -0
  9. package/src/antigravity-models.mjs +34 -0
  10. package/src/antigravity-runtime.mjs +72 -0
  11. package/src/carbon-search.mjs +37 -0
  12. package/src/carbon-tool-bridge.mjs +384 -0
  13. package/src/claude-gateway.mjs +40 -3
  14. package/src/cli-command-spec.mjs +2 -0
  15. package/src/cli-management.mjs +14 -1
  16. package/src/clients/codex-models.mjs +6 -2
  17. package/src/copilot-responses-compat.mjs +9 -1
  18. package/src/copilot-web-fetch.mjs +75 -0
  19. package/src/copilot-web.mjs +225 -0
  20. package/src/dashboard/console.js +1 -1
  21. package/src/dashboard/flow.js +2 -2
  22. package/src/dashboard/gemini.js +27 -0
  23. package/src/dashboard/index.html +14 -20
  24. package/src/dashboard/language.js +10 -0
  25. package/src/dashboard/status.js +4 -0
  26. package/src/dashboard/ui.js +3 -0
  27. package/src/dashboard-api.mjs +13 -0
  28. package/src/dashboard.mjs +17 -13
  29. package/src/gemini-app.mjs +34 -0
  30. package/src/http-transport.mjs +3 -2
  31. package/src/local-privacy.mjs +7 -1
  32. package/src/messages-tool-schema.mjs +155 -0
  33. package/src/native-images.mjs +2 -1
  34. package/src/observability.mjs +5 -1
  35. package/src/optional-routes.mjs +4 -0
  36. package/src/privacy-stream.mjs +2 -0
  37. package/src/privacy-transform.mjs +1 -0
  38. package/src/providers/api-network.mjs +1 -1
  39. package/src/providers/api.mjs +27 -3
  40. package/src/providers/github.mjs +8 -5
  41. package/src/proxy-tunnel.mjs +17 -1
  42. package/src/request-application.mjs +1 -1
  43. package/src/responses-bridge.mjs +74 -9
  44. package/src/responses-chat-payload.mjs +6 -5
  45. package/src/responses-handler.mjs +29 -6
  46. package/src/responses-tool-output.mjs +42 -0
  47. package/src/safe-upstream-error.mjs +8 -2
  48. package/src/stream-performance.mjs +1 -1
  49. package/src/terminal-state.mjs +6 -5
@@ -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
+ }
@@ -16,7 +16,7 @@ const RESPONSE_MAX_BYTES = 48 * 1024 * 1024;
16
16
  const SIZES = new Set(["auto", "1024x1024", "1536x1024", "1024x1536"]);
17
17
  const FIELDS = new Set(["model", "prompt", "images", "background", "quality", "size", "n"]);
18
18
 
19
- async function checkedImage(value, maxBytes, mime) {
19
+ export async function checkedImage(value, maxBytes, mime) {
20
20
  if (typeof value !== "string" || !value || value.length > 4 * Math.ceil(maxBytes / 3)
21
21
  || value.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) throw httpError("Invalid image data", 400);
22
22
  const bytes = Buffer.from(value, "base64");
@@ -26,6 +26,7 @@ async function checkedImage(value, maxBytes, mime) {
26
26
  catch { throw httpError("Image must be a valid PNG, JPEG or WebP", 400); }
27
27
  const type = { png: "image/png", jpeg: "image/jpeg", webp: "image/webp" }[info.format];
28
28
  if (!type || mime && mime !== type) throw httpError("Image format does not match its data", 400);
29
+ return type;
29
30
  }
30
31
 
31
32
  export async function nativeImageRequest(body, operation, selectedModel = DEFAULT_IMAGE_MODEL) {
@@ -15,8 +15,10 @@ const OBSERVABILITY_RUNTIME_CONFIG = loadRuntimeConfig();
15
15
  const OBSERVABILITY_DECODED_BODY_BYTES = decodedBodyLimitPreference().bytes;
16
16
 
17
17
  const ROUTE_NAMES = Object.freeze([
18
+ "antigravity",
18
19
  "responses",
19
20
  "responses_compact",
21
+ "search",
20
22
  "models",
21
23
  "messages",
22
24
  "messages_count_tokens",
@@ -110,9 +112,11 @@ export function classifyAdapterRoute(method, pathname) {
110
112
  if (pathname === "/anthropic/v1/models") return "claude_models";
111
113
  if (method === "POST" && pathname === "/v1/responses") return "responses";
112
114
  if (method === "POST" && pathname === "/v1/responses/compact") return "responses_compact";
115
+ if (method === "POST" && pathname === "/v1/alpha/search") return "search";
113
116
  if (method === "GET" && pathname === "/v1/models") return "models";
114
117
  if (["/v1/images/generations", "/v1/images/edits"].includes(pathname)) return "images";
115
118
  if (pathname === "/mcp/image") return "image_mcp";
119
+ if (pathname.startsWith("/antigravity/")) return ["/antigravity/v1internal:streamGenerateContent", "/antigravity/v1internal:generateContent"].includes(pathname) ? "antigravity" : "antigravity_control";
116
120
  return "not_found";
117
121
  }
118
122
 
@@ -196,7 +200,7 @@ export function runtimeStatusPayload({
196
200
  }
197
201
  const history = responseHistoryStats();
198
202
  const requests = metrics?.snapshot?.() || createRequestMetrics().snapshot();
199
- const activityCounts = ["responses", "responses_compact", "messages"].map(route => requests.by_route[route].active);
203
+ const activityCounts = ["responses", "responses_compact", "messages", "search", "antigravity"].map(route => requests.by_route[route]?.active || 0);
200
204
  activityCounts.push(imageGeneration?.active ?? 0);
201
205
  const active = activityCounts.every(value => Number.isSafeInteger(value) && value >= 0)
202
206
  && Number.isSafeInteger(activityCounts.reduce((sum, value) => sum + value, 0)) ? activityCounts.reduce((sum, value) => sum + value, 0) : null;
@@ -1,6 +1,10 @@
1
1
  export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/live.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/context.js", "/ui.js", "/console.js", "/updates.js", "/preferences.js", "/features.js", "/icons.js", "/disclosure.js", "/tools.js", "/connections.js", "/privacy.js"]);
2
2
  export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks", "/_ccdx/ui/connections", "/_ccdx/ui/context", "/_ccdx/ui/privacy"]);
3
3
 
4
+ DASHBOARD_PATHS.add("/gemini.js");
5
+ DASHBOARD_PATHS.add("/dashboard.js");
6
+ DASHBOARD_API_PATHS.add("/_ccdx/ui/gemini");
7
+
4
8
  export function isOptionalRoute(method, pathname) {
5
9
  return DASHBOARD_API_PATHS.has(pathname) || pathname === "/mcp/image"
6
10
  || ((method === "GET" || method === "HEAD") && DASHBOARD_PATHS.has(pathname));
@@ -112,6 +112,8 @@ function fragments(session, json, onRetained) {
112
112
  };
113
113
  }
114
114
 
115
+ export function createPrivacyTextFragments(session) { return fragments(session, false, () => {}); }
116
+
115
117
  function rewrite(wire, event, named = false) {
116
118
  let written = false;
117
119
  const output = wire.split(/(?<=\n)|(?<=\r)(?!\n)/).map(line => {
@@ -78,6 +78,7 @@ function requestTexts(body, protocol) {
78
78
  else text(item, "content");
79
79
  }
80
80
  }
81
+ if (protocol === "search") leaves(body.commands, add);
81
82
  return { items, nested };
82
83
  }
83
84
  function ruleSpans(text, personal) {
@@ -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" });
@@ -38,12 +38,15 @@ export function createGithubProvider({ client = defaultCopilotClient, profileId
38
38
  route(body, { requestedModel, upstreamModel, forceResponses, surface, getCachedModelEndpoints = client.getCachedModelEndpoints }) {
39
39
  let protocol = "openai-responses";
40
40
  if (surface === "responses") {
41
- const customTools = responsesBodyUsesCustomTools(body);
42
41
  const endpoints = getCachedModelEndpoints(upstreamModel);
43
- const native = forceResponses || requestedModel === CODEX_AUTO_REVIEW_MODEL
44
- || isResponsesOnly(upstreamModel, endpoints)
45
- || (customTools && Array.isArray(endpoints) && (endpoints.includes("/responses") || endpoints.includes("/v1/responses")));
46
- if (customTools && !native) {
42
+ const nativeBase = forceResponses || requestedModel === CODEX_AUTO_REVIEW_MODEL || isResponsesOnly(upstreamModel, endpoints);
43
+ const customTools = nativeBase ? false : responsesBodyUsesCustomTools(body);
44
+ const native = nativeBase
45
+ || ((customTools || body?.tool_choice?.type === "allowed_tools") && Array.isArray(endpoints)
46
+ && (endpoints.includes("/responses") || endpoints.includes("/v1/responses")));
47
+ const carbonChat = upstreamModel === "gemini-4-carbon" && Array.isArray(endpoints)
48
+ && modelSupportsChatCompletions({ supported_endpoints: endpoints });
49
+ if (customTools && !native && !carbonChat) {
47
50
  const message = `Model ${upstreamModel} has custom tool items that cannot be represented by Chat Completions, and cached endpoint metadata does not confirm Responses support`;
48
51
  throw Object.assign(new Error(message), { statusCode: 400, code: "ccdx_custom_tools_require_responses",
49
52
  jsonBody: { error: { message, type: "invalid_request_error", code: "ccdx_custom_tools_require_responses", model: upstreamModel } } });
@@ -77,10 +77,26 @@ async function connectProxy(target, route, timeoutMs, pending) {
77
77
  } catch (error) { clearTimeout(timer); socket.destroy(); throw error; }
78
78
  }
79
79
 
80
- export function createProxyAgent(plan, { timeoutMs = 30_000 } = {}) {
80
+ export function createProxyAgent(plan, { timeoutMs = 30_000, freeSocketTimeoutMs = 0 } = {}) {
81
81
  const pending = new Set();
82
82
  let closed = false;
83
83
  const agent = new https.Agent({ keepAlive: true, maxSockets: 32, maxFreeSockets: 4 });
84
+ if (freeSocketTimeoutMs > 0) {
85
+ const keepSocketAlive = agent.keepSocketAlive, reuseSocket = agent.reuseSocket;
86
+ agent.keepSocketAlive = function(socket) {
87
+ const hint = socket._httpMessage?.res?.headers?.["keep-alive"];
88
+ const seconds = /(?:^|[,;])\s*timeout\s*=\s*(\d+)\s*(?=[,;]|$)/i.exec(typeof hint === "string" ? hint : "")?.[1];
89
+ const serverTimeout = seconds === undefined ? Infinity : Number(seconds) * 1000 - 1000;
90
+ if (!keepSocketAlive.call(this, socket) || serverTimeout <= 0) return false;
91
+ const previousTimeout = socket.timeout > 0 ? socket.timeout : Infinity;
92
+ socket.setTimeout(Math.min(freeSocketTimeoutMs, serverTimeout, previousTimeout));
93
+ return true;
94
+ };
95
+ agent.reuseSocket = function(socket, request) {
96
+ socket.setTimeout(0);
97
+ reuseSocket.call(this, socket, request);
98
+ };
99
+ }
84
100
  const direct = agent.createConnection.bind(agent);
85
101
  agent.createConnection = (options, callback) => {
86
102
  if (closed) { queueMicrotask(() => callback(new Error("Proxy agent is closed"))); return undefined; }
@@ -1,4 +1,4 @@
1
- const APPLICATIONS = new Set(["codex_app", "codex_cli", "codex", "claude_app", "claude_code", "claude", "api"]);
1
+ const APPLICATIONS = new Set(["codex_app", "codex_cli", "codex", "claude_app", "claude_code", "claude", "gemini_app", "api"]);
2
2
  const DECLARED = new Map([["codex-app", "codex_app"], ["codex-cli", "codex_cli"], ["codex", "codex"], ["claude-app", "claude_app"], ["claude-code", "claude_code"]]);
3
3
  const ORIGINATORS = new Map([["codex desktop", "codex_app"], ["codex_desktop", "codex_app"], ["codex_app", "codex_app"], ["codex_cli_rs", "codex_cli"], ["codex_exec", "codex_cli"], ["codex-cli", "codex_cli"], ["codex", "codex"], ["codex_vscode", "codex"]]);
4
4
  const hint = value => typeof value === "string" && value.length <= 80 ? value.trim().toLowerCase() : "";
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { chatCompletions } from "./copilot.mjs";
3
3
  import { webStreamLines } from "./stream.mjs";
4
+ import { normalizeCallLessToolOutputs } from "./responses-tool-output.mjs";
4
5
  import {
5
6
  abortErrorStatusCode,
6
7
  isAbortLikeError,
@@ -47,9 +48,16 @@ function chatImagePart(part) {
47
48
 
48
49
  export function responsesBodyUsesCustomTools(body) {
49
50
  if (body?.tool_choice?.type === "custom") return true;
50
- if (Array.isArray(body?.tools) && body.tools.some((tool) => tool?.type === "custom")) return true;
51
+ if (body?.tool_choice?.type === "function" && body.tool_choice.namespace != null) return true;
52
+ if (Array.isArray(body?.tools) && body.tools.some((tool) => tool?.defer_loading === true || (tool?.type === "function"
53
+ ? tool.namespace != null
54
+ : tool?.type === "custom" || tool?.type === "tool_search" || tool?.type === "namespace"))) return true;
51
55
  return Array.isArray(body?.input)
52
- && body.input.some((item) => ["custom_tool_call", "custom_tool_call_output", "additional_tools", "tool_search_output"].includes(item?.type));
56
+ && body.input.some((item) => {
57
+ const type = item?.type;
58
+ return type !== "message" && (type === "function_call" ? item.namespace != null
59
+ : type === "custom_tool_call" || type === "custom_tool_call_output" || type === "additional_tools" || type === "tool_search_call" || type === "tool_search_output");
60
+ });
53
61
  }
54
62
 
55
63
  function chatCompatibilityError(kind, itemType) {
@@ -69,7 +77,7 @@ function chatCompatibilityError(kind, itemType) {
69
77
  return error;
70
78
  }
71
79
 
72
- export function responsesToChat(body, { reasoningEfforts } = {}) {
80
+ export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
73
81
  const messages = [];
74
82
  if (body.instructions) messages.push({ role: "system", content: body.instructions });
75
83
 
@@ -77,6 +85,7 @@ export function responsesToChat(body, { reasoningEfforts } = {}) {
77
85
  if (typeof content === "string") return content;
78
86
  if (content === null) return null;
79
87
  if (!Array.isArray(content)) throw chatCompatibilityError("message content", typeof content);
88
+ if (content.length === 1 && ["input_text", "output_text", "text"].includes(content[0]?.type) && typeof content[0].text === "string") return content[0].text;
80
89
  const parts = [];
81
90
  for (const part of content) {
82
91
  if (!part || typeof part !== "object") throw chatCompatibilityError("message content", part?.type);
@@ -137,6 +146,7 @@ export function responsesToChat(body, { reasoningEfforts } = {}) {
137
146
  const toolCalls = [];
138
147
  while (index < body.input.length && body.input[index]?.type === "function_call") {
139
148
  const call = body.input[index];
149
+ if (call.namespace != null) throw chatCompatibilityError("input item", "namespaced_function_call");
140
150
  toolCalls.push({
141
151
  id: call.call_id || randomUUID(),
142
152
  type: "function",
@@ -151,7 +161,13 @@ export function responsesToChat(body, { reasoningEfforts } = {}) {
151
161
  tool_calls: toolCalls,
152
162
  });
153
163
  } else if (item?.type === "function_call_output") {
154
- messages.push({ role: "tool", tool_call_id: item.call_id, content: typeof item.output === "string" ? item.output : JSON.stringify(item.output) });
164
+ if (typeof item.call_id === "string" && item.call_id.trim()) {
165
+ messages.push({ role: "tool", tool_call_id: item.call_id, content: typeof item.output === "string" ? item.output : JSON.stringify(item.output) });
166
+ } else {
167
+ const adapted = normalizeCallLessToolOutputs({ input: [item] });
168
+ if (!adapted) throw chatCompatibilityError("input item", "function_call_output");
169
+ messages.push({ role: "user", content: messageContent(adapted.input[0].content) });
170
+ }
155
171
  } else {
156
172
  throw chatCompatibilityError("input item", item?.type);
157
173
  }
@@ -162,6 +178,14 @@ export function responsesToChat(body, { reasoningEfforts } = {}) {
162
178
  for (const k of ["temperature", "top_p", "stop", "presence_penalty", "frequency_penalty"]) {
163
179
  if (body[k] !== undefined) chatReq[k] = body[k];
164
180
  }
181
+ if (cacheSupport) {
182
+ if (cacheSupport.prompt_cache_key === true && typeof body.prompt_cache_key === "string" && body.prompt_cache_key.trim()) {
183
+ chatReq.prompt_cache_key = body.prompt_cache_key;
184
+ }
185
+ if (cacheSupport.prompt_cache_retention === true && ["in_memory", "24h"].includes(body.prompt_cache_retention)) {
186
+ chatReq.prompt_cache_retention = body.prompt_cache_retention;
187
+ }
188
+ }
165
189
  const maxTok = body.max_output_tokens ?? body.max_tokens ?? body.max_completion_tokens;
166
190
  if (maxTok !== undefined) chatReq.max_completion_tokens = maxTok;
167
191
 
@@ -172,6 +196,7 @@ export function responsesToChat(body, { reasoningEfforts } = {}) {
172
196
  }
173
197
  chatReq.tools = body.tools
174
198
  .map((tool) => {
199
+ if (tool.defer_loading === true || tool.namespace != null) throw chatCompatibilityError("function tool", "deferred_or_namespaced");
175
200
  if (typeof (tool.function?.name ?? tool.name) !== "string" || !(tool.function?.name ?? tool.name).trim()) {
176
201
  throw chatCompatibilityError("function tool", "missing_name");
177
202
  }
@@ -191,10 +216,22 @@ export function responsesToChat(body, { reasoningEfforts } = {}) {
191
216
  if (!["auto", "none", "required"].includes(body.tool_choice)) throw chatCompatibilityError("tool choice", body.tool_choice);
192
217
  chatReq.tool_choice = body.tool_choice;
193
218
  } else if (body.tool_choice?.type === "function" && body.tool_choice.name) {
219
+ if (body.tool_choice.namespace != null) throw chatCompatibilityError("tool choice", "namespaced_function");
194
220
  if (!chatReq.tools?.some(tool => tool.function.name === body.tool_choice.name)) {
195
221
  throw chatCompatibilityError("tool choice", "undeclared_function");
196
222
  }
197
223
  chatReq.tool_choice = { type: "function", function: { name: body.tool_choice.name } };
224
+ } else if (body.tool_choice?.type === "allowed_tools") {
225
+ const { mode, tools } = body.tool_choice;
226
+ if (Object.keys(body.tool_choice).some(key => !["type", "mode", "tools"].includes(key))
227
+ || !["auto", "required"].includes(mode) || !Array.isArray(tools) || !tools.length
228
+ || tools.some(tool => !tool || tool.type !== "function" || typeof tool.name !== "string" || !tool.name.trim()
229
+ || Object.keys(tool).some(key => !["type", "name"].includes(key))
230
+ || !chatReq.tools?.some(declared => declared.function.name === tool.name))) {
231
+ throw chatCompatibilityError("tool choice", "allowed_tools");
232
+ }
233
+ chatReq.tool_choice = { type: "allowed_tools", allowed_tools: { mode,
234
+ tools: tools.map(tool => ({ type: "function", function: { name: tool.name } })) } };
198
235
  } else {
199
236
  throw chatCompatibilityError("tool choice", body.tool_choice?.type);
200
237
  }
@@ -236,11 +273,27 @@ function chatTerminal(finishReason) {
236
273
  : { status: "completed" };
237
274
  }
238
275
 
239
- export function chatToResponses(chatResp, model) {
276
+ function allowedToolNames(choice) {
277
+ return choice?.type === "allowed_tools" && Array.isArray(choice.allowed_tools?.tools)
278
+ ? new Set(choice.allowed_tools.tools.map(tool => tool.function?.name).filter(Boolean)) : null;
279
+ }
280
+
281
+ function disallowedUpstreamTool() {
282
+ return invalidUpstreamStream("Upstream did not honor the allowed tools", "upstream_tool_not_allowed");
283
+ }
284
+
285
+ export function chatToResponses(chatResp, model, { toolChoice, toolAdapter } = {}) {
240
286
  const id = `resp_${uid()}`, choice = chatResp.choices?.[0], msg = choice?.message, output = [];
241
287
  const terminal = chatTerminal(choice?.finish_reason);
288
+ const allowed = allowedToolNames(toolChoice);
289
+ if (allowed && (msg?.tool_calls?.some(call => {
290
+ const name = call?.function?.name || "";
291
+ return terminal.status === "completed" ? !allowed.has(name) : name && ![...allowed].some(candidate => candidate.startsWith(name));
292
+ }) || terminal.status === "completed" && toolChoice.allowed_tools.mode === "required" && !msg?.tool_calls?.length)) throw disallowedUpstreamTool();
242
293
  if (msg?.content) output.push({ type: "message", id: `msg_${uid()}`, role: "assistant", status: terminal.status, content: [{ type: "output_text", text: msg.content }] });
243
- if (msg?.tool_calls) for (const tc of msg.tool_calls) output.push({ type: "function_call", id: tc.id, call_id: tc.id, name: tc.function.name, arguments: tc.function.arguments, status: terminal.status });
294
+ if (msg?.tool_calls) for (const tc of msg.tool_calls) output.push(toolAdapter
295
+ ? toolAdapter.outputItem({ id: tc.id, callId: tc.id, name: tc.function?.name, arguments: tc.function?.arguments }, terminal.status)
296
+ : { type: "function_call", id: tc.id, call_id: tc.id, name: tc.function.name, arguments: tc.function.arguments, status: terminal.status });
244
297
  return { id, object: "response", ...terminal, model: chatResp.model || model, output, usage: chatResp.usage ? { input_tokens: chatResp.usage.prompt_tokens || 0, output_tokens: chatResp.usage.completion_tokens || 0, total_tokens: chatResp.usage.total_tokens || 0 } : undefined };
245
298
  }
246
299
 
@@ -251,6 +304,8 @@ export async function forwardToChat(chatReq, emitEvent, onDone, onError, options
251
304
  // Retain names only, not the request's schemas, images or message history.
252
305
  const declaredToolNames = new Set((Array.isArray(upstreamReq.tools) ? upstreamReq.tools : [])
253
306
  .map((tool) => tool?.function?.name).filter((name) => typeof name === "string" && name));
307
+ const allowed = allowedToolNames(upstreamReq.tool_choice), allowedRequired = upstreamReq.tool_choice?.allowed_tools?.mode === "required";
308
+ const allowedPrefix = name => !name || [...allowed].some(candidate => candidate.startsWith(name));
254
309
  let {
255
310
  abort,
256
311
  bodyText,
@@ -260,6 +315,7 @@ export async function forwardToChat(chatReq, emitEvent, onDone, onError, options
260
315
  releaseRequest,
261
316
  signal,
262
317
  streamIdleTimeoutMs,
318
+ toolAdapter,
263
319
  } = options;
264
320
  options = undefined;
265
321
  if (upstreamReq !== chatReq) bodyText = undefined;
@@ -355,8 +411,10 @@ export async function forwardToChat(chatReq, emitEvent, onDone, onError, options
355
411
  arguments: "",
356
412
  outputIndex: nextOutputIndex++,
357
413
  };
414
+ if (toolAdapter) tool.upstreamIdKnown = Boolean(chunk.id);
415
+ if (allowed && !allowedPrefix(tool.name)) throw disallowedUpstreamTool();
358
416
  toolCalls.set(key, tool);
359
- await emitEvent("response.output_item.added", {
417
+ if (!toolAdapter) await emitEvent("response.output_item.added", {
360
418
  output_index: tool.outputIndex,
361
419
  item: {
362
420
  type: "function_call",
@@ -372,6 +430,7 @@ export async function forwardToChat(chatReq, emitEvent, onDone, onError, options
372
430
 
373
431
  const emitTerminal = async () => {
374
432
  const terminal = chatTerminal(finishReason);
433
+ if (allowed && terminal.status === "completed" && ([...toolCalls.values()].some(tool => !allowed.has(tool.name)) || allowedRequired && !toolCalls.size)) throw disallowedUpstreamTool();
375
434
  if (!messageItem && toolCalls.size === 0) await ensureMessageItem();
376
435
  const output = [];
377
436
  if (messageItem) {
@@ -388,6 +447,10 @@ export async function forwardToChat(chatReq, emitEvent, onDone, onError, options
388
447
  output[messageItem.outputIndex] = item;
389
448
  }
390
449
  for (const tool of toolCalls.values()) {
450
+ if (toolAdapter) {
451
+ output[tool.outputIndex] = await toolAdapter.finish(tool, terminal, emitEvent);
452
+ continue;
453
+ }
391
454
  const item = {
392
455
  type: "function_call",
393
456
  id: tool.id,
@@ -467,7 +530,7 @@ export async function forwardToChat(chatReq, emitEvent, onDone, onError, options
467
530
  if (delta.tool_calls) {
468
531
  for (const tc of delta.tool_calls) {
469
532
  const { tool, created } = await ensureToolCall(tc);
470
- if (tc.id) tool.callId = tc.id;
533
+ if (tc.id) { tool.callId = tc.id;if (toolAdapter) tool.upstreamIdKnown = true; }
471
534
  if (!created && tc.function?.name) {
472
535
  const name = tc.function.name;
473
536
  let completeRepeat = name === tool.name && declaredToolNames.has(name);
@@ -479,16 +542,18 @@ export async function forwardToChat(chatReq, emitEvent, onDone, onError, options
479
542
  }
480
543
  if (!completeRepeat) tool.name += name;
481
544
  }
545
+ if (allowed && !allowedPrefix(tool.name)) throw disallowedUpstreamTool();
482
546
  const argumentDelta = tc.function?.arguments;
483
547
  toolArgumentGuard.observe(tool.outputIndex, argumentDelta);
484
548
  if (argumentDelta) {
485
549
  tool.arguments += argumentDelta;
486
- await emitEvent("response.function_call_arguments.delta", {
550
+ if (!toolAdapter) await emitEvent("response.function_call_arguments.delta", {
487
551
  output_index: tool.outputIndex,
488
552
  item_id: tool.id,
489
553
  delta: argumentDelta,
490
554
  });
491
555
  }
556
+ if (toolAdapter) await toolAdapter.update(tool, emitEvent);
492
557
  }
493
558
  }
494
559
  }
@@ -32,8 +32,8 @@ function jsonPayload(value, assertActive) {
32
32
  });
33
33
  }
34
34
 
35
- function chatRequest(responsesBody, stream, reasoningEfforts) {
36
- const chatReq = responsesToChat(responsesBody, { reasoningEfforts });
35
+ function chatRequest(responsesBody, stream, reasoningEfforts, cacheSupport) {
36
+ const chatReq = responsesToChat(responsesBody, { reasoningEfforts, cacheSupport });
37
37
  chatReq.stream = Boolean(stream);
38
38
  delete chatReq.max_tokens;
39
39
  return stream ? withChatStreamUsage(chatReq) : chatReq;
@@ -82,12 +82,13 @@ export async function prepareResponsesChatPayload(reqContext, {
82
82
  assertActive,
83
83
  payloadOptions = {},
84
84
  reasoningEfforts,
85
+ cacheSupport,
85
86
  signal,
86
87
  stream = false,
87
88
  } = {}) {
88
89
  assertActive?.();
89
90
  const limit = configuredBodyLimit(payloadOptions);
90
- let finalChatReq = chatRequest(reqContext.body, stream, reasoningEfforts);
91
+ let finalChatReq = chatRequest(reqContext.body, stream, reasoningEfforts, cacheSupport);
91
92
  assertActive?.();
92
93
  let finalChat = jsonPayload(finalChatReq, assertActive);
93
94
  const hasInlineImage = bodyHasInlineImage(reqContext.body, assertActive);
@@ -109,7 +110,7 @@ export async function prepareResponsesChatPayload(reqContext, {
109
110
  responsesPayload = { bodyText: prepared.bodyText, bodyBytes: prepared.bodyBytes };
110
111
  adapted = prepared.adapted;
111
112
  stage = prepared.stage;
112
- finalChatReq = chatRequest(reqContext.body, stream, reasoningEfforts);
113
+ finalChatReq = chatRequest(reqContext.body, stream, reasoningEfforts, cacheSupport);
113
114
  assertActive?.();
114
115
  finalChat = jsonPayload(finalChatReq, assertActive);
115
116
  }
@@ -133,7 +134,7 @@ export async function prepareResponsesChatPayload(reqContext, {
133
134
  initialBodyBytes: responsesPayload.bodyBytes,
134
135
  });
135
136
  if (!trimmed.adapted) break;
136
- const candidateChatReq = chatRequest(reqContext.body, stream, reasoningEfforts);
137
+ const candidateChatReq = chatRequest(reqContext.body, stream, reasoningEfforts, cacheSupport);
137
138
  assertActive?.();
138
139
  const candidateChat = jsonPayload(candidateChatReq, assertActive);
139
140
  if (candidateChat.bodyBytes >= finalChat.bodyBytes) {