codex-copilot-dx 1.3.27 → 1.3.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -1
- package/bin/cli.mjs +4 -1
- package/docs/ARCHITECTURE.md +15 -2
- package/docs/REFERENCE.md +27 -3
- package/package.json +1 -1
- package/src/adapter.mjs +4 -2
- package/src/claude-app-contract.mjs +96 -0
- package/src/claude-capability-config.mjs +26 -10
- package/src/claude-client-config.mjs +56 -7
- package/src/claude-gateway.mjs +7 -5
- package/src/claude-models.mjs +4 -2
- package/src/cli-command-spec.mjs +8 -2
- package/src/cli-management.mjs +26 -6
- package/src/connection-client-sync.mjs +1 -0
- package/src/connection-management.mjs +5 -0
- package/src/connection-policy.mjs +2 -2
- package/src/connection-routing.mjs +2 -1
- package/src/connection-runtime.mjs +26 -2
- package/src/connection-view.mjs +11 -2
- package/src/dashboard/connections.js +33 -3
- package/src/dashboard/index.html +3 -1
- package/src/dashboard/language.js +24 -0
- package/src/dashboard/ui.js +3 -0
- package/src/dashboard-api.mjs +2 -2
- package/src/doctor-compat.mjs +1 -1
- package/src/model-capabilities.mjs +17 -4
- package/src/provider-cooldown.mjs +43 -0
- package/src/providers/api-model-metadata.mjs +7 -0
- package/src/providers/api.mjs +32 -11
- package/src/request-context.mjs +5 -0
- package/src/response-failures.mjs +4 -2
- package/src/safe-upstream-error.mjs +36 -4
- package/src/source-import.mjs +51 -0
- package/src/stream-performance.mjs +7 -5
- package/src/usage-analysis.mjs +2 -2
- package/src/usage-query.mjs +5 -2
- package/src/usage-store.mjs +2 -1
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { accessError } from "./access-settings.mjs";
|
|
2
|
+
|
|
3
|
+
const NETWORK_CODES = new Set(["ECONNREFUSED", "ECONNRESET", "ETIMEDOUT", "EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"]);
|
|
4
|
+
export function confirmedNetworkFailure(error) {
|
|
5
|
+
for (let depth = 0; error && depth < 4; depth++, error = error.cause) if (NETWORK_CODES.has(error.code)) return true;
|
|
6
|
+
return false;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
// One deployment/interface, two confirmed failures, one real recovery request.
|
|
10
|
+
// No paid probes, model switching or retry after output has started.
|
|
11
|
+
export function createProviderCooldown({ now = Date.now, delayMs = 5000 } = {}) {
|
|
12
|
+
let failures = 0, until = 0, recovering = false;
|
|
13
|
+
const snapshot = () => ({ state: until > now() ? "cooling" : recovering ? "recovering" : "ready", retry_after_ms: Math.max(0, until - now()), failures });
|
|
14
|
+
function enter() {
|
|
15
|
+
if (failures < 2) return false;
|
|
16
|
+
if (until > now() || recovering) {
|
|
17
|
+
const error = accessError("ccdx_api_cooling_down", 503);
|
|
18
|
+
error.message = error.jsonBody.error.message = "This source interface is temporarily cooling down after repeated connection failures. Retry shortly.";
|
|
19
|
+
error.retryAfterMs = Math.max(1000, until - now());throw error;
|
|
20
|
+
}
|
|
21
|
+
recovering = true;return true;
|
|
22
|
+
}
|
|
23
|
+
function complete(recovery, failed = false, cancelled = false, retryAfterMs = 0) {
|
|
24
|
+
if (recovery) recovering = false;
|
|
25
|
+
if (cancelled) return;
|
|
26
|
+
if (!failed) { if (failures) { failures = 0;until = 0; }return; }
|
|
27
|
+
failures = Math.min(2, failures + 1);
|
|
28
|
+
if (failures >= 2) until = now() + Math.min(30000, Math.max(delayMs, retryAfterMs));
|
|
29
|
+
}
|
|
30
|
+
return {
|
|
31
|
+
snapshot, enter, complete,
|
|
32
|
+
acquire() {
|
|
33
|
+
const recovery = enter();
|
|
34
|
+
let finished = false;
|
|
35
|
+
return {
|
|
36
|
+
finish({ failed = false, cancelled = false, retryAfterMs = 0 } = {}) {
|
|
37
|
+
if (finished) return;finished = true;
|
|
38
|
+
complete(recovery, failed, cancelled, retryAfterMs);
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -29,6 +29,13 @@ export function apiModelMetadata(model, { deployment, checked_at }) {
|
|
|
29
29
|
delete values.max_input_tokens;
|
|
30
30
|
}
|
|
31
31
|
const protocols = Object.keys(messages).length ? { messages } : {};
|
|
32
|
+
// Parameter lists are protocol scoped. A generic OpenAI list says nothing
|
|
33
|
+
// about a gateway's Messages endpoint.
|
|
34
|
+
for (const protocol of ["messages", "responses", "chat"]) {
|
|
35
|
+
const parameters = caps.protocols?.[protocol]?.supported_parameters;
|
|
36
|
+
if (parameters !== undefined && validCapabilities({ supported_parameters: parameters }))
|
|
37
|
+
protocols[protocol] = { ...protocols[protocol], supported_parameters: parameters };
|
|
38
|
+
}
|
|
32
39
|
const reported = Object.keys(values).length || Object.keys(protocols).length;
|
|
33
40
|
const described = Object.keys(caps).length || ["max_tokens", "max_input_tokens", "max_output_tokens", "context_window", "reasoning_efforts"].some(key => Object.hasOwn(model, key));
|
|
34
41
|
return { values, ...(Object.keys(protocols).length ? { protocols } : {}), deployment, checked_at,
|
package/src/providers/api.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { createRoutePlan } from "../route-plan.mjs";
|
|
3
3
|
import { accessError } from "../access-settings.mjs";
|
|
4
4
|
import { publicModelCatalog } from "../provider-metadata.mjs";
|
|
5
|
-
import {
|
|
5
|
+
import { claudeModelEntries } from "../claude-models.mjs";
|
|
6
6
|
import { prepareResponsesPayload } from "../image-optimization.mjs";
|
|
7
7
|
import { enforceResponsesPayloadByteBudget } from "../responses-byte-budget.mjs";
|
|
8
8
|
import { MAX_UPSTREAM_MODEL_CATALOG_BYTES, MAX_UPSTREAM_ERROR_BODY_BYTES, readBoundedResponseText } from "../http-transport.mjs";
|
|
@@ -20,6 +20,9 @@ import { apiModelDisplay } from "../api-model-display.mjs";
|
|
|
20
20
|
import { adaptCallLessContext, CALL_LESS_TOOL_RETRIED, normalizeCallLessToolOutputs } from "../responses-tool-output.mjs";
|
|
21
21
|
import { adaptMessagesToolSchemas, hasRootToolSchema, MESSAGES_TOOL_GUARD } from "../messages-tool-schema.mjs";
|
|
22
22
|
import { loadRuntimeConfig } from "../runtime-config.mjs";
|
|
23
|
+
import { currentRequestContext } from "../request-context.mjs";
|
|
24
|
+
import { redactDiagnosticText } from "../diagnostic-text.mjs";
|
|
25
|
+
import { createProviderCooldown, confirmedNetworkFailure } from "../provider-cooldown.mjs";
|
|
23
26
|
|
|
24
27
|
const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
|
|
25
28
|
export function apiCatalog(config, env = process.env) {
|
|
@@ -29,7 +32,8 @@ export function apiCatalog(config, env = process.env) {
|
|
|
29
32
|
supported_endpoints: model.protocols.map(api => paths[api]), model_picker_enabled: true, policy: { state: "enabled" },
|
|
30
33
|
capability, protocol_capabilities }); });
|
|
31
34
|
}
|
|
32
|
-
export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork, modelDisplay = () => ({}) } = {}) {
|
|
35
|
+
export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork, modelDisplay = () => ({}), now = Date.now } = {}) {
|
|
36
|
+
const cooldowns = Object.fromEntries(["messages", "responses", "chat"].map(protocol => [protocol, createProviderCooldown({ now })]));
|
|
33
37
|
const catalog = apiCatalog(config, env);
|
|
34
38
|
const fingerprint = config.key_env ? createHash("sha256").update(env[config.key_env] || "").digest("hex") : "";
|
|
35
39
|
const generation = parseInt(createHash("sha256").update(JSON.stringify(config) + fingerprint).digest("hex").slice(0, 8), 16);
|
|
@@ -55,8 +59,10 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
55
59
|
return initialization.run("network", sharedSignal => networkFactory({ targets, env, platform, signal: AbortSignal.any([sharedSignal, lifetime.signal]) })
|
|
56
60
|
.then(value => { if (closed || sharedSignal.aborted) { value.close();throw accessError("ccdx_api_closed", 503); }network = value;return value; }), { signal });
|
|
57
61
|
};
|
|
62
|
+
let messageAliases;
|
|
58
63
|
const selected = (id, api) => {
|
|
59
|
-
|
|
64
|
+
if (api === "messages" && !messageAliases) messageAliases = new Map(claudeModelEntries(catalog).map((entry, index) => [entry.name, catalog[index]]));
|
|
65
|
+
const model = api === "messages" && messageAliases.get(id) || catalog.find(model => model.id === id);
|
|
60
66
|
if (!model?.supported_endpoints.includes(paths[api])) throw accessError("ccdx_api_model_unavailable");return model;
|
|
61
67
|
};
|
|
62
68
|
async function request(url, body, options = {}, api = "responses") {
|
|
@@ -64,7 +70,6 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
64
70
|
if (config.key_env && !env[config.key_env]) throw accessError("ccdx_api_environment_key_missing", 503);
|
|
65
71
|
const key = config.key_env ? checkedApiKey(env[config.key_env]) : await initialization.run("credential", () => secrets.get(config.secret_ref),
|
|
66
72
|
{ signal: options.signal ? AbortSignal.any([options.signal, lifetime.signal]) : lifetime.signal });
|
|
67
|
-
const transport = await getNetwork(options.signal);
|
|
68
73
|
const headers = { "Content-Type": "application/json", Accept: body?.stream ? "text/event-stream" : "application/json" };
|
|
69
74
|
headers[api === "messages" && config.auth_header === "x-api-key" ? "x-api-key" : "Authorization"] = api === "messages" && config.auth_header === "x-api-key" ? key : `Bearer ${key}`;
|
|
70
75
|
if (api === "messages") {
|
|
@@ -80,13 +85,21 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
80
85
|
}
|
|
81
86
|
const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
|
|
82
87
|
if (serialized !== undefined) headers["Content-Length"] = String(Buffer.byteLength(serialized));
|
|
83
|
-
options.
|
|
84
|
-
|
|
85
|
-
markUpstreamStarted(body.stream === true);
|
|
86
|
-
if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: api === "messages" ? body.max_tokens : api === "chat" ? body.max_completion_tokens : body.max_output_tokens });
|
|
87
|
-
}
|
|
88
|
+
const cooldown = body && !options.countTokens ? cooldowns[api] : null;
|
|
89
|
+
const recovery = cooldown?.enter();let observed = false;
|
|
88
90
|
try {
|
|
91
|
+
const transport = !closed && network && (network.healthy?.() ?? true) ? network : await getNetwork(options.signal);
|
|
92
|
+
options.onUpstreamStart?.();
|
|
93
|
+
if (body && options.observeUpstream !== false) {
|
|
94
|
+
markUpstreamStarted(body.stream === true);
|
|
95
|
+
if (!options.countTokens) markRequestObservation({ max_output_tokens_sent: api === "messages" ? body.max_tokens : api === "chat" ? body.max_completion_tokens : body.max_output_tokens,
|
|
96
|
+
reasoning_effort_sent: api === "messages" ? body.output_config?.effort : api === "chat" ? body.reasoning_effort : body.reasoning?.effort });
|
|
97
|
+
}
|
|
89
98
|
const result = await transport.fetch(url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal });
|
|
99
|
+
const temporary = result.status === 502 || result.status === 503 || result.status === 504;
|
|
100
|
+
let retryAfterMs = 0;
|
|
101
|
+
if (temporary) { const retry = result.headers.get("retry-after");retryAfterMs = /^\d{1,8}$/.test(retry || "") ? Number(retry) * 1000 : Math.max(0, Date.parse(retry) - now()); }
|
|
102
|
+
cooldown?.complete(recovery, temporary, false, Number.isFinite(retryAfterMs) ? retryAfterMs : 0);observed = true;
|
|
90
103
|
if (result.status >= 300 && result.status < 400) { await result.body?.cancel();throw accessError("ccdx_api_redirect_refused", 502); }
|
|
91
104
|
if (!result.ok) {
|
|
92
105
|
const adapted = api === "responses" && [400, 422].includes(result.status) && !options.compatibilityRetried && !options.skipCallLessRetry
|
|
@@ -112,13 +125,20 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
112
125
|
if (adapted || schemaCandidate) try { options.onUpstreamErrorHeaders?.(result.status); } catch { /* Preserve the original upstream failure. */ }
|
|
113
126
|
const code = `ccdx_api_http_${result.status}`;
|
|
114
127
|
const safeHeaders = { "Content-Type": "application/json" }, retry = result.headers.get("retry-after");
|
|
128
|
+
for (const name of ["x-request-id", "x-correlation-id", "request-id"]) {
|
|
129
|
+
const value = result.headers.get(name);
|
|
130
|
+
if (value && /^[a-z\d_.:-]{1,80}$/i.test(value) && redactDiagnosticText(value) === value) { safeHeaders["X-Request-Id"] = value;break; }
|
|
131
|
+
}
|
|
115
132
|
if (/^\d{1,8}$/.test(retry || "")) safeHeaders["Retry-After"] = retry;
|
|
116
133
|
else if (retry && Number.isFinite(Date.parse(retry))) safeHeaders["Retry-After"] = new Date(retry).toUTCString();
|
|
117
|
-
|
|
118
|
-
|
|
134
|
+
const requestId=currentRequestContext()?.requestId;
|
|
135
|
+
const message=(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+".":"");
|
|
136
|
+
return new Response(JSON.stringify({ type: "error", error: { type: "api_error", code, message,
|
|
137
|
+
...(reason ? { upstream_code: reason.code, ...(reason.parameter ? { param: reason.parameter } : {}), ...(reason.maximum ? { maximum: reason.maximum } : {}) } : {}) } }), { status: result.status, headers: safeHeaders });
|
|
119
138
|
}
|
|
120
139
|
return result;
|
|
121
140
|
} catch (error) {
|
|
141
|
+
if (!observed) cooldown?.complete(recovery, confirmedNetworkFailure(error), options.signal?.aborted === true);
|
|
122
142
|
if (options.signal?.aborted) throw error;
|
|
123
143
|
if (error.code === "ccdx_api_redirect_refused") throw error;
|
|
124
144
|
const failure = accessError("ccdx_api_network_unavailable", 502);
|
|
@@ -152,6 +172,7 @@ export function createApiProvider({ config, secrets, env = process.env, platform
|
|
|
152
172
|
models: family => catalog.filter(model => model.supported_endpoints.includes(family === "claude" ? paths.messages : paths.responses))
|
|
153
173
|
.map(model => ({ ...model, ...modelDisplay(model.id), capability: model.protocol_capabilities[family === "claude" ? "messages" : "responses"] })),
|
|
154
174
|
catalog: () => catalog,
|
|
175
|
+
health: () => Object.fromEntries(Object.entries(cooldowns).filter(([protocol]) => config.endpoints[protocol]).map(([protocol, cooldown]) => [protocol, cooldown.snapshot()])),
|
|
155
176
|
publicCatalog(allowed = []) { return { source: "configured", checkedAt: config.checked_at || null, upstreamHost: new URL(config.base_url).hostname,
|
|
156
177
|
advertised: catalog.length, models: publicModelCatalog(catalog.map(model => ({ ...model, ...modelDisplay(model.id) })), { maker: model => model.publisher || model.vendor || null,
|
|
157
178
|
selectable: model => allowed.some(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)),
|
package/src/request-context.mjs
CHANGED
|
@@ -3,12 +3,17 @@ import { randomUUID } from "node:crypto";
|
|
|
3
3
|
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
4
4
|
|
|
5
5
|
const requestContextStorage = new AsyncLocalStorage();
|
|
6
|
+
export const REQUEST_PURPOSES = Object.freeze(["conversation", "diagnostic", "compatibility", "unknown"]);
|
|
7
|
+
export function requestPurpose(value, fallback = "conversation") {
|
|
8
|
+
return REQUEST_PURPOSES.includes(value) ? value : fallback;
|
|
9
|
+
}
|
|
6
10
|
|
|
7
11
|
export function createRequestId() {
|
|
8
12
|
return randomUUID();
|
|
9
13
|
}
|
|
10
14
|
|
|
11
15
|
export function runWithRequestContext(context, callback) {
|
|
16
|
+
context.purpose = requestPurpose(context.purpose);
|
|
12
17
|
return requestContextStorage.run(context, callback);
|
|
13
18
|
}
|
|
14
19
|
|
|
@@ -114,19 +114,21 @@ export function upstreamErrorEvidence(text, { includeMessage = false, status = n
|
|
|
114
114
|
const technical = value => typeof value === "string" && /^[a-z\d_.:-]{1,80}$/i.test(value)
|
|
115
115
|
&& redactDiagnosticText(value) === value ? value : undefined;
|
|
116
116
|
const param = typeof error.param === "string" && error.param.length <= 160
|
|
117
|
-
&& /^(?:model|input|tools|tool_choice|reasoning|text|temperature|top_p|max_output_tokens|service_tier|store|stream|include|previous_response_id|parallel_tool_calls)(?:\.[a-z_][a-z\d_]*|\[\d+\])*$/i.test(error.param)
|
|
117
|
+
&& /^(?:model|messages|input|tools|tool_choice|reasoning|output_config|thinking|text|temperature|top_p|max_tokens|max_output_tokens|max_completion_tokens|service_tier|store|stream|include|previous_response_id|parallel_tool_calls)(?:\.[a-z_][a-z\d_]*|\[\d+\])*$/i.test(error.param)
|
|
118
118
|
? error.param : undefined;
|
|
119
119
|
const upstreamCode = (safeUpstreamReason(error.upstream_code, status) || safeUpstreamReason(error.code, status)
|
|
120
120
|
|| safeUpstreamReason(error.type, status))?.code;
|
|
121
121
|
return { error_body: "structured", code: technical(error.code), error_type: technical(error.type),
|
|
122
122
|
...(upstreamCode ? { upstream_code: upstreamCode } : {}),
|
|
123
|
+
...(upstreamCode && Number.isSafeInteger(error.maximum) && error.maximum > 0 && error.maximum <= 100000000 ? { reported_maximum: error.maximum } : {}),
|
|
123
124
|
parameter: param, ...(includeMessage && typeof error.message === "string" ? { diagnostic_message: safeFailureMessage(error.message) } : {}) };
|
|
124
125
|
}
|
|
125
126
|
|
|
126
127
|
export function requestOptionsEvidence(body) {
|
|
127
128
|
const result = {};
|
|
128
129
|
if (!body || typeof body !== "object") return result;
|
|
129
|
-
|
|
130
|
+
const effort = body.reasoning?.effort ?? body.output_config?.effort ?? body.reasoning_effort;
|
|
131
|
+
if (["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"].includes(effort)) result.reasoning_effort = effort;
|
|
130
132
|
if (["auto", "default", "flex", "priority", "scale"].includes(body.service_tier)) result.service_tier = body.service_tier;
|
|
131
133
|
if (["text", "json_object", "json_schema"].includes(body.text?.format?.type)) result.output_format = body.text.format.type;
|
|
132
134
|
if (Number.isSafeInteger(body.max_output_tokens) && body.max_output_tokens >= 0) result.max_output_tokens = body.max_output_tokens;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { isMissingCallIdError } from "./responses-tool-output.mjs";
|
|
2
2
|
import { isRootToolSchemaError } from "./messages-tool-schema.mjs";
|
|
3
|
+
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
3
4
|
|
|
4
5
|
// Only fixed, documented-shaped codes leave this module; vendor messages and
|
|
5
6
|
// request data are never returned or logged.
|
|
@@ -12,6 +13,13 @@ const reasons = new Map([
|
|
|
12
13
|
["context_length_exceeded", { statuses: [400, 413, 422], message: "The source reports that the context is too long." }],
|
|
13
14
|
["context_window_exceeded", { statuses: [400, 413, 422], message: "The source reports that the context is too long." }],
|
|
14
15
|
["content_policy_violation", { statuses: [400, 403, 422], message: "The source rejected the request under its content policy." }],
|
|
16
|
+
["invalid_request_error", { statuses: [400, 422], message: "The source rejected the request parameters." }],
|
|
17
|
+
["unsupported_parameter", { statuses: [400, 422], message: "The source does not support a requested parameter." }],
|
|
18
|
+
["output_limit_invalid", { statuses: [400, 422], message: "The source rejected the output token limit." }],
|
|
19
|
+
["tool_limit_exceeded", { statuses: [400, 422], message: "The source rejected the number of tool definitions." }],
|
|
20
|
+
["reasoning_parameter_unsupported", { statuses: [400, 422], message: "The source does not support the requested reasoning parameter." }],
|
|
21
|
+
["authentication_error", { statuses: [401], message: "The source rejected authentication." }],
|
|
22
|
+
["permission_denied", { statuses: [403], message: "The source denied access to this model or operation." }],
|
|
15
23
|
]);
|
|
16
24
|
const MAX_ACTIVE_READS = 4;
|
|
17
25
|
let activeReads = 0;
|
|
@@ -25,6 +33,32 @@ export function safeUpstreamReason(code, status) {
|
|
|
25
33
|
return reason?.statuses.includes(status) ? { code, message: reason.message } : null;
|
|
26
34
|
}
|
|
27
35
|
|
|
36
|
+
export function safeUpstreamParameter(value){
|
|
37
|
+
return typeof value==="string"&&value.length<=160&&/^(?:model|messages|input|tools|tool_choice|reasoning|output_config|thinking|temperature|top_p|max_tokens|max_output_tokens|max_completion_tokens|response_format|text|stream|stream_options|stop|stop_sequences)(?:\.[a-z_][a-z\d_]*|\[\d+\])*$/i.test(value)&&redactDiagnosticText(value)===value?value:undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function classifyUpstreamError(value,status){
|
|
41
|
+
const error=value?.error??value,text=typeof error==="string"?error:typeof error?.message==="string"?error.message:"";
|
|
42
|
+
if(text.length>65536)return null;
|
|
43
|
+
const param=safeUpstreamParameter(error?.param||error?.parameter);
|
|
44
|
+
let code;
|
|
45
|
+
if([400,413,422].includes(status)&&/(context (?:length|window)|input tokens|上下文).{0,80}(?:exceed|too (?:long|large)|超|超过)|(?:exceed|超).{0,60}(?:context|上下文)/i.test(text))code="context_length_exceeded";
|
|
46
|
+
else if([400,422].includes(status)&&/max_(?:completion_)?tokens|max_output_tokens|output token limit|输出.{0,12}(?:上限|限制)/i.test(text)&&/(?:maximum|at most|less than|exceed|between|invalid|unsupported|最多|超过|不支持)/i.test(text))code="output_limit_invalid";
|
|
47
|
+
else if([400,422].includes(status)&&/(?:too many|maximum number of|at most).{0,40}tools|工具.{0,20}(?:过多|超过)/i.test(text))code="tool_limit_exceeded";
|
|
48
|
+
else if([400,422].includes(status)&&/(?:effort|thinking|reasoning).{0,60}(?:not support|unsupported)|not support.{0,60}(?:effort|thinking|reasoning)/i.test(text))code="reasoning_parameter_unsupported";
|
|
49
|
+
const selected=safeUpstreamReason(code,status)||safeUpstreamReason(error?.code,status)||safeUpstreamReason(error?.type,status);
|
|
50
|
+
if(!selected)return null;
|
|
51
|
+
const inferred = code === "output_limit_invalid" ? /\b(max_(?:completion_)?tokens|max_output_tokens)\b/i.exec(text)?.[1]?.toLowerCase() : code === "tool_limit_exceeded" ? "tools" : undefined;
|
|
52
|
+
const bounds = {};
|
|
53
|
+
if (["output_limit_invalid", "tool_limit_exceeded", "context_length_exceeded"].includes(selected.code)) {
|
|
54
|
+
const maximum = /(?:maximum(?: (?:context length|number of tools|tokens))?(?: is| of)?|at most|must be (?:less than or equal to|<=)|最多|上限(?:为)?)\s*[:=]?\s*(\d[\d,]{0,11})(?![\d,])/i.exec(text)?.[1];
|
|
55
|
+
const n = maximum && Number(maximum.replaceAll(",", ""));
|
|
56
|
+
if (Number.isSafeInteger(n) && n > 0 && n <= 100000000) bounds.maximum = n;
|
|
57
|
+
}
|
|
58
|
+
return { ...selected, ...(param || inferred ? { parameter: param || inferred } : {}), ...bounds,
|
|
59
|
+
message: selected.message + (param ? " Parameter: " + param + "." : "") + (bounds.maximum ? " Reported maximum: " + bounds.maximum + "." : "") };
|
|
60
|
+
}
|
|
61
|
+
|
|
28
62
|
function readChunk(reader, signal) {
|
|
29
63
|
if (signal.aborted) return Promise.reject(signal.reason);
|
|
30
64
|
return new Promise((resolve, reject) => {
|
|
@@ -67,10 +101,8 @@ export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200
|
|
|
67
101
|
const text = Buffer.concat(chunks, bytes).toString("utf8");
|
|
68
102
|
if (missingCallId && isMissingCallIdError(response.status, text)) return { code: "ccdx_missing_call_id", message: "The source requires a tool call ID." };
|
|
69
103
|
if (rootToolSchema && isRootToolSchemaError(response.status, text)) return { code: "ccdx_tool_schema_root_unsupported", message: "The source rejected a tool's root schema." };
|
|
70
|
-
let value;try { value = JSON.parse(text); } catch {
|
|
71
|
-
|
|
72
|
-
if (!error || typeof error !== "object" || Array.isArray(error)) return null;
|
|
73
|
-
return safeUpstreamReason(error.code, response.status) || safeUpstreamReason(error.type, response.status);
|
|
104
|
+
let value;try { value = JSON.parse(text); } catch { value=text; }
|
|
105
|
+
return classifyUpstreamError(value,response.status);
|
|
74
106
|
} catch (error) {
|
|
75
107
|
if (signal?.aborted) signal.throwIfAborted();
|
|
76
108
|
return null;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { checkedApi, CLIENT_IDS } from "./access-settings.mjs";
|
|
2
|
+
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
3
|
+
|
|
4
|
+
const object = value => value && typeof value === "object" && !Array.isArray(value);
|
|
5
|
+
const metadata = config => Object.fromEntries(["name", "base_url", "endpoints", "auth_header", "models", "key_env"].filter(key => config[key] !== undefined).map(key => [key, config[key]]));
|
|
6
|
+
const routes = { messages: "messages", responses: "responses", chat: "chat/completions" };
|
|
7
|
+
const append = (base, route) => base.replace(/\/+$/, "") + "/" + route;
|
|
8
|
+
|
|
9
|
+
// Only an explicitly supplied JSON file is interpreted. Credential values,
|
|
10
|
+
// tool permissions, commands, cached evidence and foreign route IDs stay out.
|
|
11
|
+
export function previewSourceImport(value, existing = []) {
|
|
12
|
+
if (!object(value) && !Array.isArray(value)) throw new Error("ccdx_import_format_invalid");
|
|
13
|
+
let format, entries;
|
|
14
|
+
if (object(value.config) && value.config.base_url) { format = "ccdx";entries = [value.config]; }
|
|
15
|
+
else if (Array.isArray(value.apis)) { format = "ccdx";entries = value.apis; }
|
|
16
|
+
else if (object(value.settingsConfig)) { format = "cc-switch";entries = [value]; }
|
|
17
|
+
else if (Array.isArray(value.providers) && value.providers.some(row => row?.anthropic || row?.responses || row?.chat)) { format = "magpie";entries = value.providers; }
|
|
18
|
+
else if (object(value.providers) && Object.values(value.providers).every(row => object(row?.settingsConfig))) { format = "cc-switch";entries = Object.values(value.providers); }
|
|
19
|
+
else throw new Error("ccdx_import_format_invalid");
|
|
20
|
+
if (!entries.length || entries.length > 16) throw new Error("ccdx_import_size_invalid");
|
|
21
|
+
const drafts = entries.map((entry, index) => {
|
|
22
|
+
const warnings = [];let config;
|
|
23
|
+
if (!object(entry)) throw new Error("ccdx_import_format_invalid");
|
|
24
|
+
if (format === "ccdx") {
|
|
25
|
+
config = metadata(entry);
|
|
26
|
+
config.models = (config.models || []).map(model => Object.fromEntries(["id", "protocols", "context_window", "reasoning_efforts", "capabilities"].filter(key => model[key] !== undefined).map(key => [key, model[key]])));
|
|
27
|
+
if (entry.models?.some(model => model.metadata)) warnings.push("catalog_evidence_omitted");
|
|
28
|
+
} else if (format === "cc-switch") {
|
|
29
|
+
const env = entry.settingsConfig.env;
|
|
30
|
+
if (!object(env) || typeof env.ANTHROPIC_BASE_URL !== "string") throw new Error("ccdx_import_format_invalid");
|
|
31
|
+
const base = env.ANTHROPIC_BASE_URL;
|
|
32
|
+
config = { name: entry.name, base_url: base, endpoints: { messages: append(base, "v1/messages") }, auth_header: entry.meta?.apiKeyField === "ANTHROPIC_API_KEY" ? "x-api-key" : "bearer", models: [] };
|
|
33
|
+
warnings.push("model_protocols_review");
|
|
34
|
+
} else {
|
|
35
|
+
const endpoints = Object.fromEntries(Object.entries({ messages: entry.anthropic, responses: entry.responses, chat: entry.chat }).filter(([, base]) => base).map(([protocol, base]) => [protocol, append(base, protocol === "messages" ? "v1/messages" : routes[protocol])]));
|
|
36
|
+
config = { name: entry.name, base_url: Object.values({ responses: entry.responses, chat: entry.chat, messages: entry.anthropic }).find(Boolean), endpoints, auth_header: entry.authHeader === "x-api-key" ? "x-api-key" : "bearer", models: [] };
|
|
37
|
+
if (entry.anthropic && !["x-api-key", "bearer"].includes(entry.authHeader)) warnings.push("auth_header_review");
|
|
38
|
+
if (entry.models?.length) warnings.push("model_protocols_review");
|
|
39
|
+
if (entry.keys?.length || entry.keyProtocol || entry.groups || entry.routing) warnings.push("account_routing_omitted");
|
|
40
|
+
}
|
|
41
|
+
const allowed = format === "ccdx" && Array.isArray(value.allowed) ? value.allowed.filter(id => CLIENT_IDS.includes(id)) : [];
|
|
42
|
+
checkedApi({ ...config, id: "api_import", enabled: true, ...(config.key_env ? {} : { secret_ref: "0".repeat(32) }) });
|
|
43
|
+
if (redactDiagnosticText(config.name) !== config.name || redactDiagnosticText(config.base_url) !== config.base_url) throw new Error("ccdx_import_metadata_invalid");
|
|
44
|
+
if (Object.values(config.endpoints).some(url => redactDiagnosticText(url) !== url) || config.models.some(model => redactDiagnosticText(model.id) !== model.id)) throw new Error("ccdx_import_metadata_invalid");
|
|
45
|
+
if (config.models.some(model => /^(?:ccdx\/|mythos-ccdx-)/.test(model.id))) throw new Error("ccdx_import_route_invalid");
|
|
46
|
+
if (existing.some(source => source.name?.trim().toLowerCase() === config.name.trim().toLowerCase())) warnings.push("name_exists");
|
|
47
|
+
if (existing.some(source => source.base_url === config.base_url)) warnings.push("endpoint_exists");
|
|
48
|
+
return { number: index + 1, config, requested_access: allowed, allowed: [], warnings, credential: config.key_env ? "environment" : "private_input_required" };
|
|
49
|
+
});
|
|
50
|
+
return { format, saved: false, drafts };
|
|
51
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { performance } from "node:perf_hooks";
|
|
2
|
-
import { currentRequestContext } from "./request-context.mjs";
|
|
2
|
+
import { currentRequestContext, requestPurpose } from "./request-context.mjs";
|
|
3
3
|
import { isProviderId } from "./provider-metadata.mjs";
|
|
4
4
|
import { applicationLabel } from "./request-application.mjs";
|
|
5
5
|
import { createContextMetrics } from "./context-metrics.mjs";
|
|
@@ -225,13 +225,14 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
225
225
|
|
|
226
226
|
return {
|
|
227
227
|
subscribe: changes.subscribe,
|
|
228
|
-
begin(routeName, { requestId, application } = {}) {
|
|
228
|
+
begin(routeName, { requestId, application, purpose } = {}) {
|
|
229
229
|
const route = routes[routeName];
|
|
230
230
|
if (!route) return null;
|
|
231
231
|
const requestStartedAt = now();
|
|
232
232
|
const activeId = ++activeSequence;
|
|
233
233
|
const safeRequestId = typeof requestId === "string" && /^[a-zA-Z0-9_-]{1,80}$/.test(requestId) ? requestId : null;
|
|
234
234
|
const client = applicationLabel(application);
|
|
235
|
+
const purposeLabel = requestPurpose(purpose);
|
|
235
236
|
activeTotal++;
|
|
236
237
|
let upstreamStartedAt = null;
|
|
237
238
|
let firstOutputAt = null;
|
|
@@ -261,7 +262,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
261
262
|
let stopReason = null;
|
|
262
263
|
const elapsed = (time) => time === null ? null : Number(Math.max(0, time - requestStartedAt).toFixed(1));
|
|
263
264
|
if (activeRequests.size < MAX_ACTIVE_REQUESTS) activeRequests.set(activeId, () => ({
|
|
264
|
-
request_id: safeRequestId, session_id: session ? session.slice(0, 16) : null, application: client, route: routeName, provider, model, phase,
|
|
265
|
+
request_id: safeRequestId, session_id: session ? session.slice(0, 16) : null, application: client, purpose: purposeLabel, route: routeName, provider, model, phase,
|
|
265
266
|
started_at: at, elapsed_ms: elapsed(now()), first_output_ms: elapsed(firstOutputAt),
|
|
266
267
|
upstream_attempts: attempts, terminal_outcome: terminalOutcome,
|
|
267
268
|
previous_request: session ? (() => {
|
|
@@ -347,8 +348,9 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
347
348
|
observeContext(values) {
|
|
348
349
|
if (finished || !values || typeof values !== "object") return;
|
|
349
350
|
if (Number.isSafeInteger(values.cached_input_tokens) && values.cached_input_tokens >= 0) cachedInput = values.cached_input_tokens;
|
|
350
|
-
for (const key of [...Object.keys(context), "requested_model", "usage_state", "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "privacy_state", "privacy_pending_bytes", "privacy_new_bytes", "privacy_pending_windows", "privacy_wait_budget_ms", "privacy_error", "privacy_event_type", "privacy_channel_type", "privacy_buffered_bytes", "privacy_terminal_seen", "client_tool_errors_received"]) {
|
|
351
|
+
for (const key of [...Object.keys(context), "requested_model", "reasoning_effort_requested", "reasoning_effort_sent", "usage_state", "capability_revision", "capability_constraints", "privacy_count", "privacy_ms", "privacy_state", "privacy_pending_bytes", "privacy_new_bytes", "privacy_pending_windows", "privacy_wait_budget_ms", "privacy_error", "privacy_event_type", "privacy_channel_type", "privacy_buffered_bytes", "privacy_terminal_seen", "client_tool_errors_received"]) {
|
|
351
352
|
const value = values[key];
|
|
353
|
+
if (["reasoning_effort_requested", "reasoning_effort_sent"].includes(key)) { if (["none", "minimal", "low", "medium", "high", "xhigh", "max"].includes(value)) context[key] = value;continue; }
|
|
352
354
|
if (key === "requested_model") { if (typeof value === "string" && /^[\w][\w./:@+-]{0,159}$/.test(value) && redactDiagnosticText(value) === value) context[key] = value;continue; }
|
|
353
355
|
if (key === "usage_state") { if (["pending", "reported", "partial", "missing", "unavailable"].includes(value)) context[key] = value;continue; }
|
|
354
356
|
if (key === "privacy_state") { if (["checked", "failed", "cancelled"].includes(value)) context[key] = value;continue; }
|
|
@@ -413,7 +415,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
413
415
|
// Only scalar, allowlisted metadata survives the request; never retain payloads.
|
|
414
416
|
recentRequests.push({
|
|
415
417
|
request_id: safeRequestId, ...(session ? { session_id: session.slice(0, 16) } : {}), application: client,
|
|
416
|
-
at, route: routeName, model, outcome, origin, phase,
|
|
418
|
+
at, route: routeName, purpose: purposeLabel, model, outcome, origin, phase,
|
|
417
419
|
...(["ccdx_model_not_selected", "ccdx_client_source_disabled"].includes(rejectionReason) ? { rejection_reason: rejectionReason } : {}),
|
|
418
420
|
...(stopReason ? { stop_reason: stopReason } : {}),
|
|
419
421
|
...(provider ? { provider } : {}),
|
package/src/usage-analysis.mjs
CHANGED
|
@@ -57,8 +57,8 @@ function observe() {
|
|
|
57
57
|
});
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
-
export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "UTC", now = Date.now(), warn = console.error, provider = "", model = "", days = "all", from = "", to = "", signal } = {}) {
|
|
61
|
-
const selection = createUsageQuery({ provider, model, days, from, to, timeZone, now });
|
|
60
|
+
export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "UTC", now = Date.now(), warn = console.error, provider = "", model = "", purpose = "", days = "all", from = "", to = "", signal } = {}) {
|
|
61
|
+
const selection = createUsageQuery({ provider, model, purpose, days, from, to, timeZone, now });
|
|
62
62
|
const zone = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
|
|
63
63
|
const file = path.resolve(filePath), query = `${file}\0${selection.key}\0${zone.format(new Date(now))}`;
|
|
64
64
|
const version = warn === console.error ? await usageSummaryVersion(file, { settled: false }) : null;
|
package/src/usage-query.mjs
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { isProviderId } from "./provider-metadata.mjs";
|
|
2
2
|
import { usageProvider } from "./usage-store.mjs";
|
|
3
|
+
import { REQUEST_PURPOSES, requestPurpose } from "./request-context.mjs";
|
|
3
4
|
|
|
4
5
|
const DAY_MS = 86400000;
|
|
5
6
|
const dateValue = value => /^\d{4}-\d{2}-\d{2}$/.test(value) && Number.isFinite(Date.parse(value))
|
|
6
7
|
&& new Date(value).toISOString().slice(0, 10) === value;
|
|
7
8
|
|
|
8
|
-
export function createUsageQuery({ provider = "", model = "", days = "all", from = "", to = "", timeZone = "UTC", now = Date.now() } = {}) {
|
|
9
|
+
export function createUsageQuery({ provider = "", model = "", purpose = "", days = "all", from = "", to = "", timeZone = "UTC", now = Date.now() } = {}) {
|
|
9
10
|
if (typeof provider !== "string" || provider && !isProviderId(provider)) throw new Error("Select a valid usage source");
|
|
11
|
+
if (purpose !== "" && !REQUEST_PURPOSES.includes(purpose)) throw new Error("Select a valid request purpose");
|
|
10
12
|
if (typeof model !== "string" || model.length > 200 || /[\u0000-\u001f\u007f]/.test(model)) throw new Error("Select a valid usage model");
|
|
11
13
|
if (String(days) !== "all" && (!/^\d+$/.test(String(days)) || Number(days) < 1 || Number(days) > 365)) throw new Error("Usage days must be all or an integer from 1 to 365");
|
|
12
14
|
if (typeof timeZone !== "string" || timeZone.length > 100) throw new Error("Select a valid usage time zone");
|
|
@@ -19,11 +21,12 @@ export function createUsageQuery({ provider = "", model = "", days = "all", from
|
|
|
19
21
|
}
|
|
20
22
|
if (from && !to) to = today;
|
|
21
23
|
if (from && to && from > to) throw new Error("Usage start date must not follow its end date");
|
|
22
|
-
const filters = { provider, model, days: String(days), from, to, time_zone: zone.resolvedOptions().timeZone };
|
|
24
|
+
const filters = { provider, model, purpose, days: String(days), from, to, time_zone: zone.resolvedOptions().timeZone };
|
|
23
25
|
return {
|
|
24
26
|
filters,
|
|
25
27
|
key: JSON.stringify(filters),
|
|
26
28
|
matches(record) {
|
|
29
|
+
if (purpose && requestPurpose(record.purpose, "unknown") !== purpose) return false;
|
|
27
30
|
if (provider && usageProvider(record) !== provider) return false;
|
|
28
31
|
if (model && model !== record.model && model !== `${usageProvider(record)} / ${record.model || "unknown"}`) return false;
|
|
29
32
|
if (!from && !to) return true;
|
package/src/usage-store.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import readline from "node:readline";
|
|
|
8
8
|
import { appendRotatingLines, parseByteLimit, rotatedFilePath } from "./file-rotation.mjs";
|
|
9
9
|
import { withFileLock } from "./lock.mjs";
|
|
10
10
|
import { terminalCell } from "./terminal-text.mjs";
|
|
11
|
-
import { currentRequestContext } from "./request-context.mjs";
|
|
11
|
+
import { currentRequestContext, requestPurpose } from "./request-context.mjs";
|
|
12
12
|
|
|
13
13
|
const DEFAULT_USAGE_PATH = path.join(os.homedir(), ".local", "share", "codex-copilot-dx", "usage.jsonl");
|
|
14
14
|
const DEFAULT_USAGE_MAX_BYTES = 32 * 1024 * 1024;
|
|
@@ -203,6 +203,7 @@ function scheduleUsageWriteDrain() {
|
|
|
203
203
|
|
|
204
204
|
export function recordUsage(record) {
|
|
205
205
|
if (!record) return Promise.resolve();
|
|
206
|
+
record = { ...record, purpose: requestPurpose(record.purpose ?? currentRequestContext()?.purpose, "unknown") };
|
|
206
207
|
const usage = record.usage || {};
|
|
207
208
|
const { cached } = usageCacheEvidence(usage);
|
|
208
209
|
const provider = usageProvider(record), label = runtimeUsageByProvider.has(provider) || runtimeUsageByProvider.size < 18 ? provider : "other";
|