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
package/src/adapter.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
createRequestMetrics,
|
|
9
9
|
runtimeStatusPayload,
|
|
10
10
|
} from "./observability.mjs";
|
|
11
|
-
import { createRequestId, runWithRequestContext } from "./request-context.mjs";
|
|
11
|
+
import { createRequestId, runWithRequestContext, currentRequestContext } from "./request-context.mjs";
|
|
12
12
|
import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
|
|
13
13
|
import { status } from "./status.mjs";
|
|
14
14
|
import { createTerminalActivityIndicator } from "./terminal-activity.mjs";
|
|
@@ -27,6 +27,7 @@ import {
|
|
|
27
27
|
} from "./http-transport.mjs";
|
|
28
28
|
import { httpError } from "./http-errors.mjs";
|
|
29
29
|
import { createRequestAdmission } from "./request-admission.mjs";
|
|
30
|
+
import { PROVIDER_MANAGEMENT_PATH, handleProviderManagement } from "./provider-management.mjs";
|
|
30
31
|
|
|
31
32
|
export {
|
|
32
33
|
abortErrorStatusCode,
|
|
@@ -73,7 +74,7 @@ function sendRetiredClaudeSurface(res) {
|
|
|
73
74
|
error: {
|
|
74
75
|
type: "not_found_error",
|
|
75
76
|
code: "ccdx_claude_retired",
|
|
76
|
-
message: "
|
|
77
|
+
message: "The GitHub Claude endpoint was retired in ccdx 0.7.0. Microsoft 365 Claude uses the separate gateway; run ccdx m365 status.",
|
|
77
78
|
},
|
|
78
79
|
}));
|
|
79
80
|
}
|
|
@@ -96,13 +97,14 @@ async function sendModelList(res, models, {
|
|
|
96
97
|
headers = {},
|
|
97
98
|
rawBody,
|
|
98
99
|
statusCode = 200,
|
|
100
|
+
restrictToUpstream = false,
|
|
99
101
|
} = {}) {
|
|
100
102
|
let body = rawBody || JSON.stringify(models);
|
|
101
103
|
if (clientVersion && typeof codexModelCatalog?.load === "function") {
|
|
102
104
|
let response = null;
|
|
103
105
|
try {
|
|
104
106
|
const codexCatalog = await codexModelCatalog.load({ clientVersion });
|
|
105
|
-
response = buildCodexModelResponse({ copilotModels: models, codexCatalog });
|
|
107
|
+
response = buildCodexModelResponse({ copilotModels: models, codexCatalog, restrictToUpstream });
|
|
106
108
|
} catch {}
|
|
107
109
|
if (!response) {
|
|
108
110
|
if (res.destroyed || res.writableEnded) return false;
|
|
@@ -164,17 +166,27 @@ export function createAdapterHandler(options = {}) {
|
|
|
164
166
|
const imagePressure = options.imagePressure || createResponsesImagePressureController();
|
|
165
167
|
const responseFailures = options.responseFailures || createResponseFailureDiagnostics();
|
|
166
168
|
const httpErrors = createHttpFailureDiagnostics();
|
|
167
|
-
const optionalRoutes = createOptionalRoutes(options
|
|
169
|
+
const optionalRoutes = createOptionalRoutes({ ...options, dashboardOptions: { ...options.dashboardOptions,
|
|
170
|
+
...(options.providerRuntime ? { providerCatalogFn: () => options.providerRuntime.dashboardCatalog() } : {}) } });
|
|
168
171
|
const managementHandler = createManagementHandler({
|
|
169
172
|
nativePredictionPac: options.nativePredictionPac, fixPrediction: options.fixPrediction, requestBodyTimeoutMs,
|
|
170
|
-
statusSnapshot: () =>
|
|
171
|
-
metrics: requestMetrics, streamPerformance: streamPerformanceMetrics, admission: acquireRequest,
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
173
|
+
statusSnapshot: () => {
|
|
174
|
+
const snapshot = runtimeStatusPayload({ metrics: requestMetrics, streamPerformance: streamPerformanceMetrics, admission: acquireRequest,
|
|
175
|
+
imagePressure, responseFailures, imageGeneration: optionalRoutes.imageStats(),
|
|
176
|
+
modelRegistry: codexModelRegistry, codexClient, codexModelRegistry, codexModelCatalog,
|
|
177
|
+
clientIntegrations: options.clientIntegrationSnapshot?.() });
|
|
178
|
+
const providers = options.providerRuntime?.snapshot();
|
|
179
|
+
if (providers?.codex_provider === "m365") {
|
|
180
|
+
snapshot.routing = { ...snapshot.routing, responses: "m365" };
|
|
181
|
+
snapshot.models = { ...snapshot.models, models: providers.m365.models?.gpt || 0,
|
|
182
|
+
source: providers.m365.models?.source || "unavailable", provider: "m365",
|
|
183
|
+
refresh_in_flight: providers.m365.refresh_in_flight === true };
|
|
184
|
+
}
|
|
185
|
+
return { ...snapshot, http_errors: httpErrors.snapshot(), ...(providers ? { providers } : {}) };
|
|
186
|
+
},
|
|
176
187
|
});
|
|
177
188
|
const responsesHandler = createResponsesHandler({
|
|
189
|
+
provider: options.provider || options.providerRuntime?.github,
|
|
178
190
|
acquireRequest,
|
|
179
191
|
autoReviewModelResolver: options.autoReviewModelResolver,
|
|
180
192
|
chatCompletionsFn,
|
|
@@ -193,6 +205,7 @@ export function createAdapterHandler(options = {}) {
|
|
|
193
205
|
upstreamTimeoutMs,
|
|
194
206
|
});
|
|
195
207
|
const responsesCompactHandler = createResponsesCompactHandler({
|
|
208
|
+
provider: options.provider || options.providerRuntime?.github,
|
|
196
209
|
acquireRequest,
|
|
197
210
|
autoReviewModelResolver: options.autoReviewModelResolver,
|
|
198
211
|
imagePressure,
|
|
@@ -205,6 +218,25 @@ export function createAdapterHandler(options = {}) {
|
|
|
205
218
|
streamIdleTimeoutMs,
|
|
206
219
|
upstreamTimeoutMs,
|
|
207
220
|
});
|
|
221
|
+
const providerHandlers = new WeakMap();
|
|
222
|
+
const githubHandlers = { responses: responsesHandler, compact: responsesCompactHandler };
|
|
223
|
+
function handlersFor(provider) {
|
|
224
|
+
if (!provider || provider.id === "github") return githubHandlers;
|
|
225
|
+
if (!providerHandlers.has(provider)) {
|
|
226
|
+
const common = { provider, acquireRequest, imagePressure, keepaliveIntervalMs: options.keepaliveIntervalMs,
|
|
227
|
+
modelRegistry: provider.registry, now: options.now, openAIModelEnv: { ...openAIModelEnv, CCDX_AUTO_REVIEW_MODEL: "" },
|
|
228
|
+
autoReviewModelResolver: () => { const preference = options.providerRuntime.selection().m365;
|
|
229
|
+
return { model: preference.auto_review_model, reasoningEffort: preference.auto_review_effort === undefined ? "low" : preference.auto_review_effort }; },
|
|
230
|
+
requestBodyTimeoutMs, responsesPayloadOptions: options.responsesPayloadOptions, responseFailures,
|
|
231
|
+
streamHandshakeTimeoutMs, streamIdleTimeoutMs, upstreamTimeoutMs };
|
|
232
|
+
providerHandlers.set(provider, {
|
|
233
|
+
responses: createResponsesHandler({ ...common, responsesFn: provider.client.responses, chatCompletionsFn: provider.client.chatCompletions,
|
|
234
|
+
getCachedModelEndpointsFn: provider.client.getCachedModelEndpoints }),
|
|
235
|
+
compact: createResponsesCompactHandler({ ...common, responsesCompactFn: provider.client.responsesCompact }),
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
return providerHandlers.get(provider);
|
|
239
|
+
}
|
|
208
240
|
const dispatch = async (req, res, pathname) => {
|
|
209
241
|
if (req.method === "POST" && ["/v1/responses", "/v1/responses/compact"].includes(pathname)
|
|
210
242
|
&& Object.hasOwn(req.headers || {}, "origin")) {
|
|
@@ -215,54 +247,75 @@ export function createAdapterHandler(options = {}) {
|
|
|
215
247
|
}
|
|
216
248
|
if (isOptionalRoute(req.method, pathname)) return optionalRoutes.handle(req, res, pathname);
|
|
217
249
|
if (isManagementRoute(req.method, pathname)) return managementHandler(req, res, pathname);
|
|
250
|
+
if (pathname === PROVIDER_MANAGEMENT_PATH) return handleProviderManagement(req, res, options.providerRuntime);
|
|
251
|
+
|
|
252
|
+
let target;
|
|
253
|
+
if (["/v1/responses", "/v1/responses/compact", "/v1/models"].includes(pathname) && options.providerRuntime) {
|
|
254
|
+
try { target = options.providerRuntime.current(); }
|
|
255
|
+
catch (error) { sendJsonError(res, error, 503);return; }
|
|
256
|
+
const context = currentRequestContext();
|
|
257
|
+
if (context) {
|
|
258
|
+
context.provider = target.id;
|
|
259
|
+
context.streamPerformance?.setProvider?.(target.id);
|
|
260
|
+
context.finishProvider = options.providerRuntime.track?.(target);
|
|
261
|
+
Object.assign(context, options.providerRuntime.historyContext?.(req.headers, target));
|
|
262
|
+
context.clientHeaders = {
|
|
263
|
+
session_id: typeof req.headers.session_id === "string" ? req.headers.session_id : undefined,
|
|
264
|
+
"session-id": typeof req.headers["session-id"] === "string" ? req.headers["session-id"] : undefined,
|
|
265
|
+
"x-conversation-id": typeof req.headers["x-conversation-id"] === "string" ? req.headers["x-conversation-id"] : undefined,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
}
|
|
218
269
|
|
|
219
270
|
if (req.method === "POST" && pathname === "/v1/responses") {
|
|
220
|
-
return
|
|
271
|
+
return handlersFor(target).responses(req, res);
|
|
221
272
|
}
|
|
222
273
|
|
|
223
274
|
if (req.method === "POST" && pathname === "/v1/responses/compact") {
|
|
224
|
-
return
|
|
275
|
+
return handlersFor(target).compact(req, res);
|
|
225
276
|
}
|
|
226
277
|
|
|
227
278
|
if (req.method === "GET" && pathname === "/v1/models") {
|
|
228
279
|
const clientVersion = modelClientVersion(req.url);
|
|
280
|
+
const selectedRegistry = target?.registry || codexModelRegistry;
|
|
281
|
+
const selectedListModels = target?.id === "m365" ? target.client.listModels : listModelsFn;
|
|
282
|
+
const modelOptions = { codexModelCatalog, clientVersion, restrictToUpstream: target?.id === "m365" };
|
|
229
283
|
const abort = createRequestAbort(req, res);
|
|
230
284
|
// Keep live discovery and explicit auth failures authoritative, but do
|
|
231
285
|
// not make a usable cached picker wait the full inference timeout.
|
|
232
|
-
const modelTimeoutMs = isValidModelList(
|
|
286
|
+
const modelTimeoutMs = isValidModelList(selectedRegistry?.models)
|
|
233
287
|
? Math.min(upstreamTimeoutMs, parsePositiveInteger(options.cachedModelsTimeoutMs, 1500))
|
|
234
288
|
: upstreamTimeoutMs;
|
|
235
289
|
abort.setTimeout(modelTimeoutMs);
|
|
236
|
-
|
|
290
|
+
selectedListModels({ signal: abort.signal })
|
|
237
291
|
.then(async ({ status, body }) => {
|
|
238
292
|
abort.clearTimeout();
|
|
239
293
|
if (status >= 200 && status < 300) {
|
|
240
294
|
let models;
|
|
241
295
|
try { models = JSON.parse(body); } catch {}
|
|
242
296
|
if (isValidModelList(models)) {
|
|
243
|
-
if (
|
|
244
|
-
|
|
297
|
+
if (selectedRegistry) {
|
|
298
|
+
selectedRegistry.models = models;
|
|
245
299
|
}
|
|
246
300
|
await sendModelList(res, models, {
|
|
247
|
-
|
|
248
|
-
clientVersion,
|
|
301
|
+
...modelOptions,
|
|
249
302
|
rawBody: body,
|
|
250
303
|
statusCode: status,
|
|
251
304
|
});
|
|
252
305
|
return;
|
|
253
306
|
}
|
|
254
|
-
if (await sendLastKnownGoodModels(res,
|
|
307
|
+
if (await sendLastKnownGoodModels(res, selectedRegistry, modelOptions)) return;
|
|
255
308
|
sendJsonError(res, httpError("Copilot models response contained no valid models", 502), 502);
|
|
256
309
|
return;
|
|
257
310
|
}
|
|
258
311
|
if (modelListCanUseLastKnownGood(status)
|
|
259
|
-
&& await sendLastKnownGoodModels(res,
|
|
312
|
+
&& await sendLastKnownGoodModels(res, selectedRegistry, modelOptions)) return;
|
|
260
313
|
res.writeHead(status, { "Content-Type": "application/json" });
|
|
261
314
|
res.end(body);
|
|
262
315
|
})
|
|
263
316
|
.catch(async (e) => {
|
|
264
317
|
logRequestFailure("Models", e, abort);
|
|
265
|
-
if (await sendLastKnownGoodModels(res,
|
|
318
|
+
if (await sendLastKnownGoodModels(res, selectedRegistry, modelOptions)) return;
|
|
266
319
|
if (!res.destroyed && !res.writableEnded) {
|
|
267
320
|
if (!res.headersSent) res.writeHead(e?.statusCode || 502);
|
|
268
321
|
res.end(JSON.stringify({ error: e.message }));
|
|
@@ -307,6 +360,7 @@ export function createAdapterHandler(options = {}) {
|
|
|
307
360
|
&& pathname !== ADAPTER_STATUS_PATH
|
|
308
361
|
&& pathname !== ADAPTER_CACHE_PATH
|
|
309
362
|
&& pathname !== ADAPTER_PREDICTION_FIX_PATH
|
|
363
|
+
&& pathname !== PROVIDER_MANAGEMENT_PATH
|
|
310
364
|
&& !DASHBOARD_API_PATHS.has(pathname)
|
|
311
365
|
&& !((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname));
|
|
312
366
|
const routeName = classifyAdapterRoute(req.method, pathname);
|
|
@@ -330,12 +384,13 @@ export function createAdapterHandler(options = {}) {
|
|
|
330
384
|
target: ["/v1/responses", "/v1/responses/compact", "/mcp/image", "/.well-known/oauth-authorization-server", "/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp/image"].includes(pathname) ? pathname : "unrecognized_path",
|
|
331
385
|
request_options: context?.requestOptions, upstream_attempts: streamPerformance?.attemptCount?.(),
|
|
332
386
|
attempt_timings: streamPerformance?.attemptTimings?.(),
|
|
333
|
-
requested_model: context?.requestedModel,
|
|
387
|
+
requested_model: context?.requestedModel, provider: context?.provider,
|
|
334
388
|
})); } catch {}
|
|
335
389
|
}
|
|
336
390
|
try { complete({ statusCode, aborted }); } catch {}
|
|
337
391
|
try { streamPerformance?.finish({ failed: aborted || statusCode >= 400, aborted, statusCode }); } catch {}
|
|
338
392
|
try { finishTerminalActivity(); } catch {}
|
|
393
|
+
try { context?.finishProvider?.(); } catch {}
|
|
339
394
|
};
|
|
340
395
|
const containUnexpectedError = (error) => {
|
|
341
396
|
try { finishRequest({ statusCode: res.statusCode >= 400 ? res.statusCode : 500 }); } catch {}
|
|
@@ -370,6 +425,12 @@ export function createAdapterHandler(options = {}) {
|
|
|
370
425
|
showRequestId: options.showRequestId === true,
|
|
371
426
|
includeHttpErrorDetails: options.includeHttpErrorDetails === true || process.env.CCDX_HTTP_ERROR_DETAILS === "1",
|
|
372
427
|
streamPerformance,
|
|
428
|
+
provider: undefined,
|
|
429
|
+
finishProvider: undefined,
|
|
430
|
+
historyNamespace: undefined,
|
|
431
|
+
historyTransferNamespace: undefined,
|
|
432
|
+
onHistoryStored: undefined,
|
|
433
|
+
clientHeaders: undefined,
|
|
373
434
|
onHttpError: evidence => { httpEvidence = evidence; },
|
|
374
435
|
};
|
|
375
436
|
const result = runWithRequestContext(context, () => dispatchRequest(req, res, pathname));
|
|
@@ -88,13 +88,15 @@ export async function runAutoReviewModelCommand({
|
|
|
88
88
|
loadCatalog = loadAutoReviewModelCatalog,
|
|
89
89
|
output = process.stdout,
|
|
90
90
|
prompt,
|
|
91
|
+
getPreference = autoReviewPreference,
|
|
92
|
+
savePreference = (model, options) => writeAutoReviewModel(model === DEFAULT_CODEX_AUTO_REVIEW_MODEL ? "" : model, options),
|
|
91
93
|
} = {}) {
|
|
92
94
|
if (!prompt && (!input.isTTY || !output.isTTY)) {
|
|
93
95
|
throw new Error(`${commandName} auto-review-model requires an interactive terminal`);
|
|
94
96
|
}
|
|
95
97
|
|
|
96
98
|
readUserSettings({ env, home, strict: true });
|
|
97
|
-
const current =
|
|
99
|
+
const current = getPreference({ env, home });
|
|
98
100
|
const catalog = await loadCatalog({ env, fetchImpl, home });
|
|
99
101
|
const modelIds = sortedModelIds(catalog.modelIds, current.model);
|
|
100
102
|
if (!modelIds.length) throw new Error("No selectable Responses models are available");
|
|
@@ -167,8 +169,7 @@ export async function runAutoReviewModelCommand({
|
|
|
167
169
|
readline?.close();
|
|
168
170
|
}
|
|
169
171
|
|
|
170
|
-
const
|
|
171
|
-
const result = writeAutoReviewModel(savedModel, { env, home, reasoningEffort: selectedEffort });
|
|
172
|
+
const result = await savePreference(selectedModel, { env, home, reasoningEffort: selectedEffort });
|
|
172
173
|
output.write(`${result.changed ? "Saved" : "Kept"} Auto Review model: ${selectedModel}\n`);
|
|
173
174
|
output.write(`Reasoning: ${selectedEffort || "follow client (low when omitted)"}\n`);
|
|
174
175
|
if (String(env.CCDX_AUTO_REVIEW_MODEL || "").trim()) {
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { isDeepStrictEqual } from "node:util";
|
|
5
|
+
import { execFile } from "node:child_process";
|
|
6
|
+
import { promisify } from "node:util";
|
|
7
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
8
|
+
import { atomicWriteFileSync } from "./atomic-file.mjs";
|
|
9
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
10
|
+
import { m365Paths, readM365Json, writeM365Json } from "./m365-settings.mjs";
|
|
11
|
+
|
|
12
|
+
export const M365_CLAUDE_PROFILE_ID = "00000000-0000-4000-8000-000000202700";
|
|
13
|
+
const M365_CLAUDE_PROFILE_NAME = "CCDX Microsoft 365";
|
|
14
|
+
|
|
15
|
+
export function claudeClientPaths({ home = os.homedir(), platform = process.platform, env = process.env } = {}) {
|
|
16
|
+
const base = platform === "win32" ? env.LOCALAPPDATA || path.join(home, "AppData", "Local")
|
|
17
|
+
: platform === "darwin" ? path.join(home, "Library", "Application Support") : env.XDG_CONFIG_HOME || path.join(home, ".config");
|
|
18
|
+
const normalBase = platform === "win32" ? env.APPDATA || path.join(home, "AppData", "Roaming") : base;
|
|
19
|
+
const library = path.join(base, "Claude-3p", "configLibrary");
|
|
20
|
+
return { code: path.join(env.CLAUDE_CONFIG_DIR || path.join(home, ".claude"), "settings.json"),
|
|
21
|
+
normal: path.join(normalBase, "Claude", "claude_desktop_config.json"),
|
|
22
|
+
threep: path.join(base, "Claude-3p", "claude_desktop_config.json"),
|
|
23
|
+
meta: path.join(library, "_meta.json"), profile: path.join(library, `${M365_CLAUDE_PROFILE_ID}.json`) };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function read(file) {
|
|
27
|
+
try {
|
|
28
|
+
if (!fs.lstatSync(file).isFile()) throw Error();
|
|
29
|
+
const bytes = readBoundedFileSync(file, { maxBytes: 1024 * 1024 });
|
|
30
|
+
const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
31
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw Error();
|
|
32
|
+
return { exists: true, bytes, value };
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (error.code === "ENOENT") return { exists: false, bytes: null, value: {} };
|
|
35
|
+
throw Object.assign(new Error("Claude configuration is unreadable; existing files were preserved"), { code: "claude_config_unreadable" });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function valueAt(object, keys) {
|
|
39
|
+
const parent = keys.slice(0, -1).reduce((v, k) => v && Object.hasOwn(v, k) ? v[k] : undefined, object);
|
|
40
|
+
return parent && typeof parent === "object" && Object.hasOwn(parent, keys.at(-1)) ? { exists: true, value: parent[keys.at(-1)] } : { exists: false };
|
|
41
|
+
}
|
|
42
|
+
function setAt(object, keys, value) {
|
|
43
|
+
let parent = object;
|
|
44
|
+
for (const key of keys.slice(0, -1)) {
|
|
45
|
+
if (parent[key] === undefined) parent[key] = {};
|
|
46
|
+
if (!parent[key] || typeof parent[key] !== "object" || Array.isArray(parent[key])) throw new Error("Claude configuration has a conflicting parent field");
|
|
47
|
+
parent = parent[key];
|
|
48
|
+
}
|
|
49
|
+
if (value.exists) parent[keys.at(-1)] = value.value;
|
|
50
|
+
else {
|
|
51
|
+
delete parent[keys.at(-1)];
|
|
52
|
+
if (keys.length === 2 && Object.keys(parent).length === 0) delete object[keys[0]];
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function inspectClaudeDesktopPolicy({ platform = process.platform, home = os.homedir(), env = process.env,
|
|
57
|
+
execFileImpl = promisify(execFile) } = {}) {
|
|
58
|
+
if (platform === "darwin") {
|
|
59
|
+
const files = ["/Library/Managed Preferences/com.anthropic.claudefordesktop.plist",
|
|
60
|
+
path.join("/Library/Managed Preferences", os.userInfo().username, "com.anthropic.claudefordesktop.plist"),
|
|
61
|
+
path.join(home, "Library", "Managed Preferences", "com.anthropic.claudefordesktop.plist")];
|
|
62
|
+
return files.some(file => fs.existsSync(file));
|
|
63
|
+
}
|
|
64
|
+
if (platform === "win32") {
|
|
65
|
+
const reg = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "reg.exe");
|
|
66
|
+
for (const key of ["HKLM\\SOFTWARE\\Policies\\Claude", "HKCU\\SOFTWARE\\Policies\\Claude"]) {
|
|
67
|
+
try { await execFileImpl(reg, ["query", key], { encoding: "utf8", timeout: 3000, maxBuffer: 32768, windowsHide: true });return true; }
|
|
68
|
+
catch (error) { if (error.code !== 1) return true; }
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function operationValue(snapshot, operation) {
|
|
75
|
+
const field = valueAt(snapshot, operation.keys);
|
|
76
|
+
if (!operation.itemId) return field;
|
|
77
|
+
const item = Array.isArray(field.value) ? field.value.find(value => value?.id === operation.itemId) : undefined;
|
|
78
|
+
return item ? { exists: true, value: item } : { exists: false };
|
|
79
|
+
}
|
|
80
|
+
function setOperation(snapshot, operation, value) {
|
|
81
|
+
if (!operation.itemId) { setAt(snapshot, operation.keys, value);return; }
|
|
82
|
+
const current = valueAt(snapshot, operation.keys);
|
|
83
|
+
if (current.exists && !Array.isArray(current.value)) throw new Error("Claude profile list is invalid");
|
|
84
|
+
const next = (current.value || []).filter(item => item?.id !== operation.itemId);
|
|
85
|
+
if (value.exists) next.push(value.value);
|
|
86
|
+
setAt(snapshot, operation.keys, { exists: true, value: next });
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function reconcile(operations, { restore = false, ...options } = {}) {
|
|
90
|
+
const paths = claudeClientPaths(options), allowed = new Set(Object.values(paths)), journalPath = m365Paths(options).ownership;
|
|
91
|
+
fs.mkdirSync(path.dirname(journalPath), { recursive: true, mode: 0o700 });
|
|
92
|
+
return withFileLockSync(`${journalPath}.lock`, () => {
|
|
93
|
+
const journal = readM365Json(journalPath, { version: 1, operations: [] });
|
|
94
|
+
const keys = new Map([
|
|
95
|
+
[paths.code, new Set(["env.ANTHROPIC_BASE_URL", "env.ANTHROPIC_AUTH_TOKEN", "env.CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY", "env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS", "env.ANTHROPIC_CUSTOM_HEADERS", "env.ANTHROPIC_MODEL"])],
|
|
96
|
+
[paths.normal, new Set(["deploymentMode"])], [paths.threep, new Set(["deploymentMode"])],
|
|
97
|
+
[paths.meta, new Set(["entries", "appliedId"])],
|
|
98
|
+
[paths.profile, new Set(["inferenceProvider", "inferenceGatewayBaseUrl", "inferenceGatewayApiKey", "inferenceGatewayAuthScheme", "inferenceModels", "inferenceCustomHeaders"])],
|
|
99
|
+
]);
|
|
100
|
+
if (journal.version !== 1 || !Array.isArray(journal.operations) || journal.operations.some(op => !allowed.has(op.file)
|
|
101
|
+
|| !Array.isArray(op.keys) || !keys.get(op.file)?.has(op.keys.join("."))
|
|
102
|
+
|| op.itemId !== undefined && (op.file !== paths.meta || op.keys.join(".") !== "entries" || op.itemId !== M365_CLAUDE_PROFILE_ID))) {
|
|
103
|
+
throw new Error("Claude configuration ownership is invalid; files were preserved");
|
|
104
|
+
}
|
|
105
|
+
const states = new Map(), pending = [], nextJournal = structuredClone(journal), skipped = [];
|
|
106
|
+
const list = restore ? journal.operations : operations;
|
|
107
|
+
for (const operation of list) {
|
|
108
|
+
if (!allowed.has(operation.file)) throw new Error("Unexpected Claude configuration path");
|
|
109
|
+
if (!states.has(operation.file)) states.set(operation.file, read(operation.file));
|
|
110
|
+
const state = states.get(operation.file);state.next ||= structuredClone(state.value);
|
|
111
|
+
const previous = journal.operations.find(op => op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId);
|
|
112
|
+
const current = operationValue(state.next, operation), desired = restore ? operation.before : { exists: true, value: operation.value };
|
|
113
|
+
if (restore) {
|
|
114
|
+
if (!isDeepStrictEqual(current, { exists: true, value: operation.after })) { skipped.push(operation.file);continue; }
|
|
115
|
+
setOperation(state.next, operation, desired);
|
|
116
|
+
nextJournal.operations = nextJournal.operations.filter(op => !(op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId));
|
|
117
|
+
} else {
|
|
118
|
+
if (isDeepStrictEqual(current, desired)) continue;
|
|
119
|
+
const replaceMode = operation.keys.join(".") === "deploymentMode" && [paths.normal, paths.threep].includes(operation.file)
|
|
120
|
+
&& current.value === "1p";
|
|
121
|
+
if (current.exists && !replaceMode && (!previous || !isDeepStrictEqual(current, { exists: true, value: previous.after }))) { skipped.push(operation.file);continue; }
|
|
122
|
+
const entry = { file: operation.file, keys: operation.keys, ...(operation.itemId ? { itemId: operation.itemId } : {}),
|
|
123
|
+
before: previous?.before || current, after: operation.value };
|
|
124
|
+
setOperation(state.next, operation, desired);
|
|
125
|
+
nextJournal.operations = nextJournal.operations.filter(op => !(op.file === operation.file && isDeepStrictEqual(op.keys, operation.keys) && op.itemId === operation.itemId));
|
|
126
|
+
nextJournal.operations.push(entry);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
// Record ownership before client writes so interruption remains recoverable.
|
|
130
|
+
const oldJournal = journal;
|
|
131
|
+
if (!restore) writeM365Json(journalPath, nextJournal);
|
|
132
|
+
try {
|
|
133
|
+
for (const [file, state] of states) {
|
|
134
|
+
if (isDeepStrictEqual(state.value, state.next)) continue;
|
|
135
|
+
const latest = read(file);
|
|
136
|
+
if (latest.exists !== state.exists || latest.bytes?.equals(state.bytes) === false) throw new Error("Claude configuration changed during setup; retry after the other writer finishes");
|
|
137
|
+
const bytes = Buffer.from(`${JSON.stringify(state.next, null, 2)}\n`);
|
|
138
|
+
atomicWriteFileSync(file, bytes, { mode: 0o600, preserveMode: false });pending.push({ file, state, bytes });
|
|
139
|
+
}
|
|
140
|
+
if (restore) writeM365Json(journalPath, nextJournal);
|
|
141
|
+
} catch (error) {
|
|
142
|
+
for (const entry of pending.reverse()) {
|
|
143
|
+
const latest = read(entry.file);
|
|
144
|
+
if (!latest.bytes?.equals(entry.bytes)) continue;
|
|
145
|
+
if (entry.state.exists) atomicWriteFileSync(entry.file, entry.state.bytes, { mode: 0o600 });
|
|
146
|
+
else fs.unlinkSync(entry.file);
|
|
147
|
+
}
|
|
148
|
+
writeM365Json(journalPath, oldJournal);throw error;
|
|
149
|
+
}
|
|
150
|
+
return { changed: pending.length > 0, preserved: [...new Set(skipped)].length, remaining: nextJournal.operations.length };
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function configureClaudeClients({ baseUrl, apiKey, models, desktopInstalled, desktopManaged, ...options } = {}) {
|
|
155
|
+
const paths = claudeClientPaths(options), ids = models.map(model => model.id), operations = [], result = {};
|
|
156
|
+
const endpoint = new URL(baseUrl);
|
|
157
|
+
if (endpoint.protocol !== "http:" || endpoint.hostname !== "127.0.0.1" || endpoint.pathname !== "/" || endpoint.search || endpoint.hash || endpoint.username || endpoint.password) throw new Error("Claude gateway must use a local root URL");
|
|
158
|
+
const add = (file, keys, value, itemId) => operations.push({ file, keys, value, ...(itemId ? { itemId } : {}) });
|
|
159
|
+
const env = options.env || process.env;
|
|
160
|
+
let code;
|
|
161
|
+
try { code = read(paths.code).value; } catch { result.code = "configuration_unavailable"; }
|
|
162
|
+
const codeEnv = code?.env || {};
|
|
163
|
+
const envConflict = env.ANTHROPIC_BASE_URL && env.ANTHROPIC_BASE_URL !== baseUrl
|
|
164
|
+
|| env.ANTHROPIC_AUTH_TOKEN && env.ANTHROPIC_AUTH_TOKEN !== apiKey
|
|
165
|
+
|| codeEnv.ANTHROPIC_AUTH_TOKEN && codeEnv.ANTHROPIC_AUTH_TOKEN !== apiKey
|
|
166
|
+
|| env.ANTHROPIC_API_KEY && env.ANTHROPIC_API_KEY !== apiKey
|
|
167
|
+
|| codeEnv.ANTHROPIC_API_KEY && codeEnv.ANTHROPIC_API_KEY !== apiKey
|
|
168
|
+
|| code?.apiKeyHelper
|
|
169
|
+
|| ["CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", "CLAUDE_CODE_USE_ANTHROPIC_AWS", "CLAUDE_CODE_USE_GATEWAY"].some(key => /^(1|true)$/i.test(env[key] || codeEnv[key] || ""));
|
|
170
|
+
if (!code) { /* Keep independent App setup available when Code settings are damaged. */ }
|
|
171
|
+
else if (envConflict || codeEnv.ANTHROPIC_BASE_URL && codeEnv.ANTHROPIC_BASE_URL !== baseUrl) result.code = "preserved";
|
|
172
|
+
else {
|
|
173
|
+
add(paths.code, ["env", "ANTHROPIC_BASE_URL"], baseUrl);
|
|
174
|
+
add(paths.code, ["env", "ANTHROPIC_AUTH_TOKEN"], apiKey);
|
|
175
|
+
add(paths.code, ["env", "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY"], "1");
|
|
176
|
+
if (env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS === undefined) add(paths.code, ["env", "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"], "1");
|
|
177
|
+
add(paths.code, ["env", "ANTHROPIC_CUSTOM_HEADERS"], "X-CCDX-Client: claude-code");
|
|
178
|
+
if (!codeEnv.ANTHROPIC_MODEL && ids.length) add(paths.code, ["env", "ANTHROPIC_MODEL"], ids[0]);
|
|
179
|
+
result.code = "configured";
|
|
180
|
+
}
|
|
181
|
+
const installed = desktopInstalled ?? (fs.existsSync(path.dirname(paths.normal)) || fs.existsSync(path.dirname(paths.threep))
|
|
182
|
+
|| (options.platform || process.platform) === "darwin" && fs.existsSync("/Applications/Claude.app"));
|
|
183
|
+
if (!installed) result.app = "not_installed";
|
|
184
|
+
else if (desktopManaged !== false || env.CLAUDE_USER_DATA_DIR) result.app = "preserved";
|
|
185
|
+
else {
|
|
186
|
+
let meta, profile;
|
|
187
|
+
try { meta = read(paths.meta).value;profile = read(paths.profile).value; } catch { result.app = "configuration_unavailable"; }
|
|
188
|
+
if (!meta) { /* Code setup remains independent. */ }
|
|
189
|
+
else if (meta.hybridPointer || meta.appliedId && meta.appliedId !== M365_CLAUDE_PROFILE_ID
|
|
190
|
+
|| profile.inferenceProvider && profile.inferenceProvider !== "gateway"
|
|
191
|
+
|| profile.inferenceGatewayBaseUrl && profile.inferenceGatewayBaseUrl !== baseUrl
|
|
192
|
+
|| profile.inferenceGatewayApiKey && profile.inferenceGatewayApiKey !== apiKey) result.app = "preserved";
|
|
193
|
+
else {
|
|
194
|
+
add(paths.profile, ["inferenceProvider"], "gateway");
|
|
195
|
+
add(paths.profile, ["inferenceGatewayBaseUrl"], baseUrl);
|
|
196
|
+
add(paths.profile, ["inferenceGatewayApiKey"], apiKey);
|
|
197
|
+
add(paths.profile, ["inferenceGatewayAuthScheme"], "bearer");
|
|
198
|
+
add(paths.profile, ["inferenceModels"], JSON.stringify(ids));
|
|
199
|
+
add(paths.profile, ["inferenceCustomHeaders"], JSON.stringify({ "X-CCDX-Client": "claude-app" }));
|
|
200
|
+
add(paths.meta, ["entries"], { id: M365_CLAUDE_PROFILE_ID, name: M365_CLAUDE_PROFILE_NAME }, M365_CLAUDE_PROFILE_ID);
|
|
201
|
+
add(paths.meta, ["appliedId"], M365_CLAUDE_PROFILE_ID);
|
|
202
|
+
add(paths.threep, ["deploymentMode"], "3p");
|
|
203
|
+
result.app = "configured";
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const applied = reconcile(operations, options);
|
|
207
|
+
if (applied.preserved) {
|
|
208
|
+
if (result.code === "configured") result.code = "partially_preserved";
|
|
209
|
+
if (result.app === "configured") result.app = "partially_preserved";
|
|
210
|
+
}
|
|
211
|
+
return { ...result, changed: applied.changed };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function restoreClaudeClients(options = {}) {
|
|
215
|
+
if (!fs.existsSync(m365Paths(options).ownership)) return { changed: false, preserved: 0, remaining: 0 };
|
|
216
|
+
return reconcile([], { ...options, restore: true });
|
|
217
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import { randomUUID, timingSafeEqual } from "node:crypto";
|
|
3
|
+
import { createRequestAbort, readJsonBody, readBoundedResponseText, writeOrDrain, MAX_UPSTREAM_ERROR_BODY_BYTES } from "./http-transport.mjs";
|
|
4
|
+
import { createRequestAdmission } from "./request-admission.mjs";
|
|
5
|
+
import { loadRuntimeConfig } from "./runtime-config.mjs";
|
|
6
|
+
import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
|
|
7
|
+
import { safeUpstreamResponseHeaders } from "./upstream-headers.mjs";
|
|
8
|
+
import { runWithRequestContext } from "./request-context.mjs";
|
|
9
|
+
import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
|
|
10
|
+
import { buildMessagesUsageRecord, recordUsage } from "./usage-store.mjs";
|
|
11
|
+
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
12
|
+
import { decodedBodyLimitPreference } from "./user-settings.mjs";
|
|
13
|
+
|
|
14
|
+
function send(res, code, value) {
|
|
15
|
+
if (res.destroyed || res.writableEnded) return;
|
|
16
|
+
res.writeHead(code, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(value));
|
|
17
|
+
}
|
|
18
|
+
const apiError = (code, message) => ({ type: "error", error: { type: "api_error", code, message } });
|
|
19
|
+
function authenticated(headers, key) {
|
|
20
|
+
const candidates = [headers["x-api-key"], typeof headers.authorization === "string" ? /^Bearer (.+)$/i.exec(headers.authorization)?.[1] : null];
|
|
21
|
+
const expected = Buffer.from(key);
|
|
22
|
+
return candidates.some(value => typeof value === "string" && Buffer.byteLength(value) === expected.length && timingSafeEqual(Buffer.from(value), expected));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Observe bounded SSE frames while retaining the original wire bytes for the
|
|
26
|
+
// client. A slow client controls upstream reads; there is no independent tee.
|
|
27
|
+
export function createMessagesObserver(onEvent, maxBytes = 8 * 1024 * 1024) {
|
|
28
|
+
const decoder = new TextDecoder();let fragments = [], lineBytes = 0, data = [], frameBytes = 0;
|
|
29
|
+
const frame = () => {
|
|
30
|
+
if (data.length) { let value;try { value = JSON.parse(data.join("\n")); } catch { throw new Error("Invalid Claude stream event"); }onEvent(value); }
|
|
31
|
+
data = [];frameBytes = 0;
|
|
32
|
+
};
|
|
33
|
+
const line = value => {
|
|
34
|
+
if (value.endsWith("\r")) value = value.slice(0, -1);
|
|
35
|
+
if (!value) frame();
|
|
36
|
+
else if (value.startsWith("data:")) {
|
|
37
|
+
const part = value.slice(5).replace(/^ /, "");frameBytes += Buffer.byteLength(part);
|
|
38
|
+
if (frameBytes > maxBytes) throw new Error("Claude stream event exceeds its limit");data.push(part);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
function consume(text) {
|
|
42
|
+
let start = 0;
|
|
43
|
+
while (start < text.length) {
|
|
44
|
+
const newline = text.indexOf("\n", start), end = newline < 0 ? text.length : newline, part = text.slice(start, end);
|
|
45
|
+
lineBytes += Buffer.byteLength(part);
|
|
46
|
+
if (lineBytes > maxBytes) throw new Error("Claude stream line exceeds its limit");
|
|
47
|
+
fragments.push(part);
|
|
48
|
+
if (newline < 0) break;
|
|
49
|
+
line(fragments.join(""));fragments = [];lineBytes = 0;start = newline + 1;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return { write(chunk) { consume(decoder.decode(chunk, { stream: true })); },
|
|
53
|
+
finish() { consume(decoder.decode());if (fragments.length) line(fragments.join(""));frame(); } };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function createClaudeGatewayHandler({ provider, apiKey, log = () => {}, onRequest = () => {}, env = process.env,
|
|
57
|
+
record = recordUsage, acquireRequest = createRequestAdmission({ maxBytes: 16 * 1024 * 1024, maxQueued: 8 }) } = {}) {
|
|
58
|
+
if (!provider || typeof apiKey !== "string" || apiKey.length < 32) throw new Error("Claude gateway requires a provider and private local key");
|
|
59
|
+
const config = loadRuntimeConfig(env), performance = createStreamPerformanceMetrics({ routeNames: ["messages"] });
|
|
60
|
+
const decodedLimit = decodedBodyLimitPreference({ env }).bytes;
|
|
61
|
+
const stats = { total: 0, active: 0, completed: 0, incomplete: 0, failed: 0, cancelled: 0, last_request_at: null, last_model: null };
|
|
62
|
+
async function dispatch(req, res) {
|
|
63
|
+
if (!isLoopbackAddress(req.socket?.remoteAddress) || req.headers.host === undefined || !isLoopbackHostHeader(req.headers.host)
|
|
64
|
+
|| Object.hasOwn(req.headers, "origin")) { send(res, 403, apiError("ccdx_local_only", "The Claude gateway accepts native local clients only"));return; }
|
|
65
|
+
if (!authenticated(req.headers, apiKey)) { send(res, 401, apiError("ccdx_gateway_auth", "Invalid local gateway credential"));return; }
|
|
66
|
+
let pathname;try { pathname = new URL(req.url, "http://localhost").pathname; } catch { send(res, 400, apiError("ccdx_invalid_path", "Invalid request path"));return; }
|
|
67
|
+
if (req.method === "GET" && pathname === "/v1/models") {
|
|
68
|
+
const models = provider.models("claude").map(model => ({ id: model.id, type: "model", display_name: typeof model.name === "string" && model.name || model.id }));
|
|
69
|
+
send(res, 200, { data: models, has_more: false, first_id: models[0]?.id || null, last_id: models.at(-1)?.id || null });return;
|
|
70
|
+
}
|
|
71
|
+
if (!["/v1/messages", "/v1/messages/count_tokens"].includes(pathname)) { send(res, 404, apiError("ccdx_not_found", "Not found"));return; }
|
|
72
|
+
if (req.method !== "POST") { send(res, 405, apiError("ccdx_method", "Use POST"));return; }
|
|
73
|
+
if (!/^application\/json(?:\s*;|$)/i.test(req.headers["content-type"] || "")) { send(res, 415, apiError("ccdx_media_type", "Expected application/json"));return; }
|
|
74
|
+
const countTokens = pathname.endsWith("/count_tokens"), requestId = randomUUID();
|
|
75
|
+
const tracker = countTokens ? null : performance.begin("messages", { requestId });
|
|
76
|
+
tracker?.setProvider("m365");
|
|
77
|
+
const abort = createRequestAbort(req, res);
|
|
78
|
+
let release = () => {}, outcome = "failed", model = null, responseId = null, usage = null, stopReason = null, streamed = false, sawStop = false, failedEvent = false;
|
|
79
|
+
if (!countTokens) { stats.total++;stats.active++;stats.last_request_at = new Date().toISOString(); }
|
|
80
|
+
await runWithRequestContext({ requestId, provider: "m365", route: "messages", streamPerformance: tracker }, async () => {
|
|
81
|
+
try {
|
|
82
|
+
release = await acquireRequest(req, { signal: abort.signal });
|
|
83
|
+
abort.setTimeout(config.requestBodyTimeoutMs, "request_body_timeout");
|
|
84
|
+
let body = await readJsonBody(req, { admission: release, signal: abort.signal, maxBodyBytes: config.maxBodyBytes, maxDecodedBodyBytes: decodedLimit });
|
|
85
|
+
if (!body || typeof body.model !== "string" || !Array.isArray(body.messages)) {
|
|
86
|
+
send(res, 400, apiError("ccdx_messages_invalid", "Expected a model and messages array"));return;
|
|
87
|
+
}
|
|
88
|
+
model = body.model;stats.last_model = model;streamed = !countTokens && body.stream === true;tracker?.setModel(model);
|
|
89
|
+
const upstream = await provider.client.messages(body, { headers: req.headers, countTokens, signal: abort.signal,
|
|
90
|
+
onUpstreamStart() { abort.setTimeout(streamed ? config.streamHandshakeTimeoutMs : config.upstreamTimeoutMs, "upstream_timeout"); } });
|
|
91
|
+
body = null;
|
|
92
|
+
tracker?.upstreamHeaders(upstream.status);
|
|
93
|
+
release();release = () => {};
|
|
94
|
+
try { onRequest({ client: req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude" }); } catch {}
|
|
95
|
+
const headers = safeUpstreamResponseHeaders(upstream.headers);
|
|
96
|
+
for (const [name, value] of upstream.headers) if (/^anthropic-ratelimit-[a-z0-9-]+$/.test(name)) headers[name] = value;
|
|
97
|
+
if (!upstream.ok || !streamed) {
|
|
98
|
+
const raw = await readBoundedResponseText(upstream, { maxBytes: upstream.ok ? config.maxUpstreamResponsesResponseBytes : MAX_UPSTREAM_ERROR_BODY_BYTES,
|
|
99
|
+
label: "Claude gateway response", signal: abort.signal });
|
|
100
|
+
let value;try { value = JSON.parse(raw); } catch {}
|
|
101
|
+
if (!countTokens && upstream.ok && value?.type === "message" && Array.isArray(value.content)) {
|
|
102
|
+
model = value.model || model;responseId = value.id;usage = value.usage;stopReason = value.stop_reason;
|
|
103
|
+
sawStop = typeof stopReason === "string";outcome = stopReason === "max_tokens" ? "incomplete" : sawStop ? "completed" : "failed";
|
|
104
|
+
} else if (countTokens && upstream.ok) outcome = "completed";
|
|
105
|
+
if (!res.destroyed && !res.writableEnded) { res.writeHead(upstream.status, headers);res.end(raw); }
|
|
106
|
+
} else {
|
|
107
|
+
if (!/^text\/event-stream(?:\s*;|$)/i.test(upstream.headers.get("content-type") || "")) throw new Error("Expected a Claude event stream");
|
|
108
|
+
abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
|
|
109
|
+
res.writeHead(upstream.status, { ...headers, "Cache-Control": "no-cache" });
|
|
110
|
+
const observer = createMessagesObserver(event => {
|
|
111
|
+
if (event.type === "error") { failedEvent = true;outcome = "failed";return; }
|
|
112
|
+
if (sawStop || failedEvent) return;
|
|
113
|
+
if (event.type === "message_start") { responseId = event.message?.id;model = event.message?.model || model;usage = event.message?.usage || {}; }
|
|
114
|
+
if (event.type === "content_block_delta") tracker?.firstOutput(event.delta?.type === "input_json_delta" ? "tool_arguments" : "output_text");
|
|
115
|
+
if (event.type === "message_delta") { usage = { ...usage, ...event.usage };stopReason = event.delta?.stop_reason || stopReason; }
|
|
116
|
+
if (event.type === "message_stop") { sawStop = true;outcome = stopReason === "max_tokens" ? "incomplete" : "completed"; }
|
|
117
|
+
}, config.maxSseBufferBytes);
|
|
118
|
+
const reader = upstream.body.getReader();
|
|
119
|
+
try {
|
|
120
|
+
while (true) {
|
|
121
|
+
const { value, done } = await reader.read();if (done) break;
|
|
122
|
+
tracker?.upstreamActivity();abort.setTimeout(config.streamIdleTimeoutMs, "stream_idle_timeout");
|
|
123
|
+
observer.write(value);
|
|
124
|
+
if (!await writeOrDrain(res, value, { signal: abort.signal })) break;
|
|
125
|
+
if (sawStop || failedEvent) break;
|
|
126
|
+
}
|
|
127
|
+
observer.finish();
|
|
128
|
+
if (!sawStop && !failedEvent) throw new Error("Claude stream ended before message_stop");
|
|
129
|
+
if (!res.writableEnded) res.end();
|
|
130
|
+
} finally { await reader.cancel().catch(() => {});reader.releaseLock(); }
|
|
131
|
+
}
|
|
132
|
+
} catch (error) {
|
|
133
|
+
outcome = ["client_aborted", "client_closed"].includes(abort.reason) ? "cancelled" : "failed";
|
|
134
|
+
const message = redactDiagnosticText(error.message).split(apiKey).join("[redacted]").slice(0, 240);
|
|
135
|
+
log("warn", `Claude request ${requestId}: ${error.code || abort.reason || "gateway_error"}`);
|
|
136
|
+
if (!res.headersSent) send(res, error.statusCode || 502, apiError(error.code || "ccdx_gateway_error", message));
|
|
137
|
+
else if (!res.destroyed && !res.writableEnded) res.end(`event: error\ndata: ${JSON.stringify(apiError("ccdx_gateway_error", message))}\n\n`);
|
|
138
|
+
} finally {
|
|
139
|
+
release();abort.cleanup();
|
|
140
|
+
if (!countTokens) {
|
|
141
|
+
stats.active--;stats[outcome]++;
|
|
142
|
+
tracker?.setModel(model);tracker?.setOutputTokens(usage?.output_tokens);
|
|
143
|
+
tracker?.terminal(outcome, { origin: failedEvent ? "upstream_event" : "upstream_response", reason: stopReason === "max_tokens" ? "max_output_tokens" : undefined });
|
|
144
|
+
tracker?.finish({ failed: outcome === "failed" || outcome === "cancelled", aborted: outcome === "cancelled", statusCode: res.statusCode });
|
|
145
|
+
const client = req.headers["x-ccdx-client"] === "claude-app" ? "claude_app" : req.headers["x-ccdx-client"] === "claude-code" ? "claude_code" : "claude";
|
|
146
|
+
try { void Promise.resolve(record(buildMessagesUsageRecord({ model, responseId, usage, mode: streamed ? "stream" : "json", client }))).catch(() => {}); } catch {}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
const handler = (req, res) => dispatch(req, res).catch(() => send(res, 500, apiError("ccdx_gateway_error", "Claude gateway request failed")));
|
|
152
|
+
handler.snapshot = () => ({ ...stats, admission: acquireRequest.stats(), performance: performance.snapshot() });
|
|
153
|
+
return handler;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export async function startClaudeGateway(options = {}) {
|
|
157
|
+
const handler = createClaudeGatewayHandler(options), server = http.createServer(handler);
|
|
158
|
+
server.headersTimeout = 15000;server.requestTimeout = 120000;
|
|
159
|
+
await new Promise((resolve, reject) => { server.once("error", reject);server.listen(options.port ?? 2027, "127.0.0.1", () => { server.off("error", reject);resolve(); }); });
|
|
160
|
+
server.on("error", () => options.log?.("warn", "Claude gateway listener error"));
|
|
161
|
+
return { port: server.address().port, snapshot: handler.snapshot,
|
|
162
|
+
close: () => new Promise(resolve => { server.closeAllConnections();server.close(resolve); }) };
|
|
163
|
+
}
|