codex-copilot-dx 0.9.40 → 0.10.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 +25 -4
- package/bin/cli.mjs +37 -11
- package/docs/ARCHITECTURE.md +84 -13
- package/docs/REFERENCE.md +207 -16
- package/package.json +4 -1
- package/src/adapter.mjs +98 -152
- 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 +23 -7
- package/src/codex-model-catalog.mjs +7 -2
- package/src/copilot-client.mjs +4 -0
- package/src/copilot-responses-compat.mjs +1 -1
- package/src/copilot-responses-policy.mjs +11 -64
- package/src/dashboard/index.html +14 -4
- package/src/dashboard/language.js +40 -2
- package/src/dashboard/status.js +26 -4
- 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/http-transport.mjs +6 -3
- package/src/m365-settings.mjs +89 -0
- package/src/management-routes.mjs +118 -0
- package/src/native-prediction-windows.mjs +2 -7
- package/src/optional-routes.mjs +33 -0
- package/src/profile-model-runtime.mjs +4 -2
- package/src/provider-management.mjs +28 -0
- package/src/provider-runtime.mjs +179 -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 +66 -5
- package/src/response-history.mjs +20 -3
- package/src/responses-bridge.mjs +1 -1
- package/src/responses-handler.mjs +40 -103
- 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 +42 -10
- 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
package/src/response-history.mjs
CHANGED
|
@@ -1,10 +1,25 @@
|
|
|
1
1
|
import { httpError } from "./http-errors.mjs";
|
|
2
2
|
import { clearResponsesToolOutputPartsCache } from "./responses-content.mjs";
|
|
3
3
|
import { loadRuntimeConfig, parsePositiveInteger, RUNTIME_DEFAULTS } from "./runtime-config.mjs";
|
|
4
|
+
import { currentRequestContext } from "./request-context.mjs";
|
|
4
5
|
|
|
5
6
|
const DEFAULT_MAX_BYTES = RUNTIME_DEFAULTS.responseHistoryMaxBytes;
|
|
6
7
|
const DEFAULT_MAX_ENTRIES = RUNTIME_DEFAULTS.responseHistoryMaxEntries;
|
|
7
8
|
|
|
9
|
+
function historyKey(id, namespace = currentRequestContext()?.historyNamespace) {
|
|
10
|
+
if (typeof id === "string" && id.includes("\0")) throw httpError("Invalid previous_response_id", 400);
|
|
11
|
+
return namespace && id ? `\0${namespace}\0${id}` : id;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function readableHistoryKey(id) {
|
|
15
|
+
const current = historyKey(id), transfer = currentRequestContext()?.historyTransferNamespace;
|
|
16
|
+
if (!transfer) return current;
|
|
17
|
+
const previous = historyKey(id, transfer);
|
|
18
|
+
if (previous === current) return current;
|
|
19
|
+
if (histories.has(current) && histories.has(previous)) throw httpError("previous_response_id is ambiguous across providers; replay the full plaintext conversation", 400);
|
|
20
|
+
return histories.has(current) ? current : previous;
|
|
21
|
+
}
|
|
22
|
+
|
|
8
23
|
function cloneJson(value) {
|
|
9
24
|
return value === undefined ? undefined : structuredClone(value);
|
|
10
25
|
}
|
|
@@ -278,13 +293,13 @@ export function responseHistoryStats() {
|
|
|
278
293
|
}
|
|
279
294
|
|
|
280
295
|
export function responseHistoryRootId(responseId) {
|
|
281
|
-
return histories.get(responseId)?.rootId || null;
|
|
296
|
+
return histories.get(readableHistoryKey(responseId))?.rootId || null;
|
|
282
297
|
}
|
|
283
298
|
|
|
284
299
|
function responseHistoryChain(responseId) {
|
|
285
300
|
const chain = [];
|
|
286
301
|
const seen = new Set();
|
|
287
|
-
let currentId = responseId;
|
|
302
|
+
let currentId = readableHistoryKey(responseId);
|
|
288
303
|
while (currentId) {
|
|
289
304
|
if (seen.has(currentId)) throw httpError(`Cycle detected in local response history: ${currentId}`, 500);
|
|
290
305
|
seen.add(currentId);
|
|
@@ -294,7 +309,7 @@ function responseHistoryChain(responseId) {
|
|
|
294
309
|
const wasEvicted = evictedIds.has(currentId);
|
|
295
310
|
if (wasEvicted) evictedLookupMisses += 1;
|
|
296
311
|
const reason = wasEvicted ? " was evicted after reaching the local history limit" : " is not available";
|
|
297
|
-
throw httpError(`previous_response_id${reason}: ${currentId}`, 400);
|
|
312
|
+
throw httpError(`previous_response_id${reason}: ${String(currentId).split("\0").at(-1)}`, 400);
|
|
298
313
|
}
|
|
299
314
|
chain.push(entry);
|
|
300
315
|
currentId = entry.parentId;
|
|
@@ -381,6 +396,8 @@ export function rememberResponseHistoryNode({
|
|
|
381
396
|
takeOwnership = false,
|
|
382
397
|
}) {
|
|
383
398
|
if (!id || !Array.isArray(inputItems)) return false;
|
|
399
|
+
id = historyKey(id);
|
|
400
|
+
parentId = parentId ? historyKey(parentId) : null;
|
|
384
401
|
const existing = histories.get(id);
|
|
385
402
|
const parentEntry = parentId ? histories.get(parentId) : null;
|
|
386
403
|
if (parentId && !parentEntry) {
|
package/src/responses-bridge.mjs
CHANGED
|
@@ -273,7 +273,7 @@ export async function forwardToChat(chatReq, emitEvent, onDone, onError, options
|
|
|
273
273
|
bodyText,
|
|
274
274
|
onUpstreamStart,
|
|
275
275
|
});
|
|
276
|
-
markUpstreamHeaders();
|
|
276
|
+
markUpstreamHeaders(resp.status);
|
|
277
277
|
} finally {
|
|
278
278
|
bodyText = undefined;
|
|
279
279
|
chatReq = undefined;
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { applyCopilotResponsesRequestPolicies } 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,21 +54,33 @@ function resolveRequestModel(model, openAIModelEnv, autoReviewModelResolver) {
|
|
|
103
54
|
? preference.reasoningEffort : undefined };
|
|
104
55
|
}
|
|
105
56
|
|
|
106
|
-
function
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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;
|
|
112
74
|
}
|
|
113
75
|
}
|
|
114
76
|
|
|
115
77
|
export function createResponsesHandler(options) {
|
|
78
|
+
const provider = options.provider || defaultGithubProvider;
|
|
116
79
|
const {
|
|
117
80
|
acquireRequest,
|
|
118
81
|
autoReviewModelResolver,
|
|
119
82
|
chatCompletionsFn,
|
|
120
|
-
getCachedModelEndpointsFn = getCachedModelEndpoints,
|
|
83
|
+
getCachedModelEndpointsFn = provider.client.getCachedModelEndpoints,
|
|
121
84
|
imagePressure,
|
|
122
85
|
keepaliveIntervalMs,
|
|
123
86
|
modelRegistry,
|
|
@@ -271,15 +234,7 @@ export function createResponsesHandler(options) {
|
|
|
271
234
|
const streaming = prepared.body.stream === true;
|
|
272
235
|
const resolvedModel = resolveRequestModel(model, openAIModelEnv, autoReviewModelResolver);
|
|
273
236
|
const { requestedModel } = resolvedModel;
|
|
274
|
-
|
|
275
|
-
const priorityTierModel = requestedModel === upstreamModel
|
|
276
|
-
? resolveCopilotPriorityTierModel(upstreamModel, prepared.body.service_tier, modelRegistry?.models)
|
|
277
|
-
: null;
|
|
278
|
-
if (priorityTierModel) {
|
|
279
|
-
upstreamModel = priorityTierModel;
|
|
280
|
-
delete prepared.body.service_tier;
|
|
281
|
-
}
|
|
282
|
-
stripUnsupportedGpt6ServiceTier(prepared.body, requestedModel, upstreamModel, priorityTierModel);
|
|
237
|
+
const { upstreamModel, forceResponses } = provider.selectModel(prepared.body, resolvedModel, modelRegistry?.models);
|
|
283
238
|
if (requestedModel === CODEX_AUTO_REVIEW_MODEL) {
|
|
284
239
|
delete prepared.body.service_tier;
|
|
285
240
|
if (resolvedModel.reasoningEffort || prepared.body.reasoning?.effort === undefined) {
|
|
@@ -287,27 +242,17 @@ export function createResponsesHandler(options) {
|
|
|
287
242
|
}
|
|
288
243
|
}
|
|
289
244
|
if (upstreamModel !== requestedModel) prepared.body.model = upstreamModel;
|
|
290
|
-
markResponseModel(upstreamModel);
|
|
245
|
+
markResponseModel(upstreamModel, { requestedModel });
|
|
291
246
|
markRequestObservation({ context_window_tokens: modelContextWindowTokens(modelRegistry?.models, upstreamModel) });
|
|
292
247
|
const upstreamLog = upstreamModel === requestedModel ? "" : ` upstream_model=${upstreamModel}`;
|
|
293
248
|
console.log(status("info", `responses model=${requestedModel}${upstreamLog} stream=${streaming}`));
|
|
294
|
-
const
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
if (usesCustomTools && !useNativeResponses) throw unsupportedCustomToolsError(upstreamModel);
|
|
300
|
-
const routePlan = createRoutePlan({
|
|
301
|
-
disposition: "relay",
|
|
302
|
-
origin: "ccdx",
|
|
303
|
-
profile: "codex",
|
|
304
|
-
protocol: useNativeResponses ? "openai-responses" : "openai-chat-completions",
|
|
305
|
-
model: upstreamModel,
|
|
306
|
-
surface: "responses",
|
|
307
|
-
});
|
|
308
|
-
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;
|
|
309
254
|
if (prepared.historyParentId === null) releaseHistorySnapshot();
|
|
310
|
-
|
|
255
|
+
provider.applyRequestPolicies(prepared.body);
|
|
311
256
|
if (routePlan.protocol === "openai-responses") {
|
|
312
257
|
const restorePlaintextHistory = async (context, { reserveHistory } = {}) => {
|
|
313
258
|
assertPrepareActive();
|
|
@@ -316,6 +261,7 @@ export function createResponsesHandler(options) {
|
|
|
316
261
|
signal: abort.signal, assertActive: assertPrepareActive, reserveHistory, maxBytes: MAX_DECODED_BODY_BYTES });
|
|
317
262
|
};
|
|
318
263
|
const result = await proxyCopilotResponses(prepared, req, res, responsesFn, {
|
|
264
|
+
compatibility: provider.compatibility,
|
|
319
265
|
acquireRetryPreparation,
|
|
320
266
|
assertPrepareActive,
|
|
321
267
|
signal: abort.signal,
|
|
@@ -400,7 +346,7 @@ export function createResponsesHandler(options) {
|
|
|
400
346
|
bodyText,
|
|
401
347
|
onUpstreamStart: startUpstreamTimeout,
|
|
402
348
|
});
|
|
403
|
-
markUpstreamHeaders();
|
|
349
|
+
markUpstreamHeaders(upstream.status);
|
|
404
350
|
releaseChatPayload();
|
|
405
351
|
const data = upstream.ok
|
|
406
352
|
? await readBoundedResponseText(upstream, {
|
|
@@ -455,6 +401,7 @@ export function createResponsesHandler(options) {
|
|
|
455
401
|
}
|
|
456
402
|
|
|
457
403
|
export function createResponsesCompactHandler(options) {
|
|
404
|
+
const provider = options.provider || defaultGithubProvider;
|
|
458
405
|
const {
|
|
459
406
|
acquireRequest,
|
|
460
407
|
autoReviewModelResolver,
|
|
@@ -556,15 +503,7 @@ export function createResponsesCompactHandler(options) {
|
|
|
556
503
|
const model = parsed.model || "unknown";
|
|
557
504
|
const resolvedModel = resolveRequestModel(model, openAIModelEnv, autoReviewModelResolver);
|
|
558
505
|
const { requestedModel } = resolvedModel;
|
|
559
|
-
|
|
560
|
-
const priorityTierModel = requestedModel === upstreamModel
|
|
561
|
-
? resolveCopilotPriorityTierModel(upstreamModel, prepared.body.service_tier, modelRegistry?.models)
|
|
562
|
-
: null;
|
|
563
|
-
if (priorityTierModel) {
|
|
564
|
-
upstreamModel = priorityTierModel;
|
|
565
|
-
delete prepared.body.service_tier;
|
|
566
|
-
}
|
|
567
|
-
stripUnsupportedGpt6ServiceTier(prepared.body, requestedModel, upstreamModel, priorityTierModel);
|
|
506
|
+
const { upstreamModel, forceResponses } = provider.selectModel(prepared.body, resolvedModel, modelRegistry?.models);
|
|
568
507
|
if (requestedModel === CODEX_AUTO_REVIEW_MODEL) {
|
|
569
508
|
delete prepared.body.service_tier;
|
|
570
509
|
if (resolvedModel.reasoningEffort || prepared.body.reasoning?.effort === undefined) {
|
|
@@ -575,17 +514,15 @@ export function createResponsesCompactHandler(options) {
|
|
|
575
514
|
markRequestObservation({ context_window_tokens: modelContextWindowTokens(modelRegistry?.models, upstreamModel) });
|
|
576
515
|
const upstreamLog = upstreamModel === requestedModel ? "" : ` upstream_model=${upstreamModel}`;
|
|
577
516
|
console.log(status("info", `responses compact model=${requestedModel}${upstreamLog} stream=false`));
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
model: upstreamModel,
|
|
584
|
-
surface: "responses-compact",
|
|
585
|
-
}));
|
|
517
|
+
markResponseModel(upstreamModel, { requestedModel });
|
|
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;
|
|
586
522
|
releaseHistorySnapshot();
|
|
587
|
-
|
|
523
|
+
provider.applyRequestPolicies(prepared.body);
|
|
588
524
|
const result = await proxyCopilotResponses(prepared, req, res, responsesCompactFn, {
|
|
525
|
+
compatibility: provider.compatibility,
|
|
589
526
|
assertPrepareActive,
|
|
590
527
|
signal: abort.signal,
|
|
591
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
|
|
|
@@ -133,6 +133,7 @@ function createRoutePerformance() {
|
|
|
133
133
|
return {
|
|
134
134
|
ttft: createHistogram(TTFT_EDGES_MS),
|
|
135
135
|
tpot: createHistogram(TPOT_EDGES_US),
|
|
136
|
+
outputRate: { intervals: 0, milliseconds: 0, samples: 0 },
|
|
136
137
|
requestTtft: createHistogram(TTFT_EDGES_MS),
|
|
137
138
|
outputSources: { delta: 0, announcement: 0, snapshot: 0, runtime: 0 },
|
|
138
139
|
preparation: Object.fromEntries(PREPARATION_STAGES.map((stage) => [stage, createHistogram(PREPARATION_EDGES_MS)])),
|
|
@@ -163,6 +164,14 @@ function routeSnapshot(route) {
|
|
|
163
164
|
},
|
|
164
165
|
ttft_ms: histogramSnapshot(route.ttft, "ms"),
|
|
165
166
|
tpot_us: histogramSnapshot(route.tpot, "us"),
|
|
167
|
+
output_tokens_per_second: {
|
|
168
|
+
avg: route.outputRate.milliseconds > 0
|
|
169
|
+
? Number((route.outputRate.intervals * 1000 / route.outputRate.milliseconds).toFixed(1)) : null,
|
|
170
|
+
samples: route.outputRate.samples,
|
|
171
|
+
unit: "token/s",
|
|
172
|
+
aggregation: "time_weighted_per_request",
|
|
173
|
+
estimated: true,
|
|
174
|
+
},
|
|
166
175
|
request_ttft_ms: histogramSnapshot(route.requestTtft, "ms"),
|
|
167
176
|
first_output_sources: { ...route.outputSources },
|
|
168
177
|
timing_boundary: "gateway_observed",
|
|
@@ -171,8 +180,8 @@ function routeSnapshot(route) {
|
|
|
171
180
|
};
|
|
172
181
|
}
|
|
173
182
|
|
|
174
|
-
export function createStreamPerformanceMetrics({ now = () => performance.now(), wallNow = () => new Date().toISOString() } = {}) {
|
|
175
|
-
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()]));
|
|
176
185
|
const recentRequests = [];
|
|
177
186
|
|
|
178
187
|
return {
|
|
@@ -187,6 +196,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
187
196
|
let failed = false;
|
|
188
197
|
let finished = false;
|
|
189
198
|
let model = "other";
|
|
199
|
+
let provider = null;
|
|
190
200
|
let terminalOutcome = null;
|
|
191
201
|
let terminalOrigin = null;
|
|
192
202
|
let incompleteReason = null;
|
|
@@ -195,6 +205,7 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
195
205
|
const preparationMs = Object.fromEntries(PREPARATION_STAGES.map((stage) => [stage, 0]));
|
|
196
206
|
let phase = "received";
|
|
197
207
|
let attempts = 0;
|
|
208
|
+
const attemptTimings = [];
|
|
198
209
|
let firstAttemptAt = null;
|
|
199
210
|
let headersAt = null;
|
|
200
211
|
let lastActivityAt = null;
|
|
@@ -221,15 +232,22 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
221
232
|
if (finished) return;
|
|
222
233
|
const time = now();
|
|
223
234
|
attempts += 1;
|
|
235
|
+
if (attemptTimings.length === 3) attemptTimings.splice(1, 1);
|
|
236
|
+
attemptTimings.push({ attempt: attempts, started_ms: elapsed(time), headers_ms: null, http_status: null });
|
|
224
237
|
firstAttemptAt ??= time;
|
|
225
238
|
phase = "upstream_connection";
|
|
226
239
|
if (streaming && upstreamStartedAt === null) upstreamStartedAt = time;
|
|
227
240
|
},
|
|
228
|
-
upstreamHeaders() {
|
|
241
|
+
upstreamHeaders(statusCode) {
|
|
229
242
|
if (finished) return;
|
|
230
243
|
headersAt = now();
|
|
231
244
|
lastActivityAt = headersAt;
|
|
232
245
|
phase = "upstream_response";
|
|
246
|
+
const attempt = attemptTimings.at(-1);
|
|
247
|
+
if (attempt) {
|
|
248
|
+
attempt.headers_ms = elapsed(headersAt);
|
|
249
|
+
attempt.http_status = Number.isInteger(statusCode) && statusCode >= 100 && statusCode <= 599 ? statusCode : null;
|
|
250
|
+
}
|
|
233
251
|
},
|
|
234
252
|
upstreamActivity() {
|
|
235
253
|
if (finished) return;
|
|
@@ -249,6 +267,9 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
249
267
|
setModel(value) {
|
|
250
268
|
model = modelLabel(value);
|
|
251
269
|
},
|
|
270
|
+
setProvider(value) { if (["github", "m365"].includes(value)) provider = value; },
|
|
271
|
+
attemptCount() { return attempts; },
|
|
272
|
+
attemptTimings() { return attemptTimings.map(attempt => ({ ...attempt })); },
|
|
252
273
|
observeContext(values) {
|
|
253
274
|
if (finished || !values || typeof values !== "object") return;
|
|
254
275
|
for (const key of Object.keys(context)) {
|
|
@@ -293,10 +314,12 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
293
314
|
recentRequests.push({
|
|
294
315
|
request_id: typeof requestId === "string" && /^[a-zA-Z0-9_-]{1,80}$/.test(requestId) ? requestId : null,
|
|
295
316
|
at, route: routeName, model, outcome, origin, phase,
|
|
317
|
+
...(provider ? { provider } : {}),
|
|
296
318
|
empty_stream_completion: emptyStreamCompletion,
|
|
297
319
|
failed: failed || aborted || (terminalOutcome !== null && terminalOutcome !== "completed"),
|
|
298
320
|
http_status: Number.isInteger(statusCode) && statusCode >= 100 && statusCode <= 599 ? statusCode : null,
|
|
299
321
|
upstream_attempts: attempts,
|
|
322
|
+
attempts: attemptTimings.map(attempt => ({ ...attempt })),
|
|
300
323
|
first_output_source: firstOutputSource,
|
|
301
324
|
context: { ...context },
|
|
302
325
|
timings_ms: {
|
|
@@ -321,6 +344,12 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
321
344
|
observe(route.ttft, Math.max(0, firstOutputAt - upstreamStartedAt));
|
|
322
345
|
if (outputTokens !== null && outputTokens >= 2) {
|
|
323
346
|
observe(route.tpot, Math.max(0, ((finishedAt - firstOutputAt) * 1_000) / (outputTokens - 1)));
|
|
347
|
+
const milliseconds = finishedAt - firstOutputAt;
|
|
348
|
+
if (Number.isSafeInteger(outputTokens) && milliseconds > 0) {
|
|
349
|
+
route.outputRate.intervals += outputTokens - 1;
|
|
350
|
+
route.outputRate.milliseconds += milliseconds;
|
|
351
|
+
route.outputRate.samples += 1;
|
|
352
|
+
}
|
|
324
353
|
}
|
|
325
354
|
if (failed) route.errors_with_output += 1;
|
|
326
355
|
else route.success_with_output += 1;
|
|
@@ -329,8 +358,8 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
|
|
|
329
358
|
},
|
|
330
359
|
snapshot() {
|
|
331
360
|
return {
|
|
332
|
-
by_route: Object.fromEntries(
|
|
333
|
-
recent_requests: recentRequests.map((entry) => ({ ...entry, context: { ...entry.context }, timings_ms: { ...entry.timings_ms } })),
|
|
361
|
+
by_route: Object.fromEntries(routeNames.map((name) => [name, routeSnapshot(routes[name])])),
|
|
362
|
+
recent_requests: recentRequests.map((entry) => ({ ...entry, attempts: entry.attempts.map(attempt => ({ ...attempt })), context: { ...entry.context }, timings_ms: { ...entry.timings_ms } })),
|
|
334
363
|
};
|
|
335
364
|
},
|
|
336
365
|
};
|
|
@@ -362,8 +391,8 @@ export function markUpstreamStarted(streaming = true) {
|
|
|
362
391
|
tracker()?.upstreamStarted(streaming);
|
|
363
392
|
}
|
|
364
393
|
|
|
365
|
-
export function markUpstreamHeaders() {
|
|
366
|
-
tracker()?.upstreamHeaders?.();
|
|
394
|
+
export function markUpstreamHeaders(statusCode) {
|
|
395
|
+
tracker()?.upstreamHeaders?.(statusCode);
|
|
367
396
|
}
|
|
368
397
|
|
|
369
398
|
export function markUpstreamActivity() {
|
|
@@ -386,9 +415,12 @@ export function markStreamFailure() {
|
|
|
386
415
|
tracker()?.fail();
|
|
387
416
|
}
|
|
388
417
|
|
|
389
|
-
export function markResponseModel(model) {
|
|
418
|
+
export function markResponseModel(model, { requestedModel } = {}) {
|
|
390
419
|
const context = currentRequestContext();
|
|
391
|
-
if (context)
|
|
420
|
+
if (context) {
|
|
421
|
+
context.model = model;
|
|
422
|
+
if (requestedModel !== undefined) context.requestedModel = modelLabel(requestedModel);
|
|
423
|
+
}
|
|
392
424
|
tracker()?.setModel?.(model);
|
|
393
425
|
}
|
|
394
426
|
|
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
|
});
|