codex-copilot-dx 1.3.28 → 1.4.1
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.
- package/README.md +4 -1
- package/docs/ARCHITECTURE.md +23 -1
- package/docs/REFERENCE.md +34 -3
- package/package.json +1 -1
- package/src/adapter.mjs +13 -3
- package/src/antigravity-handler.mjs +44 -15
- package/src/antigravity-runtime.mjs +22 -2
- package/src/claude-capability-config.mjs +3 -2
- package/src/claude-client-config.mjs +2 -2
- package/src/claude-gateway.mjs +22 -4
- package/src/cli-command-spec.mjs +9 -4
- package/src/cli-management.mjs +28 -0
- package/src/cli-options.mjs +1 -1
- package/src/connection-routing.mjs +1 -0
- package/src/connection-runtime.mjs +11 -0
- package/src/context-compaction-plan.mjs +122 -0
- package/src/context-compaction-seal.mjs +56 -0
- package/src/context-compaction-wire.mjs +137 -0
- package/src/context-compaction.mjs +161 -0
- package/src/context-metrics.mjs +3 -2
- package/src/conversation-source-guard.mjs +15 -5
- package/src/dashboard/console.js +1 -1
- package/src/dashboard/index.html +14 -1
- package/src/dashboard/language.js +33 -0
- package/src/dashboard/preferences.js +1 -1
- package/src/dashboard/status.js +2 -2
- package/src/dashboard/tool-activity.js +153 -0
- package/src/dashboard/ui.css +26 -0
- package/src/dashboard/ui.js +2 -2
- package/src/dashboard.mjs +1 -0
- package/src/http-transport.mjs +1 -1
- package/src/local-privacy.mjs +15 -7
- package/src/lock.mjs +9 -2
- package/src/privacy-detection.mjs +4 -3
- package/src/privacy-transform.mjs +20 -6
- package/src/provider-runtime.mjs +8 -5
- package/src/providers/api.mjs +15 -4
- package/src/request-context.mjs +1 -1
- package/src/responses-bridge.mjs +14 -5
- package/src/responses-handler.mjs +81 -1
- package/src/responses-proxy.mjs +22 -5
- package/src/responses-request.mjs +11 -4
- package/src/safe-upstream-error.mjs +29 -11
- package/src/service-control.mjs +8 -1
- package/src/settings-preferences.mjs +3 -3
- package/src/stream-performance.mjs +19 -2
- package/src/tool-activity.mjs +135 -0
- package/src/upstream-body.mjs +1 -1
- package/src/upstream-error-capture.mjs +29 -0
- package/src/user-settings.mjs +1 -1
package/src/local-privacy.mjs
CHANGED
|
@@ -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,
|
|
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
|
-
},
|
|
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}`);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
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 =
|
|
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 {
|
|
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}:` +
|
|
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
|
|
package/src/provider-runtime.mjs
CHANGED
|
@@ -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() {
|
package/src/providers/api.mjs
CHANGED
|
@@ -32,7 +32,7 @@ export function apiCatalog(config, env = process.env) {
|
|
|
32
32
|
supported_endpoints: model.protocols.map(api => paths[api]), model_picker_enabled: true, policy: { state: "enabled" },
|
|
33
33
|
capability, protocol_capabilities }); });
|
|
34
34
|
}
|
|
35
|
-
export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork, modelDisplay = () => ({}), now = Date.now } = {}) {
|
|
35
|
+
export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork, modelDisplay = () => ({}), now = Date.now, errorCapture } = {}) {
|
|
36
36
|
const cooldowns = Object.fromEntries(["messages", "responses", "chat"].map(protocol => [protocol, createProviderCooldown({ now })]));
|
|
37
37
|
const catalog = apiCatalog(config, env);
|
|
38
38
|
const fingerprint = config.key_env ? createHash("sha256").update(env[config.key_env] || "").digest("hex") : "";
|
|
@@ -107,7 +107,16 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
107
107
|
const schemaCandidate = api === "messages" && !options.countTokens && [400, 422].includes(result.status)
|
|
108
108
|
&& !options.compatibilityRetried && hasRootToolSchema(body);
|
|
109
109
|
if (!adapted && !schemaCandidate) try { options.onUpstreamErrorHeaders?.(result.status); } catch { /* Optional admission release cannot hide the upstream response. */ }
|
|
110
|
-
const
|
|
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
|
+
}
|
|
111
120
|
if (adapted && reason?.code === "ccdx_missing_call_id") {
|
|
112
121
|
const recovered = await request(url, adapted, { ...options, bodyText: undefined, compatibilityRetried: true }, api);
|
|
113
122
|
if (recovered.ok) Object.defineProperty(recovered, CALL_LESS_TOOL_RETRIED, { value: true });
|
|
@@ -132,8 +141,10 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
132
141
|
if (/^\d{1,8}$/.test(retry || "")) safeHeaders["Retry-After"] = retry;
|
|
133
142
|
else if (retry && Number.isFinite(Date.parse(retry))) safeHeaders["Retry-After"] = new Date(retry).toUTCString();
|
|
134
143
|
const requestId=currentRequestContext()?.requestId;
|
|
135
|
-
const
|
|
136
|
-
|
|
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,
|
|
137
148
|
...(reason ? { upstream_code: reason.code, ...(reason.parameter ? { param: reason.parameter } : {}), ...(reason.maximum ? { maximum: reason.maximum } : {}) } : {}) } }), { status: result.status, headers: safeHeaders });
|
|
138
149
|
}
|
|
139
150
|
return result;
|
package/src/request-context.mjs
CHANGED
|
@@ -3,7 +3,7 @@ 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", "diagnostic", "compatibility", "unknown"]);
|
|
6
|
+
export const REQUEST_PURPOSES = Object.freeze(["conversation", "compaction", "diagnostic", "compatibility", "unknown"]);
|
|
7
7
|
export function requestPurpose(value, fallback = "conversation") {
|
|
8
8
|
return REQUEST_PURPOSES.includes(value) ? value : fallback;
|
|
9
9
|
}
|
package/src/responses-bridge.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { markToolActivity } from "./stream-performance.mjs";
|
|
1
2
|
import { randomUUID } from "node:crypto";
|
|
2
3
|
import { chatCompletions } from "./copilot.mjs";
|
|
3
4
|
import { webStreamLines } from "./stream.mjs";
|
|
@@ -77,6 +78,13 @@ function chatCompatibilityError(kind, itemType) {
|
|
|
77
78
|
return error;
|
|
78
79
|
}
|
|
79
80
|
|
|
81
|
+
function emptyReasoningItem(item) {
|
|
82
|
+
return item?.type === "reasoning" && Array.isArray(item.summary) && item.summary.length === 0
|
|
83
|
+
&& (item.content === undefined || Array.isArray(item.content) && item.content.length === 0)
|
|
84
|
+
&& item.encrypted_content == null
|
|
85
|
+
&& Object.keys(item).every(key => ["type", "id", "status", "summary", "content", "encrypted_content"].includes(key));
|
|
86
|
+
}
|
|
87
|
+
|
|
80
88
|
export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
|
|
81
89
|
const messages = [];
|
|
82
90
|
if (body.instructions) messages.push({ role: "system", content: body.instructions });
|
|
@@ -155,11 +163,9 @@ export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
|
|
|
155
163
|
index += 1;
|
|
156
164
|
}
|
|
157
165
|
index -= 1;
|
|
158
|
-
messages.
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
tool_calls: toolCalls,
|
|
162
|
-
});
|
|
166
|
+
const previous = messages.at(-1);
|
|
167
|
+
if (previous?.tool_calls) previous.tool_calls.push(...toolCalls);
|
|
168
|
+
else messages.push({ role: "assistant", content: null, tool_calls: toolCalls });
|
|
163
169
|
} else if (item?.type === "function_call_output") {
|
|
164
170
|
if (typeof item.call_id === "string" && item.call_id.trim()) {
|
|
165
171
|
messages.push({ role: "tool", tool_call_id: item.call_id, content: typeof item.output === "string" ? item.output : JSON.stringify(item.output) });
|
|
@@ -168,6 +174,8 @@ export function responsesToChat(body, { reasoningEfforts, cacheSupport } = {}) {
|
|
|
168
174
|
if (!adapted) throw chatCompatibilityError("input item", "function_call_output");
|
|
169
175
|
messages.push({ role: "user", content: messageContent(adapted.input[0].content) });
|
|
170
176
|
}
|
|
177
|
+
} else if (emptyReasoningItem(item)) {
|
|
178
|
+
continue;
|
|
171
179
|
} else {
|
|
172
180
|
throw chatCompatibilityError("input item", item?.type);
|
|
173
181
|
}
|
|
@@ -376,6 +384,7 @@ export async function forwardToChat(chatReq, emitEvent, onDone, onError, options
|
|
|
376
384
|
emitEvent = async (...args) => {
|
|
377
385
|
const written = await configuredEmitEvent(...args);
|
|
378
386
|
if (written === false) throw downstreamClosed;
|
|
387
|
+
if (args[1]?.item || args[1]?.response?.output) markToolActivity(args[1]);
|
|
379
388
|
return written;
|
|
380
389
|
};
|
|
381
390
|
let performanceOutputSeen = false;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { markToolActivity } from "./stream-performance.mjs";
|
|
1
2
|
import { defaultGithubProvider } from "./providers/github.mjs";
|
|
2
3
|
import { observeContextSession } from "./context-metrics.mjs";
|
|
3
4
|
import {
|
|
@@ -36,6 +37,10 @@ import { endStreamWithError } from "./stream-errors.mjs";
|
|
|
36
37
|
import { createSseKeepalive } from "./sse-keepalive.mjs";
|
|
37
38
|
import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
|
|
38
39
|
import { recordResponsesUsage } from "./usage-store.mjs";
|
|
40
|
+
import { compactionScope, resolveGatewayCompactionItem, protectNativeCompactionResult, COMPACTION_USAGE_RECORDED } from "./context-compaction.mjs";
|
|
41
|
+
import { compactionSummarizer } from "./context-compaction-wire.mjs";
|
|
42
|
+
import { catalogCapabilities } from "./model-capabilities.mjs";
|
|
43
|
+
import { currentRequestContext, requestPurpose } from "./request-context.mjs";
|
|
39
44
|
import {
|
|
40
45
|
markResponseErrorOrigin,
|
|
41
46
|
markResponseModel,
|
|
@@ -46,6 +51,54 @@ import {
|
|
|
46
51
|
measureRequestStageAsync,
|
|
47
52
|
} from "./stream-performance.mjs";
|
|
48
53
|
|
|
54
|
+
function gatewayCompactionContext(options, provider, res) {
|
|
55
|
+
let key, inherited, wrappedNative;
|
|
56
|
+
const loadKey = () => key ||= options.compactionKey?.();
|
|
57
|
+
const scope = compactionScope(provider, "codex", "responses");
|
|
58
|
+
return {
|
|
59
|
+
scope, key: loadKey,
|
|
60
|
+
resolve: item => resolveGatewayCompactionItem(item, { scope, key: loadKey, onMappings(entries) {
|
|
61
|
+
inherited ||= new Map();for (const entry of entries) inherited.set(...entry);
|
|
62
|
+
} }),
|
|
63
|
+
async importMappings() { if (inherited?.size) {
|
|
64
|
+
if (!options.privacy?.importResponseMappings) throw Object.assign(new Error("Private compression mappings cannot be restored by this gateway."), { code: "ccdx_compaction_privacy_unavailable", statusCode: 409 });
|
|
65
|
+
await options.privacy.importResponseMappings(res, [...inherited]);inherited = null;
|
|
66
|
+
} },
|
|
67
|
+
protect(value) {
|
|
68
|
+
if (wrappedNative) {
|
|
69
|
+
if (!value.output?.some(item => item?.encrypted_content === wrappedNative.original)) return value;
|
|
70
|
+
return { ...value, output: value.output.map(item => item?.encrypted_content === wrappedNative.original ? { ...item, encrypted_content: wrappedNative.sealed } : item) };
|
|
71
|
+
}
|
|
72
|
+
const next = protectNativeCompactionResult(value, { scope, key: loadKey, mappings: () => options.privacy?.responseMappings?.(res) || [] });
|
|
73
|
+
if (next !== value) { const index = next.output.findIndex((item, index) => item !== value.output[index]);wrappedNative = { original: value.output[index].encrypted_content, sealed: next.output[index].encrypted_content }; }
|
|
74
|
+
return next;
|
|
75
|
+
},
|
|
76
|
+
restoreText: text => options.privacy?.restoreResponse(res, { output: [{ type: "message", role: "assistant", content: [{ type: "output_text", text }] }] })?.output[0].content[0].text || text,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function adaptiveResponsesCompaction(options, state) {
|
|
81
|
+
return async (value, callOptions) => {
|
|
82
|
+
const raw = state.modelRegistry?.models, entries = Array.isArray(raw) ? raw : Array.isArray(raw?.data) ? raw.data : [];
|
|
83
|
+
const entry = entries.find(model => model.id === value.model), limits = entry?.protocol_capabilities?.responses?.values || entry?.capability?.values || catalogCapabilities(entry || {});
|
|
84
|
+
const endpoints = state.getCachedModelEndpoints?.(value.model), carriesResponses = !Array.isArray(endpoints) || !endpoints.length || endpoints.some(path => ["/responses", "/v1/responses"].includes(path));
|
|
85
|
+
let summarize;
|
|
86
|
+
const result = await options.compaction.run({ body: value, protocol: "responses", scope: state.context.scope, key: state.context.key, source: state.provider.id, client: "codex",
|
|
87
|
+
nativeKind: state.kind, inputLimit: limits.max_input_tokens || limits.context_window, outputAllowance: value.max_output_tokens || 0,
|
|
88
|
+
native: state.kind === "inline" && !carriesResponses ? undefined : state.native, options: callOptions,
|
|
89
|
+
summarize(text, summaryOptions) {
|
|
90
|
+
if (!summarize) {
|
|
91
|
+
const route = state.provider.route({ model: value.model, input: [], reasoning: value.reasoning }, { requestedModel: value.model, upstreamModel: value.model, forceResponses: state.forceResponses,
|
|
92
|
+
surface: "responses", getCachedModelEndpoints: state.getCachedModelEndpoints });
|
|
93
|
+
const chat = route.protocol === "openai-chat-completions", template = chat ? { model: value.model, max_completion_tokens: value.max_output_tokens, reasoning_effort: value.reasoning?.effort, service_tier: value.service_tier } : value;
|
|
94
|
+
summarize = compactionSummarizer(template, chat ? "chat" : "responses", chat ? state.chat : state.responses);
|
|
95
|
+
}
|
|
96
|
+
return summarize(text, summaryOptions);
|
|
97
|
+
}, restoreText: state.context.restoreText, onActivity: state.onActivity });
|
|
98
|
+
if (result[COMPACTION_USAGE_RECORDED]) state.prepared.compactionUsageRecorded = true;return result;
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
49
102
|
function resolveRequestModel(model, openAIModelEnv, autoReviewModelResolver) {
|
|
50
103
|
const preference = model === CODEX_AUTO_REVIEW_MODEL && typeof autoReviewModelResolver === "function"
|
|
51
104
|
? autoReviewModelResolver() : undefined;
|
|
@@ -221,6 +274,7 @@ export function createResponsesHandler(options) {
|
|
|
221
274
|
const validation = options.validateConversation?.(parsed, req.headers, provider, abort.signal);
|
|
222
275
|
if (validation?.then) await validation;
|
|
223
276
|
observeContextSession(parsed, req.headers, provider);
|
|
277
|
+
const compactionContext = options.compaction ? gatewayCompactionContext(options, provider, res) : null;
|
|
224
278
|
activeDeadline = now() + upstreamTimeoutMs;
|
|
225
279
|
activeTimeoutReason = "responses_prepare_timeout";
|
|
226
280
|
abort.setTimeout(upstreamTimeoutMs, "responses_prepare_timeout");
|
|
@@ -239,7 +293,9 @@ export function createResponsesHandler(options) {
|
|
|
239
293
|
copilotBoundary: false,
|
|
240
294
|
historySnapshot,
|
|
241
295
|
mutate: true,
|
|
296
|
+
resolveCompaction: compactionContext?.resolve,
|
|
242
297
|
}));
|
|
298
|
+
await compactionContext?.importMappings();
|
|
243
299
|
parsed = null;
|
|
244
300
|
assertPrepareActive();
|
|
245
301
|
imagePressureResult = imagePressure?.apply?.(prepared, { assertActive: assertPrepareActive }) || null;
|
|
@@ -260,17 +316,29 @@ export function createResponsesHandler(options) {
|
|
|
260
316
|
}
|
|
261
317
|
}
|
|
262
318
|
if (upstreamModel !== requestedModel) prepared.body.model = upstreamModel;
|
|
319
|
+
const inlineCompacting = options.compaction && prepared.body.input?.at(-1)?.type === "compaction_trigger";
|
|
320
|
+
if (inlineCompacting) {
|
|
321
|
+
const context = currentRequestContext();if (context) { context.purpose = requestPurpose(req.headers["x-ccdx-purpose"], "compaction");context.streamPerformance?.setPurpose(context.purpose); }
|
|
322
|
+
markRequestObservation({ compaction: 1 });
|
|
323
|
+
}
|
|
263
324
|
markResponseModel(upstreamModel, { requestedModel, configuredModel: provider.configuredModels === true });
|
|
264
325
|
markRequestObservation({ context_window_tokens: modelContextWindowTokens(modelRegistry?.models, upstreamModel) });
|
|
265
326
|
const upstreamLog = upstreamModel === requestedModel ? "" : ` upstream_model=${upstreamModel}`;
|
|
266
327
|
console.log(status("info", `responses model=${requestedModel}${upstreamLog} stream=${streaming}`));
|
|
267
|
-
const routePlan = provider.route(prepared.body, { requestedModel, upstreamModel, forceResponses,
|
|
328
|
+
const routePlan = provider.route(prepared.body, { requestedModel, upstreamModel, forceResponses: forceResponses || inlineCompacting,
|
|
268
329
|
surface: "responses", getCachedModelEndpoints: getCachedModelEndpointsFn });
|
|
269
330
|
const selected = applySelectedRoute(prepared, routePlan, { req, env: openAIModelEnv, signal: abort.signal,
|
|
270
331
|
assertActive: assertPrepareActive, reserveHistory: releaseRequest.reserveResponseHistory });
|
|
271
332
|
prepared = selected instanceof Promise ? await selected : selected;
|
|
272
333
|
if (prepared.historyParentId === null) releaseHistorySnapshot();
|
|
273
334
|
provider.applyRequestPolicies(prepared.body);
|
|
335
|
+
if (inlineCompacting) {
|
|
336
|
+
const source = responsesFn;
|
|
337
|
+
responsesFn = adaptiveResponsesCompaction(options, { provider, modelRegistry, prepared, context: compactionContext, kind: "inline", native: source, responses: source,
|
|
338
|
+
chat: chatCompletionsFn, forceResponses, getCachedModelEndpoints: getCachedModelEndpointsFn,
|
|
339
|
+
onActivity() { activeDeadline = Number.POSITIVE_INFINITY;abort.setTimeout(streamIdleTimeoutMs, "compaction_idle_timeout"); } });
|
|
340
|
+
prepared.protectCompactionResult = compactionContext.protect;
|
|
341
|
+
}
|
|
274
342
|
if (options.privacy) {
|
|
275
343
|
prepared.privacyRestore = value => options.privacy.restoreResponse(res, value);
|
|
276
344
|
responsesFn = options.privacy.wrap(responsesFn, { res, protocol: "responses", client: "codex" });
|
|
@@ -417,6 +485,7 @@ export function createResponsesHandler(options) {
|
|
|
417
485
|
return;
|
|
418
486
|
}
|
|
419
487
|
const response = chatToResponses(JSON.parse(data), model, { toolChoice, ...(carbonBridge ? { toolAdapter: carbonBridge } : {}) });
|
|
488
|
+
markToolActivity(response);
|
|
420
489
|
markResponseTerminal(response.status, {
|
|
421
490
|
model: response.model || model, origin: "chat_completion", reason: response.incomplete_details?.reason,
|
|
422
491
|
});
|
|
@@ -529,6 +598,8 @@ export function createResponsesCompactHandler(options) {
|
|
|
529
598
|
releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal }));
|
|
530
599
|
abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
|
|
531
600
|
const parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
|
|
601
|
+
const context = currentRequestContext();if (context) { context.purpose = requestPurpose(req.headers["x-ccdx-purpose"], "compaction");context.streamPerformance?.setPurpose(context.purpose); }
|
|
602
|
+
markRequestObservation({ compaction: 1 });
|
|
532
603
|
observeRequestedModel(parsed);
|
|
533
604
|
markRequestObservation({ max_output_tokens_requested: parsed?.max_output_tokens });
|
|
534
605
|
const selectedProvider = options.resolveProvider?.(parsed, req);
|
|
@@ -542,6 +613,7 @@ export function createResponsesCompactHandler(options) {
|
|
|
542
613
|
const validation = options.validateConversation?.(parsed, req.headers, provider, abort.signal);
|
|
543
614
|
if (validation?.then) await validation;
|
|
544
615
|
observeContextSession(parsed, req.headers, provider);
|
|
616
|
+
const compactionContext = options.compaction ? gatewayCompactionContext(options, provider, res) : null;
|
|
545
617
|
activeDeadline = now() + upstreamTimeoutMs;
|
|
546
618
|
activeTimeoutReason = "responses_prepare_timeout";
|
|
547
619
|
abort.setTimeout(upstreamTimeoutMs, "responses_prepare_timeout");
|
|
@@ -560,7 +632,9 @@ export function createResponsesCompactHandler(options) {
|
|
|
560
632
|
copilotBoundary: false,
|
|
561
633
|
historySnapshot,
|
|
562
634
|
mutate: true,
|
|
635
|
+
resolveCompaction: compactionContext?.resolve,
|
|
563
636
|
}));
|
|
637
|
+
await compactionContext?.importMappings();
|
|
564
638
|
imagePressureResult = imagePressure?.applyRecovery?.(prepared, { assertActive: assertPrepareActive }) || null;
|
|
565
639
|
if (imagePressureResult?.adapted) {
|
|
566
640
|
console.warn(status("warn", `responses compact visual history mode=recovery historical_images=${imagePressureResult.initialHistoricalImages}->${imagePressureResult.historicalImages} omitted=${imagePressureResult.imagesOmitted} bytes=${imagePressureResult.initialBodyBytes}->${imagePressureResult.bodyBytes}`));
|
|
@@ -589,6 +663,12 @@ export function createResponsesCompactHandler(options) {
|
|
|
589
663
|
prepared = selected instanceof Promise ? await selected : selected;
|
|
590
664
|
releaseHistorySnapshot();
|
|
591
665
|
provider.applyRequestPolicies(prepared.body);
|
|
666
|
+
if (options.compaction) {
|
|
667
|
+
responsesCompactFn = adaptiveResponsesCompaction(options, { provider, modelRegistry, prepared, context: compactionContext, kind: "compact", native: responsesCompactFn,
|
|
668
|
+
responses: responsesFn, chat: chatCompletionsFn, forceResponses, getCachedModelEndpoints: getCachedModelEndpointsFn,
|
|
669
|
+
onActivity() { activeDeadline = Number.POSITIVE_INFINITY;abort.setTimeout(options.streamIdleTimeoutMs || upstreamTimeoutMs, "compaction_idle_timeout"); } });
|
|
670
|
+
prepared.protectCompactionResult = compactionContext.protect;
|
|
671
|
+
}
|
|
592
672
|
if (options.privacy) {
|
|
593
673
|
prepared.privacyRestore = value => options.privacy.restoreResponse(res, value);
|
|
594
674
|
responsesCompactFn = options.privacy.wrap(responsesCompactFn, { res, protocol: "responses", client: "codex" });
|
package/src/responses-proxy.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { markToolActivity } from "./stream-performance.mjs";
|
|
1
2
|
import { responses as copilotResponses } from "./copilot.mjs";
|
|
2
3
|
import {
|
|
3
4
|
logRequestFailure,
|
|
@@ -50,6 +51,7 @@ import {
|
|
|
50
51
|
} from "./stream-performance.mjs";
|
|
51
52
|
import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
|
|
52
53
|
import { recordResponsesUsage } from "./usage-store.mjs";
|
|
54
|
+
import { COMPACTION_USAGE_RECORDED } from "./context-compaction.mjs";
|
|
53
55
|
import { status } from "./status.mjs";
|
|
54
56
|
|
|
55
57
|
const MAX_SSE_BUFFER_BYTES = loadRuntimeConfig().maxSseBufferBytes;
|
|
@@ -123,6 +125,7 @@ function inspectResponseSseEvent(state, eventName, data) {
|
|
|
123
125
|
);
|
|
124
126
|
}
|
|
125
127
|
const eventType = event.type || (event.error ? "error" : eventName);
|
|
128
|
+
if (event.item || event.response?.output) markToolActivity(event);
|
|
126
129
|
const previousSequence = state.lastSequence;
|
|
127
130
|
state.lastSequence = event.sequence_number ?? previousSequence + 1;
|
|
128
131
|
if (event.response && typeof event.response === "object" && !Array.isArray(event.response)) {
|
|
@@ -130,7 +133,17 @@ function inspectResponseSseEvent(state, eventName, data) {
|
|
|
130
133
|
if (Number.isSafeInteger(event.response.created_at) && event.response.created_at >= 0) state.response.created_at = event.response.created_at;
|
|
131
134
|
if (typeof event.response.model === "string" && event.response.model) state.response.model = event.response.model;
|
|
132
135
|
}
|
|
133
|
-
|
|
136
|
+
let changed = normalizeMessageIds(state, event, eventType);
|
|
137
|
+
if (state.protectCompactionResult) {
|
|
138
|
+
if (event.item?.type === "compaction") {
|
|
139
|
+
const protectedItem = state.protectCompactionResult({ output: [event.item] }).output[0];
|
|
140
|
+
if (protectedItem !== event.item) { event.item = protectedItem;changed = true; }
|
|
141
|
+
}
|
|
142
|
+
if (Array.isArray(event.response?.output)) {
|
|
143
|
+
const protectedResponse = state.protectCompactionResult(event.response);
|
|
144
|
+
if (protectedResponse !== event.response) { event.response = protectedResponse;changed = true; }
|
|
145
|
+
}
|
|
146
|
+
}
|
|
134
147
|
const outputTokens = event.response?.usage?.output_tokens ?? event.usage?.output_tokens;
|
|
135
148
|
if (outputTokens !== undefined) markOutputTokens(outputTokens);
|
|
136
149
|
const inputTokens = event.response?.usage?.input_tokens ?? event.usage?.input_tokens;
|
|
@@ -400,7 +413,7 @@ function parseSuccessfulResponsesResult(text) {
|
|
|
400
413
|
function storeCompletedResponse(reqContext, completed) {
|
|
401
414
|
if (!completed) return;
|
|
402
415
|
rememberResponseHistory(reqContext, reqContext.privacyRestore?.(completed.response) || completed.response);
|
|
403
|
-
recordResponsesUsage({
|
|
416
|
+
if (!reqContext.compactionUsageRecorded) recordResponsesUsage({
|
|
404
417
|
surface: reqContext.surface,
|
|
405
418
|
mode: "stream",
|
|
406
419
|
model: reqContext.body?.model,
|
|
@@ -501,6 +514,7 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
|
|
|
501
514
|
lastSequence: -1,
|
|
502
515
|
toolArgumentGuard: new ToolArgumentDeltaGuard(),
|
|
503
516
|
messageIds: new Map(),
|
|
517
|
+
protectCompactionResult: reqContext.protectCompactionResult,
|
|
504
518
|
};
|
|
505
519
|
const transformer = createResponseSseTransformer(streamState);
|
|
506
520
|
let holdPrelude = streamRetryEligible;
|
|
@@ -656,12 +670,14 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
|
|
|
656
670
|
label: "Copilot Responses error body",
|
|
657
671
|
});
|
|
658
672
|
if (resp.ok && reqContext.surface === "responses_compact") {
|
|
659
|
-
|
|
673
|
+
let response = parseResponsesCompactionResult(
|
|
660
674
|
compactionInputWithoutTrigger(reqContext.body.input),
|
|
661
675
|
data,
|
|
662
676
|
);
|
|
677
|
+
response = reqContext.protectCompactionResult?.(response) || response;
|
|
678
|
+
markToolActivity(response);
|
|
663
679
|
rememberResponseHistory(reqContext, reqContext.privacyRestore?.(response) || response);
|
|
664
|
-
recordResponsesUsage({
|
|
680
|
+
if (!resp[COMPACTION_USAGE_RECORDED]) recordResponsesUsage({
|
|
665
681
|
surface: reqContext.surface,
|
|
666
682
|
mode: "json",
|
|
667
683
|
model: reqContext.body?.model,
|
|
@@ -709,8 +725,9 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
|
|
|
709
725
|
continue;
|
|
710
726
|
}
|
|
711
727
|
}
|
|
728
|
+
markToolActivity(response);
|
|
712
729
|
rememberResponseHistory(reqContext, reqContext.privacyRestore?.(response) || response);
|
|
713
|
-
recordResponsesUsage({
|
|
730
|
+
if (!reqContext.compactionUsageRecorded) recordResponsesUsage({
|
|
714
731
|
surface: reqContext.surface,
|
|
715
732
|
mode: "json",
|
|
716
733
|
model: reqContext.body?.model,
|
|
@@ -45,12 +45,13 @@ function responsesInputItems(input, { assertActive, clone = true } = {}) {
|
|
|
45
45
|
return [item];
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
export function stripInternalResponsesInputFields(inputItems, { assertActive } = {}) {
|
|
48
|
+
export function stripInternalResponsesInputFields(inputItems, { assertActive, resolveCompaction } = {}) {
|
|
49
49
|
if (!Array.isArray(inputItems)) return inputItems;
|
|
50
50
|
for (let index = 0; index < inputItems.length; index += 1) {
|
|
51
51
|
if ((index & 63) === 0) assertActive?.();
|
|
52
|
-
|
|
52
|
+
let item = inputItems[index];
|
|
53
53
|
if (!item || typeof item !== "object") continue;
|
|
54
|
+
if (resolveCompaction && item.type === "compaction") item = inputItems[index] = resolveCompaction(item);
|
|
54
55
|
for (const key of Object.keys(item)) {
|
|
55
56
|
if (key.startsWith("internal_")) delete item[key];
|
|
56
57
|
}
|
|
@@ -357,6 +358,7 @@ export function prepareResponsesRequest(reqBody, {
|
|
|
357
358
|
copilotBoundary = true,
|
|
358
359
|
historySnapshot,
|
|
359
360
|
mutate = false,
|
|
361
|
+
resolveCompaction,
|
|
360
362
|
} = {}) {
|
|
361
363
|
assertActive?.();
|
|
362
364
|
const body = mutate ? reqBody : cloneJson(reqBody);
|
|
@@ -411,10 +413,15 @@ export function prepareResponsesRequest(reqBody, {
|
|
|
411
413
|
// pass copilotBoundary:false and apply the policy only after selecting a
|
|
412
414
|
// concrete Copilot RoutePlan.
|
|
413
415
|
if (copilotBoundary) applyCopilotResponsesRequestPolicies(body);
|
|
414
|
-
|
|
416
|
+
let expanded = false;
|
|
417
|
+
const resolve = resolveCompaction ? item => {
|
|
418
|
+
const next = resolveCompaction(item);if (next !== item) { expanded = true;if (currentInputRefs.delete(item)) currentInputRefs.add(next); }return next;
|
|
419
|
+
} : undefined;
|
|
420
|
+
stripInternalResponsesInputFields(body.input, { assertActive, resolveCompaction: resolve });
|
|
415
421
|
// The first pass already covers shared current items. Only an independent
|
|
416
422
|
// pre-adaptation snapshot needs another pass.
|
|
417
|
-
if (historyInputItems !== currentInputItems) stripInternalResponsesInputFields(historyInputItems, { assertActive });
|
|
423
|
+
if (historyInputItems !== currentInputItems) stripInternalResponsesInputFields(historyInputItems, { assertActive, resolveCompaction: resolve });
|
|
424
|
+
if (expanded && !responseValueHasOpaqueState(body.input)) for (const metadata of historyRouteMetadata) metadata.hasOpaque = false;
|
|
418
425
|
assertActive?.();
|
|
419
426
|
const retainedCurrentInputStart = body.input.findIndex((item) => currentInputRefs.has(item));
|
|
420
427
|
|