codex-copilot-dx 1.3.27 → 1.4.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 (62) hide show
  1. package/README.md +7 -2
  2. package/bin/cli.mjs +4 -1
  3. package/docs/ARCHITECTURE.md +32 -3
  4. package/docs/REFERENCE.md +51 -5
  5. package/package.json +1 -1
  6. package/src/adapter.mjs +17 -5
  7. package/src/antigravity-handler.mjs +38 -13
  8. package/src/antigravity-runtime.mjs +22 -2
  9. package/src/claude-app-contract.mjs +96 -0
  10. package/src/claude-capability-config.mjs +28 -11
  11. package/src/claude-client-config.mjs +58 -9
  12. package/src/claude-gateway.mjs +25 -7
  13. package/src/claude-models.mjs +4 -2
  14. package/src/cli-command-spec.mjs +13 -3
  15. package/src/cli-management.mjs +47 -6
  16. package/src/cli-options.mjs +1 -1
  17. package/src/connection-client-sync.mjs +1 -0
  18. package/src/connection-management.mjs +5 -0
  19. package/src/connection-policy.mjs +2 -2
  20. package/src/connection-routing.mjs +3 -1
  21. package/src/connection-runtime.mjs +37 -2
  22. package/src/connection-view.mjs +11 -2
  23. package/src/context-compaction-plan.mjs +122 -0
  24. package/src/context-compaction-seal.mjs +56 -0
  25. package/src/context-compaction-wire.mjs +137 -0
  26. package/src/context-compaction.mjs +161 -0
  27. package/src/context-metrics.mjs +1 -1
  28. package/src/conversation-source-guard.mjs +15 -5
  29. package/src/dashboard/connections.js +33 -3
  30. package/src/dashboard/index.html +9 -1
  31. package/src/dashboard/language.js +28 -0
  32. package/src/dashboard/preferences.js +1 -1
  33. package/src/dashboard/ui.js +3 -0
  34. package/src/dashboard-api.mjs +2 -2
  35. package/src/doctor-compat.mjs +1 -1
  36. package/src/http-transport.mjs +1 -1
  37. package/src/local-privacy.mjs +15 -7
  38. package/src/lock.mjs +9 -2
  39. package/src/model-capabilities.mjs +17 -4
  40. package/src/privacy-detection.mjs +4 -3
  41. package/src/privacy-transform.mjs +20 -6
  42. package/src/provider-cooldown.mjs +43 -0
  43. package/src/provider-runtime.mjs +8 -5
  44. package/src/providers/api-model-metadata.mjs +7 -0
  45. package/src/providers/api.mjs +44 -12
  46. package/src/request-context.mjs +5 -0
  47. package/src/response-failures.mjs +4 -2
  48. package/src/responses-bridge.mjs +12 -5
  49. package/src/responses-handler.mjs +79 -1
  50. package/src/responses-proxy.mjs +18 -5
  51. package/src/responses-request.mjs +11 -4
  52. package/src/safe-upstream-error.mjs +59 -9
  53. package/src/service-control.mjs +8 -1
  54. package/src/settings-preferences.mjs +3 -3
  55. package/src/source-import.mjs +51 -0
  56. package/src/stream-performance.mjs +8 -5
  57. package/src/upstream-body.mjs +1 -1
  58. package/src/upstream-error-capture.mjs +29 -0
  59. package/src/usage-analysis.mjs +2 -2
  60. package/src/usage-query.mjs +5 -2
  61. package/src/usage-store.mjs +2 -1
  62. package/src/user-settings.mjs +1 -1
@@ -6,7 +6,7 @@ import { withFileLockSync } from "./lock.mjs";
6
6
  import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
7
7
  import { createChangeSignal } from "./activity-events.mjs";
8
8
  import { createPrivacyModel, privacyFailure } from "./privacy-model.mjs";
9
- import { maskPrivacyRequest, protectPrivacyResponse, createPrivacyRuleCache } from "./privacy-transform.mjs";
9
+ import { maskPrivacyRequest, protectPrivacyResponse, createPrivacyRuleCache, privacySessionMappings, restorePrivacyMappings } from "./privacy-transform.mjs";
10
10
  import { createPrivacyDetection, PRIVACY_BATCH_BYTES } from "./privacy-detection.mjs";
11
11
  import { markRequestObservation } from "./stream-performance.mjs";
12
12
 
@@ -48,7 +48,7 @@ export function createLocalPrivacy(options = {}) {
48
48
  if (disposed) throw privacyFailure("engine_unavailable");
49
49
  loadKey();
50
50
  const start = performance.now();
51
- const deadline = new AbortController();let session, timer, budget = options.checkTimeoutMs ?? 15000;
51
+ const deadline = new AbortController();let session, timer, textKeys, budget = options.checkTimeoutMs ?? 15000;
52
52
  const arm = () => {
53
53
  clearTimeout(timer);timer = setTimeout(() => deadline.abort(privacyFailure("check_timeout", "waiting")), Math.max(1, budget - (performance.now() - start)));
54
54
  timer.unref?.();
@@ -60,7 +60,9 @@ export function createLocalPrivacy(options = {}) {
60
60
  markRequestObservation({ ...(Number.isSafeInteger(plan.pending_bytes) ? { privacy_pending_bytes: plan.pending_bytes, privacy_new_bytes: plan.new_bytes } : {}),
61
61
  ...(Number.isSafeInteger(plan.pending_windows) ? { privacy_pending_windows: plan.pending_windows } : {}), privacy_wait_budget_ms: budget });
62
62
  };
63
- try { session = await maskPrivacyRequest(body, { protocol, client, personal: saved.personal, secret, find, rules: rules.find, onPlan,
63
+ try { session = await maskPrivacyRequest(body, { protocol, client, personal: saved.personal, secret,
64
+ find: (texts, context) => detection.find(texts, { ...context, onKey(text, key) { if (text.length >= 256) (textKeys ||= new Map()).set(text, key); } }),
65
+ rules: (text, personal) => rules.find(text, personal, textKeys?.get(text)), onPlan,
64
66
  signal: signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal }); }
65
67
  catch (error) {
66
68
  const failure = deadline.signal.aborted && !signal?.aborted ? privacyFailure("check_timeout", "waiting") : error;
@@ -68,12 +70,15 @@ export function createLocalPrivacy(options = {}) {
68
70
  lastCheck = { state: cancelled ? "cancelled" : "failed", at: new Date().toISOString(), elapsed_ms: elapsed,
69
71
  code: /^ccdx_privacy_[a-z_]+$/.test(failure?.code || "") ? failure.code : cancelled ? "ccdx_privacy_cancelled" : "ccdx_privacy_unavailable", continuing: !cancelled && failure?.retryAfter === 5, wait_budget_ms: budget };
70
72
  markRequestObservation({ privacy_ms: elapsed, privacy_state: cancelled ? "cancelled" : "failed" });changes.changed();throw failure;
71
- } finally { clearTimeout(timer); }
73
+ } finally { clearTimeout(timer);textKeys?.clear(); }
72
74
  if (signal?.aborted) { session.release();throw signal.reason; }
73
75
  markRequestObservation({ privacy_count: session.count, privacy_ms: Math.round(performance.now() - start), privacy_state: "checked" });
74
76
  actionError = null;lastCheck = { state: "checked", at: new Date().toISOString(), elapsed_ms: Math.round(performance.now() - start), count: session.count, wait_budget_ms: budget };changes.changed();
75
77
  if (onSession) { onSession(session);return session.body; }
76
- if (res && session.count) {
78
+ if (res && session.count) attachSession(res, session);
79
+ return session.body;
80
+ }
81
+ function attachSession(res, session) {
77
82
  let current = responses.get(res);
78
83
  if (!current) {
79
84
  const sessions = [];
@@ -87,8 +92,6 @@ export function createLocalPrivacy(options = {}) {
87
92
  onComplete() { lastResponse = { state: "completed", at: new Date().toISOString() };changes.changed(); },
88
93
  });
89
94
  } else current.sessions.push(session);
90
- }
91
- return session.body;
92
95
  }
93
96
  async function action(input) {
94
97
  if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some(key => !["action", "revision", "personal", "text"].includes(key))) throw privacyFailure("action_invalid");
@@ -137,6 +140,11 @@ export function createLocalPrivacy(options = {}) {
137
140
  };
138
141
  },
139
142
  restoreResponse: (res, value) => responses.get(res)?.restoreValue(value) || value,
143
+ responseMappings(res) {
144
+ const entries = new Map();for (const session of responses.get(res)?.sessions || []) for (const [token, value] of privacySessionMappings(session)) entries.set(token, value);
145
+ return [...entries];
146
+ },
147
+ async importResponseMappings(res, entries) { const session = await restorePrivacyMappings(entries);if (session.count) attachSession(res, session); },
140
148
  settingsChanged() { actionError = null;if (!settings().enabled) { generation++;model.stop(); }else warm();changes.changed(); },
141
149
  close() { disposed = true;generation++;detection.close();model.close();rules.clear();secret.fill(0); } };
142
150
  }
package/src/lock.mjs CHANGED
@@ -265,6 +265,7 @@ export async function withFileLock(lockPath, fn, {
265
265
  pollMs = 50,
266
266
  now = Date.now,
267
267
  fsImpl = fs,
268
+ platform = process.platform,
268
269
  processAlive = processIsAlive,
269
270
  signal,
270
271
  } = {}) {
@@ -290,7 +291,7 @@ export async function withFileLock(lockPath, fn, {
290
291
  pid: process.pid,
291
292
  owner,
292
293
  created_at: new Date().toISOString(),
293
- }, fs);
294
+ }, fsImpl);
294
295
  if (lockPathExists(guardPath, fsImpl)) {
295
296
  fs.closeSync(fd);
296
297
  fd = null;
@@ -299,8 +300,14 @@ export async function withFileLock(lockPath, fn, {
299
300
  }
300
301
  break;
301
302
  } catch (e) {
302
- if (e?.code !== "EEXIST") throw e;
303
303
  const nowMs = now();
304
+ if (e?.code !== "EEXIST") {
305
+ // Windows can deny creation while a previous lock is pending deletion.
306
+ // Retry only acquisition, within the original lock deadline.
307
+ if (platform !== "win32" || e?.code !== "EPERM" || nowMs - started >= timeoutMs) throw e;
308
+ await delay(Math.min(pollMs, Math.max(1, timeoutMs - (nowMs - started))), undefined, { signal });
309
+ continue;
310
+ }
304
311
  if (maybeRemoveStaleLock(lockPath, staleMs, nowMs, fsImpl, processAlive)) continue;
305
312
  if (nowMs - started >= timeoutMs) {
306
313
  throw new Error(`Timed out waiting for lock: ${lockPath}`);
@@ -2,16 +2,17 @@ import { createHash } from "node:crypto";
2
2
 
3
3
  export const MODEL_PROTOCOLS = Object.freeze(["messages", "responses", "chat"]);
4
4
  export const REASONING_EFFORTS = Object.freeze(["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
5
- const limits = ["context_window", "max_input_tokens", "max_output_tokens", "reasoning_budget_min", "reasoning_budget_max"];
5
+ const limits = ["context_window", "max_input_tokens", "max_output_tokens", "reasoning_budget_min", "reasoning_budget_max", "max_tool_definitions"];
6
+ export const MODEL_PARAMETERS = Object.freeze(["max_tokens", "max_output_tokens", "max_completion_tokens", "temperature", "top_p", "tools", "tool_choice", "parallel_tool_calls", "thinking", "output_config", "reasoning", "reasoning_effort", "response_format", "text", "stop", "stop_sequences", "stream", "stream_options"]);
6
7
  const flags = ["reasoning", "reasoning_required", "reasoning_adaptive", "tools", "parallel_tools", "streaming", "structured_output", "mid_conversation_system"];
7
- export const CAPABILITY_FIELDS = Object.freeze([...limits, ...flags, "reasoning_efforts", "reasoning_format", "thinking_modes", "input_modalities", "web_search"]);
8
+ export const CAPABILITY_FIELDS = Object.freeze([...limits, ...flags, "reasoning_efforts", "reasoning_format", "thinking_modes", "input_modalities", "web_search", "supported_parameters"]);
8
9
  const object = value => value && typeof value === "object" && !Array.isArray(value);
9
10
  export function validCapabilities(value) {
10
11
  return object(value) && Object.entries(value).every(([key, item]) => {
11
12
  if (limits.includes(key)) return Number.isSafeInteger(item) && item > 0 && item <= 100000000;
12
13
  if (flags.includes(key)) return typeof item === "boolean";
13
14
  if (key === "reasoning_format") return MODEL_PROTOCOLS.includes(item);
14
- const choices = key === "reasoning_efforts" ? REASONING_EFFORTS : key === "thinking_modes" ? ["disabled", "enabled", "adaptive", "between_tools"] : key === "input_modalities" ? ["text", "image", "audio", "video", "file"] : key === "web_search" ? MODEL_PROTOCOLS : null;
15
+ const choices = key === "supported_parameters" ? MODEL_PARAMETERS : key === "reasoning_efforts" ? REASONING_EFFORTS : key === "thinking_modes" ? ["disabled", "enabled", "adaptive", "between_tools"] : key === "input_modalities" ? ["text", "image", "audio", "video", "file"] : key === "web_search" ? MODEL_PROTOCOLS : null;
15
16
  return choices && Array.isArray(item) && item.length <= choices.length && new Set(item).size === item.length && item.every(v => choices.includes(v));
16
17
  }) && !(value.max_input_tokens && value.context_window && value.max_input_tokens > value.context_window)
17
18
  && !(value.reasoning_budget_min && value.reasoning_budget_max && value.reasoning_budget_min > value.reasoning_budget_max);
@@ -36,6 +37,7 @@ export function catalogCapabilities(model) {
36
37
  context_window: first(model.context_window, window.max_context_window_tokens),
37
38
  max_input_tokens: first(model.max_input_tokens, window.max_prompt_tokens, window.max_input_tokens),
38
39
  max_output_tokens: first(model.max_output_tokens, window.max_output_tokens),
40
+ max_tool_definitions: first(model.max_tool_definitions, window.max_tool_definitions),
39
41
  reasoning: first(typeof caps.reasoning === "boolean" ? caps.reasoning : undefined, supports.reasoning),
40
42
  reasoning_efforts: first(model.reasoning_efforts, supports.reasoning_effort),
41
43
  input_modalities: first(model.input_modalities, caps.input_modalities, supports.vision === true ? ["text", "image"] : undefined),
@@ -72,7 +74,8 @@ export function resolveModelCapabilities(model, { revision, checkedAt = null, bu
72
74
  export function claudeEffortsExpressible(values = {}) {
73
75
  const levels = values.reasoning === false ? [] : values.reasoning_efforts || [];
74
76
  const native = ["low", "medium", "high", "xhigh", "max"];
75
- return levels.length > 0 && levels.every(value => native.includes(value)) && native.slice(0, Math.max(...levels.map(value => native.indexOf(value))) + 1).every(value => levels.includes(value));
77
+ const base = Math.min(2, Math.max(...levels.map(value => native.indexOf(value))));
78
+ return levels.length > 0 && levels.every(value => native.includes(value)) && native.slice(0, base + 1).every(value => levels.includes(value));
76
79
  }
77
80
 
78
81
  export function claudeEffortPrefix(values = {}) {
@@ -84,9 +87,19 @@ export function claudeEffortPrefix(values = {}) {
84
87
  return prefix.length === levels.length || prefix.length >= 2 ? prefix : [];
85
88
  }
86
89
 
90
+ function invalidRequestParameter(message, code, param) {
91
+ throw Object.assign(new Error(message), { code, statusCode: 400, param });
92
+ }
87
93
  export function constrainModelRequest(body, capability, protocol) {
88
94
  const values = capability?.values || {}, outputKey = protocol === "messages" ? "max_tokens" : protocol === "responses" ? "max_output_tokens" : "max_completion_tokens";
89
95
  let result = body;const applied = [];
96
+ if (body[outputKey] !== undefined && (!Number.isSafeInteger(body[outputKey]) || body[outputKey] <= 0)) invalidRequestParameter("The output token limit must be a positive integer.", "ccdx_api_output_limit_invalid", outputKey);
97
+ if (protocol === "chat" && body.max_tokens !== undefined && (!Number.isSafeInteger(body.max_tokens) || body.max_tokens <= 0)) invalidRequestParameter("The output token limit must be a positive integer.", "ccdx_api_output_limit_invalid", "max_tokens");
98
+ if (values.supported_parameters) for (const key of MODEL_PARAMETERS) {
99
+ if (Object.hasOwn(body, key) && !values.supported_parameters.includes(key)) invalidRequestParameter("This deployment does not declare support for the requested parameter: " + key + ".", "ccdx_api_parameter_unavailable", key);
100
+ }
101
+ if (values.max_tool_definitions && Array.isArray(body.tools) && body.tools.length > values.max_tool_definitions)
102
+ invalidRequestParameter("The number of tool definitions exceeds this deployment's declared limit of " + values.max_tool_definitions + ".", "ccdx_api_tool_limit_exceeded", "tools");
90
103
  if (values.max_output_tokens && Number.isFinite(body[outputKey]) && body[outputKey] > values.max_output_tokens) {
91
104
  result = { ...result, [outputKey]: values.max_output_tokens };applied.push("output_limit");
92
105
  }
@@ -1,4 +1,4 @@
1
- import { createHash } from "node:crypto";
1
+ import { hash } from "node:crypto";
2
2
  import { privacyFailure } from "./privacy-model.mjs";
3
3
  import { validatePrivacyFindings } from "./privacy-findings.mjs";
4
4
 
@@ -77,11 +77,12 @@ export function createPrivacyDetection(model, {
77
77
  if (!closed && turns.length) setImmediate(() => { for (let worker = running; worker < maxConcurrent && turns.length; worker++) void pump(); });
78
78
  }
79
79
  }
80
- async function find(texts, { signal, onPlan } = {}) {
80
+ async function find(texts, { signal, onPlan, onKey } = {}) {
81
81
  if (closed) throw privacyFailure("engine_unavailable");if (signal?.aborted) throw signal.reason;
82
82
  const staged = new Map(), waiters = new Set(), results = [];let newBytes = 0, waitingBytes = 0;
83
83
  for (const text of texts) {
84
- const key = createHash("sha256").update(text).digest("hex"), known = get(key);
84
+ const key = hash("sha256", text, "hex"), known = get(key);
85
+ onKey?.(text, key);
85
86
  if (known !== undefined) { results.push(Promise.resolve(known));continue; }
86
87
  let entry = flights.get(key) || staged.get(key);
87
88
  if (!entry) {
@@ -1,4 +1,4 @@
1
- import { createHash, createHmac } from "node:crypto";
1
+ import { hash, createHmac } from "node:crypto";
2
2
  import { createPrivacyStream } from "./privacy-stream.mjs";
3
3
  export { createPrivacyStream };
4
4
  import { privacyFailure } from "./privacy-model.mjs";
@@ -7,6 +7,20 @@ export { validatePrivacyFindings };
7
7
  import { markRequestObservation, markResponseTerminal } from "./stream-performance.mjs";
8
8
 
9
9
  const TOKEN_START = "{{CCDX_", tokenPattern = /\{\{CCDX_[a-f0-9]{24}\}\}/g;
10
+ const SESSION_MAPPINGS = Symbol("privacy-session-mappings");
11
+ export const privacySessionMappings = session => [...(session?.[SESSION_MAPPINGS] || [])];
12
+
13
+ export async function restorePrivacyMappings(entries) {
14
+ if (!Array.isArray(entries) || entries.length > 8192) throw privacyFailure("mapping_limit");
15
+ const values = new Map();let bytes = 0;
16
+ for (const entry of entries) {
17
+ if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== "string" || !/^\{\{CCDX_[a-f0-9]{24}\}\}$/.test(entry[0]) || typeof entry[1] !== "string"
18
+ || values.has(entry[0]) && values.get(entry[0]) !== entry[1]) throw privacyFailure("mapping_invalid");
19
+ bytes += Buffer.byteLength(entry[1]);if (bytes > 4 * 1024 * 1024) throw privacyFailure("mapping_limit");values.set(...entry);
20
+ }
21
+ const session = await maskPrivacyRequest({ input: [] }, { protocol: "responses", find: async () => [], seedMappings: values });
22
+ session.count = values.size;return session;
23
+ }
10
24
  const secretPatterns = [
11
25
  /\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|sk-(?:ant-|proj-)?[A-Za-z0-9_-]{16,}|AIza[A-Za-z0-9_-]{25,}|xox[baprs]-[A-Za-z0-9-]{16,}|AKIA[A-Z0-9]{16}|hf_[A-Za-z0-9]{20,}|npm_[A-Za-z0-9]{20,})\b/g,
12
26
  /-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z]+ )?PRIVATE KEY-----/g,
@@ -104,9 +118,9 @@ function ruleSpans(text, personal) {
104
118
  export function createPrivacyRuleCache({ maxBytes = 1024 * 1024, maxEntries = 2048 } = {}) {
105
119
  const entries = new Map();let bytes = 0, hits = 0, scans = 0;
106
120
  return {
107
- find(text, personal) {
121
+ find(text, personal, digest) {
108
122
  if (text.length < 256) { scans++;return ruleSpans(text, personal); }
109
- const key = `${personal ? 1 : 0}:` + createHash("sha256").update(text).digest("hex");
123
+ const key = `${personal ? 1 : 0}:` + (digest ?? hash("sha256", text, "hex"));
110
124
  if (entries.has(key)) {
111
125
  const entry = entries.get(key);entries.delete(key);entries.set(key, entry);hits++;
112
126
  return entry.spans.map(span => ({ ...span }));
@@ -133,10 +147,10 @@ function modelSpanFits(text, start, end, label) {
133
147
  && /\b(?:function|class|const|let|var)\s+$/.test(text.slice(Math.max(0, start - 32), start))) return false;
134
148
  return true;
135
149
  }
136
- export async function maskPrivacyRequest(body, { protocol, client = "api", personal = false, secret, find, signal, onPlan, rules = ruleSpans }) {
150
+ export async function maskPrivacyRequest(body, { protocol, client = "api", personal = false, secret, find, signal, onPlan, rules = ruleSpans, seedMappings }) {
137
151
  const copy = structuredClone(body), { items, nested } = requestTexts(copy, protocol), texts = items.map(item => item.text);
138
152
  if (items.length > 8192 || texts.reduce((n, text) => n + Buffer.byteLength(text), 0) > 8 * 1024 * 1024) throw privacyFailure("request_too_large");
139
- const found = texts.length ? await find(texts, { signal, onPlan }) : [], values = new Map(), kinds = {}, total = { count: 0, bytes: 0 };
153
+ const found = texts.length ? await find(texts, { signal, onPlan }) : [], values = new Map(seedMappings), kinds = {}, total = { count: 0, bytes: 0 };
140
154
  if (!Array.isArray(found) || found.length !== texts.length) throw privacyFailure("engine_invalid");
141
155
  for (let i = 0; i < items.length; i++) {
142
156
  const item = items[i], spans = rules(item.text, personal);let bytes;
@@ -181,7 +195,7 @@ export async function maskPrivacyRequest(body, { protocol, client = "api", perso
181
195
  if (!text.includes(TOKEN_START) && !text.includes("\\u")) return text;
182
196
  try { return JSON.stringify(restoreValue(parseToolArguments(text), true)); } catch { return restoreText(text); }
183
197
  }
184
- return { body: total.count ? copy : body, count: total.count, kinds, restoreText, restoreValue,
198
+ return { body: total.count ? copy : body, count: total.count, kinds, restoreText, restoreValue, [SESSION_MAPPINGS]: values,
185
199
  restoreToolValue: value => restoreValue(value, true), release: () => values.clear() };
186
200
  }
187
201
 
@@ -0,0 +1,43 @@
1
+ import { accessError } from "./access-settings.mjs";
2
+
3
+ const NETWORK_CODES = new Set(["ECONNREFUSED", "ECONNRESET", "ETIMEDOUT", "EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"]);
4
+ export function confirmedNetworkFailure(error) {
5
+ for (let depth = 0; error && depth < 4; depth++, error = error.cause) if (NETWORK_CODES.has(error.code)) return true;
6
+ return false;
7
+ }
8
+
9
+ // One deployment/interface, two confirmed failures, one real recovery request.
10
+ // No paid probes, model switching or retry after output has started.
11
+ export function createProviderCooldown({ now = Date.now, delayMs = 5000 } = {}) {
12
+ let failures = 0, until = 0, recovering = false;
13
+ const snapshot = () => ({ state: until > now() ? "cooling" : recovering ? "recovering" : "ready", retry_after_ms: Math.max(0, until - now()), failures });
14
+ function enter() {
15
+ if (failures < 2) return false;
16
+ if (until > now() || recovering) {
17
+ const error = accessError("ccdx_api_cooling_down", 503);
18
+ error.message = error.jsonBody.error.message = "This source interface is temporarily cooling down after repeated connection failures. Retry shortly.";
19
+ error.retryAfterMs = Math.max(1000, until - now());throw error;
20
+ }
21
+ recovering = true;return true;
22
+ }
23
+ function complete(recovery, failed = false, cancelled = false, retryAfterMs = 0) {
24
+ if (recovery) recovering = false;
25
+ if (cancelled) return;
26
+ if (!failed) { if (failures) { failures = 0;until = 0; }return; }
27
+ failures = Math.min(2, failures + 1);
28
+ if (failures >= 2) until = now() + Math.min(30000, Math.max(delayMs, retryAfterMs));
29
+ }
30
+ return {
31
+ snapshot, enter, complete,
32
+ acquire() {
33
+ const recovery = enter();
34
+ let finished = false;
35
+ return {
36
+ finish({ failed = false, cancelled = false, retryAfterMs = 0 } = {}) {
37
+ if (finished) return;finished = true;
38
+ complete(recovery, failed, cancelled, retryAfterMs);
39
+ },
40
+ };
41
+ },
42
+ };
43
+ }
@@ -1,7 +1,8 @@
1
1
  import { isImageModel, imageModelCatalog } from "./image-models.mjs";
2
2
  import fs from "node:fs";
3
3
  import { providerDescriptors } from "./provider-descriptors.mjs";
4
- import { autoReviewPreference, writeAutoReviewModel } from "./user-settings.mjs";
4
+ import { autoReviewPreference, writeAutoReviewModel, servicePreferences } from "./user-settings.mjs";
5
+ import { createContextCompactionService } from "./context-compaction.mjs";
5
6
  import { autoReviewReasoningEfforts, DEFAULT_CODEX_AUTO_REVIEW_MODEL, responsesModelIdsFromCopilotModels } from "./models.mjs";
6
7
  import { publicModelCatalog } from "./provider-metadata.mjs";
7
8
  import { publicCopilotModelCatalog } from "./live-models.mjs";
@@ -26,8 +27,9 @@ const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavaila
26
27
  // image configuration or each other's credentials.
27
28
  export function createProviderRuntime(options = {}) {
28
29
  options = { ...options, corePort: options.corePort ?? Number((options.env || process.env).ADAPTER_PORT || 2026) };
30
+ const compaction = options.compaction || createContextCompactionService({ enabled() { try { return servicePreferences(options).context_compaction_enabled; } catch { return false; } } });
29
31
  let connections;
30
- const legacy = createBuiltinProviderRuntime({ ...options, managedClaude: () => connections?.managesClaude() !== false,
32
+ const legacy = createBuiltinProviderRuntime({ ...options, compaction, managedClaude: () => connections?.managesClaude() !== false,
31
33
  privacy: { wrap: (fn, context) => connections?.privacy.wrap(fn, context) || fn },
32
34
  onClaudeReady: () => connections?.syncSourceClients("m365") });
33
35
  connections = createConnectionRuntime({ ...options, legacy });return connections;
@@ -35,7 +37,7 @@ export function createProviderRuntime(options = {}) {
35
37
 
36
38
  function createBuiltinProviderRuntime({ githubClient, githubRegistry, refreshGithubCatalog, githubCredentialFingerprint = "", githubClientConfigured = true, home, env = process.env, platform = process.platform,
37
39
  corePort = Number(env.ADAPTER_PORT || 2026), log = () => {}, createM365, startGateway, configureClients, restoreClients,
38
- discoverM365 = requestM365Accounts, managedClaude, onClaudeReady, preserveClientConfiguration, privacy } = {}) {
40
+ discoverM365 = requestM365Accounts, managedClaude, onClaudeReady, preserveClientConfiguration, privacy, compaction } = {}) {
39
41
  const options = { home, env, platform }, github = { ...createGithubProvider({ client: githubClient,
40
42
  profileId: () => { const value = typeof githubCredentialFingerprint === "function" ? githubCredentialFingerprint() : githubCredentialFingerprint;
41
43
  return value ? `codex:${value}` : "codex"; } }), registry: githubRegistry };
@@ -87,7 +89,7 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, refreshGit
87
89
  const apiKey = ensureM365GatewayKey({ ...options, create: !preserveClientConfiguration?.() });
88
90
  if (!gateway) {
89
91
  const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
90
- const opened = await start({ privacy, provider: m365, apiKey, port: corePort, env, log, performance: claudePerformance,
92
+ const opened = await start({ privacy, compaction, provider: m365, apiKey, port: corePort, env, log, performance: claudePerformance,
91
93
  onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
92
94
  if (closed || !enabled) { await opened.close();return null; }
93
95
  gateway = opened;
@@ -154,7 +156,7 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, refreshGit
154
156
  if (closed) throw unavailable("m365_runtime_closed");
155
157
  if (candidate.models("claude").length) {
156
158
  const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
157
- opened = await start({ privacy, provider: candidate, apiKey: ensureM365GatewayKey(options), port: corePort, env, log, performance: claudePerformance,
159
+ opened = await start({ privacy, compaction, provider: candidate, apiKey: ensureM365GatewayKey(options), port: corePort, env, log, performance: claudePerformance,
158
160
  onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
159
161
  }
160
162
  candidate.commitSelection(discovered.binding);
@@ -210,6 +212,7 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, refreshGit
210
212
  return snapshot();
211
213
  }
212
214
  return {
215
+ compaction,
213
216
  claudePerformance,
214
217
  source: id => sources.get(id),
215
218
  async pauseM365() {
@@ -29,6 +29,13 @@ export function apiModelMetadata(model, { deployment, checked_at }) {
29
29
  delete values.max_input_tokens;
30
30
  }
31
31
  const protocols = Object.keys(messages).length ? { messages } : {};
32
+ // Parameter lists are protocol scoped. A generic OpenAI list says nothing
33
+ // about a gateway's Messages endpoint.
34
+ for (const protocol of ["messages", "responses", "chat"]) {
35
+ const parameters = caps.protocols?.[protocol]?.supported_parameters;
36
+ if (parameters !== undefined && validCapabilities({ supported_parameters: parameters }))
37
+ protocols[protocol] = { ...protocols[protocol], supported_parameters: parameters };
38
+ }
32
39
  const reported = Object.keys(values).length || Object.keys(protocols).length;
33
40
  const described = Object.keys(caps).length || ["max_tokens", "max_input_tokens", "max_output_tokens", "context_window", "reasoning_efforts"].some(key => Object.hasOwn(model, key));
34
41
  return { values, ...(Object.keys(protocols).length ? { protocols } : {}), deployment, checked_at,
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { createRoutePlan } from "../route-plan.mjs";
3
3
  import { accessError } from "../access-settings.mjs";
4
4
  import { publicModelCatalog } from "../provider-metadata.mjs";
5
- import { resolveClaudeModel } from "../claude-models.mjs";
5
+ import { claudeModelEntries } from "../claude-models.mjs";
6
6
  import { prepareResponsesPayload } from "../image-optimization.mjs";
7
7
  import { enforceResponsesPayloadByteBudget } from "../responses-byte-budget.mjs";
8
8
  import { MAX_UPSTREAM_MODEL_CATALOG_BYTES, MAX_UPSTREAM_ERROR_BODY_BYTES, readBoundedResponseText } from "../http-transport.mjs";
@@ -20,6 +20,9 @@ import { apiModelDisplay } from "../api-model-display.mjs";
20
20
  import { adaptCallLessContext, CALL_LESS_TOOL_RETRIED, normalizeCallLessToolOutputs } from "../responses-tool-output.mjs";
21
21
  import { adaptMessagesToolSchemas, hasRootToolSchema, MESSAGES_TOOL_GUARD } from "../messages-tool-schema.mjs";
22
22
  import { loadRuntimeConfig } from "../runtime-config.mjs";
23
+ import { currentRequestContext } from "../request-context.mjs";
24
+ import { redactDiagnosticText } from "../diagnostic-text.mjs";
25
+ import { createProviderCooldown, confirmedNetworkFailure } from "../provider-cooldown.mjs";
23
26
 
24
27
  const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
25
28
  export function apiCatalog(config, env = process.env) {
@@ -29,7 +32,8 @@ export function apiCatalog(config, env = process.env) {
29
32
  supported_endpoints: model.protocols.map(api => paths[api]), model_picker_enabled: true, policy: { state: "enabled" },
30
33
  capability, protocol_capabilities }); });
31
34
  }
32
- export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork, modelDisplay = () => ({}) } = {}) {
35
+ export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork, modelDisplay = () => ({}), now = Date.now, errorCapture } = {}) {
36
+ const cooldowns = Object.fromEntries(["messages", "responses", "chat"].map(protocol => [protocol, createProviderCooldown({ now })]));
33
37
  const catalog = apiCatalog(config, env);
34
38
  const fingerprint = config.key_env ? createHash("sha256").update(env[config.key_env] || "").digest("hex") : "";
35
39
  const generation = parseInt(createHash("sha256").update(JSON.stringify(config) + fingerprint).digest("hex").slice(0, 8), 16);
@@ -55,8 +59,10 @@ export function createApiProvider({ config, secrets, env = process.env, platform
55
59
  return initialization.run("network", sharedSignal => networkFactory({ targets, env, platform, signal: AbortSignal.any([sharedSignal, lifetime.signal]) })
56
60
  .then(value => { if (closed || sharedSignal.aborted) { value.close();throw accessError("ccdx_api_closed", 503); }network = value;return value; }), { signal });
57
61
  };
62
+ let messageAliases;
58
63
  const selected = (id, api) => {
59
- const model = api === "messages" ? resolveClaudeModel(catalog, id) : catalog.find(model => model.id === id);
64
+ if (api === "messages" && !messageAliases) messageAliases = new Map(claudeModelEntries(catalog).map((entry, index) => [entry.name, catalog[index]]));
65
+ const model = api === "messages" && messageAliases.get(id) || catalog.find(model => model.id === id);
60
66
  if (!model?.supported_endpoints.includes(paths[api])) throw accessError("ccdx_api_model_unavailable");return model;
61
67
  };
62
68
  async function request(url, body, options = {}, api = "responses") {
@@ -64,7 +70,6 @@ export function createApiProvider({ config, secrets, env = process.env, platform
64
70
  if (config.key_env && !env[config.key_env]) throw accessError("ccdx_api_environment_key_missing", 503);
65
71
  const key = config.key_env ? checkedApiKey(env[config.key_env]) : await initialization.run("credential", () => secrets.get(config.secret_ref),
66
72
  { signal: options.signal ? AbortSignal.any([options.signal, lifetime.signal]) : lifetime.signal });
67
- const transport = await getNetwork(options.signal);
68
73
  const headers = { "Content-Type": "application/json", Accept: body?.stream ? "text/event-stream" : "application/json" };
69
74
  headers[api === "messages" && config.auth_header === "x-api-key" ? "x-api-key" : "Authorization"] = api === "messages" && config.auth_header === "x-api-key" ? key : `Bearer ${key}`;
70
75
  if (api === "messages") {
@@ -80,13 +85,21 @@ export function createApiProvider({ config, secrets, env = process.env, platform
80
85
  }
81
86
  const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
82
87
  if (serialized !== undefined) headers["Content-Length"] = String(Buffer.byteLength(serialized));
83
- options.onUpstreamStart?.();
84
- if (body && options.observeUpstream !== false) {
85
- markUpstreamStarted(body.stream === true);
86
- if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: api === "messages" ? body.max_tokens : api === "chat" ? body.max_completion_tokens : body.max_output_tokens });
87
- }
88
+ const cooldown = body && !options.countTokens ? cooldowns[api] : null;
89
+ const recovery = cooldown?.enter();let observed = false;
88
90
  try {
91
+ const transport = !closed && network && (network.healthy?.() ?? true) ? network : await getNetwork(options.signal);
92
+ options.onUpstreamStart?.();
93
+ if (body && options.observeUpstream !== false) {
94
+ markUpstreamStarted(body.stream === true);
95
+ if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: api === "messages" ? body.max_tokens : api === "chat" ? body.max_completion_tokens : body.max_output_tokens,
96
+ reasoning_effort_sent: api === "messages" ? body.output_config?.effort : api === "chat" ? body.reasoning_effort : body.reasoning?.effort });
97
+ }
89
98
  const result = await transport.fetch(url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal });
99
+ const temporary = result.status === 502 || result.status === 503 || result.status === 504;
100
+ let retryAfterMs = 0;
101
+ if (temporary) { const retry = result.headers.get("retry-after");retryAfterMs = /^\d{1,8}$/.test(retry || "") ? Number(retry) * 1000 : Math.max(0, Date.parse(retry) - now()); }
102
+ cooldown?.complete(recovery, temporary, false, Number.isFinite(retryAfterMs) ? retryAfterMs : 0);observed = true;
90
103
  if (result.status >= 300 && result.status < 400) { await result.body?.cancel();throw accessError("ccdx_api_redirect_refused", 502); }
91
104
  if (!result.ok) {
92
105
  const adapted = api === "responses" && [400, 422].includes(result.status) && !options.compatibilityRetried && !options.skipCallLessRetry
@@ -94,7 +107,16 @@ export function createApiProvider({ config, secrets, env = process.env, platform
94
107
  const schemaCandidate = api === "messages" && !options.countTokens && [400, 422].includes(result.status)
95
108
  && !options.compatibilityRetried && hasRootToolSchema(body);
96
109
  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 });
110
+ const context = currentRequestContext();
111
+ const finishCapture = options.countTokens ? null : errorCapture?.claim(config.id, body?.model, api, result.status, context?.requestId);
112
+ let reason;
113
+ try {
114
+ reason = await readSafeUpstreamReason(result, { signal: options.signal, missingCallId: Boolean(adapted), rootToolSchema: schemaCandidate,
115
+ ...(finishCapture ? { diagnosticRedact: text => text.replaceAll(key, "[redacted]") } : {}) });
116
+ } finally {
117
+ const retained = finishCapture?.(reason?.diagnostic_message);
118
+ if (retained && reason?.diagnostic_message) context?.onHttpError?.({ diagnostic_message: reason.diagnostic_message });
119
+ }
98
120
  if (adapted && reason?.code === "ccdx_missing_call_id") {
99
121
  const recovered = await request(url, adapted, { ...options, bodyText: undefined, compatibilityRetried: true }, api);
100
122
  if (recovered.ok) Object.defineProperty(recovered, CALL_LESS_TOOL_RETRIED, { value: true });
@@ -112,13 +134,22 @@ export function createApiProvider({ config, secrets, env = process.env, platform
112
134
  if (adapted || schemaCandidate) try { options.onUpstreamErrorHeaders?.(result.status); } catch { /* Preserve the original upstream failure. */ }
113
135
  const code = `ccdx_api_http_${result.status}`;
114
136
  const safeHeaders = { "Content-Type": "application/json" }, retry = result.headers.get("retry-after");
137
+ for (const name of ["x-request-id", "x-correlation-id", "request-id"]) {
138
+ const value = result.headers.get(name);
139
+ if (value && /^[a-z\d_.:-]{1,80}$/i.test(value) && redactDiagnosticText(value) === value) { safeHeaders["X-Request-Id"] = value;break; }
140
+ }
115
141
  if (/^\d{1,8}$/.test(retry || "")) safeHeaders["Retry-After"] = retry;
116
142
  else if (retry && Number.isFinite(Date.parse(retry))) safeHeaders["Retry-After"] = new Date(retry).toUTCString();
117
- return new Response(JSON.stringify({ type: "error", error: { type: "api_error", code, message: reason?.message || code,
118
- ...(reason ? { upstream_code: reason.code } : {}) } }), { status: result.status, headers: safeHeaders });
143
+ const requestId=currentRequestContext()?.requestId;
144
+ const contextOverflow = api === "messages" && ["context_length_exceeded", "context_window_exceeded"].includes(reason?.code);
145
+ const message=(contextOverflow ? "prompt is too long. " : "")+(reason?.message||"The source rejected the request (HTTP "+result.status+"); no recognised technical reason was returned.")+" Source: "+redactDiagnosticText(config.name||config.id)+". Model: "+redactDiagnosticText(body?.model||"unknown")+". API: "+api+"."+(requestId?" Request: "+requestId+".":"");
146
+ const errorType = api === "messages" && ["input_length_invalid", "context_length_exceeded", "context_window_exceeded"].includes(reason?.code) ? "invalid_request_error" : "api_error";
147
+ return new Response(JSON.stringify({ type: "error", error: { type: errorType, code, message,
148
+ ...(reason ? { upstream_code: reason.code, ...(reason.parameter ? { param: reason.parameter } : {}), ...(reason.maximum ? { maximum: reason.maximum } : {}) } : {}) } }), { status: result.status, headers: safeHeaders });
119
149
  }
120
150
  return result;
121
151
  } catch (error) {
152
+ if (!observed) cooldown?.complete(recovery, confirmedNetworkFailure(error), options.signal?.aborted === true);
122
153
  if (options.signal?.aborted) throw error;
123
154
  if (error.code === "ccdx_api_redirect_refused") throw error;
124
155
  const failure = accessError("ccdx_api_network_unavailable", 502);
@@ -152,6 +183,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
152
183
  models: family => catalog.filter(model => model.supported_endpoints.includes(family === "claude" ? paths.messages : paths.responses))
153
184
  .map(model => ({ ...model, ...modelDisplay(model.id), capability: model.protocol_capabilities[family === "claude" ? "messages" : "responses"] })),
154
185
  catalog: () => catalog,
186
+ health: () => Object.fromEntries(Object.entries(cooldowns).filter(([protocol]) => config.endpoints[protocol]).map(([protocol, cooldown]) => [protocol, cooldown.snapshot()])),
155
187
  publicCatalog(allowed = []) { return { source: "configured", checkedAt: config.checked_at || null, upstreamHost: new URL(config.base_url).hostname,
156
188
  advertised: catalog.length, models: publicModelCatalog(catalog.map(model => ({ ...model, ...modelDisplay(model.id) })), { maker: model => model.publisher || model.vendor || null,
157
189
  selectable: model => allowed.some(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)),
@@ -3,12 +3,17 @@ import { randomUUID } from "node:crypto";
3
3
  import { redactDiagnosticText } from "./diagnostic-text.mjs";
4
4
 
5
5
  const requestContextStorage = new AsyncLocalStorage();
6
+ export const REQUEST_PURPOSES = Object.freeze(["conversation", "compaction", "diagnostic", "compatibility", "unknown"]);
7
+ export function requestPurpose(value, fallback = "conversation") {
8
+ return REQUEST_PURPOSES.includes(value) ? value : fallback;
9
+ }
6
10
 
7
11
  export function createRequestId() {
8
12
  return randomUUID();
9
13
  }
10
14
 
11
15
  export function runWithRequestContext(context, callback) {
16
+ context.purpose = requestPurpose(context.purpose);
12
17
  return requestContextStorage.run(context, callback);
13
18
  }
14
19
 
@@ -114,19 +114,21 @@ export function upstreamErrorEvidence(text, { includeMessage = false, status = n
114
114
  const technical = value => typeof value === "string" && /^[a-z\d_.:-]{1,80}$/i.test(value)
115
115
  && redactDiagnosticText(value) === value ? value : undefined;
116
116
  const param = typeof error.param === "string" && error.param.length <= 160
117
- && /^(?:model|input|tools|tool_choice|reasoning|text|temperature|top_p|max_output_tokens|service_tier|store|stream|include|previous_response_id|parallel_tool_calls)(?:\.[a-z_][a-z\d_]*|\[\d+\])*$/i.test(error.param)
117
+ && /^(?:model|messages|input|tools|tool_choice|reasoning|output_config|thinking|text|temperature|top_p|max_tokens|max_output_tokens|max_completion_tokens|service_tier|store|stream|include|previous_response_id|parallel_tool_calls)(?:\.[a-z_][a-z\d_]*|\[\d+\])*$/i.test(error.param)
118
118
  ? error.param : undefined;
119
119
  const upstreamCode = (safeUpstreamReason(error.upstream_code, status) || safeUpstreamReason(error.code, status)
120
120
  || safeUpstreamReason(error.type, status))?.code;
121
121
  return { error_body: "structured", code: technical(error.code), error_type: technical(error.type),
122
122
  ...(upstreamCode ? { upstream_code: upstreamCode } : {}),
123
+ ...(upstreamCode && Number.isSafeInteger(error.maximum) && error.maximum > 0 && error.maximum <= 100000000 ? { reported_maximum: error.maximum } : {}),
123
124
  parameter: param, ...(includeMessage && typeof error.message === "string" ? { diagnostic_message: safeFailureMessage(error.message) } : {}) };
124
125
  }
125
126
 
126
127
  export function requestOptionsEvidence(body) {
127
128
  const result = {};
128
129
  if (!body || typeof body !== "object") return result;
129
- if (["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"].includes(body.reasoning?.effort)) result.reasoning_effort = body.reasoning.effort;
130
+ const effort = body.reasoning?.effort ?? body.output_config?.effort ?? body.reasoning_effort;
131
+ if (["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"].includes(effort)) result.reasoning_effort = effort;
130
132
  if (["auto", "default", "flex", "priority", "scale"].includes(body.service_tier)) result.service_tier = body.service_tier;
131
133
  if (["text", "json_object", "json_schema"].includes(body.text?.format?.type)) result.output_format = body.text.format.type;
132
134
  if (Number.isSafeInteger(body.max_output_tokens) && body.max_output_tokens >= 0) result.max_output_tokens = body.max_output_tokens;
@@ -77,6 +77,13 @@ function chatCompatibilityError(kind, itemType) {
77
77
  return error;
78
78
  }
79
79
 
80
+ function emptyReasoningItem(item) {
81
+ return item?.type === "reasoning" && Array.isArray(item.summary) && item.summary.length === 0
82
+ && (item.content === undefined || Array.isArray(item.content) && item.content.length === 0)
83
+ && item.encrypted_content == null
84
+ && Object.keys(item).every(key => ["type", "id", "status", "summary", "content", "encrypted_content"].includes(key));
85
+ }
86
+
80
87
  export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
81
88
  const messages = [];
82
89
  if (body.instructions) messages.push({ role: "system", content: body.instructions });
@@ -155,11 +162,9 @@ export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
155
162
  index += 1;
156
163
  }
157
164
  index -= 1;
158
- messages.push({
159
- role: "assistant",
160
- content: null,
161
- tool_calls: toolCalls,
162
- });
165
+ const previous = messages.at(-1);
166
+ if (previous?.tool_calls) previous.tool_calls.push(...toolCalls);
167
+ else messages.push({ role: "assistant", content: null, tool_calls: toolCalls });
163
168
  } else if (item?.type === "function_call_output") {
164
169
  if (typeof item.call_id === "string" && item.call_id.trim()) {
165
170
  messages.push({ role: "tool", tool_call_id: item.call_id, content: typeof item.output === "string" ? item.output : JSON.stringify(item.output) });
@@ -168,6 +173,8 @@ export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
168
173
  if (!adapted) throw chatCompatibilityError("input item", "function_call_output");
169
174
  messages.push({ role: "user", content: messageContent(adapted.input[0].content) });
170
175
  }
176
+ } else if (emptyReasoningItem(item)) {
177
+ continue;
171
178
  } else {
172
179
  throw chatCompatibilityError("input item", item?.type);
173
180
  }