codex-copilot-dx 1.3.28 → 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.
- package/README.md +3 -1
- package/docs/ARCHITECTURE.md +17 -1
- package/docs/REFERENCE.md +25 -3
- package/package.json +1 -1
- package/src/adapter.mjs +13 -3
- package/src/antigravity-handler.mjs +38 -13
- 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 +19 -3
- package/src/cli-command-spec.mjs +7 -3
- package/src/cli-management.mjs +21 -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 +1 -1
- package/src/conversation-source-guard.mjs +15 -5
- package/src/dashboard/index.html +7 -1
- package/src/dashboard/language.js +4 -0
- package/src/dashboard/preferences.js +1 -1
- 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 +12 -5
- package/src/responses-handler.mjs +79 -1
- package/src/responses-proxy.mjs +18 -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 +3 -2
- package/src/upstream-body.mjs +1 -1
- package/src/upstream-error-capture.mjs +29 -0
- package/src/user-settings.mjs +1 -1
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
const theme = () => globalThis.ccdxDashboardTheme;
|
|
5
5
|
const backupKey = "ccdx.dashboard.preferences-backup";
|
|
6
6
|
const fields = { terminal_color_theme: "terminal-color-theme", terminal_animation_enabled: "setting-terminal_animation_enabled",
|
|
7
|
-
open_webui: "setting-open_webui", nightly_updates: "nightly-update" };
|
|
7
|
+
open_webui: "setting-open_webui", nightly_updates: "nightly-update", context_compaction_enabled: "setting-context_compaction_enabled" };
|
|
8
8
|
let base, draft = {}, appearance, appearanceBase, pending, timer, error = null, conflict = false, version = 0, dialog, dialogRevision, resetting = false, retrying = false, locks = {}, terminalMode;
|
|
9
9
|
const dirty = () => Object.keys(draft).length + (appearance ? 1 : 0);
|
|
10
10
|
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
package/src/http-transport.mjs
CHANGED
|
@@ -26,7 +26,7 @@ export const MAX_DECODED_BODY_BYTES = decodedBodyLimitPreference().bytes;
|
|
|
26
26
|
|
|
27
27
|
export {
|
|
28
28
|
MAX_UPSTREAM_ERROR_BODY_BYTES, MAX_UPSTREAM_MODEL_CATALOG_BYTES, MAX_UPSTREAM_RETRY_DRAIN_BYTES,
|
|
29
|
-
readBoundedResponseBuffer, readBoundedResponseText, discardBoundedResponseBody,
|
|
29
|
+
readBoundedResponseBuffer, readBoundedResponseText, discardBoundedResponseBody, readResponseChunk,
|
|
30
30
|
} from "./upstream-body.mjs";
|
|
31
31
|
export const MAX_UPSTREAM_CHAT_SUCCESS_BODY_BYTES = HTTP_RUNTIME_CONFIG.maxUpstreamChatResponseBytes;
|
|
32
32
|
export const MAX_UPSTREAM_RESPONSES_SUCCESS_BODY_BYTES = HTTP_RUNTIME_CONFIG.maxUpstreamResponsesResponseBytes;
|
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
|
@@ -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.
|
|
159
|
-
|
|
160
|
-
|
|
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
|
}
|
|
@@ -36,6 +36,10 @@ import { endStreamWithError } from "./stream-errors.mjs";
|
|
|
36
36
|
import { createSseKeepalive } from "./sse-keepalive.mjs";
|
|
37
37
|
import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
|
|
38
38
|
import { recordResponsesUsage } from "./usage-store.mjs";
|
|
39
|
+
import { compactionScope, resolveGatewayCompactionItem, protectNativeCompactionResult, COMPACTION_USAGE_RECORDED } from "./context-compaction.mjs";
|
|
40
|
+
import { compactionSummarizer } from "./context-compaction-wire.mjs";
|
|
41
|
+
import { catalogCapabilities } from "./model-capabilities.mjs";
|
|
42
|
+
import { currentRequestContext, requestPurpose } from "./request-context.mjs";
|
|
39
43
|
import {
|
|
40
44
|
markResponseErrorOrigin,
|
|
41
45
|
markResponseModel,
|
|
@@ -46,6 +50,54 @@ import {
|
|
|
46
50
|
measureRequestStageAsync,
|
|
47
51
|
} from "./stream-performance.mjs";
|
|
48
52
|
|
|
53
|
+
function gatewayCompactionContext(options, provider, res) {
|
|
54
|
+
let key, inherited, wrappedNative;
|
|
55
|
+
const loadKey = () => key ||= options.compactionKey?.();
|
|
56
|
+
const scope = compactionScope(provider, "codex", "responses");
|
|
57
|
+
return {
|
|
58
|
+
scope, key: loadKey,
|
|
59
|
+
resolve: item => resolveGatewayCompactionItem(item, { scope, key: loadKey, onMappings(entries) {
|
|
60
|
+
inherited ||= new Map();for (const entry of entries) inherited.set(...entry);
|
|
61
|
+
} }),
|
|
62
|
+
async importMappings() { if (inherited?.size) {
|
|
63
|
+
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 });
|
|
64
|
+
await options.privacy.importResponseMappings(res, [...inherited]);inherited = null;
|
|
65
|
+
} },
|
|
66
|
+
protect(value) {
|
|
67
|
+
if (wrappedNative) {
|
|
68
|
+
if (!value.output?.some(item => item?.encrypted_content === wrappedNative.original)) return value;
|
|
69
|
+
return { ...value, output: value.output.map(item => item?.encrypted_content === wrappedNative.original ? { ...item, encrypted_content: wrappedNative.sealed } : item) };
|
|
70
|
+
}
|
|
71
|
+
const next = protectNativeCompactionResult(value, { scope, key: loadKey, mappings: () => options.privacy?.responseMappings?.(res) || [] });
|
|
72
|
+
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 }; }
|
|
73
|
+
return next;
|
|
74
|
+
},
|
|
75
|
+
restoreText: text => options.privacy?.restoreResponse(res, { output: [{ type: "message", role: "assistant", content: [{ type: "output_text", text }] }] })?.output[0].content[0].text || text,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function adaptiveResponsesCompaction(options, state) {
|
|
80
|
+
return async (value, callOptions) => {
|
|
81
|
+
const raw = state.modelRegistry?.models, entries = Array.isArray(raw) ? raw : Array.isArray(raw?.data) ? raw.data : [];
|
|
82
|
+
const entry = entries.find(model => model.id === value.model), limits = entry?.protocol_capabilities?.responses?.values || entry?.capability?.values || catalogCapabilities(entry || {});
|
|
83
|
+
const endpoints = state.getCachedModelEndpoints?.(value.model), carriesResponses = !Array.isArray(endpoints) || !endpoints.length || endpoints.some(path => ["/responses", "/v1/responses"].includes(path));
|
|
84
|
+
let summarize;
|
|
85
|
+
const result = await options.compaction.run({ body: value, protocol: "responses", scope: state.context.scope, key: state.context.key, source: state.provider.id, client: "codex",
|
|
86
|
+
nativeKind: state.kind, inputLimit: limits.max_input_tokens || limits.context_window, outputAllowance: value.max_output_tokens || 0,
|
|
87
|
+
native: state.kind === "inline" && !carriesResponses ? undefined : state.native, options: callOptions,
|
|
88
|
+
summarize(text, summaryOptions) {
|
|
89
|
+
if (!summarize) {
|
|
90
|
+
const route = state.provider.route({ model: value.model, input: [], reasoning: value.reasoning }, { requestedModel: value.model, upstreamModel: value.model, forceResponses: state.forceResponses,
|
|
91
|
+
surface: "responses", getCachedModelEndpoints: state.getCachedModelEndpoints });
|
|
92
|
+
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;
|
|
93
|
+
summarize = compactionSummarizer(template, chat ? "chat" : "responses", chat ? state.chat : state.responses);
|
|
94
|
+
}
|
|
95
|
+
return summarize(text, summaryOptions);
|
|
96
|
+
}, restoreText: state.context.restoreText, onActivity: state.onActivity });
|
|
97
|
+
if (result[COMPACTION_USAGE_RECORDED]) state.prepared.compactionUsageRecorded = true;return result;
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
49
101
|
function resolveRequestModel(model, openAIModelEnv, autoReviewModelResolver) {
|
|
50
102
|
const preference = model === CODEX_AUTO_REVIEW_MODEL && typeof autoReviewModelResolver === "function"
|
|
51
103
|
? autoReviewModelResolver() : undefined;
|
|
@@ -221,6 +273,7 @@ export function createResponsesHandler(options) {
|
|
|
221
273
|
const validation = options.validateConversation?.(parsed, req.headers, provider, abort.signal);
|
|
222
274
|
if (validation?.then) await validation;
|
|
223
275
|
observeContextSession(parsed, req.headers, provider);
|
|
276
|
+
const compactionContext = options.compaction ? gatewayCompactionContext(options, provider, res) : null;
|
|
224
277
|
activeDeadline = now() + upstreamTimeoutMs;
|
|
225
278
|
activeTimeoutReason = "responses_prepare_timeout";
|
|
226
279
|
abort.setTimeout(upstreamTimeoutMs, "responses_prepare_timeout");
|
|
@@ -239,7 +292,9 @@ export function createResponsesHandler(options) {
|
|
|
239
292
|
copilotBoundary: false,
|
|
240
293
|
historySnapshot,
|
|
241
294
|
mutate: true,
|
|
295
|
+
resolveCompaction: compactionContext?.resolve,
|
|
242
296
|
}));
|
|
297
|
+
await compactionContext?.importMappings();
|
|
243
298
|
parsed = null;
|
|
244
299
|
assertPrepareActive();
|
|
245
300
|
imagePressureResult = imagePressure?.apply?.(prepared, { assertActive: assertPrepareActive }) || null;
|
|
@@ -260,17 +315,29 @@ export function createResponsesHandler(options) {
|
|
|
260
315
|
}
|
|
261
316
|
}
|
|
262
317
|
if (upstreamModel !== requestedModel) prepared.body.model = upstreamModel;
|
|
318
|
+
const inlineCompacting = options.compaction && prepared.body.input?.at(-1)?.type === "compaction_trigger";
|
|
319
|
+
if (inlineCompacting) {
|
|
320
|
+
const context = currentRequestContext();if (context) { context.purpose = requestPurpose(req.headers["x-ccdx-purpose"], "compaction");context.streamPerformance?.setPurpose(context.purpose); }
|
|
321
|
+
markRequestObservation({ compaction: 1 });
|
|
322
|
+
}
|
|
263
323
|
markResponseModel(upstreamModel, { requestedModel, configuredModel: provider.configuredModels === true });
|
|
264
324
|
markRequestObservation({ context_window_tokens: modelContextWindowTokens(modelRegistry?.models, upstreamModel) });
|
|
265
325
|
const upstreamLog = upstreamModel === requestedModel ? "" : ` upstream_model=${upstreamModel}`;
|
|
266
326
|
console.log(status("info", `responses model=${requestedModel}${upstreamLog} stream=${streaming}`));
|
|
267
|
-
const routePlan = provider.route(prepared.body, { requestedModel, upstreamModel, forceResponses,
|
|
327
|
+
const routePlan = provider.route(prepared.body, { requestedModel, upstreamModel, forceResponses: forceResponses || inlineCompacting,
|
|
268
328
|
surface: "responses", getCachedModelEndpoints: getCachedModelEndpointsFn });
|
|
269
329
|
const selected = applySelectedRoute(prepared, routePlan, { req, env: openAIModelEnv, signal: abort.signal,
|
|
270
330
|
assertActive: assertPrepareActive, reserveHistory: releaseRequest.reserveResponseHistory });
|
|
271
331
|
prepared = selected instanceof Promise ? await selected : selected;
|
|
272
332
|
if (prepared.historyParentId === null) releaseHistorySnapshot();
|
|
273
333
|
provider.applyRequestPolicies(prepared.body);
|
|
334
|
+
if (inlineCompacting) {
|
|
335
|
+
const source = responsesFn;
|
|
336
|
+
responsesFn = adaptiveResponsesCompaction(options, { provider, modelRegistry, prepared, context: compactionContext, kind: "inline", native: source, responses: source,
|
|
337
|
+
chat: chatCompletionsFn, forceResponses, getCachedModelEndpoints: getCachedModelEndpointsFn,
|
|
338
|
+
onActivity() { activeDeadline = Number.POSITIVE_INFINITY;abort.setTimeout(streamIdleTimeoutMs, "compaction_idle_timeout"); } });
|
|
339
|
+
prepared.protectCompactionResult = compactionContext.protect;
|
|
340
|
+
}
|
|
274
341
|
if (options.privacy) {
|
|
275
342
|
prepared.privacyRestore = value => options.privacy.restoreResponse(res, value);
|
|
276
343
|
responsesFn = options.privacy.wrap(responsesFn, { res, protocol: "responses", client: "codex" });
|
|
@@ -529,6 +596,8 @@ export function createResponsesCompactHandler(options) {
|
|
|
529
596
|
releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal }));
|
|
530
597
|
abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
|
|
531
598
|
const parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
|
|
599
|
+
const context = currentRequestContext();if (context) { context.purpose = requestPurpose(req.headers["x-ccdx-purpose"], "compaction");context.streamPerformance?.setPurpose(context.purpose); }
|
|
600
|
+
markRequestObservation({ compaction: 1 });
|
|
532
601
|
observeRequestedModel(parsed);
|
|
533
602
|
markRequestObservation({ max_output_tokens_requested: parsed?.max_output_tokens });
|
|
534
603
|
const selectedProvider = options.resolveProvider?.(parsed, req);
|
|
@@ -542,6 +611,7 @@ export function createResponsesCompactHandler(options) {
|
|
|
542
611
|
const validation = options.validateConversation?.(parsed, req.headers, provider, abort.signal);
|
|
543
612
|
if (validation?.then) await validation;
|
|
544
613
|
observeContextSession(parsed, req.headers, provider);
|
|
614
|
+
const compactionContext = options.compaction ? gatewayCompactionContext(options, provider, res) : null;
|
|
545
615
|
activeDeadline = now() + upstreamTimeoutMs;
|
|
546
616
|
activeTimeoutReason = "responses_prepare_timeout";
|
|
547
617
|
abort.setTimeout(upstreamTimeoutMs, "responses_prepare_timeout");
|
|
@@ -560,7 +630,9 @@ export function createResponsesCompactHandler(options) {
|
|
|
560
630
|
copilotBoundary: false,
|
|
561
631
|
historySnapshot,
|
|
562
632
|
mutate: true,
|
|
633
|
+
resolveCompaction: compactionContext?.resolve,
|
|
563
634
|
}));
|
|
635
|
+
await compactionContext?.importMappings();
|
|
564
636
|
imagePressureResult = imagePressure?.applyRecovery?.(prepared, { assertActive: assertPrepareActive }) || null;
|
|
565
637
|
if (imagePressureResult?.adapted) {
|
|
566
638
|
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 +661,12 @@ export function createResponsesCompactHandler(options) {
|
|
|
589
661
|
prepared = selected instanceof Promise ? await selected : selected;
|
|
590
662
|
releaseHistorySnapshot();
|
|
591
663
|
provider.applyRequestPolicies(prepared.body);
|
|
664
|
+
if (options.compaction) {
|
|
665
|
+
responsesCompactFn = adaptiveResponsesCompaction(options, { provider, modelRegistry, prepared, context: compactionContext, kind: "compact", native: responsesCompactFn,
|
|
666
|
+
responses: responsesFn, chat: chatCompletionsFn, forceResponses, getCachedModelEndpoints: getCachedModelEndpointsFn,
|
|
667
|
+
onActivity() { activeDeadline = Number.POSITIVE_INFINITY;abort.setTimeout(options.streamIdleTimeoutMs || upstreamTimeoutMs, "compaction_idle_timeout"); } });
|
|
668
|
+
prepared.protectCompactionResult = compactionContext.protect;
|
|
669
|
+
}
|
|
592
670
|
if (options.privacy) {
|
|
593
671
|
prepared.privacyRestore = value => options.privacy.restoreResponse(res, value);
|
|
594
672
|
responsesCompactFn = options.privacy.wrap(responsesCompactFn, { res, protocol: "responses", client: "codex" });
|
package/src/responses-proxy.mjs
CHANGED
|
@@ -50,6 +50,7 @@ import {
|
|
|
50
50
|
} from "./stream-performance.mjs";
|
|
51
51
|
import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
|
|
52
52
|
import { recordResponsesUsage } from "./usage-store.mjs";
|
|
53
|
+
import { COMPACTION_USAGE_RECORDED } from "./context-compaction.mjs";
|
|
53
54
|
import { status } from "./status.mjs";
|
|
54
55
|
|
|
55
56
|
const MAX_SSE_BUFFER_BYTES = loadRuntimeConfig().maxSseBufferBytes;
|
|
@@ -130,7 +131,17 @@ function inspectResponseSseEvent(state, eventName, data) {
|
|
|
130
131
|
if (Number.isSafeInteger(event.response.created_at) && event.response.created_at >= 0) state.response.created_at = event.response.created_at;
|
|
131
132
|
if (typeof event.response.model === "string" && event.response.model) state.response.model = event.response.model;
|
|
132
133
|
}
|
|
133
|
-
|
|
134
|
+
let changed = normalizeMessageIds(state, event, eventType);
|
|
135
|
+
if (state.protectCompactionResult) {
|
|
136
|
+
if (event.item?.type === "compaction") {
|
|
137
|
+
const protectedItem = state.protectCompactionResult({ output: [event.item] }).output[0];
|
|
138
|
+
if (protectedItem !== event.item) { event.item = protectedItem;changed = true; }
|
|
139
|
+
}
|
|
140
|
+
if (Array.isArray(event.response?.output)) {
|
|
141
|
+
const protectedResponse = state.protectCompactionResult(event.response);
|
|
142
|
+
if (protectedResponse !== event.response) { event.response = protectedResponse;changed = true; }
|
|
143
|
+
}
|
|
144
|
+
}
|
|
134
145
|
const outputTokens = event.response?.usage?.output_tokens ?? event.usage?.output_tokens;
|
|
135
146
|
if (outputTokens !== undefined) markOutputTokens(outputTokens);
|
|
136
147
|
const inputTokens = event.response?.usage?.input_tokens ?? event.usage?.input_tokens;
|
|
@@ -400,7 +411,7 @@ function parseSuccessfulResponsesResult(text) {
|
|
|
400
411
|
function storeCompletedResponse(reqContext, completed) {
|
|
401
412
|
if (!completed) return;
|
|
402
413
|
rememberResponseHistory(reqContext, reqContext.privacyRestore?.(completed.response) || completed.response);
|
|
403
|
-
recordResponsesUsage({
|
|
414
|
+
if (!reqContext.compactionUsageRecorded) recordResponsesUsage({
|
|
404
415
|
surface: reqContext.surface,
|
|
405
416
|
mode: "stream",
|
|
406
417
|
model: reqContext.body?.model,
|
|
@@ -501,6 +512,7 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
|
|
|
501
512
|
lastSequence: -1,
|
|
502
513
|
toolArgumentGuard: new ToolArgumentDeltaGuard(),
|
|
503
514
|
messageIds: new Map(),
|
|
515
|
+
protectCompactionResult: reqContext.protectCompactionResult,
|
|
504
516
|
};
|
|
505
517
|
const transformer = createResponseSseTransformer(streamState);
|
|
506
518
|
let holdPrelude = streamRetryEligible;
|
|
@@ -656,12 +668,13 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
|
|
|
656
668
|
label: "Copilot Responses error body",
|
|
657
669
|
});
|
|
658
670
|
if (resp.ok && reqContext.surface === "responses_compact") {
|
|
659
|
-
|
|
671
|
+
let response = parseResponsesCompactionResult(
|
|
660
672
|
compactionInputWithoutTrigger(reqContext.body.input),
|
|
661
673
|
data,
|
|
662
674
|
);
|
|
675
|
+
response = reqContext.protectCompactionResult?.(response) || response;
|
|
663
676
|
rememberResponseHistory(reqContext, reqContext.privacyRestore?.(response) || response);
|
|
664
|
-
recordResponsesUsage({
|
|
677
|
+
if (!resp[COMPACTION_USAGE_RECORDED]) recordResponsesUsage({
|
|
665
678
|
surface: reqContext.surface,
|
|
666
679
|
mode: "json",
|
|
667
680
|
model: reqContext.body?.model,
|
|
@@ -710,7 +723,7 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
|
|
|
710
723
|
}
|
|
711
724
|
}
|
|
712
725
|
rememberResponseHistory(reqContext, reqContext.privacyRestore?.(response) || response);
|
|
713
|
-
recordResponsesUsage({
|
|
726
|
+
if (!reqContext.compactionUsageRecorded) recordResponsesUsage({
|
|
714
727
|
surface: reqContext.surface,
|
|
715
728
|
mode: "json",
|
|
716
729
|
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
|
|