codex-copilot-dx 1.2.21 → 1.2.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -7
- package/bin/cli.mjs +77 -14
- package/docs/ARCHITECTURE.md +94 -3
- package/docs/REFERENCE.md +142 -6
- package/package.json +2 -1
- package/src/account-tools.mjs +1 -1
- package/src/adapter.mjs +23 -6
- package/src/api-catalog-refresh.mjs +6 -2
- package/src/api-secrets.mjs +28 -9
- package/src/auth.mjs +2 -0
- package/src/bounded-result-cache.mjs +12 -0
- package/src/claude-gateway.mjs +19 -3
- package/src/cli-status.mjs +2 -2
- package/src/client-gateway-keys.mjs +7 -3
- package/src/client-integration.mjs +3 -0
- package/src/connection-runtime.mjs +25 -6
- package/src/conversation-source-guard.mjs +3 -1
- package/src/dashboard/console.js +12 -2
- package/src/dashboard/flow.js +62 -33
- package/src/dashboard/index.html +8 -0
- package/src/dashboard/language.js +47 -0
- package/src/dashboard/status.js +29 -8
- package/src/dashboard/ui.css +18 -2
- package/src/dashboard/ui.js +4 -4
- package/src/dashboard/view-boundary.js +41 -0
- package/src/dashboard-tools.mjs +1 -0
- package/src/dashboard.mjs +26 -5
- package/src/image-mcp.mjs +3 -0
- package/src/image-references.mjs +9 -0
- package/src/local-tools.mjs +1 -1
- package/src/m365-settings.mjs +5 -0
- package/src/nightly-update.mjs +107 -0
- package/src/optional-routes.mjs +19 -5
- package/src/provider-runtime.mjs +3 -2
- package/src/providers/api-token-count.mjs +61 -0
- package/src/providers/api.mjs +17 -7
- package/src/release-install.mjs +24 -12
- package/src/request-context.mjs +8 -0
- package/src/response-failures.mjs +25 -5
- package/src/response-history.mjs +50 -0
- package/src/responses-handler.mjs +3 -0
- package/src/service-control.mjs +9 -3
- package/src/service-supervisor.mjs +168 -0
- package/src/service-worker.mjs +87 -0
- package/src/stream-performance.mjs +3 -1
- package/src/terminal-console.mjs +1 -0
- package/src/user-settings.mjs +15 -0
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { execFile } from 'node:child_process';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
import { inspectPackageUpdateEnvironment } from './package-update.mjs';
|
|
7
|
+
import { downloadRelease, createNpmReleaseFetch, protectInstallation, stableVersion, writePrivateLaunchers, privateUnixLauncher } from './release-install.mjs';
|
|
8
|
+
import { inspectWindowsCommand } from './windows-command.mjs';
|
|
9
|
+
import { isVersionGreater } from './version.mjs';
|
|
10
|
+
import { readBoundedResponseText } from './upstream-body.mjs';
|
|
11
|
+
import { readBoundedFileSync } from './bounded-file.mjs';
|
|
12
|
+
|
|
13
|
+
const run = promisify(execFile);
|
|
14
|
+
export const NIGHTLY_IDLE_MS = 10 * 60 * 1000;
|
|
15
|
+
export function nightlyWindow(now) { return now.getHours() < 4; }
|
|
16
|
+
export function nightlyDay(now) { return `${now.getFullYear()}-${now.getMonth()+1}-${now.getDate()}`; }
|
|
17
|
+
export function eligiblePatch(current, release, now = Date.now()) {
|
|
18
|
+
const version = stableVersion(release?.version), before = stableVersion(current), published = Date.parse(release?.published_at);
|
|
19
|
+
return Boolean(before && version && isVersionGreater(version, before) && version.split('.').slice(0,2).join('.') === before.split('.').slice(0,2).join('.')
|
|
20
|
+
&& Number.isFinite(published) && now - published >= 24 * 60 * 60 * 1000);
|
|
21
|
+
}
|
|
22
|
+
export function installedUpdateEnvironment(options = {}) {
|
|
23
|
+
const environment = inspectPackageUpdateEnvironment(options);
|
|
24
|
+
if (environment.state !== 'matched') throw new Error('installation_not_owned');
|
|
25
|
+
fs.accessSync(path.dirname(environment.target), fs.constants.W_OK);
|
|
26
|
+
const windows = (options.platform || process.platform) === 'win32';
|
|
27
|
+
const cli = windows ? path.win32.join(path.win32.dirname(environment.npm), 'node_modules/npm/bin/npm-cli.js') : fs.realpathSync(environment.npm);
|
|
28
|
+
if (!fs.statSync(cli).isFile()) throw new Error('npm_unavailable');
|
|
29
|
+
if (windows) {
|
|
30
|
+
if (inspectWindowsCommand({ packageRoot: environment.target }).status !== 'ready') throw new Error('command_not_owned');
|
|
31
|
+
} else {
|
|
32
|
+
const privateInstall = options.env?.CCDX_PRIVATE_INSTALL_PREFIX || process.env.CCDX_PRIVATE_INSTALL_PREFIX;
|
|
33
|
+
for (const name of ['ccdx','codex-copilot-dx']) {
|
|
34
|
+
const file = path.join(environment.prefix,'bin',name);
|
|
35
|
+
if (privateInstall && path.resolve(privateInstall) === path.resolve(environment.prefix)) {
|
|
36
|
+
if (readBoundedFileSync(file,{encoding:'utf8',maxBytes:16384}) !== privateUnixLauncher({...environment,name})) throw new Error('command_not_owned');
|
|
37
|
+
} else if (fs.realpathSync(file) !== fs.realpathSync(path.join(environment.target,'bin',name === 'ccdx' ? 'cli.mjs' : 'codex-copilot-dx.mjs'))) throw new Error('command_not_owned');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return { ...environment, npmCli: cli };
|
|
41
|
+
}
|
|
42
|
+
export async function lookupNightlyRelease(fetchImpl, { signal } = {}) {
|
|
43
|
+
const response = await fetchImpl('https://api.github.com/repos/DaleXiao/codex-copilot-dx/releases/latest', {
|
|
44
|
+
signal: AbortSignal.any([signal || new AbortController().signal, AbortSignal.timeout(10000)]), redirect:'error',
|
|
45
|
+
headers:{Accept:'application/vnd.github+json','User-Agent':'codex-copilot-dx'},
|
|
46
|
+
});
|
|
47
|
+
if (!response.ok) { await response.body?.cancel();throw new Error('release_unavailable'); }
|
|
48
|
+
const value = JSON.parse(await readBoundedResponseText(response,{maxBytes:128*1024,signal,label:'Release metadata'}));
|
|
49
|
+
const version = stableVersion(value.tag_name);
|
|
50
|
+
if (!version || value.draft !== false || value.prerelease !== false || !Number.isFinite(Date.parse(value.published_at))) throw new Error('release_invalid');
|
|
51
|
+
return {version,published_at:value.published_at};
|
|
52
|
+
}
|
|
53
|
+
export async function verifyNightlyRuntime(target, version, { signal, brokerRequired = false } = {}) {
|
|
54
|
+
const program = `const {createRequire}=require('node:module');const r=createRequire(${JSON.stringify(path.join(target,'package.json'))});const p=r('./package.json');if(p.name!=='codex-copilot-dx'||p.version!==${JSON.stringify(version)})throw Error('version');r('sharp')({create:{width:1,height:1,channels:3,background:'white'}}).png().toBuffer().then(()=>{${brokerRequired?"if(!r('@azure/msal-node-runtime').msalNodeRuntime)throw Error('broker');":''}}).catch(()=>process.exitCode=1);`;
|
|
55
|
+
await run(process.execPath,['-e',program],{signal,timeout:30000,maxBuffer:65536,windowsHide:true});
|
|
56
|
+
const {stdout}=await run(process.execPath,[path.join(target,'bin/cli.mjs'),'version'],{signal,timeout:15000,maxBuffer:65536,windowsHide:true});
|
|
57
|
+
if (!stdout.includes(`ccdx v${version} `)) throw new Error('command_version_invalid');
|
|
58
|
+
}
|
|
59
|
+
export function nightlyRuntimeRoot({home=os.homedir()}={}) { return path.join(home,'.local/share/codex-copilot-dx/runtime'); }
|
|
60
|
+
export async function prepareNightlyRelease(release, { environment, root=nightlyRuntimeRoot(), env=process.env, signal,
|
|
61
|
+
fetchImpl=createNpmReleaseFetch(environment.npmCli,{env}), execute=run, verify=verifyNightlyRuntime }={}) {
|
|
62
|
+
const version=stableVersion(release?.version);if(!version)throw new Error('release_invalid');
|
|
63
|
+
fs.mkdirSync(root,{recursive:true,mode:0o700});const directory=fs.mkdtempSync(path.join(root,'candidate-'));
|
|
64
|
+
const target=path.join(directory,...(process.platform==='win32'?[]:['lib']),'node_modules/codex-copilot-dx');
|
|
65
|
+
const brokerRequired=fs.existsSync(path.join(environment.target,'node_modules/@azure/msal-node-runtime'));
|
|
66
|
+
try {
|
|
67
|
+
const artifact=await downloadRelease(version,{directory,fetchImpl,signal});
|
|
68
|
+
const args=['install','--global','--ignore-scripts','--no-audit','--no-fund'];
|
|
69
|
+
await execute(process.execPath,[environment.npmCli,...args,'--prefix',directory,artifact.file],{env,signal,timeout:300000,maxBuffer:128*1024,windowsHide:true});
|
|
70
|
+
await verify(target,version,{signal,brokerRequired});
|
|
71
|
+
return { version, target, directory,
|
|
72
|
+
async install() {
|
|
73
|
+
signal?.throwIfAborted();const transaction=protectInstallation(environment);
|
|
74
|
+
try {
|
|
75
|
+
await execute(process.execPath,[environment.npmCli,...args,'--prefix',environment.prefix,artifact.file],{env,signal,timeout:300000,maxBuffer:128*1024,windowsHide:true});
|
|
76
|
+
await verify(environment.target,version,{signal,brokerRequired});
|
|
77
|
+
const normalize=value=>process.platform==='win32'?path.resolve(value).toLowerCase():path.resolve(value);
|
|
78
|
+
if(env.CCDX_PRIVATE_INSTALL_PREFIX&&normalize(env.CCDX_PRIVATE_INSTALL_PREFIX)===normalize(environment.prefix))await writePrivateLaunchers(environment);
|
|
79
|
+
if (process.platform==='win32') {
|
|
80
|
+
const {inspectWindowsCommand}=await import(new URL('./windows-command.mjs',import.meta.url));
|
|
81
|
+
if(inspectWindowsCommand({packageRoot:environment.target,repair:true}).status!=='ready')throw new Error('command_setup_failed');
|
|
82
|
+
}
|
|
83
|
+
return transaction;
|
|
84
|
+
}catch(error){transaction.rollback();throw error;}
|
|
85
|
+
},
|
|
86
|
+
cleanup(){fs.rmSync(directory,{recursive:true,force:true});},
|
|
87
|
+
};
|
|
88
|
+
}catch(error){fs.rmSync(directory,{recursive:true,force:true});throw error;}
|
|
89
|
+
}
|
|
90
|
+
// The foreground supervisor keeps its workers on immutable package trees, so a
|
|
91
|
+
// global npm install cannot replace modules under an in-flight request.
|
|
92
|
+
export function retainCurrentRuntime(environment,{root=nightlyRuntimeRoot(),copy=fs.cpSync}={}) {
|
|
93
|
+
fs.mkdirSync(root,{recursive:true,mode:0o700});const directory=fs.mkdtempSync(path.join(root,'current-'));
|
|
94
|
+
const target=path.join(directory,'codex-copilot-dx');
|
|
95
|
+
try {copy(environment.package_root,target,{recursive:true,verbatimSymlinks:true,mode:fs.constants.COPYFILE_FICLONE});return {target,directory,cleanup(){fs.rmSync(directory,{recursive:true,force:true});}};}
|
|
96
|
+
catch(error){fs.rmSync(directory,{recursive:true,force:true});throw error;}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function readNightlyState(file) {
|
|
100
|
+
try {
|
|
101
|
+
const value=JSON.parse(readBoundedFileSync(file,{encoding:'utf8',maxBytes:8192}));
|
|
102
|
+
if(!value||typeof value!=='object'||Array.isArray(value)||Object.keys(value).some(key=>!['attempted_day','paused_version'].includes(key))
|
|
103
|
+
||value.attempted_day!==null&&!/^\d{4}-\d{1,2}-\d{1,2}$/.test(value.attempted_day||'')
|
|
104
|
+
||value.paused_version!==null&&!stableVersion(value.paused_version))throw new Error('invalid_update_state');
|
|
105
|
+
return value;
|
|
106
|
+
}catch(error){if(error.code==='ENOENT')return {attempted_day:null,paused_version:null};throw error;}
|
|
107
|
+
}
|
package/src/optional-routes.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/time.js", "/animation.js", "/status.js", "/activity.js", "/flow.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js", "/connections.js"]);
|
|
1
|
+
export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/time.js", "/animation.js", "/status.js", "/view-boundary.js", "/activity.js", "/flow.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js", "/connections.js"]);
|
|
2
2
|
export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks", "/_ccdx/ui/connections"]);
|
|
3
3
|
|
|
4
4
|
export function isOptionalRoute(method, pathname) {
|
|
@@ -11,29 +11,43 @@ export function isOptionalRoute(method, pathname) {
|
|
|
11
11
|
export function createOptionalRoutes(options = {}) {
|
|
12
12
|
let imageMcpHandler = options.imageMcpHandler || null;
|
|
13
13
|
let tools = null;
|
|
14
|
+
let pending = 0;
|
|
14
15
|
return {
|
|
15
16
|
dispose() { tools?.dispose(); },
|
|
17
|
+
busy: () => pending > 0 || tools?.busy?.() === true,
|
|
18
|
+
exportState() { const images = imageMcpHandler?.exportState?.() || [];return { images, bytes: (imageMcpHandler?.referenceBytes?.() || 0) + images.length * 64 }; },
|
|
19
|
+
async importState(state) {
|
|
20
|
+
if (!state || !Array.isArray(state.images)) throw new Error("Invalid optional-service handoff");
|
|
21
|
+
if (state.images.length) {
|
|
22
|
+
const { createImageMcpHandler } = await import("./image-mcp.mjs");
|
|
23
|
+
imageMcpHandler ||= createImageMcpHandler({ localHostname: options.imageMcpHostname });
|
|
24
|
+
imageMcpHandler.importState(state.images);
|
|
25
|
+
}
|
|
26
|
+
},
|
|
16
27
|
imageStats() { return imageMcpHandler?.stats?.(); },
|
|
17
28
|
async handle(req, res, pathname) {
|
|
29
|
+
pending++;
|
|
30
|
+
try {
|
|
18
31
|
if (DASHBOARD_API_PATHS.has(pathname)) {
|
|
19
32
|
const { handleDashboardApi } = await import("./dashboard-api.mjs");
|
|
20
33
|
if (["/_ccdx/ui/account", "/_ccdx/ui/checks"].includes(pathname)) {
|
|
21
34
|
const { createDashboardTools } = await import("./dashboard-tools.mjs");
|
|
22
35
|
tools ||= createDashboardTools(options.dashboardOptions);
|
|
23
36
|
}
|
|
24
|
-
return handleDashboardApi(req, res, pathname, { ...options.dashboardOptions, tools });
|
|
37
|
+
return await handleDashboardApi(req, res, pathname, { ...options.dashboardOptions, tools });
|
|
25
38
|
}
|
|
26
39
|
if ((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname)) {
|
|
27
40
|
const { serveDashboard } = await import("./dashboard.mjs");
|
|
28
|
-
return serveDashboard(req, res, pathname);
|
|
41
|
+
return await serveDashboard(req, res, pathname);
|
|
29
42
|
}
|
|
30
43
|
if (pathname === "/mcp/image") {
|
|
31
|
-
if (imageMcpHandler) return imageMcpHandler(req, res);
|
|
32
|
-
return import("./image-mcp.mjs").then(({ createImageMcpHandler }) => {
|
|
44
|
+
if (imageMcpHandler) return await imageMcpHandler(req, res);
|
|
45
|
+
return await import("./image-mcp.mjs").then(({ createImageMcpHandler }) => {
|
|
33
46
|
imageMcpHandler ||= createImageMcpHandler({ localHostname: options.imageMcpHostname });
|
|
34
47
|
return imageMcpHandler(req, res);
|
|
35
48
|
});
|
|
36
49
|
}
|
|
50
|
+
} finally { pending--; }
|
|
37
51
|
},
|
|
38
52
|
};
|
|
39
53
|
}
|
package/src/provider-runtime.mjs
CHANGED
|
@@ -34,7 +34,7 @@ export function createProviderRuntime(options = {}) {
|
|
|
34
34
|
|
|
35
35
|
function createBuiltinProviderRuntime({ githubClient, githubRegistry, githubCredentialFingerprint = "", githubClientConfigured = true, home, env = process.env, platform = process.platform,
|
|
36
36
|
corePort = Number(env.ADAPTER_PORT || 2026), log = () => {}, createM365, startGateway, configureClients, restoreClients,
|
|
37
|
-
discoverM365 = requestM365Accounts, managedClaude, onClaudeReady } = {}) {
|
|
37
|
+
discoverM365 = requestM365Accounts, managedClaude, onClaudeReady, preserveClientConfiguration } = {}) {
|
|
38
38
|
const options = { home, env, platform }, github = { ...createGithubProvider({ client: githubClient,
|
|
39
39
|
profileId: () => { const value = typeof githubCredentialFingerprint === "function" ? githubCredentialFingerprint() : githubCredentialFingerprint;
|
|
40
40
|
return value ? `codex:${value}` : "codex"; } }), registry: githubRegistry };
|
|
@@ -56,6 +56,7 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
56
56
|
catch { enabled = false;reason = "m365_config_invalid"; }
|
|
57
57
|
|
|
58
58
|
async function syncClaudeClients() {
|
|
59
|
+
if (preserveClientConfiguration?.()) return;
|
|
59
60
|
if (managedClaude?.()) { await onClaudeReady?.();return; }
|
|
60
61
|
const source = m365, profile = source?.profileId();
|
|
61
62
|
if (!source || !gateway || closed || !enabled) return;
|
|
@@ -82,7 +83,7 @@ function createBuiltinProviderRuntime({ githubClient, githubRegistry, githubCred
|
|
|
82
83
|
const claudeModels = m365.models("claude");
|
|
83
84
|
claudeReason = !claudeModels.length ? "m365_no_claude_models" : null;
|
|
84
85
|
if (claudeModels.length && !claudeReason) try {
|
|
85
|
-
const apiKey = ensureM365GatewayKey(options);
|
|
86
|
+
const apiKey = ensureM365GatewayKey({ ...options, create: !preserveClientConfiguration?.() });
|
|
86
87
|
if (!gateway) {
|
|
87
88
|
const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
|
|
88
89
|
const opened = await start({ provider: m365, apiKey, port: corePort, env, log, performance: claudePerformance,
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { createAbortAwareSingleflight } from "../bounded-result-cache.mjs";
|
|
3
|
+
import { readBoundedResponseText } from "../http-transport.mjs";
|
|
4
|
+
|
|
5
|
+
// Owned by one immutable API/key configuration. No conversation or credential
|
|
6
|
+
// is cached; only small response envelopes and bounded in-flight hashes exist.
|
|
7
|
+
export function createApiTokenCounter({ request, now = Date.now }) {
|
|
8
|
+
const flights = new Map(), unavailable = new Map(), shared = createAbortAwareSingleflight();
|
|
9
|
+
let bytes = 0;
|
|
10
|
+
const missed = () => new Response(JSON.stringify({ type: "error", error: { type: "api_error",
|
|
11
|
+
code: "ccdx_api_count_tokens_unavailable", message: "This source's token-count endpoint returned HTTP 404. Message generation is separate." } }),
|
|
12
|
+
{ status: 404, headers: { "Content-Type": "application/json" } });
|
|
13
|
+
return {
|
|
14
|
+
async count(body, options = {}) {
|
|
15
|
+
if (options.signal?.aborted) throw options.signal.reason;
|
|
16
|
+
const headers = Object.fromEntries(["anthropic-version", "anthropic-beta"].map(name => [name, options.headers?.[name] || ""]));
|
|
17
|
+
const scope = createHash("sha256").update(JSON.stringify([body.model, headers])).digest("hex");
|
|
18
|
+
const at = now(), seen = unavailable.get(scope);
|
|
19
|
+
if (seen !== undefined && at >= seen && at - seen < 60000) { options.onCountObservation?.({ cached: true });return missed(); }
|
|
20
|
+
unavailable.delete(scope);
|
|
21
|
+
const serialized = JSON.stringify(body), size = Buffer.byteLength(serialized);
|
|
22
|
+
const key = size <= 1024 * 1024 ? createHash("sha256").update(scope).update(serialized).digest("hex") : null;
|
|
23
|
+
const waiter = { start: options.onUpstreamStart, observe: options.onCountObservation, signal: options.signal };
|
|
24
|
+
let flight = flights.get(key);
|
|
25
|
+
if (flight && [...flight.waiters].every(item => item.signal?.aborted)) {
|
|
26
|
+
flights.delete(key);bytes -= size;flight = null;
|
|
27
|
+
}
|
|
28
|
+
const joinable = Boolean(flight) || size <= 1024 * 1024 && flights.size < 16 && bytes + size <= 4 * 1024 * 1024;
|
|
29
|
+
if (!flight) {
|
|
30
|
+
flight = { key: {}, waiters: new Set(), started: false, shared: false };
|
|
31
|
+
if (joinable) { flights.set(key, flight);bytes += size; }
|
|
32
|
+
} else flight.shared = true;
|
|
33
|
+
flight.waiters.add(waiter);
|
|
34
|
+
const start = item => { item.start?.();item.observe?.({ upstream: true, shared: flight.shared }); };
|
|
35
|
+
if (flight.started) start(waiter);
|
|
36
|
+
const run = async signal => {
|
|
37
|
+
try {
|
|
38
|
+
if (signal?.aborted) throw signal.reason;
|
|
39
|
+
const response = await request(body, { ...options, bodyText: serialized, signal, observeUpstream: false,
|
|
40
|
+
onUpstreamStart() { flight.started = true;for (const item of flight.waiters) start(item); } });
|
|
41
|
+
if (signal?.aborted) { await response.body?.cancel();throw signal.reason; }
|
|
42
|
+
if (response.status === 404) {
|
|
43
|
+
await response.body?.cancel();unavailable.set(scope, now());
|
|
44
|
+
while (unavailable.size > 128) unavailable.delete(unavailable.keys().next().value);
|
|
45
|
+
const result = missed();return { status: result.status, headers: [...result.headers], text: await result.text() };
|
|
46
|
+
}
|
|
47
|
+
const text = await readBoundedResponseText(response, { maxBytes: 64 * 1024, label: "API token count", signal });
|
|
48
|
+
return { status: response.status, headers: [...response.headers], text };
|
|
49
|
+
} finally { if (joinable && flights.get(key) === flight) { flights.delete(key);bytes -= size; } }
|
|
50
|
+
};
|
|
51
|
+
try {
|
|
52
|
+
const result = joinable ? await shared.run(flight.key, run, { signal: options.signal }) : await run(options.signal);
|
|
53
|
+
options.onCountObservation?.({ shared: flight.shared });
|
|
54
|
+
return new Response(result.text || null, { status: result.status, headers: result.headers });
|
|
55
|
+
} finally {
|
|
56
|
+
flight.waiters.delete(waiter);
|
|
57
|
+
if (!flight.waiters.size && joinable && flights.get(key) === flight) { flights.delete(key);bytes -= size; }
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
package/src/providers/api.mjs
CHANGED
|
@@ -12,7 +12,9 @@ import { checkedApiKey } from "../api-secrets.mjs";
|
|
|
12
12
|
import { transportErrorDetails } from "../operation-error.mjs";
|
|
13
13
|
import { resolveModelCapabilities, deploymentRevision, constrainModelRequest } from "../model-capabilities.mjs";
|
|
14
14
|
import { apiModelMetadata } from "./api-model-metadata.mjs";
|
|
15
|
-
import { markRequestObservation } from "../stream-performance.mjs";
|
|
15
|
+
import { markRequestObservation, markUpstreamStarted } from "../stream-performance.mjs";
|
|
16
|
+
import { createAbortAwareSingleflight } from "../bounded-result-cache.mjs";
|
|
17
|
+
import { createApiTokenCounter } from "./api-token-count.mjs";
|
|
16
18
|
|
|
17
19
|
const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
|
|
18
20
|
export function apiCatalog(config, env = process.env) {
|
|
@@ -33,7 +35,8 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
33
35
|
const modelsUrl = config.base_url.replace(/\/+$/, "") + "/models", targets = [...Object.values(config.endpoints), modelsUrl];
|
|
34
36
|
if (config.endpoints.messages) targets.push(config.endpoints.messages.replace(/\/+$/, "") + "/count_tokens");
|
|
35
37
|
if (config.endpoints.responses) targets.push(config.endpoints.responses.replace(/\/+$/, "") + "/compact");
|
|
36
|
-
let network,
|
|
38
|
+
let network, closed = false;
|
|
39
|
+
const initialization = createAbortAwareSingleflight(), lifetime = new AbortController();
|
|
37
40
|
const retiring = new Set();
|
|
38
41
|
const registry = { models: { data: catalog.filter(model => model.supported_endpoints.includes(paths.responses)) }, source: "configured", generation };
|
|
39
42
|
const getNetwork = async signal => {
|
|
@@ -44,8 +47,8 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
44
47
|
retiring.add(previous);
|
|
45
48
|
void Promise.resolve(previous.retire()).then(() => retiring.delete(previous), () => { previous.close();retiring.delete(previous); });
|
|
46
49
|
} else previous?.close();
|
|
47
|
-
|
|
48
|
-
|
|
50
|
+
return initialization.run("network", sharedSignal => networkFactory({ targets, env, platform, signal: AbortSignal.any([sharedSignal, lifetime.signal]) })
|
|
51
|
+
.then(value => { if (closed || sharedSignal.aborted) { value.close();throw accessError("ccdx_api_closed", 503); }network = value;return value; }), { signal });
|
|
49
52
|
};
|
|
50
53
|
const selected = (id, api) => {
|
|
51
54
|
const model = api === "messages" ? resolveClaudeModel(catalog, id) : catalog.find(model => model.id === id);
|
|
@@ -69,6 +72,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
69
72
|
const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
|
|
70
73
|
if (serialized !== undefined) headers["Content-Length"] = String(Buffer.byteLength(serialized));
|
|
71
74
|
options.onUpstreamStart?.();
|
|
75
|
+
if (body && options.observeUpstream !== false) markUpstreamStarted(body.stream === true);
|
|
72
76
|
try {
|
|
73
77
|
const result = await transport.fetch(url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal });
|
|
74
78
|
if (result.status >= 300 && result.status < 400) { await result.body?.cancel();throw accessError("ccdx_api_redirect_refused", 502); }
|
|
@@ -89,6 +93,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
89
93
|
throw failure;
|
|
90
94
|
}
|
|
91
95
|
}
|
|
96
|
+
const counter = createApiTokenCounter({ request: (body, options) => request(config.endpoints.messages.replace(/\/+$/, "") + "/count_tokens", body, options, "messages") });
|
|
92
97
|
const client = {
|
|
93
98
|
listModels: async () => ({ status: 200, body: JSON.stringify(registry.models) }),
|
|
94
99
|
getCachedModelEndpoints: id => catalog.find(model => model.id === id)?.supported_endpoints || null,
|
|
@@ -104,7 +109,8 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
104
109
|
chatCompletions(body, options = {}) { selected(body.model, "chat");return request(config.endpoints.chat, body, options, "chat"); },
|
|
105
110
|
messages(body, options = {}) {
|
|
106
111
|
const model = selected(body.model, "messages");
|
|
107
|
-
|
|
112
|
+
const outgoing = model.id === body.model ? body : { ...body, model: model.id };
|
|
113
|
+
return options.countTokens ? counter.count(outgoing, options) : request(config.endpoints.messages, outgoing, options, "messages");
|
|
108
114
|
},
|
|
109
115
|
};
|
|
110
116
|
return {
|
|
@@ -120,7 +126,11 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
120
126
|
const models = [], ids = new Set(), checked_at = new Date().toISOString();let url = modelsUrl, bytes = 0;
|
|
121
127
|
for (let page = 0; page < 25; page++) {
|
|
122
128
|
const response = await request(url, undefined, { signal }, config.endpoints.responses ? "responses" : "messages");
|
|
123
|
-
if (!response.ok) {
|
|
129
|
+
if (!response.ok) {
|
|
130
|
+
await response.body?.cancel();const error = accessError(`ccdx_api_catalog_http_${response.status}`, response.status === 401 || response.status === 403 ? response.status : 502);
|
|
131
|
+
const retry = response.headers.get("retry-after"), delay = /^\d{1,8}$/.test(retry || "") ? Number(retry) * 1000 : Date.parse(retry) - Date.now();
|
|
132
|
+
if (Number.isFinite(delay) && delay > 0) error.retryAfterMs = Math.min(delay, 86400000);throw error;
|
|
133
|
+
}
|
|
124
134
|
const text = await readBoundedResponseText(response, { maxBytes: MAX_UPSTREAM_MODEL_CATALOG_BYTES - bytes, label: "API model catalog", signal });bytes += Buffer.byteLength(text);
|
|
125
135
|
let value;try { value = JSON.parse(text); } catch { throw accessError("ccdx_api_catalog_invalid", 502); }
|
|
126
136
|
if (!Array.isArray(value.data) || models.length + value.data.length > 500) throw accessError("ccdx_api_catalog_invalid", 502);
|
|
@@ -147,6 +157,6 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
147
157
|
if (!resp.ok) { await resp.body?.cancel();const code = `ccdx_api_http_${resp.status}`;return { resp: new Response(JSON.stringify({ error: { code, message: code } }), { status: resp.status, headers: { "Content-Type": "application/json" } }), reqContext: context, errorText: code, usedRetryPolicies: new Set() }; }
|
|
148
158
|
return { resp, reqContext: context, errorText: undefined, usedRetryPolicies: new Set() };
|
|
149
159
|
} },
|
|
150
|
-
close() { closed = true;network?.close();for (const previous of retiring) previous.close();retiring.clear(); },
|
|
160
|
+
close() { closed = true;lifetime.abort();network?.close();for (const previous of retiring) previous.close();retiring.clear(); },
|
|
151
161
|
};
|
|
152
162
|
}
|
package/src/release-install.mjs
CHANGED
|
@@ -47,8 +47,8 @@ export function createNpmReleaseFetch(npmCli, { env = process.env, exec = execFi
|
|
|
47
47
|
}
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
export async function releaseBytes(url, { fetchImpl = fetch, maxBytes, timeoutMs = 60000 } = {}) {
|
|
51
|
-
const response = await fetchImpl(url, { redirect: "follow", signal: AbortSignal.timeout(timeoutMs), headers: { "User-Agent": "codex-copilot-dx", Accept: "application/octet-stream" } });
|
|
50
|
+
export async function releaseBytes(url, { fetchImpl = fetch, maxBytes, timeoutMs = 60000, signal } = {}) {
|
|
51
|
+
const response = await fetchImpl(url, { redirect: "follow", signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs), headers: { "User-Agent": "codex-copilot-dx", Accept: "application/octet-stream" } });
|
|
52
52
|
const final = response.url && new URL(response.url);
|
|
53
53
|
if (!response.ok || final && (final.protocol !== "https:" || !["github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com"].includes(final.hostname))) {
|
|
54
54
|
await response.body?.cancel();throw new Error(`Release download refused (HTTP ${response.status}). Check company proxy, certificates and approved download access. No fallback was attempted.`);
|
|
@@ -85,12 +85,12 @@ export function packageMetadata(bytes) {
|
|
|
85
85
|
if (metadata?.name !== "codex-copilot-dx" || !stableVersion(metadata.version)) throw new Error("Release package identity is invalid");
|
|
86
86
|
return metadata;
|
|
87
87
|
}
|
|
88
|
-
export async function downloadRelease(tag, { fetchImpl = fetch, directory } = {}) {
|
|
88
|
+
export async function downloadRelease(tag, { fetchImpl = fetch, directory, signal } = {}) {
|
|
89
89
|
const version = stableVersion(tag);if (!version) throw new Error("A valid stable GitHub release tag is required");
|
|
90
90
|
const name = `codex-copilot-dx-${version}.tgz`, base = `${RELEASE_BASE}/v${version}`;
|
|
91
|
-
const manifest = await releaseBytes(`${base}/SHA256SUMS`, { fetchImpl, maxBytes: 65536 });
|
|
91
|
+
const manifest = await releaseBytes(`${base}/SHA256SUMS`, { fetchImpl, maxBytes: 65536, signal });
|
|
92
92
|
const expected = releaseChecksum(manifest, name);
|
|
93
|
-
const bytes = await releaseBytes(`${base}/${name}`, { fetchImpl, maxBytes: 16 * 1024 * 1024 });
|
|
93
|
+
const bytes = await releaseBytes(`${base}/${name}`, { fetchImpl, maxBytes: 16 * 1024 * 1024, signal });
|
|
94
94
|
if (createHash("sha256").update(bytes).digest("hex") !== expected) throw new Error("Release checksum mismatch; no installation was started");
|
|
95
95
|
if (packageMetadata(bytes).version !== version) throw new Error("Release package version does not match its tag");
|
|
96
96
|
const file = path.join(directory, name);fs.writeFileSync(file, bytes, { flag: "wx", mode: 0o600 });return { file, name, version };
|
|
@@ -109,19 +109,25 @@ export function protectInstallation({ target, prefix, platform = process.platfor
|
|
|
109
109
|
const entries = [target, ...["ccdx", "codex-copilot-dx"].flatMap(name => platform === "win32"
|
|
110
110
|
? [name, `${name}.cmd`, `${name}.ps1`].map(file => path.join(prefix, file)) : [path.join(prefix, "bin", name)])];
|
|
111
111
|
const saved = [];
|
|
112
|
-
const
|
|
112
|
+
const closeLock = () => { if (fd !== undefined) { const handle = fd;fd = undefined;fs.closeSync(handle); } };
|
|
113
|
+
const copyEntry = (from, to) => {
|
|
114
|
+
if (fs.lstatSync(from).isSymbolicLink()) fs.symlinkSync(fs.readlinkSync(from), to);
|
|
115
|
+
else fs.cpSync(from, to, { recursive: true, verbatimSymlinks: true, preserveTimestamps: true });
|
|
116
|
+
};
|
|
117
|
+
const clean = () => { fs.rmSync(backup, { recursive: true, force: true });closeLock();fs.unlinkSync(lock); };
|
|
113
118
|
try {
|
|
114
119
|
entries.forEach((file, index) => {
|
|
115
120
|
let stat;try { stat = fs.lstatSync(file); } catch (error) { if (error.code !== "ENOENT") throw error; }
|
|
116
121
|
if (file === target && stat && (!stat.isDirectory() || stat.isSymbolicLink())) throw new Error("The npm target is linked or not a regular installation; use its owning installer");
|
|
117
122
|
const copy = path.join(backup, String(index));
|
|
118
|
-
if (stat)
|
|
123
|
+
if (stat) copyEntry(file, copy);
|
|
119
124
|
saved.push({ file, copy, existed: Boolean(stat) });
|
|
120
125
|
});
|
|
121
126
|
} catch (error) { clean();throw error; }
|
|
122
127
|
let finalized = false;
|
|
123
128
|
return {
|
|
124
129
|
commit() {
|
|
130
|
+
if (finalized) return;
|
|
125
131
|
finalized = true;
|
|
126
132
|
try { clean(); }
|
|
127
133
|
catch { console.error(`CCDX was installed, but backup cleanup needs attention: ${backup}; check ${lock} before retrying.`); }
|
|
@@ -131,13 +137,15 @@ export function protectInstallation({ target, prefix, platform = process.platfor
|
|
|
131
137
|
try {
|
|
132
138
|
for (const { file, copy, existed } of saved) {
|
|
133
139
|
fs.rmSync(file, { recursive: true, force: true });
|
|
134
|
-
if (existed)
|
|
140
|
+
if (existed) copyEntry(copy, file);
|
|
135
141
|
}
|
|
136
|
-
clean();
|
|
137
142
|
} catch (error) {
|
|
138
|
-
|
|
143
|
+
closeLock();
|
|
139
144
|
throw new Error(`Restore could not finish. Previous package and commands remain at ${backup}; do not delete the install lock until restored.`, { cause: error });
|
|
140
145
|
}
|
|
146
|
+
finalized = true;
|
|
147
|
+
try { clean(); }
|
|
148
|
+
catch { console.error(`Previous CCDX was restored, but backup cleanup needs attention: ${backup}; check ${lock} before retrying.`); }
|
|
141
149
|
},
|
|
142
150
|
};
|
|
143
151
|
}
|
|
@@ -149,8 +157,12 @@ export function verifyPackageRuntime(target, version, { brokerRequired = false }
|
|
|
149
157
|
if (!output.includes(`ccdx v${version} `)) throw new Error("Installed command version could not be verified");
|
|
150
158
|
}
|
|
151
159
|
|
|
152
|
-
export
|
|
160
|
+
export function privateUnixLauncher({ prefix, target, name, node = process.execPath }) {
|
|
153
161
|
const quote = value => "'" + value.replaceAll("'", "'\\''") + "'";
|
|
162
|
+
const cli = path.join(target, "bin", name === "ccdx" ? "cli.mjs" : "codex-copilot-dx.mjs");
|
|
163
|
+
return `#!/bin/sh\nPATH=${quote(path.dirname(node))}:"$PATH"\nexport PATH\nCCDX_PRIVATE_INSTALL_PREFIX=${quote(prefix)}\nexport CCDX_PRIVATE_INSTALL_PREFIX\nif [ -z "\${npm_config_prefix:-}\${NPM_CONFIG_PREFIX:-}" ]; then npm_config_prefix=${quote(prefix)}; export npm_config_prefix; fi\nexec ${quote(node)} ${quote(cli)} "$@"\n`;
|
|
164
|
+
}
|
|
165
|
+
export async function writePrivateLaunchers({ prefix, target }) {
|
|
154
166
|
const windows = process.platform === "win32"
|
|
155
167
|
? await import(pathToFileURL(path.join(target, "src", "windows-command.mjs")).href) : null;
|
|
156
168
|
for (const name of ["ccdx", "codex-copilot-dx"]) {
|
|
@@ -159,7 +171,7 @@ export async function writePrivateLaunchers({ prefix, target }) {
|
|
|
159
171
|
fs.writeFileSync(path.join(prefix, `${name}.cmd`), windows.privateWindowsCommand({ node: process.execPath, cli, prefix }));
|
|
160
172
|
} else {
|
|
161
173
|
const file = path.join(prefix, "bin", name);fs.rmSync(file, { force: true });
|
|
162
|
-
fs.writeFileSync(file,
|
|
174
|
+
fs.writeFileSync(file, privateUnixLauncher({ prefix, target, name }), { mode: 0o755 });
|
|
163
175
|
}
|
|
164
176
|
}
|
|
165
177
|
if (windows && windows.inspectWindowsCommand({ packageRoot: target, repair: true }).status !== "ready") throw new Error("Private Windows commands could not be verified");
|
package/src/request-context.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
3
4
|
|
|
4
5
|
const requestContextStorage = new AsyncLocalStorage();
|
|
5
6
|
|
|
@@ -14,3 +15,10 @@ export function runWithRequestContext(context, callback) {
|
|
|
14
15
|
export function currentRequestContext() {
|
|
15
16
|
return requestContextStorage.getStore() || null;
|
|
16
17
|
}
|
|
18
|
+
|
|
19
|
+
// Capture before route validation; never retain a body or an arbitrary string.
|
|
20
|
+
export function observeRequestedModel(body) {
|
|
21
|
+
const value = body?.model, context = currentRequestContext();
|
|
22
|
+
if (context && typeof value === "string" && /^[\w][\w./:@+-]{0,159}$/.test(value)
|
|
23
|
+
&& redactDiagnosticText(value) === value) { context.requestedModel = value;context.streamPerformance?.setModel?.(value); }
|
|
24
|
+
}
|
|
@@ -138,26 +138,43 @@ export function createHttpFailureDiagnostics({ maxEntries = 20, now } = {}) {
|
|
|
138
138
|
const all = createResponseFailureDiagnostics({ maxEntries, now });
|
|
139
139
|
const actionable = createResponseFailureDiagnostics({ maxEntries, now });
|
|
140
140
|
const protocol = createResponseFailureDiagnostics({ maxEntries: 8, now });
|
|
141
|
-
const
|
|
141
|
+
const capability = createResponseFailureDiagnostics({ maxEntries: 20, now });
|
|
142
|
+
const routes = createResponseFailureDiagnostics({ maxEntries: 8, now });
|
|
143
|
+
const counts = { inference: 0, capability: 0, protocol: 0, route: 0, other: 0 };
|
|
142
144
|
return {
|
|
143
145
|
record(details) {
|
|
144
146
|
all.record(details);
|
|
145
|
-
const category =
|
|
147
|
+
const category = details.route === "messages_count_tokens" ? "capability"
|
|
148
|
+
: ["responses", "responses_compact", "messages"].includes(details.route) ? "inference"
|
|
146
149
|
: details.route === "image_mcp" && details.http_status === 405 ? "protocol"
|
|
147
150
|
: details.route === "not_found" ? "route" : "other";
|
|
148
151
|
counts[category]++;
|
|
149
152
|
if (category === "inference" || category === "other") actionable.record(details);
|
|
153
|
+
if (category === "capability") {
|
|
154
|
+
capability.record(details);
|
|
155
|
+
if (![404, 405, 501].includes(details.http_status)) actionable.record(details);
|
|
156
|
+
}
|
|
150
157
|
if (category === "protocol") protocol.record(details);
|
|
158
|
+
if (category === "route") routes.record(details);
|
|
151
159
|
},
|
|
152
160
|
snapshot() { return { ...all.snapshot(), by_category: { ...counts },
|
|
153
|
-
actionable_recent: actionable.snapshot().recent,
|
|
161
|
+
actionable_recent: actionable.snapshot().recent, capability_recent: capability.snapshot().recent,
|
|
162
|
+
protocol_recent: protocol.snapshot().recent, route_recent: routes.snapshot().recent }; },
|
|
154
163
|
};
|
|
155
164
|
}
|
|
156
165
|
|
|
157
166
|
export function buildHttpFailureDetails({ statusCode, route, requestId, model, code, origin, headers,
|
|
158
|
-
error_body, error_type, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider
|
|
167
|
+
error_body, error_type, parameter, diagnostic_message, method, target, request_options, upstream_attempts, attempt_timings, requested_model, provider,
|
|
168
|
+
application, reason, capability_cached, shared_upstream }) {
|
|
169
|
+
const reasons = { ccdx_model_not_selected: "This model is not selected for this app.",
|
|
170
|
+
ccdx_model_ambiguous: "This model name matches multiple sources. Select its source-specific entry.",
|
|
171
|
+
ccdx_model_catalog_unavailable: "The selected model is not currently available in its source catalog.",
|
|
172
|
+
ccdx_client_source_disabled: "This app or its model source is turned off." };
|
|
173
|
+
const message = (Object.hasOwn(reasons, reason) ? reasons[reason] : null) || (route === "messages_count_tokens" && statusCode === 404 ? "The source's token-count endpoint returned HTTP 404. Message generation is separate."
|
|
174
|
+
: origin === "client_validation" ? "The request was rejected locally before an upstream call."
|
|
175
|
+
: error_body === "empty" ? "Upstream returned no error details." : "HTTP request failed; original response was preserved.");
|
|
159
176
|
const details = responseFailureDetails({ model, error: { code: typeof code === "string" && /^[a-z\d_.:-]{1,80}$/i.test(code) ? code : `http_${statusCode}`,
|
|
160
|
-
message
|
|
177
|
+
message } }, "http.error", { headers, provider });
|
|
161
178
|
return { ...details, request_id: requestId, http_status: statusCode, route,
|
|
162
179
|
origin: origin || (route === "not_found" ? "route" : "unclassified"), local_message: true,
|
|
163
180
|
...(error_body ? { error_body } : {}), ...(error_type ? { error_type } : {}), ...(parameter ? { parameter } : {}),
|
|
@@ -166,5 +183,8 @@ export function buildHttpFailureDetails({ statusCode, route, requestId, model, c
|
|
|
166
183
|
...(request_options ? { request_options } : {}),
|
|
167
184
|
...(attempt_timings ? { attempt_timings } : {}),
|
|
168
185
|
...(requested_model ? { requested_model, request_kind: requested_model === "codex-auto-review" ? "auto_review" : "unknown" } : {}),
|
|
186
|
+
...(["codex_app", "codex_cli", "codex", "claude_app", "claude_code", "claude", "api"].includes(application) ? { application } : {}),
|
|
187
|
+
...(Object.hasOwn(reasons, reason) ? { reason } : {}),
|
|
188
|
+
...(capability_cached === true ? { capability_cached: true } : {}), ...(shared_upstream === true ? { shared_upstream: true } : {}),
|
|
169
189
|
...(Number.isSafeInteger(upstream_attempts) ? { upstream_attempts } : {}) };
|
|
170
190
|
}
|
package/src/response-history.mjs
CHANGED
|
@@ -455,3 +455,53 @@ export function rememberResponseHistoryNode({
|
|
|
455
455
|
touchTree(rootId);
|
|
456
456
|
return true;
|
|
457
457
|
}
|
|
458
|
+
|
|
459
|
+
// Private process handoff only: no HTTP route or plaintext persistence.
|
|
460
|
+
export function exportResponseHistory() {
|
|
461
|
+
if (pinnedTrees.size) throw new Error('Response history is busy');
|
|
462
|
+
let bytes = totalBytes;
|
|
463
|
+
for (const [id, entry] of histories) {
|
|
464
|
+
bytes += Buffer.byteLength(id) + Buffer.byteLength(entry.parentId || '') + Buffer.byteLength(entry.rootId) + 512;
|
|
465
|
+
if (bytes > 64 * 1024 * 1024) throw new Error('state_too_large');
|
|
466
|
+
}
|
|
467
|
+
return { version: 1, bytes, entries: [...histories], roots: [...treeLru.keys()], evicted: [...evictedIds],
|
|
468
|
+
counters: { evictedEntriesTotal, lookupMisses, evictedLookupMisses } };
|
|
469
|
+
}
|
|
470
|
+
export function importResponseHistory(state) {
|
|
471
|
+
if (histories.size || pinnedTrees.size || state?.version !== 1 || !Array.isArray(state.entries) || state.entries.length > maxEntries
|
|
472
|
+
|| !Array.isArray(state.roots) || !Array.isArray(state.evicted) || state.evicted.length > 256) throw new Error('Invalid response-history handoff');
|
|
473
|
+
const restored = new Map();let bytes = 0;
|
|
474
|
+
const idOK = id => typeof id === 'string' && id.length > 0 && id.length <= 2048;
|
|
475
|
+
for (const pair of state.entries) {
|
|
476
|
+
if (!Array.isArray(pair) || pair.length !== 2 || !idOK(pair[0]) || restored.has(pair[0])) throw new Error('Invalid response-history handoff');
|
|
477
|
+
const [id, entry] = pair;
|
|
478
|
+
if (!entry || !Array.isArray(entry.inputItems) || !(entry.outputItems === undefined || Array.isArray(entry.outputItems))
|
|
479
|
+
|| !(entry.parentId === null || idOK(entry.parentId)) || !idOK(entry.rootId) || typeof entry.hasOpaque !== 'boolean'
|
|
480
|
+
|| !(entry.routeAffinity === null || typeof entry.routeAffinity === 'object')) throw new Error('Invalid response-history handoff');
|
|
481
|
+
const owned = structuredClone(entry);
|
|
482
|
+
owned.bytes = jsonByteLength(owned.routeAffinity ? [owned.inputItems, owned.outputItems, { routeAffinity: owned.routeAffinity, hasOpaque: owned.hasOpaque }] : [owned.inputItems, owned.outputItems]);
|
|
483
|
+
bytes += owned.bytes;if (bytes > maxBytes) throw new Error('Response-history handoff exceeds this version\'s limit');
|
|
484
|
+
restored.set(id, owned);
|
|
485
|
+
}
|
|
486
|
+
const roots = new Map();
|
|
487
|
+
for (const [id, entry] of restored) {
|
|
488
|
+
let at = id;const seen = new Set(), chain = [];
|
|
489
|
+
while (!roots.has(at)) {
|
|
490
|
+
if (seen.has(at)) throw new Error('Cyclic response-history handoff');
|
|
491
|
+
seen.add(at);chain.push(at);const current = restored.get(at);
|
|
492
|
+
if (!current) throw new Error('Incomplete response-history handoff');
|
|
493
|
+
if (!current.parentId) { roots.set(at, at);break; }at = current.parentId;
|
|
494
|
+
}
|
|
495
|
+
for (const item of chain) roots.set(item, roots.get(at));
|
|
496
|
+
if (entry.rootId !== roots.get(id)) throw new Error('Invalid response-history root');
|
|
497
|
+
}
|
|
498
|
+
if (state.roots.some(id => !idOK(id) || roots.get(id) !== id) || new Set(state.roots).size !== state.roots.length
|
|
499
|
+
|| state.evicted.some(id => !idOK(id) || restored.has(id))) throw new Error('Invalid response-history handoff');
|
|
500
|
+
for (const [id, entry] of restored) { histories.set(id, entry);linkChild(entry.parentId, id); }
|
|
501
|
+
for (const id of state.roots) touchTree(id);
|
|
502
|
+
for (const [id, root] of roots) if (id === root && !treeLru.has(id)) touchTree(id);
|
|
503
|
+
for (const id of state.evicted) evictedIds.add(id);
|
|
504
|
+
totalBytes = bytes;
|
|
505
|
+
const count = name => Number.isSafeInteger(state.counters?.[name]) && state.counters[name] >= 0 ? state.counters[name] : 0;
|
|
506
|
+
evictedEntriesTotal = count('evictedEntriesTotal');lookupMisses = count('lookupMisses');evictedLookupMisses = count('evictedLookupMisses');
|
|
507
|
+
}
|
|
@@ -30,6 +30,7 @@ import {
|
|
|
30
30
|
responseHistoryPressureRootId,
|
|
31
31
|
} from "./responses-request.mjs";
|
|
32
32
|
import { status } from "./status.mjs";
|
|
33
|
+
import { observeRequestedModel } from "./request-context.mjs";
|
|
33
34
|
import { endStreamWithError } from "./stream-errors.mjs";
|
|
34
35
|
import { createSseKeepalive } from "./sse-keepalive.mjs";
|
|
35
36
|
import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
|
|
@@ -206,6 +207,7 @@ export function createResponsesHandler(options) {
|
|
|
206
207
|
releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal }));
|
|
207
208
|
abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
|
|
208
209
|
parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
|
|
210
|
+
observeRequestedModel(parsed);
|
|
209
211
|
const selectedProvider = options.resolveProvider?.(parsed, req);
|
|
210
212
|
if (selectedProvider) {
|
|
211
213
|
provider = selectedProvider;modelRegistry = provider.registry;
|
|
@@ -489,6 +491,7 @@ export function createResponsesCompactHandler(options) {
|
|
|
489
491
|
releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal }));
|
|
490
492
|
abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
|
|
491
493
|
const parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
|
|
494
|
+
observeRequestedModel(parsed);
|
|
492
495
|
const selectedProvider = options.resolveProvider?.(parsed, req);
|
|
493
496
|
if (selectedProvider) {
|
|
494
497
|
provider = selectedProvider;modelRegistry = provider.registry;
|