codex-copilot-dx 1.3.27 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -2
- package/bin/cli.mjs +4 -1
- package/docs/ARCHITECTURE.md +32 -3
- package/docs/REFERENCE.md +51 -5
- package/package.json +1 -1
- package/src/adapter.mjs +17 -5
- package/src/antigravity-handler.mjs +38 -13
- package/src/antigravity-runtime.mjs +22 -2
- package/src/claude-app-contract.mjs +96 -0
- package/src/claude-capability-config.mjs +28 -11
- package/src/claude-client-config.mjs +58 -9
- package/src/claude-gateway.mjs +25 -7
- package/src/claude-models.mjs +4 -2
- package/src/cli-command-spec.mjs +13 -3
- package/src/cli-management.mjs +47 -6
- package/src/cli-options.mjs +1 -1
- 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 +3 -1
- package/src/connection-runtime.mjs +37 -2
- package/src/connection-view.mjs +11 -2
- 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/connections.js +33 -3
- package/src/dashboard/index.html +9 -1
- package/src/dashboard/language.js +28 -0
- package/src/dashboard/preferences.js +1 -1
- package/src/dashboard/ui.js +3 -0
- package/src/dashboard-api.mjs +2 -2
- package/src/doctor-compat.mjs +1 -1
- package/src/http-transport.mjs +1 -1
- package/src/local-privacy.mjs +15 -7
- package/src/lock.mjs +9 -2
- package/src/model-capabilities.mjs +17 -4
- package/src/privacy-detection.mjs +4 -3
- package/src/privacy-transform.mjs +20 -6
- package/src/provider-cooldown.mjs +43 -0
- package/src/provider-runtime.mjs +8 -5
- package/src/providers/api-model-metadata.mjs +7 -0
- package/src/providers/api.mjs +44 -12
- package/src/request-context.mjs +5 -0
- package/src/response-failures.mjs +4 -2
- 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 +59 -9
- package/src/service-control.mjs +8 -1
- package/src/settings-preferences.mjs +3 -3
- package/src/source-import.mjs +51 -0
- package/src/stream-performance.mjs +8 -5
- package/src/upstream-body.mjs +1 -1
- package/src/upstream-error-capture.mjs +29 -0
- package/src/usage-analysis.mjs +2 -2
- package/src/usage-query.mjs +5 -2
- package/src/usage-store.mjs +2 -1
- package/src/user-settings.mjs +1 -1
|
@@ -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
|
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { isMissingCallIdError } from "./responses-tool-output.mjs";
|
|
2
2
|
import { isRootToolSchemaError } from "./messages-tool-schema.mjs";
|
|
3
|
+
import { redactDiagnosticText, boundedDiagnosticText } from "./diagnostic-text.mjs";
|
|
3
4
|
|
|
4
|
-
//
|
|
5
|
-
//
|
|
5
|
+
// Default evidence contains only fixed categories. A separately authorized
|
|
6
|
+
// one-shot capture can retain a bounded, redacted technical message.
|
|
6
7
|
const reasons = new Map([
|
|
7
8
|
["credit_balance_exhausted", { statuses: [429], message: "The source account has no remaining credits." }],
|
|
8
9
|
["insufficient_quota", { statuses: [429], message: "The source account has insufficient quota." }],
|
|
@@ -12,6 +13,15 @@ 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
|
+
["input_length_invalid", { statuses: [400, 413, 422], message: "The source rejected the input length." }],
|
|
18
|
+
["compaction_unavailable", { statuses: [400, 404, 405, 501], message: "The source does not support this compression operation." }],
|
|
19
|
+
["unsupported_parameter", { statuses: [400, 422], message: "The source does not support a requested parameter." }],
|
|
20
|
+
["output_limit_invalid", { statuses: [400, 422], message: "The source rejected the output token limit." }],
|
|
21
|
+
["tool_limit_exceeded", { statuses: [400, 422], message: "The source rejected the number of tool definitions." }],
|
|
22
|
+
["reasoning_parameter_unsupported", { statuses: [400, 422], message: "The source does not support the requested reasoning parameter." }],
|
|
23
|
+
["authentication_error", { statuses: [401], message: "The source rejected authentication." }],
|
|
24
|
+
["permission_denied", { statuses: [403], message: "The source denied access to this model or operation." }],
|
|
15
25
|
]);
|
|
16
26
|
const MAX_ACTIVE_READS = 4;
|
|
17
27
|
let activeReads = 0;
|
|
@@ -25,6 +35,42 @@ export function safeUpstreamReason(code, status) {
|
|
|
25
35
|
return reason?.statuses.includes(status) ? { code, message: reason.message } : null;
|
|
26
36
|
}
|
|
27
37
|
|
|
38
|
+
export function safeUpstreamParameter(value){
|
|
39
|
+
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;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function classifyUpstreamError(value,status){
|
|
43
|
+
const error=value?.error??value,text=typeof error==="string"?error:typeof error?.message==="string"?error.message:"";
|
|
44
|
+
if(text.length>65536)return null;
|
|
45
|
+
const param=safeUpstreamParameter(error?.param||error?.parameter);
|
|
46
|
+
const range = /^Range of input length should be\s*\[\s*1\s*,\s*(\d{1,9})\s*\]\.?\s*$/i.exec(text.trim());
|
|
47
|
+
let code;
|
|
48
|
+
if([400,404,405,501].includes(status)&&(["unsupported_compaction","compaction_not_supported"].includes(error?.code)
|
|
49
|
+
|| /^(?:unsupported|unknown|unrecognized) (?:input item(?: type)?|parameter|type)\s*[:=]?\s*["']?compaction_trigger["']?\.?$/i.test(text.trim())
|
|
50
|
+
|| param?.endsWith(".type")&&/compaction_trigger/i.test(text)&&/unsupported|not supported|supported values|unknown type/i.test(text)))code="compaction_unavailable";
|
|
51
|
+
else if([400,413,422].includes(status)&&range&&Number(range[1])>0&&Number(range[1])<=100000000)code="input_length_invalid";
|
|
52
|
+
else if([400,413,422].includes(status)&&/(context (?:length|window)|input tokens?|input token count|上下文).{0,80}(?:exceed|too (?:long|large)|超|超过)|(?:exceed|超).{0,60}(?:context|上下文)/i.test(text))code="context_length_exceeded";
|
|
53
|
+
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";
|
|
54
|
+
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";
|
|
55
|
+
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";
|
|
56
|
+
const selected=safeUpstreamReason(code,status)||safeUpstreamReason(error?.code,status)||safeUpstreamReason(error?.upstream_code,status)||safeUpstreamReason(error?.type,status);
|
|
57
|
+
if(!selected)return null;
|
|
58
|
+
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;
|
|
59
|
+
const bounds = {};
|
|
60
|
+
if (code === "input_length_invalid") bounds.maximum = Number(range[1]);
|
|
61
|
+
if (["input_length_invalid", "output_limit_invalid", "tool_limit_exceeded", "context_length_exceeded", "context_window_exceeded"].includes(selected.code)
|
|
62
|
+
&& Number.isSafeInteger(error?.maximum) && error.maximum > 0 && error.maximum <= 100000000) bounds.maximum = error.maximum;
|
|
63
|
+
if (["output_limit_invalid", "tool_limit_exceeded", "context_length_exceeded"].includes(selected.code)) {
|
|
64
|
+
const maximum = /maximum number of tokens allowed\s*\((\d[\d,]{0,11})\)/i.exec(text)?.[1]
|
|
65
|
+
|| /(?: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];
|
|
66
|
+
const n = maximum && Number(maximum.replaceAll(",", ""));
|
|
67
|
+
if (Number.isSafeInteger(n) && n > 0 && n <= 100000000) bounds.maximum = n;
|
|
68
|
+
}
|
|
69
|
+
return { ...selected, ...(param || inferred ? { parameter: param || inferred } : {}), ...bounds,
|
|
70
|
+
message: code === "input_length_invalid" ? `Range of input length should be [1, ${bounds.maximum}].`
|
|
71
|
+
: selected.message + (param ? " Parameter: " + param + "." : "") + (bounds.maximum ? " Reported maximum: " + bounds.maximum + "." : "") };
|
|
72
|
+
}
|
|
73
|
+
|
|
28
74
|
function readChunk(reader, signal) {
|
|
29
75
|
if (signal.aborted) return Promise.reject(signal.reason);
|
|
30
76
|
return new Promise((resolve, reject) => {
|
|
@@ -39,7 +85,7 @@ function readChunk(reader, signal) {
|
|
|
39
85
|
|
|
40
86
|
// Failure responses only. A stalled body or a stalled cancellation cannot delay
|
|
41
87
|
// the caller beyond the budget. The original request's cancellation wins.
|
|
42
|
-
export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200, maxBytes = 64 * 1024, missingCallId = false, rootToolSchema = false } = {}) {
|
|
88
|
+
export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200, maxBytes = 64 * 1024, missingCallId = false, rootToolSchema = false, diagnosticRedact } = {}) {
|
|
43
89
|
if (signal?.aborted) {
|
|
44
90
|
cancelBody(response?.body);
|
|
45
91
|
signal.throwIfAborted();
|
|
@@ -65,12 +111,16 @@ export async function readSafeUpstreamReason(response, { signal, timeoutMs = 200
|
|
|
65
111
|
chunks.push(chunk);
|
|
66
112
|
}
|
|
67
113
|
const text = Buffer.concat(chunks, bytes).toString("utf8");
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
114
|
+
let value;try { value = JSON.parse(text); } catch { value=text; }
|
|
115
|
+
const reason = missingCallId && isMissingCallIdError(response.status, text)
|
|
116
|
+
? { code: "ccdx_missing_call_id", message: "The source requires a tool call ID." }
|
|
117
|
+
: rootToolSchema && isRootToolSchemaError(response.status, text)
|
|
118
|
+
? { code: "ccdx_tool_schema_root_unsupported", message: "The source rejected a tool's root schema." }
|
|
119
|
+
: classifyUpstreamError(value,response.status);
|
|
120
|
+
if (!diagnosticRedact) return reason;
|
|
121
|
+
const error = value?.error ?? value, message = typeof error === "string" ? error : error?.message;
|
|
122
|
+
if (typeof message !== "string") return reason;
|
|
123
|
+
return { ...reason, diagnostic_message: boundedDiagnosticText(diagnosticRedact(message), { maxChars: 512 }) };
|
|
74
124
|
} catch (error) {
|
|
75
125
|
if (signal?.aborted) signal.throwIfAborted();
|
|
76
126
|
return null;
|
package/src/service-control.mjs
CHANGED
|
@@ -32,8 +32,11 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
32
32
|
return { source: "service_settings", saved, theme, color_theme, preferences: settingsPreferencesSnapshot(options), local_privacy: localPrivacy,
|
|
33
33
|
features: { prediction: { ...featureSnapshot(predictionControlSnapshot), bridge: prediction?.bridge || "stopped", active: prediction?.active === true }, image: { ...image, runtime: imageHostState.snapshot() } },
|
|
34
34
|
decoded_body: decodedBodyLimitPreference(options), manual_update: { available: typeof manualUpdate === "function" }, last_operation: lastOperation,
|
|
35
|
+
...(providerRuntime?.errorCaptureSnapshot ? { error_capture: providerRuntime.errorCaptureSnapshot() } : {}),
|
|
36
|
+
...(providerRuntime?.compaction ? { compaction: providerRuntime.compaction.snapshot() } : {}),
|
|
35
37
|
nightly_update: { enabled, ...nightly, effect: enabled && !nightly ? "next_start" : "immediate" },
|
|
36
38
|
effective: {
|
|
39
|
+
context_compaction_enabled: { value: saved.context_compaction_enabled && Boolean(providerRuntime?.compaction), state: providerRuntime?.compaction ? saved.context_compaction_enabled ? "ready" : "off" : "unavailable" },
|
|
37
40
|
privacy_enabled: { value: localPrivacy?.effective_enabled === true, state: !localPrivacy ? "unavailable" : !localPrivacy.enabled ? "off" : localPrivacy.state === "ready" ? "ready" : "not_ready" },
|
|
38
41
|
terminal_animation_enabled: { value: terminal?.enabled === true && saved.terminal_animation_enabled && !/^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || ""),
|
|
39
42
|
state: terminal?.enabled === true ? "immediate" : "terminal_unavailable", locked: /^(0|false|no|off)$/i.test(env.CCDX_TERMINAL_ANIMATION || "") },
|
|
@@ -51,11 +54,15 @@ export function createServiceControl({ env = process.env, home, providerRuntime,
|
|
|
51
54
|
prediction: ["action", "operation"], image: ["action", "operation", "model", "evidence", "confirmed"],
|
|
52
55
|
codex_app: ["action", "operation", "intent", "confirmed"],
|
|
53
56
|
update: ["action", "confirmed"], decoded_limit: ["action", "mib"],
|
|
57
|
+
error_capture: ["action", "operation", "source", "model"],
|
|
54
58
|
preferences: ["action", "values", "revision"], reset_preferences: ["action", "revision", "backup_id", "scope"], restore_preferences: ["action", "revision", "backup_id", "scope"],
|
|
55
59
|
provider: ["action", "operation", "provider", "model", "auto_review_model", "auto_review_effort", "account_id"] }[input.action];
|
|
56
60
|
if (!allowed || Object.keys(input).some(key => !allowed.includes(key))) throw new Error("Unknown setting action or field");
|
|
57
61
|
lastOperation = null;
|
|
58
|
-
if (input.action === "
|
|
62
|
+
if (input.action === "error_capture") {
|
|
63
|
+
if (!providerRuntime?.captureUpstreamError) throw new Error("This service cannot capture upstream errors.");
|
|
64
|
+
lastOperation = { feature: "error_capture", result: providerRuntime.captureUpstreamError(input) };
|
|
65
|
+
} else if (input.action === "codex_app") {
|
|
59
66
|
lastOperation = { feature: "codex_app", result: await codexLaunchControl(input.operation, { ...options, host: adapterHost, port: adapterPort,
|
|
60
67
|
integration: clientIntegration, state: imageHostState, intent: input.intent, confirmed: input.confirmed, models: providerRuntime?.imageModels?.().models || [] }) };
|
|
61
68
|
} else if (input.action === "prediction") {
|
|
@@ -9,7 +9,7 @@ import { atomicWriteFileIfChangedSync, atomicWriteFilePairSync } from "./atomic-
|
|
|
9
9
|
import { withFileLockSync } from "./lock.mjs";
|
|
10
10
|
|
|
11
11
|
export const SETTINGS_DEFAULTS = Object.freeze({ terminal_color_theme: "green", terminal_animation: DEFAULT_TERMINAL_ANIMATION_THEME,
|
|
12
|
-
terminal_animation_enabled: true, open_webui: true, nightly_updates: false, auto_save_settings: true, privacy_enabled: false, privacy_personal: false });
|
|
12
|
+
terminal_animation_enabled: true, open_webui: true, nightly_updates: false, auto_save_settings: true, privacy_enabled: false, privacy_personal: false, context_compaction_enabled: true });
|
|
13
13
|
const keys = Object.keys(SETTINGS_DEFAULTS);
|
|
14
14
|
const fail = (code, message, statusCode = 409) => Object.assign(new Error(message), { code, statusCode });
|
|
15
15
|
const idValid = value => typeof value === "string" && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(value);
|
|
@@ -30,8 +30,8 @@ function readBackup(options) {
|
|
|
30
30
|
const value = JSON.parse(readBoundedFileSync(settingsBackupPath(options), { encoding: "utf8", maxBytes: 8192 }));
|
|
31
31
|
if (value?.version !== 1 || !idValid(value.id) || typeof value.created_at !== "string" || !Number.isFinite(Date.parse(value.created_at))
|
|
32
32
|
|| Object.keys(value).some(key => !["version", "id", "created_at", "values"].includes(key))
|
|
33
|
-
|| keys.filter(key => !key.startsWith("privacy_")).some(key => !Object.hasOwn(value.values || {}, key))) throw Error();
|
|
34
|
-
value.values = { privacy_enabled: false, privacy_personal: false, ...value.values };
|
|
33
|
+
|| keys.filter(key => !key.startsWith("privacy_") && key !== "context_compaction_enabled").some(key => !Object.hasOwn(value.values || {}, key))) throw Error();
|
|
34
|
+
value.values = { privacy_enabled: false, privacy_personal: false, context_compaction_enabled: true, ...value.values };
|
|
35
35
|
checkedPreferenceValues(value.values);return value;
|
|
36
36
|
} catch (error) {
|
|
37
37
|
if (error.code === "ENOENT") 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
|
+
let 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 ? (() => {
|
|
@@ -341,14 +342,16 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
341
342
|
if (next !== model) { model = next;changes.changed(); }
|
|
342
343
|
},
|
|
343
344
|
setProvider: assignProvider,
|
|
345
|
+
setPurpose(value) { if (!finished) { purposeLabel = requestPurpose(value);changes.changed(); } },
|
|
344
346
|
observeSession(key) { if (!finished && typeof key === "string" && /^[a-f0-9]{64}$/.test(key)) session = key; },
|
|
345
347
|
attemptCount() { return attempts; },
|
|
346
348
|
attemptTimings() { return attemptTimings.map(attempt => ({ ...attempt })); },
|
|
347
349
|
observeContext(values) {
|
|
348
350
|
if (finished || !values || typeof values !== "object") return;
|
|
349
351
|
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"]) {
|
|
352
|
+
for (const key of [...Object.keys(context), "compaction", "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
353
|
const value = values[key];
|
|
354
|
+
if (["reasoning_effort_requested", "reasoning_effort_sent"].includes(key)) { if (["none", "minimal", "low", "medium", "high", "xhigh", "max"].includes(value)) context[key] = value;continue; }
|
|
352
355
|
if (key === "requested_model") { if (typeof value === "string" && /^[\w][\w./:@+-]{0,159}$/.test(value) && redactDiagnosticText(value) === value) context[key] = value;continue; }
|
|
353
356
|
if (key === "usage_state") { if (["pending", "reported", "partial", "missing", "unavailable"].includes(value)) context[key] = value;continue; }
|
|
354
357
|
if (key === "privacy_state") { if (["checked", "failed", "cancelled"].includes(value)) context[key] = value;continue; }
|
|
@@ -413,7 +416,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
413
416
|
// Only scalar, allowlisted metadata survives the request; never retain payloads.
|
|
414
417
|
recentRequests.push({
|
|
415
418
|
request_id: safeRequestId, ...(session ? { session_id: session.slice(0, 16) } : {}), application: client,
|
|
416
|
-
at, route: routeName, model, outcome, origin, phase,
|
|
419
|
+
at, route: routeName, purpose: purposeLabel, model, outcome, origin, phase,
|
|
417
420
|
...(["ccdx_model_not_selected", "ccdx_client_source_disabled"].includes(rejectionReason) ? { rejection_reason: rejectionReason } : {}),
|
|
418
421
|
...(stopReason ? { stop_reason: stopReason } : {}),
|
|
419
422
|
...(provider ? { provider } : {}),
|
package/src/upstream-body.mjs
CHANGED
|
@@ -41,7 +41,7 @@ function responseAbortError(signal) {
|
|
|
41
41
|
return error;
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
-
function readResponseChunk(reader, signal) {
|
|
44
|
+
export function readResponseChunk(reader, signal) {
|
|
45
45
|
if (!signal) return reader.read();
|
|
46
46
|
if (signal.aborted) return Promise.reject(responseAbortError(signal));
|
|
47
47
|
return new Promise((resolve, reject) => {
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { boundedDiagnosticText } from "./diagnostic-text.mjs";
|
|
2
|
+
|
|
3
|
+
// Explicit, process-local consent for one failed Messages request. Only the
|
|
4
|
+
// bounded, redacted error message is retained; request bodies are never copied.
|
|
5
|
+
export function createUpstreamErrorCapture({ now = Date.now } = {}) {
|
|
6
|
+
let state = { state: "off" };
|
|
7
|
+
const expire = () => { if (state.state === "armed" && now() >= state.expires_at_ms) state = { ...state, state: "expired" }; };
|
|
8
|
+
return {
|
|
9
|
+
snapshot() { expire();return { ...state }; },
|
|
10
|
+
arm(source, model) {
|
|
11
|
+
expire();
|
|
12
|
+
if (["armed", "reading"].includes(state.state)) throw Object.assign(new Error("An error capture is already pending; cancel it before arming another."), { statusCode: 409 });
|
|
13
|
+
state = { state: "armed", source, model, expires_at_ms: now() + 10 * 60 * 1000 };
|
|
14
|
+
return { ...state };
|
|
15
|
+
},
|
|
16
|
+
cancel() { state = { state: "off" };return { ...state }; },
|
|
17
|
+
claim(source, model, protocol, status, requestId) {
|
|
18
|
+
expire();
|
|
19
|
+
if (state.state !== "armed" || source !== state.source || model !== state.model || protocol !== "messages" || ![400, 422].includes(status)) return null;
|
|
20
|
+
const claimed = state = { ...state, state: "reading", request_id: requestId || null };
|
|
21
|
+
return message => {
|
|
22
|
+
if (state !== claimed) return false;
|
|
23
|
+
state = { ...state, state: message ? "captured" : "unavailable",
|
|
24
|
+
...(message ? { diagnostic_message: boundedDiagnosticText(message, { maxChars: 512 }) } : {}) };
|
|
25
|
+
return true;
|
|
26
|
+
};
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|
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;
|