codex-copilot-dx 0.9.41 → 0.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -2
- package/bin/cli.mjs +38 -11
- package/docs/ARCHITECTURE.md +62 -8
- package/docs/REFERENCE.md +161 -4
- package/package.json +4 -1
- package/src/adapter.mjs +83 -22
- package/src/auto-review-model.mjs +4 -3
- package/src/claude-client-config.mjs +217 -0
- package/src/claude-gateway.mjs +163 -0
- package/src/cli-m365.mjs +133 -0
- package/src/cli-models.mjs +1 -1
- package/src/cli-options.mjs +20 -6
- package/src/cli-status.mjs +6 -0
- package/src/codex-model-catalog.mjs +7 -2
- package/src/copilot-responses-policy.mjs +2 -64
- package/src/dashboard/index.html +11 -1
- package/src/dashboard/language.js +26 -0
- package/src/dashboard/status.js +16 -2
- package/src/dashboard/ui.css +2 -2
- package/src/dashboard/ui.js +16 -7
- package/src/dashboard/usage.js +3 -1
- package/src/dashboard-api.mjs +10 -7
- package/src/doctor-repair.mjs +2 -0
- package/src/doctor.mjs +18 -2
- package/src/m365-settings.mjs +89 -0
- package/src/native-prediction-windows.mjs +2 -7
- package/src/profile-model-runtime.mjs +4 -2
- package/src/provider-management.mjs +28 -0
- package/src/provider-runtime.mjs +180 -0
- package/src/provider-settings.mjs +32 -0
- package/src/providers/github.mjs +62 -0
- package/src/providers/m365-auth-helper.mjs +72 -0
- package/src/providers/m365-auth.mjs +105 -0
- package/src/providers/m365-messages-policy.mjs +20 -0
- package/src/providers/m365-network.mjs +73 -0
- package/src/providers/m365.mjs +238 -0
- package/src/response-failures.mjs +4 -2
- package/src/response-history.mjs +20 -3
- package/src/responses-handler.mjs +40 -95
- package/src/responses-image-tools.mjs +61 -0
- package/src/responses-proxy.mjs +5 -5
- package/src/responses-request.mjs +25 -0
- package/src/stream-performance.mjs +7 -4
- package/src/usage-analysis.mjs +3 -2
- package/src/usage-store.mjs +41 -12
- package/src/usage.mjs +8 -2
- package/src/windows-http-network.mjs +122 -0
- package/src/windows-prediction-network.cs +13 -6
- package/src/windows-prediction-network.mjs +4 -108
- package/src/windows-process.mjs +8 -0
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { applyCopilotResponsesRequestPolicies, stripUnsupportedGpt6ServiceTier } from "./copilot-responses-policy.mjs";
|
|
1
|
+
import { defaultGithubProvider } from "./providers/github.mjs";
|
|
3
2
|
import {
|
|
4
3
|
createRequestAbort,
|
|
5
4
|
logRequestFailure,
|
|
@@ -13,15 +12,11 @@ import {
|
|
|
13
12
|
writeOrDrain,
|
|
14
13
|
} from "./http-transport.mjs";
|
|
15
14
|
import {
|
|
16
|
-
CODEX_GPT6_MODEL,
|
|
17
15
|
CODEX_AUTO_REVIEW_MODEL,
|
|
18
|
-
modelIsResponsesOnly,
|
|
19
|
-
modelSupportsChatCompletions,
|
|
20
16
|
modelContextWindowTokens,
|
|
21
|
-
resolveCopilotPriorityTierModel,
|
|
22
17
|
resolveOpenAIModel,
|
|
23
18
|
} from "./models.mjs";
|
|
24
|
-
import { chatToResponses, forwardToChat
|
|
19
|
+
import { chatToResponses, forwardToChat } from "./responses-bridge.mjs";
|
|
25
20
|
import { prepareResponsesChatPayload } from "./responses-chat-payload.mjs";
|
|
26
21
|
import { prepareResponsesCompactionRequest } from "./responses-compaction.mjs";
|
|
27
22
|
import { clearResponsesToolOutputPartsCache } from "./responses-content.mjs";
|
|
@@ -34,7 +29,6 @@ import {
|
|
|
34
29
|
rememberResponseHistory,
|
|
35
30
|
responseHistoryPressureRootId,
|
|
36
31
|
} from "./responses-request.mjs";
|
|
37
|
-
import { createRoutePlan } from "./route-plan.mjs";
|
|
38
32
|
import { status } from "./status.mjs";
|
|
39
33
|
import { endStreamWithError } from "./stream-errors.mjs";
|
|
40
34
|
import { createSseKeepalive } from "./sse-keepalive.mjs";
|
|
@@ -50,49 +44,6 @@ import {
|
|
|
50
44
|
measureRequestStageAsync,
|
|
51
45
|
} from "./stream-performance.mjs";
|
|
52
46
|
|
|
53
|
-
const RESPONSES_ONLY_FALLBACK = new Set([
|
|
54
|
-
"gpt-5.6-luna",
|
|
55
|
-
"gpt-5.6-sol",
|
|
56
|
-
"gpt-5.6-terra",
|
|
57
|
-
"gpt-5.5",
|
|
58
|
-
"gpt-5.4",
|
|
59
|
-
"gpt-5.4-mini",
|
|
60
|
-
"gpt-5.3-codex",
|
|
61
|
-
"gpt-5.2-codex",
|
|
62
|
-
]);
|
|
63
|
-
|
|
64
|
-
function isResponsesOnlyModel(model, getCachedModelEndpointsFn = getCachedModelEndpoints) {
|
|
65
|
-
const endpoints = getCachedModelEndpointsFn(model);
|
|
66
|
-
if (endpoints) {
|
|
67
|
-
const fakeModel = { supported_endpoints: endpoints };
|
|
68
|
-
if (modelSupportsChatCompletions(fakeModel)) return false;
|
|
69
|
-
if (modelIsResponsesOnly(fakeModel)) return true;
|
|
70
|
-
}
|
|
71
|
-
return RESPONSES_ONLY_FALLBACK.has(model);
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
function cachedModelSupportsResponses(model, getCachedModelEndpointsFn = getCachedModelEndpoints) {
|
|
75
|
-
const endpoints = getCachedModelEndpointsFn(model);
|
|
76
|
-
return Array.isArray(endpoints)
|
|
77
|
-
&& (endpoints.includes("/responses") || endpoints.includes("/v1/responses"));
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
function unsupportedCustomToolsError(model) {
|
|
81
|
-
const message = `Model ${model} has custom tool items that cannot be represented by Chat Completions, and cached endpoint metadata does not confirm Responses support`;
|
|
82
|
-
const error = new Error(message);
|
|
83
|
-
error.statusCode = 400;
|
|
84
|
-
error.code = "ccdx_custom_tools_require_responses";
|
|
85
|
-
error.jsonBody = {
|
|
86
|
-
error: {
|
|
87
|
-
message,
|
|
88
|
-
type: "invalid_request_error",
|
|
89
|
-
code: error.code,
|
|
90
|
-
model,
|
|
91
|
-
},
|
|
92
|
-
};
|
|
93
|
-
return error;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
47
|
function resolveRequestModel(model, openAIModelEnv, autoReviewModelResolver) {
|
|
97
48
|
const preference = model === CODEX_AUTO_REVIEW_MODEL && typeof autoReviewModelResolver === "function"
|
|
98
49
|
? autoReviewModelResolver() : undefined;
|
|
@@ -103,12 +54,33 @@ function resolveRequestModel(model, openAIModelEnv, autoReviewModelResolver) {
|
|
|
103
54
|
? preference.reasoningEffort : undefined };
|
|
104
55
|
}
|
|
105
56
|
|
|
57
|
+
function applySelectedRoute(prepared, routePlan, options) {
|
|
58
|
+
try { return applyResponseHistoryRoutePlan(prepared, routePlan); }
|
|
59
|
+
catch (error) {
|
|
60
|
+
if (error.code !== "ccdx_provider_history_rebuild_required") throw error;
|
|
61
|
+
return recoverSelectedRoute(prepared, routePlan, error, options);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function recoverSelectedRoute(prepared, routePlan, error, { req, env, signal, assertActive, reserveHistory }) {
|
|
66
|
+
try {
|
|
67
|
+
const { recoverLocalCompaction } = await import("./local-compaction-recovery.mjs");
|
|
68
|
+
const restored = await recoverLocalCompaction(prepared, { request: req, env, signal, assertActive, reserveHistory, maxBytes: MAX_DECODED_BODY_BYTES });
|
|
69
|
+
return applyResponseHistoryRoutePlan(restored, routePlan);
|
|
70
|
+
} catch (failure) {
|
|
71
|
+
assertActive?.();
|
|
72
|
+
error.jsonBody.error.recovery.local_status = /^[a-z][a-z_]{1,60}$/.test(failure.code || "") ? failure.code : "local_history_unavailable";
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
106
77
|
export function createResponsesHandler(options) {
|
|
78
|
+
const provider = options.provider || defaultGithubProvider;
|
|
107
79
|
const {
|
|
108
80
|
acquireRequest,
|
|
109
81
|
autoReviewModelResolver,
|
|
110
82
|
chatCompletionsFn,
|
|
111
|
-
getCachedModelEndpointsFn = getCachedModelEndpoints,
|
|
83
|
+
getCachedModelEndpointsFn = provider.client.getCachedModelEndpoints,
|
|
112
84
|
imagePressure,
|
|
113
85
|
keepaliveIntervalMs,
|
|
114
86
|
modelRegistry,
|
|
@@ -262,15 +234,7 @@ export function createResponsesHandler(options) {
|
|
|
262
234
|
const streaming = prepared.body.stream === true;
|
|
263
235
|
const resolvedModel = resolveRequestModel(model, openAIModelEnv, autoReviewModelResolver);
|
|
264
236
|
const { requestedModel } = resolvedModel;
|
|
265
|
-
|
|
266
|
-
const priorityTierModel = requestedModel === upstreamModel
|
|
267
|
-
? resolveCopilotPriorityTierModel(upstreamModel, prepared.body.service_tier, modelRegistry?.models)
|
|
268
|
-
: null;
|
|
269
|
-
if (priorityTierModel) {
|
|
270
|
-
upstreamModel = priorityTierModel;
|
|
271
|
-
delete prepared.body.service_tier;
|
|
272
|
-
}
|
|
273
|
-
stripUnsupportedGpt6ServiceTier(prepared.body, requestedModel, upstreamModel, priorityTierModel);
|
|
237
|
+
const { upstreamModel, forceResponses } = provider.selectModel(prepared.body, resolvedModel, modelRegistry?.models);
|
|
274
238
|
if (requestedModel === CODEX_AUTO_REVIEW_MODEL) {
|
|
275
239
|
delete prepared.body.service_tier;
|
|
276
240
|
if (resolvedModel.reasoningEffort || prepared.body.reasoning?.effort === undefined) {
|
|
@@ -282,23 +246,13 @@ export function createResponsesHandler(options) {
|
|
|
282
246
|
markRequestObservation({ context_window_tokens: modelContextWindowTokens(modelRegistry?.models, upstreamModel) });
|
|
283
247
|
const upstreamLog = upstreamModel === requestedModel ? "" : ` upstream_model=${upstreamModel}`;
|
|
284
248
|
console.log(status("info", `responses model=${requestedModel}${upstreamLog} stream=${streaming}`));
|
|
285
|
-
const
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
if (usesCustomTools && !useNativeResponses) throw unsupportedCustomToolsError(upstreamModel);
|
|
291
|
-
const routePlan = createRoutePlan({
|
|
292
|
-
disposition: "relay",
|
|
293
|
-
origin: "ccdx",
|
|
294
|
-
profile: "codex",
|
|
295
|
-
protocol: useNativeResponses ? "openai-responses" : "openai-chat-completions",
|
|
296
|
-
model: upstreamModel,
|
|
297
|
-
surface: "responses",
|
|
298
|
-
});
|
|
299
|
-
prepared = applyResponseHistoryRoutePlan(prepared, routePlan);
|
|
249
|
+
const routePlan = provider.route(prepared.body, { requestedModel, upstreamModel, forceResponses,
|
|
250
|
+
surface: "responses", getCachedModelEndpoints: getCachedModelEndpointsFn });
|
|
251
|
+
const selected = applySelectedRoute(prepared, routePlan, { req, env: openAIModelEnv, signal: abort.signal,
|
|
252
|
+
assertActive: assertPrepareActive, reserveHistory: releaseRequest.reserveResponseHistory });
|
|
253
|
+
prepared = selected instanceof Promise ? await selected : selected;
|
|
300
254
|
if (prepared.historyParentId === null) releaseHistorySnapshot();
|
|
301
|
-
|
|
255
|
+
provider.applyRequestPolicies(prepared.body);
|
|
302
256
|
if (routePlan.protocol === "openai-responses") {
|
|
303
257
|
const restorePlaintextHistory = async (context, { reserveHistory } = {}) => {
|
|
304
258
|
assertPrepareActive();
|
|
@@ -307,6 +261,7 @@ export function createResponsesHandler(options) {
|
|
|
307
261
|
signal: abort.signal, assertActive: assertPrepareActive, reserveHistory, maxBytes: MAX_DECODED_BODY_BYTES });
|
|
308
262
|
};
|
|
309
263
|
const result = await proxyCopilotResponses(prepared, req, res, responsesFn, {
|
|
264
|
+
compatibility: provider.compatibility,
|
|
310
265
|
acquireRetryPreparation,
|
|
311
266
|
assertPrepareActive,
|
|
312
267
|
signal: abort.signal,
|
|
@@ -446,6 +401,7 @@ export function createResponsesHandler(options) {
|
|
|
446
401
|
}
|
|
447
402
|
|
|
448
403
|
export function createResponsesCompactHandler(options) {
|
|
404
|
+
const provider = options.provider || defaultGithubProvider;
|
|
449
405
|
const {
|
|
450
406
|
acquireRequest,
|
|
451
407
|
autoReviewModelResolver,
|
|
@@ -547,15 +503,7 @@ export function createResponsesCompactHandler(options) {
|
|
|
547
503
|
const model = parsed.model || "unknown";
|
|
548
504
|
const resolvedModel = resolveRequestModel(model, openAIModelEnv, autoReviewModelResolver);
|
|
549
505
|
const { requestedModel } = resolvedModel;
|
|
550
|
-
|
|
551
|
-
const priorityTierModel = requestedModel === upstreamModel
|
|
552
|
-
? resolveCopilotPriorityTierModel(upstreamModel, prepared.body.service_tier, modelRegistry?.models)
|
|
553
|
-
: null;
|
|
554
|
-
if (priorityTierModel) {
|
|
555
|
-
upstreamModel = priorityTierModel;
|
|
556
|
-
delete prepared.body.service_tier;
|
|
557
|
-
}
|
|
558
|
-
stripUnsupportedGpt6ServiceTier(prepared.body, requestedModel, upstreamModel, priorityTierModel);
|
|
506
|
+
const { upstreamModel, forceResponses } = provider.selectModel(prepared.body, resolvedModel, modelRegistry?.models);
|
|
559
507
|
if (requestedModel === CODEX_AUTO_REVIEW_MODEL) {
|
|
560
508
|
delete prepared.body.service_tier;
|
|
561
509
|
if (resolvedModel.reasoningEffort || prepared.body.reasoning?.effort === undefined) {
|
|
@@ -567,17 +515,14 @@ export function createResponsesCompactHandler(options) {
|
|
|
567
515
|
const upstreamLog = upstreamModel === requestedModel ? "" : ` upstream_model=${upstreamModel}`;
|
|
568
516
|
console.log(status("info", `responses compact model=${requestedModel}${upstreamLog} stream=false`));
|
|
569
517
|
markResponseModel(upstreamModel, { requestedModel });
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
protocol: "openai-responses",
|
|
575
|
-
model: upstreamModel,
|
|
576
|
-
surface: "responses-compact",
|
|
577
|
-
}));
|
|
518
|
+
const selected = applySelectedRoute(prepared, provider.route(prepared.body, {
|
|
519
|
+
requestedModel, upstreamModel, forceResponses, surface: "responses-compact" }), { req, env: openAIModelEnv,
|
|
520
|
+
signal: abort.signal, assertActive: assertPrepareActive, reserveHistory: releaseRequest.reserveResponseHistory });
|
|
521
|
+
prepared = selected instanceof Promise ? await selected : selected;
|
|
578
522
|
releaseHistorySnapshot();
|
|
579
|
-
|
|
523
|
+
provider.applyRequestPolicies(prepared.body);
|
|
580
524
|
const result = await proxyCopilotResponses(prepared, req, res, responsesCompactFn, {
|
|
525
|
+
compatibility: provider.compatibility,
|
|
581
526
|
assertPrepareActive,
|
|
582
527
|
signal: abort.signal,
|
|
583
528
|
abort,
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export function isNativeImageTool(tool, { collisionFallback = false } = {}) {
|
|
2
|
+
if (!tool || typeof tool !== "object") return false;
|
|
3
|
+
const type = String(tool.type || "").toLowerCase();
|
|
4
|
+
if (["image_gen", "image_generation"].includes(type)) return true;
|
|
5
|
+
if (!collisionFallback) return false;
|
|
6
|
+
const name = String(tool.name || tool.function?.name || "").toLowerCase();
|
|
7
|
+
const namespace = String(tool.namespace || "").toLowerCase();
|
|
8
|
+
if (["image_gen", "image_generation"].includes(name)) return true;
|
|
9
|
+
if (namespace === "image_gen" || namespace === "image_generation") return true;
|
|
10
|
+
return [type, name, namespace].some((value) => value.startsWith("image_gen"));
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function toolName(tool) {
|
|
14
|
+
return String(tool?.name || tool?.function?.name || "").trim();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Providers opt into this only after verifying that their native image tools
|
|
18
|
+
// are unavailable. Preserve named function/MCP tools and tool_choice invariants.
|
|
19
|
+
export function removeNativeImageTools(body, options = {}) {
|
|
20
|
+
if (!body || typeof body !== "object") return false;
|
|
21
|
+
const removedNames = new Set();
|
|
22
|
+
const survivingNames = new Set();
|
|
23
|
+
let survivingTools = 0;
|
|
24
|
+
let changed = false;
|
|
25
|
+
const filter = (container, topLevel = false) => {
|
|
26
|
+
if (!Array.isArray(container?.tools)) return;
|
|
27
|
+
const tools = container.tools;
|
|
28
|
+
const filtered = tools.filter((tool) => {
|
|
29
|
+
const removed = isNativeImageTool(tool, options);
|
|
30
|
+
const name = toolName(tool);
|
|
31
|
+
if (removed && name) removedNames.add(name);
|
|
32
|
+
if (!removed) {
|
|
33
|
+
survivingTools += 1;
|
|
34
|
+
if (name) survivingNames.add(name);
|
|
35
|
+
}
|
|
36
|
+
return !removed;
|
|
37
|
+
});
|
|
38
|
+
if (filtered.length === tools.length) return;
|
|
39
|
+
changed = true;
|
|
40
|
+
if (topLevel && !filtered.length) delete container.tools;
|
|
41
|
+
else container.tools = filtered;
|
|
42
|
+
};
|
|
43
|
+
filter(body, true);
|
|
44
|
+
for (const item of Array.isArray(body.input) ? body.input : []) {
|
|
45
|
+
if (["additional_tools", "tool_search_output"].includes(item?.type)) filter(item);
|
|
46
|
+
}
|
|
47
|
+
if (!changed) return false;
|
|
48
|
+
|
|
49
|
+
const removedChoice = (choice) => isNativeImageTool(choice, options)
|
|
50
|
+
|| (removedNames.has(toolName(choice)) && !survivingNames.has(toolName(choice)));
|
|
51
|
+
if (body.tool_choice?.type === "allowed_tools" && Array.isArray(body.tool_choice.tools)) {
|
|
52
|
+
const choices = body.tool_choice.tools.filter((choice) => !removedChoice(choice));
|
|
53
|
+
body.tool_choice = choices.length ? { ...body.tool_choice, tools: choices } : "none";
|
|
54
|
+
} else if (removedChoice(body.tool_choice)) {
|
|
55
|
+
if (survivingTools) body.tool_choice = "none";
|
|
56
|
+
else delete body.tool_choice;
|
|
57
|
+
} else if (body.tool_choice === "required" && !survivingTools) {
|
|
58
|
+
delete body.tool_choice;
|
|
59
|
+
}
|
|
60
|
+
return true;
|
|
61
|
+
}
|
package/src/responses-proxy.mjs
CHANGED
|
@@ -337,7 +337,7 @@ function streamHeaders(resp) {
|
|
|
337
337
|
async function selectStreamFailureRetry(reqContext, failure, usedRetryPolicies, options) {
|
|
338
338
|
if (!failure) return null;
|
|
339
339
|
const errorText = responseFailureText(failure.event, failure.eventType);
|
|
340
|
-
if (!hasCopilotResponseRetryPolicy(400, errorText, usedRetryPolicies)) return null;
|
|
340
|
+
if (!(options.compatibility?.hasRetry || hasCopilotResponseRetryPolicy)(400, errorText, usedRetryPolicies)) return null;
|
|
341
341
|
const preparation = await options.acquireRetryPreparation?.(reqContext);
|
|
342
342
|
let keepReservation = false;
|
|
343
343
|
try {
|
|
@@ -345,7 +345,7 @@ async function selectStreamFailureRetry(reqContext, failure, usedRetryPolicies,
|
|
|
345
345
|
assertActive: options.assertPrepareActive,
|
|
346
346
|
historySnapshot: preparation?.historySnapshot,
|
|
347
347
|
});
|
|
348
|
-
const retry = await selectCopilotResponseRetryWithHistory(restored, 400, errorText, usedRetryPolicies, {
|
|
348
|
+
const retry = await (options.compatibility?.selectRetry || selectCopilotResponseRetryWithHistory)(restored, 400, errorText, usedRetryPolicies, {
|
|
349
349
|
...options, reserveHistory: preparation?.reserveHistory || options.reserveHistory,
|
|
350
350
|
});
|
|
351
351
|
options.assertPrepareActive?.();
|
|
@@ -489,7 +489,7 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
|
|
|
489
489
|
if (retry) {
|
|
490
490
|
console.warn(status("warn", retry.warning));
|
|
491
491
|
try {
|
|
492
|
-
opened = await openCopilotResponse(retry.reqContext, upstream, {
|
|
492
|
+
opened = await (options.compatibility?.openResponse || openCopilotResponse)(retry.reqContext, upstream, {
|
|
493
493
|
...options,
|
|
494
494
|
usedRetryPolicies: retry.usedPolicies,
|
|
495
495
|
});
|
|
@@ -537,7 +537,7 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
|
|
|
537
537
|
export async function proxyCopilotResponses(reqContext, req, res, upstream = copilotResponses, options = {}) {
|
|
538
538
|
let opened;
|
|
539
539
|
try {
|
|
540
|
-
opened = await openCopilotResponse(reqContext, upstream, options);
|
|
540
|
+
opened = await (options.compatibility?.openResponse || openCopilotResponse)(reqContext, upstream, options);
|
|
541
541
|
opened.streamRetryEligible = opened.reqContext.body.stream === true
|
|
542
542
|
&& hasEncryptedResponseState(opened.reqContext.body?.input);
|
|
543
543
|
} finally {
|
|
@@ -609,7 +609,7 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
|
|
|
609
609
|
if (retry) {
|
|
610
610
|
console.warn(status("warn", retry.warning));
|
|
611
611
|
try {
|
|
612
|
-
opened = await openCopilotResponse(retry.reqContext, upstream, {
|
|
612
|
+
opened = await (options.compatibility?.openResponse || openCopilotResponse)(retry.reqContext, upstream, {
|
|
613
613
|
...options,
|
|
614
614
|
usedRetryPolicies: retry.usedPolicies,
|
|
615
615
|
});
|
|
@@ -8,6 +8,8 @@ import {
|
|
|
8
8
|
import { isResponsesToolOutputItem, readResponsesToolOutputParts } from "./responses-content.mjs";
|
|
9
9
|
import { enforceResponsesImageLimit } from "./responses-image-limit.mjs";
|
|
10
10
|
import { routePlanAffinity, sameRoutePlanAffinity } from "./route-plan.mjs";
|
|
11
|
+
import { currentRequestContext } from "./request-context.mjs";
|
|
12
|
+
import { httpError } from "./http-errors.mjs";
|
|
11
13
|
|
|
12
14
|
export {
|
|
13
15
|
isEncryptedContentVerificationError,
|
|
@@ -301,6 +303,26 @@ export function finalizeEncryptedHistoryRebase(reqContext) {
|
|
|
301
303
|
export function applyResponseHistoryRoutePlan(reqContext, routePlan) {
|
|
302
304
|
const next = reqContext;
|
|
303
305
|
next.routePlan = routePlan;
|
|
306
|
+
const context = currentRequestContext();
|
|
307
|
+
if (!next.historyParentId && !context?.historyTransferNamespace && !next.historyRouteMetadata?.length) return next;
|
|
308
|
+
const affinity = routePlanAffinity(routePlan);
|
|
309
|
+
const routeMetadata = next.historyRouteMetadata || [];
|
|
310
|
+
const knownHistory = routeMetadata.length > 0 && routeMetadata.every(metadata => metadata.affinity && affinity);
|
|
311
|
+
const providerChanged = (Boolean(context?.historyTransferNamespace) && !knownHistory)
|
|
312
|
+
|| routeMetadata.some(metadata => metadata.affinity && affinity
|
|
313
|
+
&& (metadata.affinity.origin !== affinity.origin || metadata.affinity.profile !== affinity.profile));
|
|
314
|
+
if (providerChanged) {
|
|
315
|
+
const input = next.body.input || [];
|
|
316
|
+
if (input.some(item => item?.type !== "reasoning" && hasEncryptedResponseState(item))) {
|
|
317
|
+
const message = "This conversation contains opaque state owned by another provider. Restore complete plaintext history before switching; earlier context was preserved.";
|
|
318
|
+
throw Object.assign(httpError(message, 400), { code: "ccdx_provider_history_rebuild_required", jsonBody: {
|
|
319
|
+
error: { message, type: "invalid_request_error", code: "ccdx_provider_history_rebuild_required", recovery: { action: "restore_plaintext_history" } },
|
|
320
|
+
} });
|
|
321
|
+
}
|
|
322
|
+
const plaintext = input.filter(item => !(item?.type === "reasoning" && item.encrypted_content));
|
|
323
|
+
return { ...next, body: { ...next.body, input: plaintext }, historyParentId: null, historyRootId: null,
|
|
324
|
+
inputItems: plaintext, historyInputItems: plaintext, currentInputStart: 0 };
|
|
325
|
+
}
|
|
304
326
|
if (!next.historyParentId) return next;
|
|
305
327
|
const currentAffinity = routePlanAffinity(routePlan);
|
|
306
328
|
const historyMetadata = next.historyRouteMetadata;
|
|
@@ -457,4 +479,7 @@ export function rememberResponseHistory(reqContext, responseJson) {
|
|
|
457
479
|
routeAffinity: routePlanAffinity(reqContext.routePlan),
|
|
458
480
|
takeOwnership: reqContext.takeHistoryOwnership,
|
|
459
481
|
});
|
|
482
|
+
if (responseJson.status === "completed" || compacted) {
|
|
483
|
+
try { currentRequestContext()?.onHistoryStored?.(); } catch {}
|
|
484
|
+
}
|
|
460
485
|
}
|
|
@@ -125,7 +125,7 @@ function emptyOutcomes() {
|
|
|
125
125
|
|
|
126
126
|
function modelLabel(value) {
|
|
127
127
|
const model = String(value || "").trim();
|
|
128
|
-
return model === "codex-auto-review" || /^gpt-[A-Za-z0-9._-]{1,72}$/.test(model)
|
|
128
|
+
return model === "codex-auto-review" || /^(?:gpt|claude)-[A-Za-z0-9._-]{1,72}$/.test(model)
|
|
129
129
|
? model : "other";
|
|
130
130
|
}
|
|
131
131
|
|
|
@@ -180,8 +180,8 @@ function routeSnapshot(route) {
|
|
|
180
180
|
};
|
|
181
181
|
}
|
|
182
182
|
|
|
183
|
-
export function createStreamPerformanceMetrics({ now = () => performance.now(), wallNow = () => new Date().toISOString() } = {}) {
|
|
184
|
-
const routes = Object.fromEntries(
|
|
183
|
+
export function createStreamPerformanceMetrics({ now = () => performance.now(), wallNow = () => new Date().toISOString(), routeNames = PERFORMANCE_ROUTES } = {}) {
|
|
184
|
+
const routes = Object.fromEntries(routeNames.map((name) => [name, createRoutePerformance()]));
|
|
185
185
|
const recentRequests = [];
|
|
186
186
|
|
|
187
187
|
return {
|
|
@@ -196,6 +196,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
196
196
|
let failed = false;
|
|
197
197
|
let finished = false;
|
|
198
198
|
let model = "other";
|
|
199
|
+
let provider = null;
|
|
199
200
|
let terminalOutcome = null;
|
|
200
201
|
let terminalOrigin = null;
|
|
201
202
|
let incompleteReason = null;
|
|
@@ -266,6 +267,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
266
267
|
setModel(value) {
|
|
267
268
|
model = modelLabel(value);
|
|
268
269
|
},
|
|
270
|
+
setProvider(value) { if (["github", "m365"].includes(value)) provider = value; },
|
|
269
271
|
attemptCount() { return attempts; },
|
|
270
272
|
attemptTimings() { return attemptTimings.map(attempt => ({ ...attempt })); },
|
|
271
273
|
observeContext(values) {
|
|
@@ -312,6 +314,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
312
314
|
recentRequests.push({
|
|
313
315
|
request_id: typeof requestId === "string" && /^[a-zA-Z0-9_-]{1,80}$/.test(requestId) ? requestId : null,
|
|
314
316
|
at, route: routeName, model, outcome, origin, phase,
|
|
317
|
+
...(provider ? { provider } : {}),
|
|
315
318
|
empty_stream_completion: emptyStreamCompletion,
|
|
316
319
|
failed: failed || aborted || (terminalOutcome !== null && terminalOutcome !== "completed"),
|
|
317
320
|
http_status: Number.isInteger(statusCode) && statusCode >= 100 && statusCode <= 599 ? statusCode : null,
|
|
@@ -355,7 +358,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
355
358
|
},
|
|
356
359
|
snapshot() {
|
|
357
360
|
return {
|
|
358
|
-
by_route: Object.fromEntries(
|
|
361
|
+
by_route: Object.fromEntries(routeNames.map((name) => [name, routeSnapshot(routes[name])])),
|
|
359
362
|
recent_requests: recentRequests.map((entry) => ({ ...entry, attempts: entry.attempts.map(attempt => ({ ...attempt })), context: { ...entry.context }, timings_ms: { ...entry.timings_ms } })),
|
|
360
363
|
};
|
|
361
364
|
},
|
package/src/usage-analysis.mjs
CHANGED
|
@@ -6,11 +6,11 @@ const MAX_BYTES = 2 * 1024 * 1024;
|
|
|
6
6
|
const cache = new Map();
|
|
7
7
|
|
|
8
8
|
// Only bounded, settled-file aggregates survive. No record index or payload cache.
|
|
9
|
-
export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "UTC", now = Date.now(), warn = console.error } = {}) {
|
|
9
|
+
export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "UTC", now = Date.now(), warn = console.error, provider = "" } = {}) {
|
|
10
10
|
const analytics = createUsageAnalytics({ timeZone, now });
|
|
11
11
|
const zone = new Intl.DateTimeFormat("sv-SE", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
|
|
12
12
|
const version = warn === console.error ? await usageSummaryVersion(filePath) : null;
|
|
13
|
-
const key = version === null ? null : `${version}\0${zone.resolvedOptions().timeZone}\0${zone.format(new Date(now))}`;
|
|
13
|
+
const key = version === null ? null : `${version}\0${provider}\0${zone.resolvedOptions().timeZone}\0${zone.format(new Date(now))}`;
|
|
14
14
|
if (key && cache.has(key)) return structuredClone(await cache.get(key).promise);
|
|
15
15
|
if (key) {
|
|
16
16
|
for (const [old, entry] of cache) if (entry.version !== version) cache.delete(old);
|
|
@@ -20,6 +20,7 @@ export async function analyzeUsageLogs(filePath = usageLogPath(), { timeZone = "
|
|
|
20
20
|
entry.promise = (async () => {
|
|
21
21
|
let warned = false;
|
|
22
22
|
const summary = await summarizeUsageLogs(filePath, {
|
|
23
|
+
provider,
|
|
23
24
|
onRecord: analytics.record,
|
|
24
25
|
warn(message) { warned = true; warn(message); },
|
|
25
26
|
});
|
package/src/usage-store.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import readline from "node:readline";
|
|
|
6
6
|
import { appendRotatingLines, parseByteLimit, rotatedFilePath } from "./file-rotation.mjs";
|
|
7
7
|
import { withFileLock } from "./lock.mjs";
|
|
8
8
|
import { terminalCell } from "./terminal-text.mjs";
|
|
9
|
+
import { currentRequestContext } from "./request-context.mjs";
|
|
9
10
|
|
|
10
11
|
const DEFAULT_USAGE_PATH = path.join(os.homedir(), ".local", "share", "codex-copilot-dx", "usage.jsonl");
|
|
11
12
|
const DEFAULT_USAGE_MAX_BYTES = 32 * 1024 * 1024;
|
|
@@ -108,9 +109,25 @@ export function buildResponsesUsageRecord({ surface = "responses", mode, model,
|
|
|
108
109
|
response_id: responseObj?.id,
|
|
109
110
|
usage,
|
|
110
111
|
copilot_usage: copilotUsage,
|
|
112
|
+
...(currentRequestContext()?.provider ? { provider: currentRequestContext().provider } : {}),
|
|
111
113
|
});
|
|
112
114
|
}
|
|
113
115
|
|
|
116
|
+
export function buildMessagesUsageRecord({ model, responseId, usage, mode, client = "claude" } = {}) {
|
|
117
|
+
if (!usage || typeof usage !== "object") return null;
|
|
118
|
+
const count = key => Number.isFinite(usage[key]) && usage[key] >= 0 ? usage[key] : undefined;
|
|
119
|
+
const uncached = count("input_tokens"), read = count("cache_read_input_tokens"), written = count("cache_creation_input_tokens");
|
|
120
|
+
const input = uncached === undefined ? undefined : uncached + (read || 0) + (written || 0);
|
|
121
|
+
const output = count("output_tokens");
|
|
122
|
+
if (input === undefined && output === undefined) return null;
|
|
123
|
+
return compactObject({ ts: new Date().toISOString(), provider: "m365", surface: "messages", client, mode, model, response_id: responseId,
|
|
124
|
+
usage: compactObject({ input_tokens: input, output_tokens: output, cached_input_tokens: read,
|
|
125
|
+
cache_write_input_tokens: written, total_tokens: input !== undefined && output !== undefined ? input + output : undefined,
|
|
126
|
+
reasoning_output_tokens: numberOrUndefined(usage.output_tokens_details?.thinking_tokens) }),
|
|
127
|
+
anthropic_usage: compactObject({ input_tokens: uncached, cache_read_input_tokens: read,
|
|
128
|
+
cache_creation_input_tokens: written, output_tokens: output }) });
|
|
129
|
+
}
|
|
130
|
+
|
|
114
131
|
function takePendingWrites(filePath, maxBytes) {
|
|
115
132
|
const batch = [];
|
|
116
133
|
let retained = 0;
|
|
@@ -260,9 +277,17 @@ function addUsageTotals(target, usage = {}) {
|
|
|
260
277
|
}
|
|
261
278
|
}
|
|
262
279
|
|
|
263
|
-
export function
|
|
264
|
-
|
|
280
|
+
export function usageProvider(record) {
|
|
281
|
+
return record.provider === undefined || record.provider === "github" ? "github" : record.provider === "m365" ? "m365" : "unknown";
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export function summarizeUsage(records, { provider = "" } = {}) {
|
|
285
|
+
if (provider && !["github", "m365"].includes(provider)) throw new Error("Usage provider must be github or m365");
|
|
286
|
+
const summary = { requests: 0, totals: {}, byModel: {}, providers: { github: 0, m365: 0, unknown: 0 }, ...(provider ? { provider_filter: provider } : {}) };
|
|
265
287
|
for (const record of records) {
|
|
288
|
+
const source = usageProvider(record);
|
|
289
|
+
if (provider && provider !== source) continue;
|
|
290
|
+
summary.providers[source] += 1;
|
|
266
291
|
summary.requests += 1;
|
|
267
292
|
addUsageTotals(summary.totals, record.usage);
|
|
268
293
|
if (record.copilot_usage) {
|
|
@@ -270,7 +295,7 @@ export function summarizeUsage(records) {
|
|
|
270
295
|
summary.totals.total_nano_aiu = (summary.totals.total_nano_aiu || 0) + (record.copilot_usage.total_nano_aiu || 0);
|
|
271
296
|
}
|
|
272
297
|
const model = record.model || "unknown";
|
|
273
|
-
if (!summary.byModel
|
|
298
|
+
if (!Object.hasOwn(summary.byModel, model)) Object.defineProperty(summary.byModel, model, { value: { requests: 0 }, enumerable: true, configurable: true, writable: true });
|
|
274
299
|
const modelTotals = summary.byModel[model];
|
|
275
300
|
modelTotals.requests += 1;
|
|
276
301
|
addUsageTotals(modelTotals, record.usage);
|
|
@@ -291,16 +316,18 @@ export function summarizeUsage(records) {
|
|
|
291
316
|
return summary;
|
|
292
317
|
}
|
|
293
318
|
|
|
294
|
-
async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord } = {}) {
|
|
295
|
-
const summary =
|
|
319
|
+
async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord, provider = "" } = {}) {
|
|
320
|
+
const summary = summarizeUsage([], { provider });
|
|
296
321
|
for (const candidate of [rotatedFilePath(filePath), filePath]) {
|
|
297
322
|
for await (const record of iterateUsageRecords(candidate, { warn })) {
|
|
323
|
+
if (provider && provider !== usageProvider(record)) continue;
|
|
298
324
|
const one = summarizeUsage([record]);
|
|
299
325
|
onRecord?.(record, one);
|
|
300
326
|
summary.requests += one.requests;
|
|
301
327
|
addUsageTotals(summary.totals, one.totals);
|
|
328
|
+
addUsageTotals(summary.providers, one.providers);
|
|
302
329
|
for (const [model, values] of Object.entries(one.byModel)) {
|
|
303
|
-
if (!summary.byModel
|
|
330
|
+
if (!Object.hasOwn(summary.byModel, model)) Object.defineProperty(summary.byModel, model, { value: { requests: 0 }, enumerable: true, configurable: true, writable: true });
|
|
304
331
|
addUsageTotals(summary.byModel[model], values);
|
|
305
332
|
}
|
|
306
333
|
}
|
|
@@ -330,21 +357,23 @@ export async function usageSummaryVersion(filePath) {
|
|
|
330
357
|
} catch { return null; } // Uncacheable metadata never replaces the normal read/error path.
|
|
331
358
|
}
|
|
332
359
|
|
|
333
|
-
export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = console.error, onRecord } = {}) {
|
|
334
|
-
if (
|
|
335
|
-
|
|
360
|
+
export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = console.error, onRecord, provider = "" } = {}) {
|
|
361
|
+
if (provider && !["github", "m365"].includes(provider)) throw new Error("Usage provider must be github or m365");
|
|
362
|
+
if (onRecord || warn !== console.error) return summarizeUsageLogFiles(filePath, { warn, onRecord, provider });
|
|
363
|
+
const fileVersion = await usageSummaryVersion(filePath);
|
|
364
|
+
const version = fileVersion === null ? null : `${fileVersion}\0${provider}`;
|
|
336
365
|
if (version === null) {
|
|
337
366
|
cachedSummary = null;
|
|
338
|
-
return summarizeUsageLogFiles(filePath, { warn });
|
|
367
|
+
return summarizeUsageLogFiles(filePath, { warn, provider });
|
|
339
368
|
}
|
|
340
369
|
if (cachedSummary?.version === version) return structuredClone(await cachedSummary.promise);
|
|
341
370
|
const entry = { version, promise: null };
|
|
342
371
|
cachedSummary = entry;
|
|
343
372
|
entry.promise = (async () => {
|
|
344
373
|
let warned = false;
|
|
345
|
-
const summary = await summarizeUsageLogFiles(filePath, { warn(message) { warned = true; warn(message); } });
|
|
374
|
+
const summary = await summarizeUsageLogFiles(filePath, { provider, warn(message) { warned = true; warn(message); } });
|
|
346
375
|
const after = await usageSummaryVersion(filePath);
|
|
347
|
-
const retain = !warned && after ===
|
|
376
|
+
const retain = !warned && after === fileVersion && Object.keys(summary.byModel).length <= 128
|
|
348
377
|
&& Buffer.byteLength(JSON.stringify(summary)) <= SUMMARY_CACHE_MAX_BYTES;
|
|
349
378
|
if (!retain && cachedSummary === entry) cachedSummary = null;
|
|
350
379
|
return summary;
|
package/src/usage.mjs
CHANGED
|
@@ -7,6 +7,8 @@ export {
|
|
|
7
7
|
usageLogPath,
|
|
8
8
|
usageLogMaxBytes,
|
|
9
9
|
buildResponsesUsageRecord,
|
|
10
|
+
buildMessagesUsageRecord,
|
|
11
|
+
usageProvider,
|
|
10
12
|
recordUsage,
|
|
11
13
|
recordResponsesUsage,
|
|
12
14
|
flushUsageWritesForTests,
|
|
@@ -33,6 +35,8 @@ function cacheHitPercent(usage) {
|
|
|
33
35
|
|
|
34
36
|
function formatPlainUsageSummary(summary, filePath, { sanitize = false } = {}) {
|
|
35
37
|
const lines = [`Usage log: ${filePath}`];
|
|
38
|
+
if (summary.provider_filter) lines.push(`Provider: ${summary.provider_filter}`);
|
|
39
|
+
else if (summary.providers?.m365) lines.push(`Providers: GitHub ${fmt(summary.providers.github)} / M365 ${fmt(summary.providers.m365)} (combined totals; use --provider to separate)`);
|
|
36
40
|
if (summary.requests === 0) {
|
|
37
41
|
lines.push("No usage records yet.");
|
|
38
42
|
return (sanitize ? lines.map((line) => terminalCell(line, { fallback: "" })) : lines).join("\n");
|
|
@@ -103,7 +107,8 @@ function formatTableUsageSummary(summary, filePath, output) {
|
|
|
103
107
|
} else {
|
|
104
108
|
table.compact = false;
|
|
105
109
|
}
|
|
106
|
-
const lines = [`Usage log: ${safePath}`,
|
|
110
|
+
const lines = [`Usage log: ${safePath}`, ...(summary.provider_filter ? [`Provider: ${summary.provider_filter}`]
|
|
111
|
+
: summary.providers?.m365 ? [`Providers: GitHub ${fmt(summary.providers.github)} / M365 ${fmt(summary.providers.m365)} (combined totals; use --provider to separate)`] : []), "", table.output];
|
|
107
112
|
if (table.compact) {
|
|
108
113
|
lines.push(
|
|
109
114
|
"",
|
|
@@ -137,7 +142,8 @@ export async function printUsageSummary({
|
|
|
137
142
|
output = process.stdout,
|
|
138
143
|
log = console.log,
|
|
139
144
|
warn = console.error,
|
|
145
|
+
provider = "",
|
|
140
146
|
} = {}) {
|
|
141
|
-
const summary = await summarizeUsageLogs(filePath, { warn });
|
|
147
|
+
const summary = await summarizeUsageLogs(filePath, { warn, provider });
|
|
142
148
|
log(formatUsageSummary(summary, { filePath, format, output }));
|
|
143
149
|
}
|