codex-copilot-dx 1.2.11 → 1.2.13

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.
Files changed (44) hide show
  1. package/README.md +14 -14
  2. package/bin/cli.mjs +12 -8
  3. package/docs/ARCHITECTURE.md +75 -5
  4. package/docs/REFERENCE.md +117 -4
  5. package/package.json +2 -2
  6. package/src/access-settings.mjs +98 -0
  7. package/src/adapter.mjs +19 -7
  8. package/src/api-secrets.mjs +69 -0
  9. package/src/auto-review-model.mjs +4 -3
  10. package/src/claude-client-config.mjs +16 -11
  11. package/src/claude-gateway.mjs +11 -8
  12. package/src/cli-m365.mjs +48 -8
  13. package/src/cli-models.mjs +2 -1
  14. package/src/cli-options.mjs +1 -1
  15. package/src/cli-status.mjs +1 -1
  16. package/src/client-gateway-keys.mjs +29 -0
  17. package/src/codex-api-config.mjs +51 -0
  18. package/src/connection-runtime.mjs +289 -0
  19. package/src/conversation-source-guard.mjs +42 -0
  20. package/src/dashboard/connections.js +163 -0
  21. package/src/dashboard/console.js +6 -4
  22. package/src/dashboard/flow.js +17 -18
  23. package/src/dashboard/index.html +46 -3
  24. package/src/dashboard/language.js +88 -3
  25. package/src/dashboard/status.js +1 -1
  26. package/src/dashboard/ui.css +54 -26
  27. package/src/dashboard/ui.js +5 -3
  28. package/src/dashboard-api.mjs +19 -4
  29. package/src/dashboard.mjs +1 -0
  30. package/src/optional-routes.mjs +2 -2
  31. package/src/private-helper-environment.mjs +7 -0
  32. package/src/provider-management.mjs +1 -1
  33. package/src/provider-runtime.mjs +37 -5
  34. package/src/providers/api-network.mjs +51 -0
  35. package/src/providers/api.mjs +129 -0
  36. package/src/proxy-tunnel.mjs +6 -4
  37. package/src/request-application.mjs +12 -6
  38. package/src/responses-handler.mjs +6 -4
  39. package/src/startup-ui.mjs +9 -0
  40. package/src/stream-performance.mjs +7 -6
  41. package/src/terminal-console.mjs +1 -1
  42. package/src/usage-store.mjs +1 -1
  43. package/src/windows-http-network.mjs +11 -6
  44. package/src/windows-prediction-network.cs +6 -4
package/src/dashboard.mjs CHANGED
@@ -18,6 +18,7 @@ const ASSETS = new Map([
18
18
  ["/refresh.js", ["./dashboard/refresh.js", "text/javascript; charset=utf-8"]],
19
19
  ["/icons.js", ["./dashboard/icons.js", "text/javascript; charset=utf-8"]],
20
20
  ["/tools.js", ["./dashboard/tools.js", "text/javascript; charset=utf-8"]],
21
+ ["/connections.js", ["./dashboard/connections.js", "text/javascript; charset=utf-8"]],
21
22
  ]);
22
23
 
23
24
  export async function serveDashboard(req, res, pathname) {
@@ -1,5 +1,5 @@
1
- export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/time.js", "/animation.js", "/status.js", "/activity.js", "/flow.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js"]);
2
- export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks"]);
1
+ export const DASHBOARD_PATHS = new Set(["/", "/ui.css", "/theme.js", "/language.js", "/refresh.js", "/time.js", "/animation.js", "/status.js", "/activity.js", "/flow.js", "/usage.js", "/ui.js", "/console.js", "/updates.js", "/icons.js", "/tools.js", "/connections.js"]);
2
+ export const DASHBOARD_API_PATHS = new Set(["/_ccdx/ui/animation", "/_ccdx/ui/models/live", "/_ccdx/ui/usage", "/_ccdx/ui/auth", "/_ccdx/ui/providers", "/_ccdx/ui/settings", "/_ccdx/ui/m365/accounts", "/_ccdx/ui/updates", "/_ccdx/ui/account", "/_ccdx/ui/checks", "/_ccdx/ui/connections"]);
3
3
 
4
4
  export function isOptionalRoute(method, pathname) {
5
5
  return DASHBOARD_API_PATHS.has(pathname) || pathname === "/mcp/image"
@@ -0,0 +1,7 @@
1
+ // Keep company routing and OS credential access; omit unrelated application secrets and Node hooks.
2
+ export function privateHelperEnvironment(env = process.env) {
3
+ const keys = new Set(["PATH", "HOME", "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "SYSTEMROOT", "WINDIR", "APPDATA", "LOCALAPPDATA",
4
+ "TMPDIR", "TMP", "TEMP", "LANG", "LC_ALL", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "NODE_EXTRA_CA_CERTS",
5
+ "DBUS_SESSION_BUS_ADDRESS", "XDG_RUNTIME_DIR", "DISPLAY"]);
6
+ return Object.fromEntries(Object.entries(env).filter(([key]) => keys.has(key.toUpperCase())));
7
+ }
@@ -20,7 +20,7 @@ export async function handleProviderManagement(req, res, runtime) {
20
20
  || !["models", "switch", "on", "off", "remove", "auto-review", "accounts", "account"].includes(input.action)) throw httpError("Invalid provider action", 400);
21
21
  if (input.action === "account" && (typeof input.account_id !== "string" || !/^[a-f0-9]{64}$/.test(input.account_id))) throw httpError("Select an available company account", 400);
22
22
  if (input.effort !== undefined && input.effort !== null && (typeof input.effort !== "string" || input.effort.length > 16)) throw httpError("Invalid reasoning effort", 400);
23
- for (const key of ["provider", "model", "auto_review_model", "family"]) if (input[key] !== undefined && (typeof input[key] !== "string" || input[key].length > 128)) throw httpError("Invalid provider selection", 400);
23
+ for (const key of ["provider", "model", "auto_review_model", "family"]) if (input[key] !== undefined && (typeof input[key] !== "string" || input[key].length > (key.includes("model") ? 160 : 128))) throw httpError("Invalid provider selection", 400);
24
24
  abort.clearTimeout();
25
25
  const result = await runtime.action(input);
26
26
  if (!res.destroyed && !res.writableEnded) { res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(result)); }
@@ -11,15 +11,30 @@ import { publicM365Accounts, accountChoiceId, m365AccountMessage } from "./provi
11
11
  import { providerRegistry } from "./provider-registry.mjs";
12
12
  import { createClaudeClientLifecycle } from "./claude-client-lifecycle.mjs";
13
13
  import { m365NetworkMessage } from "./providers/m365-network-diagnostic.mjs";
14
+ import { createConnectionRuntime } from "./connection-runtime.mjs";
15
+ import { accessSettingsPath, readAccessSettings } from "./access-settings.mjs";
16
+ import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
14
17
 
15
18
  const unavailable = reason => Object.assign(new Error(`Microsoft 365 is unavailable (${reason}); GitHub routing was not substituted`),
16
19
  { code: reason, statusCode: 503 });
17
20
 
18
21
  // Composition owns source selection. Providers never modify Codex, prediction,
19
22
  // image configuration or each other's credentials.
20
- export function createProviderRuntime({ githubClient, githubRegistry, githubCredentialFingerprint = "", githubClientConfigured = true, home, env = process.env, platform = process.platform,
23
+ export function createProviderRuntime(options = {}) {
24
+ options = { ...options, corePort: options.corePort ?? Number((options.env || process.env).ADAPTER_PORT || 2026) };
25
+ let connections;
26
+ const legacy = createBuiltinProviderRuntime({ ...options, managedClaude: () => {
27
+ if (!fs.existsSync(accessSettingsPath(options))) return false;
28
+ const graph = readAccessSettings(options);
29
+ return graph.claude_private_keys || !["claude_app", "claude_code"].every(id => graph.clients[id].enabled && graph.clients[id].source === "m365" && graph.clients[id].allowed.includes("m365"));
30
+ },
31
+ onClaudeReady: () => connections?.syncClients() });
32
+ connections = createConnectionRuntime({ ...options, legacy });return connections;
33
+ }
34
+
35
+ function createBuiltinProviderRuntime({ githubClient, githubRegistry, githubCredentialFingerprint = "", githubClientConfigured = true, home, env = process.env, platform = process.platform,
21
36
  corePort = Number(env.ADAPTER_PORT || 2026), log = () => {}, createM365, startGateway, configureClients, restoreClients,
22
- discoverM365 = requestM365Accounts } = {}) {
37
+ discoverM365 = requestM365Accounts, managedClaude, onClaudeReady } = {}) {
23
38
  const options = { home, env, platform }, github = { ...createGithubProvider({ client: githubClient,
24
39
  profileId: () => { const value = typeof githubCredentialFingerprint === "function" ? githubCredentialFingerprint() : githubCredentialFingerprint;
25
40
  return value ? `codex:${value}` : "codex"; } }), registry: githubRegistry };
@@ -27,6 +42,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
27
42
  let reason = null, claudeReason = null, lastClients = {};
28
43
  let changingAccount = false;
29
44
  const clientLifecycle = createClaudeClientLifecycle({ options, configureClients, restoreClients });
45
+ const claudePerformance = createStreamPerformanceMetrics({ routeNames: ["messages"] });
30
46
  const sources = new Map([[github.id, github]]);
31
47
  const dashboardProfiles = new Map();
32
48
  const dashboardGeneration = provider => {
@@ -36,10 +52,11 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
36
52
  };
37
53
  const sessions = new Map();let priorNamespace = null, requestOrder = 0, activeM365Requests = 0;
38
54
  let enabled;
39
- try { enabled = readM365Settings(options).enabled && env.CCDX_M365 !== "0"; }
55
+ try { enabled = readM365Settings(options).enabled && readAccessSettings(options).providers.m365 && env.CCDX_M365 !== "0"; }
40
56
  catch { enabled = false;reason = "m365_config_invalid"; }
41
57
 
42
58
  async function syncClaudeClients() {
59
+ if (managedClaude?.()) { await onClaudeReady?.();return; }
43
60
  const source = m365, profile = source?.profileId();
44
61
  if (!source || !gateway || closed || !enabled) return;
45
62
  await clientLifecycle.sync({ source, baseUrl: `http://127.0.0.1:${corePort}/anthropic`, apiKey: () => ensureM365GatewayKey(options),
@@ -68,7 +85,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
68
85
  const apiKey = ensureM365GatewayKey(options);
69
86
  if (!gateway) {
70
87
  const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
71
- const opened = await start({ provider: m365, apiKey, port: corePort, env, log,
88
+ const opened = await start({ provider: m365, apiKey, port: corePort, env, log, performance: claudePerformance,
72
89
  onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
73
90
  if (closed || !enabled) { await opened.close();return null; }
74
91
  gateway = opened;
@@ -135,7 +152,7 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
135
152
  if (closed) throw unavailable("m365_runtime_closed");
136
153
  if (candidate.models("claude").length) {
137
154
  const start = startGateway || (await import("./claude-gateway.mjs")).createClaudeGateway;
138
- opened = await start({ provider: candidate, apiKey: ensureM365GatewayKey(options), port: corePort, env, log,
155
+ opened = await start({ provider: candidate, apiKey: ensureM365GatewayKey(options), port: corePort, env, log, performance: claudePerformance,
139
156
  onRequest({ client }) { lastClients[client] = new Date().toISOString(); } });
140
157
  }
141
158
  candidate.commitSelection(discovered.binding);
@@ -191,6 +208,21 @@ export function createProviderRuntime({ githubClient, githubRegistry, githubCred
191
208
  return snapshot();
192
209
  }
193
210
  return {
211
+ claudePerformance,
212
+ source: id => sources.get(id),
213
+ async pauseM365() {
214
+ updateM365Settings({ enabled: false }, options);enabled = false;
215
+ // Existing handlers retain their source until their request finishes.
216
+ const previous = m365, oldGateway = gateway;m365 = null;gateway = null;sources.delete("m365");
217
+ await pending;await oldGateway?.close();return previous;
218
+ },
219
+ removeM365SavedProfile() {
220
+ if (activeM365Requests > 0) throw Object.assign(new Error("M365 requests are active; finish them before removing the account"), { code: "m365_profile_busy", statusCode: 409 });
221
+ const paths = m365Paths(options);
222
+ for (const file of [paths.account, paths.catalog, paths.gateway, paths.conversations]) {
223
+ try { if (!fs.lstatSync(file).isFile()) throw Error();fs.unlinkSync(file); } catch (error) { if (error.code !== "ENOENT") throw new Error("M365 cleanup preserved an unexpected file"); }
224
+ }
225
+ },
194
226
  github, current, snapshot, start: startM365, refresh: () => startM365(true),
195
227
  handleClaude(req, res) {
196
228
  if (changingAccount) { res.writeHead(409, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify({ error: { code: "m365_account_busy", message: m365AccountMessage("m365_account_busy") } }));return; }
@@ -0,0 +1,51 @@
1
+ import https from "node:https";
2
+ import { Readable } from "node:stream";
3
+ import { execFile } from "node:child_process";
4
+ import { promisify } from "node:util";
5
+ import { resolveNetworkRoute, networkProxyFor, bypassNetworkProxy } from "../network-route.mjs";
6
+ import { createProxyAgent } from "../proxy-tunnel.mjs";
7
+ import { apiUrl, accessError } from "../access-settings.mjs";
8
+ import { privateHelperEnvironment } from "../private-helper-environment.mjs";
9
+
10
+ export async function createApiNetwork({ targets, env = process.env, platform = process.platform, signal,
11
+ requestImpl = https.request, exec = promisify(execFile), startWindowsNetwork } = {}) {
12
+ const urls = new Set(targets.map(raw => new URL(apiUrl(raw)).href));if (!urls.size || urls.size > 8) throw accessError("ccdx_api_url_invalid");
13
+ const first = new URL([...urls][0]);
14
+ let plan = resolveNetworkRoute({ env, checkApi: false }), worker;
15
+ if (!networkProxyFor(first, plan) && !bypassNetworkProxy(first.hostname, first.port || 443, plan)) {
16
+ if (platform === "darwin") {
17
+ const { stdout } = await exec("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8", timeout: 2500, maxBuffer: 65536, signal });
18
+ plan = resolveNetworkRoute({ env, systemProxy: stdout, checkApi: false });
19
+ } else if (platform === "win32") {
20
+ const start = startWindowsNetwork || (await import("../windows-http-network.mjs")).startWindowsHttpNetwork;
21
+ worker = await start({ target: "api", apiTargets: [...urls], env: privateHelperEnvironment(env), signal, timeoutMs: 120000 });
22
+ requestImpl = worker.requestImpl;
23
+ }
24
+ }
25
+ const agent = worker ? undefined : createProxyAgent(plan);let closed = false;
26
+ return {
27
+ healthy: () => !closed && (!worker || worker.healthy()),
28
+ fetch(raw, init = {}) {
29
+ return new Promise((resolve, reject) => {
30
+ let url;try { url = new URL(raw); } catch { reject(accessError("ccdx_api_url_invalid"));return; }
31
+ if (closed || !urls.has(url.href) || !["GET", "POST"].includes(init.method || "GET")) { reject(accessError("ccdx_api_url_invalid"));return; }
32
+ if (init.signal?.aborted) { reject(init.signal.reason);return; }
33
+ let req, incoming;
34
+ const cleanup = () => init.signal?.removeEventListener("abort", abort);
35
+ const abort = () => { req?.destroy(init.signal.reason || accessError("ccdx_api_cancelled"));incoming?.destroy(); };
36
+ try {
37
+ req = requestImpl({ hostname: worker ? url.hostname : url.hostname.replace(/^\[|\]$/g, ""), port: Number(url.port || 443), protocol: "https:", path: url.pathname,
38
+ method: init.method || "GET", headers: { ...Object.fromEntries(new Headers(init.headers)), "accept-encoding": "identity" }, agent, rejectUnauthorized: true }, res => {
39
+ incoming = res;res.once("end", cleanup);res.once("close", cleanup);res.on("error", reject);
40
+ const headers = new Headers();for (const [key, value] of Object.entries(res.headers)) for (const item of Array.isArray(value) ? value : value === undefined ? [] : [value]) headers.append(key, String(item));
41
+ try { const empty = [204, 205, 304].includes(res.statusCode);if (empty) res.resume();resolve(new Response(empty ? null : Readable.toWeb(res), { status: res.statusCode, headers })); }
42
+ catch (error) { cleanup();res.destroy();reject(error); }
43
+ });
44
+ req.on("error", error => { cleanup();reject(error); });init.signal?.addEventListener("abort", abort, { once: true });
45
+ if (init.signal?.aborted) { abort();return; }req.end(init.body);
46
+ } catch (error) { cleanup();req?.destroy();reject(error); }
47
+ });
48
+ },
49
+ close() { closed = true;agent?.destroy();worker?.close(); },
50
+ };
51
+ }
@@ -0,0 +1,129 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createRoutePlan } from "../route-plan.mjs";
3
+ import { accessError } from "../access-settings.mjs";
4
+ import { publicModelCatalog } from "../provider-metadata.mjs";
5
+ import { resolveClaudeModel } from "../claude-models.mjs";
6
+ import { prepareResponsesPayload } from "../image-optimization.mjs";
7
+ import { enforceResponsesPayloadByteBudget } from "../responses-byte-budget.mjs";
8
+ import { MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "../http-transport.mjs";
9
+ import { markUpstreamHeaders } from "../stream-performance.mjs";
10
+ import { createApiNetwork } from "./api-network.mjs";
11
+ import { checkedApiKey } from "../api-secrets.mjs";
12
+
13
+ const paths = { messages: "/v1/messages", responses: "/v1/responses", chat: "/v1/chat/completions" };
14
+ export function apiCatalog(config) {
15
+ return config.models.map(model => ({ id: model.id, name: model.id, publisher: "Unknown",
16
+ supported_endpoints: model.protocols.map(api => paths[api]), model_picker_enabled: true, policy: { state: "enabled" },
17
+ capabilities: { limits: { max_context_window_tokens: model.context_window }, supports: { reasoning_effort: model.reasoning_efforts || [] } } }));
18
+ }
19
+ export function createApiProvider({ config, secrets, env = process.env, platform = process.platform, networkFactory = createApiNetwork } = {}) {
20
+ const catalog = apiCatalog(config), declarations = new Map(config.models.map(model => [model.id, model]));
21
+ const fingerprint = config.key_env ? createHash("sha256").update(env[config.key_env] || "").digest("hex") : "";
22
+ const generation = parseInt(createHash("sha256").update(JSON.stringify(config) + fingerprint).digest("hex").slice(0, 8), 16);
23
+ const profiles = Object.fromEntries(["messages", "responses", "chat"].map(protocol => [protocol, `api:${config.id}:${createHash("sha256").update(JSON.stringify({
24
+ endpoint: config.endpoints[protocol] ? new URL(config.endpoints[protocol]).href : null, key: config.secret_ref || fingerprint, auth: protocol === "messages" ? config.auth_header : "bearer",
25
+ })).digest("hex").slice(0, 24)}`]));
26
+ const profile = profiles.responses;
27
+ const modelsUrl = config.base_url.replace(/\/+$/, "") + "/models", targets = [...Object.values(config.endpoints), modelsUrl];
28
+ if (config.endpoints.messages) targets.push(config.endpoints.messages.replace(/\/+$/, "") + "/count_tokens");
29
+ if (config.endpoints.responses) targets.push(config.endpoints.responses.replace(/\/+$/, "") + "/compact");
30
+ let network, flight, closed = false;
31
+ const registry = { models: { data: catalog.filter(model => model.supported_endpoints.includes(paths.responses)) }, source: "configured", generation };
32
+ const getNetwork = async signal => {
33
+ if (closed) throw accessError("ccdx_api_closed", 503);
34
+ if (network && (network.healthy?.() ?? true)) return network;
35
+ network?.close();network = null;
36
+ flight ||= networkFactory({ targets, env, platform, signal }).then(value => { if (closed) { value.close();throw accessError("ccdx_api_closed", 503); }network = value;return value; }).finally(() => { flight = null; });
37
+ return flight;
38
+ };
39
+ const selected = (id, api) => {
40
+ const model = api === "messages" ? resolveClaudeModel(catalog, id) : catalog.find(model => model.id === id);
41
+ if (!model?.supported_endpoints.includes(paths[api])) throw accessError("ccdx_api_model_unavailable");return model;
42
+ };
43
+ async function request(url, body, options = {}, api = "responses") {
44
+ if (config.key_env && !env[config.key_env]) throw accessError("ccdx_api_environment_key_missing", 503);
45
+ const key = config.key_env ? checkedApiKey(env[config.key_env]) : await secrets.get(config.secret_ref), transport = await getNetwork(options.signal);
46
+ const headers = { "Content-Type": "application/json", Accept: body?.stream ? "text/event-stream" : "application/json" };
47
+ headers[api === "messages" && config.auth_header === "x-api-key" ? "x-api-key" : "Authorization"] = api === "messages" && config.auth_header === "x-api-key" ? key : `Bearer ${key}`;
48
+ if (api === "messages") {
49
+ headers["anthropic-version"] = "2023-06-01";
50
+ for (const name of ["anthropic-version", "anthropic-beta"]) { const value = options.headers?.[name];if (typeof value === "string" && value.length < 8192 && !/[\r\n]/.test(value)) headers[name] = value; }
51
+ }
52
+ const serialized = body ? options.bodyText ?? JSON.stringify(body) : undefined;
53
+ if (serialized !== undefined) headers["Content-Length"] = String(Buffer.byteLength(serialized));
54
+ options.onUpstreamStart?.();
55
+ try {
56
+ const result = await transport.fetch(url, { method: body ? "POST" : "GET", headers, body: serialized, signal: options.signal });
57
+ if (result.status >= 300 && result.status < 400) { await result.body?.cancel();throw accessError("ccdx_api_redirect_refused", 502); }
58
+ if (!result.ok) {
59
+ await result.body?.cancel();const code = `ccdx_api_http_${result.status}`;
60
+ const safeHeaders = { "Content-Type": "application/json" }, retry = result.headers.get("retry-after");
61
+ if (/^\d{1,8}$/.test(retry || "")) safeHeaders["Retry-After"] = retry;
62
+ else if (retry && Number.isFinite(Date.parse(retry))) safeHeaders["Retry-After"] = new Date(retry).toUTCString();
63
+ return new Response(JSON.stringify({ type: "error", error: { type: "api_error", code, message: code } }), { status: result.status, headers: safeHeaders });
64
+ }
65
+ return result;
66
+ } catch (error) { if (options.signal?.aborted) throw error;throw accessError(error.code === "ccdx_api_redirect_refused" ? error.code : "ccdx_api_network_unavailable", 502); }
67
+ }
68
+ const client = {
69
+ listModels: async () => ({ status: 200, body: JSON.stringify(registry.models) }),
70
+ getCachedModelEndpoints: id => catalog.find(model => model.id === id)?.supported_endpoints || null,
71
+ async responses(body, options = {}) {
72
+ selected(body.model, "responses");
73
+ const prepared = await prepareResponsesPayload(body, { ...options.payloadOptions, assertActive: options.assertActive,
74
+ currentInputStart: options.currentInputStart || 0, signal: options.signal, profiles: options.payloadPrepared ? [] : options.payloadOptions?.profiles,
75
+ skipInitialOptimization: options.payloadPrepared || options.payloadOptions?.skipInitialOptimization });
76
+ const final = enforceResponsesPayloadByteBudget(body, prepared, { assertActive: options.assertActive });
77
+ return request(config.endpoints.responses, body, { ...options, bodyText: final.bodyText });
78
+ },
79
+ responsesCompact(body, options = {}) { selected(body.model, "responses");return request(config.endpoints.responses.replace(/\/+$/, "") + "/compact", body, options); },
80
+ chatCompletions(body, options = {}) { selected(body.model, "chat");return request(config.endpoints.chat, body, options, "chat"); },
81
+ messages(body, options = {}) {
82
+ const model = selected(body.model, "messages");
83
+ return request(options.countTokens ? config.endpoints.messages.replace(/\/+$/, "") + "/count_tokens" : config.endpoints.messages, model.id === body.model ? body : { ...body, model: model.id }, options, "messages");
84
+ },
85
+ };
86
+ return {
87
+ id: config.id, client, registry, configuredModels: true, defaultReviewEffort: null, profileId: (protocol = "responses") => profiles[protocol] || profile, models: family => catalog.filter(model => model.supported_endpoints.includes(family === "claude" ? paths.messages : paths.responses)),
88
+ codexCatalog(models) {
89
+ return { ...models, models: config.models.filter(model => model.protocols.includes("responses")).map((model, priority) => ({
90
+ slug: model.id, display_name: model.id, description: config.name, visibility: "list", supported_in_api: true, priority,
91
+ default_reasoning_level: model.reasoning_efforts?.[0] || null, supported_reasoning_levels: (model.reasoning_efforts || []).map(effort => ({ effort, description: effort })),
92
+ shell_type: "unified_exec", availability_nux: null, upgrade: null, additional_speed_tiers: [], service_tiers: [],
93
+ // Neutral metadata for a native Responses API. Never borrow another model's instructions or capabilities.
94
+ base_instructions: "", support_verbosity: false, default_verbosity: null, apply_patch_tool_type: null,
95
+ supports_reasoning_summary_parameter: false, default_reasoning_summary: "none", truncation_policy: { mode: "bytes", limit: 10000 },
96
+ context_window: model.context_window || null, max_context_window: model.context_window || null, experimental_supported_tools: [], input_modalities: ["text"],
97
+ })) };
98
+ },
99
+ catalog: () => catalog,
100
+ publicCatalog(allowed = []) { return { source: "configured", checkedAt: config.checked_at || null, upstreamHost: new URL(config.base_url).hostname,
101
+ advertised: catalog.length, models: publicModelCatalog(catalog, { selectable: model => allowed.some(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)),
102
+ clients: model => allowed.filter(id => model.supported_endpoints.includes(id === "codex" ? paths.responses : paths.messages)) }).map(model => ({ ...model,
103
+ auto_review_efforts: [...(declarations.get(model.id)?.reasoning_efforts || [])] })) }; },
104
+ async discover({ signal } = {}) {
105
+ const response = await request(modelsUrl, undefined, { signal }, config.endpoints.responses ? "responses" : "messages");
106
+ if (!response.ok) { await response.body?.cancel();throw accessError(`ccdx_api_catalog_http_${response.status}`, response.status === 401 || response.status === 403 ? response.status : 502); }
107
+ const text = await readBoundedResponseText(response, { maxBytes: MAX_UPSTREAM_MODEL_CATALOG_BYTES, label: "API model catalog", signal });
108
+ let value;try { value = JSON.parse(text); } catch { throw accessError("ccdx_api_catalog_invalid", 502); }
109
+ if (!Array.isArray(value.data) || value.data.length > 500) throw accessError("ccdx_api_catalog_invalid", 502);
110
+ const ids = new Set();
111
+ for (const model of value.data) { if (!model || typeof model.id !== "string" || !/^[\w][\w./:@+-]{0,159}$/.test(model.id) || ids.has(model.id)) throw accessError("ccdx_api_catalog_invalid", 502);ids.add(model.id); }
112
+ // A catalog listing is not evidence that every model supports every API.
113
+ return value.data.map(model => ({ id: model.id, protocols: Array.isArray(model.supported_endpoints)
114
+ ? Object.entries(paths).filter(([, endpoint]) => model.supported_endpoints.includes(endpoint) || model.supported_endpoints.includes(endpoint.slice(3))).map(([api]) => api).filter(api => config.endpoints[api]) : [] }));
115
+ },
116
+ selectModel(_body, { upstreamModel }) { selected(upstreamModel, "responses");return { upstreamModel, forceResponses: true }; },
117
+ route(_body, { upstreamModel, surface }) { return createRoutePlan({ disposition: "relay", origin: config.id, profile, protocol: "openai-responses", model: upstreamModel, surface }); },
118
+ applyRequestPolicies() {},
119
+ compatibility: { hasRetry: () => false, selectRetry: async () => null,
120
+ async openResponse(context, upstream, options) {
121
+ const resp = await upstream(context.body, { assertActive: options.assertPrepareActive, signal: options.signal, currentInputStart: context.currentInputStart, onUpstreamStart: options.onUpstreamStart });
122
+ markUpstreamHeaders(resp.status);
123
+ // Upstream errors may echo its key; never forward its error body.
124
+ if (!resp.ok) { await resp.body?.cancel();const code = `ccdx_api_http_${resp.status}`;return { resp: new Response(JSON.stringify({ error: { code, message: code } }), { status: resp.status, headers: { "Content-Type": "application/json" } }), reqContext: context, errorText: code, usedRetryPolicies: new Set() }; }
125
+ return { resp, reqContext: context, errorText: undefined, usedRetryPolicies: new Set() };
126
+ } },
127
+ close() { closed = true;network?.close(); },
128
+ };
129
+ }
@@ -26,6 +26,7 @@ function readSocket(socket, ready, maxBytes = 16 * 1024) {
26
26
 
27
27
  async function connectProxy(target, route, timeoutMs, pending) {
28
28
  const proxy = route.url;
29
+ const targetPort = Number(target.port || 443);
29
30
  const proxyHost = proxy.hostname.replace(/^\[|\]$/g, "");
30
31
  const socket = proxy.protocol === "https:"
31
32
  ? tls.connect({ host: proxyHost, port: Number(proxy.port || 443), servername: net.isIP(proxyHost) ? undefined : proxyHost, rejectUnauthorized: true })
@@ -52,21 +53,21 @@ async function connectProxy(target, route, timeoutMs, pending) {
52
53
  socket.write(Buffer.concat([Buffer.from([1, user.length]), user, Buffer.from([password.length]), password]));
53
54
  const result = await auth; if (result[0] !== 1 || result[1] !== 0) throw new Error("SOCKS5 proxy authentication failed");
54
55
  }
55
- const host = Buffer.from(target.hostname);
56
+ const host = Buffer.from(target.hostname.replace(/^\[|\]$/g, ""));
56
57
  if (host.length > 255) throw new Error("Proxy target hostname is too long");
57
58
  const response = readSocket(socket, b => {
58
59
  if (b.length < 5) return null;
59
60
  const size = b[3] === 1 ? 10 : b[3] === 4 ? 22 : b[3] === 3 ? 7 + b[4] : 5;
60
61
  return b.length >= size ? size : null;
61
62
  });
62
- socket.write(Buffer.concat([Buffer.from([5, 1, 0, 3, host.length]), host, Buffer.from([1, 187])]));
63
+ socket.write(Buffer.concat([Buffer.from([5, 1, 0, 3, host.length]), host, Buffer.from([targetPort >> 8, targetPort & 255])]));
63
64
  const result = await response;
64
65
  if (result[0] !== 5 || result[1] !== 0 || ![1, 3, 4].includes(result[3])) throw new Error("SOCKS5 proxy rejected the connection");
65
66
  } else {
66
67
  const response = readSocket(socket, b => { const end = b.indexOf("\r\n\r\n"); return end < 0 ? null : end + 4; });
67
68
  const credentials = proxy.username || proxy.password
68
69
  ? `Proxy-Authorization: Basic ${Buffer.from(`${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`).toString("base64")}\r\n` : "";
69
- socket.write(`CONNECT ${target.hostname}:443 HTTP/1.1\r\nHost: ${target.hostname}:443\r\n${credentials}\r\n`);
70
+ socket.write(`CONNECT ${target.hostname}:${targetPort} HTTP/1.1\r\nHost: ${target.hostname}:${targetPort}\r\n${credentials}\r\n`);
70
71
  const headers = (await response).toString("latin1");
71
72
  const status = /^HTTP\/1\.[01] (\d{3})/.exec(headers)?.[1];
72
73
  if (status !== "200") throw new Error(`HTTP proxy rejected CONNECT (${status || "invalid response"})`);
@@ -83,7 +84,8 @@ export function createProxyAgent(plan, { timeoutMs = 30_000 } = {}) {
83
84
  const direct = agent.createConnection.bind(agent);
84
85
  agent.createConnection = (options, callback) => {
85
86
  if (closed) { queueMicrotask(() => callback(new Error("Proxy agent is closed"))); return undefined; }
86
- const target = new URL(`https://${options.host}`), route = networkProxyFor(target, plan);
87
+ const host = options.hostname || options.host;
88
+ const target = new URL(`https://${net.isIP(host) === 6 ? `[${host}]` : host}:${options.port || 443}`), route = networkProxyFor(target, plan);
87
89
  if (!route) return direct(options, callback);
88
90
  void connectProxy(target, route, timeoutMs, pending).then(socket => {
89
91
  if (closed) { socket.destroy(); callback(new Error("Proxy agent is closed")); return; }
@@ -1,13 +1,19 @@
1
- const APPLICATIONS = new Set(["codex_app", "codex_cli", "claude_app", "claude_code", "claude", "api"]);
2
- const DECLARED = new Map([["codex-app", "codex_app"], ["codex-cli", "codex_cli"], ["claude-app", "claude_app"], ["claude-code", "claude_code"]]);
3
- const ORIGINATORS = new Map([["codex_desktop", "codex_app"], ["codex_app", "codex_app"], ["codex_cli_rs", "codex_cli"]]);
1
+ const APPLICATIONS = new Set(["codex_app", "codex_cli", "codex", "claude_app", "claude_code", "claude", "api"]);
2
+ const DECLARED = new Map([["codex-app", "codex_app"], ["codex-cli", "codex_cli"], ["codex", "codex"], ["claude-app", "claude_app"], ["claude-code", "claude_code"]]);
3
+ const ORIGINATORS = new Map([["codex desktop", "codex_app"], ["codex_desktop", "codex_app"], ["codex_app", "codex_app"], ["codex_cli_rs", "codex_cli"], ["codex_exec", "codex_cli"], ["codex-cli", "codex_cli"], ["codex", "codex"], ["codex_vscode", "codex"]]);
4
+ const hint = value => typeof value === "string" && value.length <= 80 ? value.trim().toLowerCase() : "";
4
5
 
5
6
  export function requestApplication(headers = {}, fallback = "api") {
6
- const declared = DECLARED.get(headers?.["x-ccdx-client"]);
7
+ const declared = DECLARED.get(hint(headers?.["x-ccdx-client"]));
7
8
  if (declared) return declared;
8
9
  // These are client-reported presentation hints, never routing or auth evidence.
9
- const originator = ORIGINATORS.get(headers?.originator);
10
- return originator || (APPLICATIONS.has(fallback) ? fallback : "api");
10
+ const originator = ORIGINATORS.get(hint(headers?.originator));
11
+ if (originator) return originator;
12
+ // Accept only a known, versioned Codex agent prefix, never a substring match.
13
+ const agent = headers?.["user-agent"];
14
+ const prefix = typeof agent === "string" && agent.length <= 512
15
+ ? /^(codex desktop|codex_desktop|codex_app|codex_cli_rs|codex_exec|codex-cli|codex_vscode|codex)\/\d[\w.+-]{0,63}(?:\s|$)/i.exec(agent)?.[1] : null;
16
+ return ORIGINATORS.get(hint(prefix)) || (APPLICATIONS.has(fallback) ? fallback : "api");
11
17
  }
12
18
 
13
19
  export function applicationLabel(value) {
@@ -203,6 +203,7 @@ export function createResponsesHandler(options) {
203
203
  releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal }));
204
204
  abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
205
205
  parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
206
+ options.validateConversation?.(parsed, req.headers, provider);
206
207
  activeDeadline = now() + upstreamTimeoutMs;
207
208
  activeTimeoutReason = "responses_prepare_timeout";
208
209
  abort.setTimeout(upstreamTimeoutMs, "responses_prepare_timeout");
@@ -237,12 +238,12 @@ export function createResponsesHandler(options) {
237
238
  const { upstreamModel, forceResponses } = provider.selectModel(prepared.body, resolvedModel, modelRegistry?.models);
238
239
  if (requestedModel === CODEX_AUTO_REVIEW_MODEL) {
239
240
  delete prepared.body.service_tier;
240
- if (resolvedModel.reasoningEffort || prepared.body.reasoning?.effort === undefined) {
241
+ if (resolvedModel.reasoningEffort || provider.defaultReviewEffort !== null && prepared.body.reasoning?.effort === undefined) {
241
242
  prepared.body.reasoning = { ...prepared.body.reasoning, effort: resolvedModel.reasoningEffort || "low" };
242
243
  }
243
244
  }
244
245
  if (upstreamModel !== requestedModel) prepared.body.model = upstreamModel;
245
- markResponseModel(upstreamModel, { requestedModel });
246
+ markResponseModel(upstreamModel, { requestedModel, configuredModel: provider.configuredModels === true });
246
247
  markRequestObservation({ context_window_tokens: modelContextWindowTokens(modelRegistry?.models, upstreamModel) });
247
248
  const upstreamLog = upstreamModel === requestedModel ? "" : ` upstream_model=${upstreamModel}`;
248
249
  console.log(status("info", `responses model=${requestedModel}${upstreamLog} stream=${streaming}`));
@@ -474,6 +475,7 @@ export function createResponsesCompactHandler(options) {
474
475
  releaseRequest = await measureRequestStageAsync("admission", () => acquireRequest(req, { signal: abort.signal }));
475
476
  abort.setTimeout(requestBodyTimeoutMs, "request_body_timeout");
476
477
  const parsed = await measureRequestStageAsync("body", () => readJsonBody(req, { admission: releaseRequest, signal: abort.signal }));
478
+ options.validateConversation?.(parsed, req.headers, provider);
477
479
  activeDeadline = now() + upstreamTimeoutMs;
478
480
  activeTimeoutReason = "responses_prepare_timeout";
479
481
  abort.setTimeout(upstreamTimeoutMs, "responses_prepare_timeout");
@@ -506,7 +508,7 @@ export function createResponsesCompactHandler(options) {
506
508
  const { upstreamModel, forceResponses } = provider.selectModel(prepared.body, resolvedModel, modelRegistry?.models);
507
509
  if (requestedModel === CODEX_AUTO_REVIEW_MODEL) {
508
510
  delete prepared.body.service_tier;
509
- if (resolvedModel.reasoningEffort || prepared.body.reasoning?.effort === undefined) {
511
+ if (resolvedModel.reasoningEffort || provider.defaultReviewEffort !== null && prepared.body.reasoning?.effort === undefined) {
510
512
  prepared.body.reasoning = { ...prepared.body.reasoning, effort: resolvedModel.reasoningEffort || "low" };
511
513
  }
512
514
  }
@@ -514,7 +516,7 @@ export function createResponsesCompactHandler(options) {
514
516
  markRequestObservation({ context_window_tokens: modelContextWindowTokens(modelRegistry?.models, upstreamModel) });
515
517
  const upstreamLog = upstreamModel === requestedModel ? "" : ` upstream_model=${upstreamModel}`;
516
518
  console.log(status("info", `responses compact model=${requestedModel}${upstreamLog} stream=false`));
517
- markResponseModel(upstreamModel, { requestedModel });
519
+ markResponseModel(upstreamModel, { requestedModel, configuredModel: provider.configuredModels === true });
518
520
  const selected = applySelectedRoute(prepared, provider.route(prepared.body, {
519
521
  requestedModel, upstreamModel, forceResponses, surface: "responses-compact" }), { req, env: openAIModelEnv,
520
522
  signal: abort.signal, assertActive: assertPrepareActive, reserveHistory: releaseRequest.reserveResponseHistory });
@@ -60,6 +60,15 @@ export function predictionStartupCheck(prediction) {
60
60
  // Catalog discovery, client configuration and inference access are distinct.
61
61
  export function providerStartupSummary(data = {}) {
62
62
  if (!data.providers) return { catalogs: "Status unavailable; see WebUI", claude: "Configuration not checked", warning: false };
63
+ const connections = data.providers.connections;
64
+ if (connections?.managed) {
65
+ const enabled = connections.providers.filter(provider => provider.enabled);
66
+ const states = { configured: "configured", not_configured: "not configured", not_installed: "not installed", preserved: "custom settings kept", configuration_unavailable: "config unavailable", partially_preserved: "partly configured", unavailable: "source unavailable" };
67
+ const sourceLines = enabled.map(provider => `${terminalCell(provider.name)} / ${provider.builtin ? provider.id === "m365" ? terminalCell(connections.m365_state) : "sign-in checked separately" : `${provider.model_count} configured models`}`);
68
+ const claudeLines = connections.clients.filter(client => client.id !== "codex").map(client => `${client.name}: ${!client.enabled ? "off" : client.source ? states[client.setup] || "not checked" : "paused"}`);
69
+ return { catalogs: `${enabled.length} enabled source${enabled.length === 1 ? "" : "s"}`, claude: claudeLines.join(" / "), sourceLines, claudeLines,
70
+ compactSources: sourceLines.length ? sourceLines : ["No source enabled"], compactClaude: claudeLines, warning: connections.clients.some(client => client.setup === "configuration_unavailable") };
71
+ }
63
72
  const providers = data.providers, ms = providers?.m365;
64
73
  const github = data.profiles?.codex?.models || (data.models?.provider !== "m365" ? data.models : null);
65
74
  const found = catalog => ["cache", "live"].includes(catalog?.source) && Number.isSafeInteger(catalog?.models ?? catalog?.total) && (catalog.models ?? catalog.total) > 0;
@@ -14,7 +14,7 @@ const TERMINAL_ORIGINS = new Set([
14
14
  const MAX_MODEL_OUTCOME_LABELS = 32;
15
15
  const MAX_RECENT_REQUESTS = 20;
16
16
  const MAX_ACTIVE_REQUESTS = 64;
17
- const MAX_PROVIDER_LABELS = 16;
17
+ const MAX_PROVIDER_LABELS = 18;
18
18
  const PREPARATION_EDGES_MS = Object.freeze([1, 2, 5, 10, 20, 50, 100, 250, 500, 1_000, 5_000, 30_000, 120_000]);
19
19
  const TTFT_EDGES_MS = Object.freeze([
20
20
  100, 200, 300, 500, 700, 1_000, 1_400, 2_000, 2_800, 4_000,
@@ -147,8 +147,9 @@ function emptyOutcomes() {
147
147
  return Object.fromEntries(TERMINAL_OUTCOMES.map((outcome) => [outcome, 0]));
148
148
  }
149
149
 
150
- function modelLabel(value) {
150
+ function modelLabel(value, configured = false) {
151
151
  const model = String(value || "").trim();
152
+ if (configured && /^[\w][\w./:@+-]{0,159}$/.test(model)) return model;
152
153
  return model === "codex-auto-review" || /^(?:gpt|claude)-[A-Za-z0-9._-]{1,72}$/.test(model)
153
154
  ? model : "other";
154
155
  }
@@ -317,8 +318,8 @@ export function createStreamPerformanceMetrics({ now = () => performance.now(),
317
318
  const tokens = Number(value);
318
319
  if (Number.isFinite(tokens) && tokens >= 0) outputTokens = tokens;
319
320
  },
320
- setModel(value) {
321
- model = modelLabel(value);
321
+ setModel(value, { configured = false } = {}) {
322
+ model = modelLabel(value, configured);
322
323
  },
323
324
  setProvider: assignProvider,
324
325
  attemptCount() { return attempts; },
@@ -481,13 +482,13 @@ export function markStreamFailure() {
481
482
  tracker()?.fail();
482
483
  }
483
484
 
484
- export function markResponseModel(model, { requestedModel } = {}) {
485
+ export function markResponseModel(model, { requestedModel, configuredModel = false } = {}) {
485
486
  const context = currentRequestContext();
486
487
  if (context) {
487
488
  context.model = model;
488
489
  if (requestedModel !== undefined) context.requestedModel = modelLabel(requestedModel);
489
490
  }
490
- tracker()?.setModel?.(model);
491
+ tracker()?.setModel?.(model, { configured: configuredModel });
491
492
  }
492
493
 
493
494
  export function markResponseErrorOrigin(origin) {
@@ -76,7 +76,7 @@ export function createTerminalConsole({ output = process.stdout, errorOutput = p
76
76
  }
77
77
  if (dirty) {
78
78
  const usage = data.runtime_usage || {}, routes = data.requests?.by_route || {};
79
- const outcomes = [data.stream_performance?.by_route?.responses, data.stream_performance?.by_route?.responses_compact, data.providers?.m365?.claude?.requests?.performance?.by_route?.messages]
79
+ const outcomes = [data.stream_performance?.by_route?.responses, data.stream_performance?.by_route?.responses_compact, (data.providers?.claude || data.providers?.m365?.claude)?.requests?.performance?.by_route?.messages]
80
80
  .map(route => route?.terminal_outcomes?.totals || {});
81
81
  const sum = key => outcomes.reduce((total, item) => total + (Number(item[key]) || 0), 0);
82
82
  const requests = ["responses", "responses_compact", "messages"].reduce((total, key) => total + (routes[key]?.total || 0), 0);
@@ -192,7 +192,7 @@ export function recordUsage(record) {
192
192
  if (!record) return Promise.resolve();
193
193
  const usage = record.usage || {};
194
194
  const { cached, unknown, invalid } = usageCacheEvidence(usage);
195
- const provider = usageProvider(record), label = runtimeUsageByProvider.has(provider) || runtimeUsageByProvider.size < 16 ? provider : "other";
195
+ const provider = usageProvider(record), label = runtimeUsageByProvider.has(provider) || runtimeUsageByProvider.size < 18 ? provider : "other";
196
196
  if (!runtimeUsageByProvider.has(label)) runtimeUsageByProvider.set(label, { records: 0, input_tokens: 0, cached_input_tokens: 0, output_tokens: 0, partial_records: 0 });
197
197
  for (const totals of [runtimeUsage, runtimeUsageByProvider.get(label)]) {
198
198
  totals.records++;
@@ -10,10 +10,13 @@ function failure(code) {
10
10
 
11
11
  // Private, credit-based WinHTTP transport. Each consumer owns its worker and a
12
12
  // fixed target group; prediction and M365 cannot share credentials or requests.
13
- export async function startWindowsHttpNetwork({ settings = {}, target = "prediction", validatePac = () => {}, env = process.env, spawnImpl = spawn, timeoutMs = 30_000, onFailure = () => {}, signal } = {}) {
13
+ export async function startWindowsHttpNetwork({ settings = {}, target = "prediction", apiTargets = [], validatePac = () => {}, env = process.env, spawnImpl = spawn, timeoutMs = 30_000, onFailure = () => {}, signal } = {}) {
14
14
  signal?.throwIfAborted();
15
- if (!["prediction", "m365"].includes(target)) throw failure("proxy_target_invalid");
16
- const allowedHosts = target === "m365" ? ["df.loki.delve.office.com"] : ["chatgpt.com", "ab.chatgpt.com"];
15
+ if (!["prediction", "m365", "api"].includes(target)) throw failure("proxy_target_invalid");
16
+ if (target === "api" && (!Array.isArray(apiTargets) || !apiTargets.length || apiTargets.length > 8 || apiTargets.some(raw => {
17
+ try { const url = new URL(raw);return url.protocol !== "https:" || url.username || url.password || url.search || url.hash || url.href !== raw; } catch { return true; }
18
+ }))) throw failure("proxy_target_invalid");
19
+ const allowedHosts = target === "api" ? apiTargets.map(raw => new URL(raw).hostname) : target === "m365" ? ["df.loki.delve.office.com"] : ["chatgpt.com", "ab.chatgpt.com"];
17
20
  const command = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
18
21
  const source = fileURLToPath(new URL("./windows-prediction-network.cs", import.meta.url));
19
22
  const child = spawnImpl(command, ["-NoProfile", "-NonInteractive", "-Command",
@@ -54,7 +57,7 @@ export async function startWindowsHttpNetwork({ settings = {}, target = "predict
54
57
  req.frame(event);
55
58
  }
56
59
  });
57
- write({autoDetect:settings.autoDetect===true,pac:settings.pac||"",...(target === "m365" ? {target,timeoutMs} : {})});
60
+ write({autoDetect:settings.autoDetect===true,pac:settings.pac||"",...(target !== "prediction" ? {target,timeoutMs} : {}),...(target === "api" ? {apiTargets} : {})});
58
61
  const timer=setTimeout(()=>stop(failure("proxy_wpad_timeout")),timeoutMs);
59
62
  let script;
60
63
  try{if(signal?.aborted)cancelled();script=await ready;}catch(error){stop(error);throw error;}finally{clearTimeout(timer);signal?.removeEventListener("abort",cancelled);}
@@ -66,8 +69,10 @@ export async function startWindowsHttpNetwork({ settings = {}, target = "predict
66
69
  const start=()=>{
67
70
  if(started)return;started=true;
68
71
  const host=options.hostname;
69
- if(!allowedHosts.includes(host)||!String(options.path).startsWith("/")||String(options.path).startsWith("//"))throw failure("proxy_target_invalid");
72
+ if(!allowedHosts.includes(host)||!String(options.path).startsWith("/")||target !== "api" && String(options.path).startsWith("//"))throw failure("proxy_target_invalid");
70
73
  if(target === "m365" && !String(options.path).startsWith("/api/v1/llmapi/")) throw failure("proxy_target_invalid");
74
+ const requestUrl = `https://${host}${options.port && Number(options.port) !== 443 ? `:${options.port}` : ""}${options.path}`;
75
+ if(target === "api" && !apiTargets.includes(requestUrl)) throw failure("proxy_target_invalid");
71
76
  const headers=[];
72
77
  for(const [name,value]of Object.entries(options.headers||{})){
73
78
  if(!/^[!#$%&'*+.^_`|~0-9a-z-]+$/i.test(name))throw failure("proxy_headers_invalid");
@@ -81,7 +86,7 @@ export async function startWindowsHttpNetwork({ settings = {}, target = "predict
81
86
  const rawLength=options.headers?.["content-length"];
82
87
  const length=rawLength===undefined?(["GET","HEAD"].includes(options.method||"GET")?0:-1):Number(rawLength);
83
88
  if(!Number.isSafeInteger(length)||length < -1)throw failure("proxy_upload_length_invalid");
84
- requests.set(id,req);write({op:"request",id,url:`https://${host}${options.path}`,method:options.method||"GET",headers:headerText,length});
89
+ requests.set(id,req);write({op:"request",id,url:requestUrl,method:options.method||"GET",headers:headerText,length});
85
90
  };
86
91
  const req=new Writable({highWaterMark:32*1024,autoDestroy:false,
87
92
  write(chunk,_encoding,complete){