codex-copilot-dx 0.9.40 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -4
- package/bin/cli.mjs +37 -11
- package/docs/ARCHITECTURE.md +84 -13
- package/docs/REFERENCE.md +207 -16
- package/package.json +4 -1
- package/src/adapter.mjs +98 -152
- package/src/auto-review-model.mjs +4 -3
- package/src/claude-client-config.mjs +217 -0
- package/src/claude-gateway.mjs +163 -0
- package/src/cli-m365.mjs +133 -0
- package/src/cli-models.mjs +1 -1
- package/src/cli-options.mjs +20 -6
- package/src/cli-status.mjs +23 -7
- package/src/codex-model-catalog.mjs +7 -2
- package/src/copilot-client.mjs +4 -0
- package/src/copilot-responses-compat.mjs +1 -1
- package/src/copilot-responses-policy.mjs +11 -64
- package/src/dashboard/index.html +14 -4
- package/src/dashboard/language.js +40 -2
- package/src/dashboard/status.js +26 -4
- package/src/dashboard/ui.css +2 -2
- package/src/dashboard/ui.js +16 -7
- package/src/dashboard/usage.js +3 -1
- package/src/dashboard-api.mjs +10 -7
- package/src/doctor-repair.mjs +2 -0
- package/src/doctor.mjs +18 -2
- package/src/http-transport.mjs +6 -3
- package/src/m365-settings.mjs +89 -0
- package/src/management-routes.mjs +118 -0
- package/src/native-prediction-windows.mjs +2 -7
- package/src/optional-routes.mjs +33 -0
- package/src/profile-model-runtime.mjs +4 -2
- package/src/provider-management.mjs +28 -0
- package/src/provider-runtime.mjs +179 -0
- package/src/provider-settings.mjs +32 -0
- package/src/providers/github.mjs +62 -0
- package/src/providers/m365-auth-helper.mjs +72 -0
- package/src/providers/m365-auth.mjs +105 -0
- package/src/providers/m365-messages-policy.mjs +20 -0
- package/src/providers/m365-network.mjs +73 -0
- package/src/providers/m365.mjs +238 -0
- package/src/response-failures.mjs +66 -5
- package/src/response-history.mjs +20 -3
- package/src/responses-bridge.mjs +1 -1
- package/src/responses-handler.mjs +40 -103
- package/src/responses-image-tools.mjs +61 -0
- package/src/responses-proxy.mjs +5 -5
- package/src/responses-request.mjs +25 -0
- package/src/stream-performance.mjs +42 -10
- package/src/usage-analysis.mjs +3 -2
- package/src/usage-store.mjs +41 -12
- package/src/usage.mjs +8 -2
- package/src/windows-http-network.mjs +122 -0
- package/src/windows-prediction-network.cs +13 -6
- package/src/windows-prediction-network.mjs +4 -108
- package/src/windows-process.mjs +8 -0
package/src/usage-store.mjs
CHANGED
|
@@ -6,6 +6,7 @@ import readline from "node:readline";
|
|
|
6
6
|
import { appendRotatingLines, parseByteLimit, rotatedFilePath } from "./file-rotation.mjs";
|
|
7
7
|
import { withFileLock } from "./lock.mjs";
|
|
8
8
|
import { terminalCell } from "./terminal-text.mjs";
|
|
9
|
+
import { currentRequestContext } from "./request-context.mjs";
|
|
9
10
|
|
|
10
11
|
const DEFAULT_USAGE_PATH = path.join(os.homedir(), ".local", "share", "codex-copilot-dx", "usage.jsonl");
|
|
11
12
|
const DEFAULT_USAGE_MAX_BYTES = 32 * 1024 * 1024;
|
|
@@ -108,9 +109,25 @@ export function buildResponsesUsageRecord({ surface = "responses", mode, model,
|
|
|
108
109
|
response_id: responseObj?.id,
|
|
109
110
|
usage,
|
|
110
111
|
copilot_usage: copilotUsage,
|
|
112
|
+
...(currentRequestContext()?.provider ? { provider: currentRequestContext().provider } : {}),
|
|
111
113
|
});
|
|
112
114
|
}
|
|
113
115
|
|
|
116
|
+
export function buildMessagesUsageRecord({ model, responseId, usage, mode, client = "claude" } = {}) {
|
|
117
|
+
if (!usage || typeof usage !== "object") return null;
|
|
118
|
+
const count = key => Number.isFinite(usage[key]) && usage[key] >= 0 ? usage[key] : undefined;
|
|
119
|
+
const uncached = count("input_tokens"), read = count("cache_read_input_tokens"), written = count("cache_creation_input_tokens");
|
|
120
|
+
const input = uncached === undefined ? undefined : uncached + (read || 0) + (written || 0);
|
|
121
|
+
const output = count("output_tokens");
|
|
122
|
+
if (input === undefined && output === undefined) return null;
|
|
123
|
+
return compactObject({ ts: new Date().toISOString(), provider: "m365", surface: "messages", client, mode, model, response_id: responseId,
|
|
124
|
+
usage: compactObject({ input_tokens: input, output_tokens: output, cached_input_tokens: read,
|
|
125
|
+
cache_write_input_tokens: written, total_tokens: input !== undefined && output !== undefined ? input + output : undefined,
|
|
126
|
+
reasoning_output_tokens: numberOrUndefined(usage.output_tokens_details?.thinking_tokens) }),
|
|
127
|
+
anthropic_usage: compactObject({ input_tokens: uncached, cache_read_input_tokens: read,
|
|
128
|
+
cache_creation_input_tokens: written, output_tokens: output }) });
|
|
129
|
+
}
|
|
130
|
+
|
|
114
131
|
function takePendingWrites(filePath, maxBytes) {
|
|
115
132
|
const batch = [];
|
|
116
133
|
let retained = 0;
|
|
@@ -260,9 +277,17 @@ function addUsageTotals(target, usage = {}) {
|
|
|
260
277
|
}
|
|
261
278
|
}
|
|
262
279
|
|
|
263
|
-
export function
|
|
264
|
-
|
|
280
|
+
export function usageProvider(record) {
|
|
281
|
+
return record.provider === undefined || record.provider === "github" ? "github" : record.provider === "m365" ? "m365" : "unknown";
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export function summarizeUsage(records, { provider = "" } = {}) {
|
|
285
|
+
if (provider && !["github", "m365"].includes(provider)) throw new Error("Usage provider must be github or m365");
|
|
286
|
+
const summary = { requests: 0, totals: {}, byModel: {}, providers: { github: 0, m365: 0, unknown: 0 }, ...(provider ? { provider_filter: provider } : {}) };
|
|
265
287
|
for (const record of records) {
|
|
288
|
+
const source = usageProvider(record);
|
|
289
|
+
if (provider && provider !== source) continue;
|
|
290
|
+
summary.providers[source] += 1;
|
|
266
291
|
summary.requests += 1;
|
|
267
292
|
addUsageTotals(summary.totals, record.usage);
|
|
268
293
|
if (record.copilot_usage) {
|
|
@@ -270,7 +295,7 @@ export function summarizeUsage(records) {
|
|
|
270
295
|
summary.totals.total_nano_aiu = (summary.totals.total_nano_aiu || 0) + (record.copilot_usage.total_nano_aiu || 0);
|
|
271
296
|
}
|
|
272
297
|
const model = record.model || "unknown";
|
|
273
|
-
if (!summary.byModel
|
|
298
|
+
if (!Object.hasOwn(summary.byModel, model)) Object.defineProperty(summary.byModel, model, { value: { requests: 0 }, enumerable: true, configurable: true, writable: true });
|
|
274
299
|
const modelTotals = summary.byModel[model];
|
|
275
300
|
modelTotals.requests += 1;
|
|
276
301
|
addUsageTotals(modelTotals, record.usage);
|
|
@@ -291,16 +316,18 @@ export function summarizeUsage(records) {
|
|
|
291
316
|
return summary;
|
|
292
317
|
}
|
|
293
318
|
|
|
294
|
-
async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord } = {}) {
|
|
295
|
-
const summary =
|
|
319
|
+
async function summarizeUsageLogFiles(filePath, { warn = console.error, onRecord, provider = "" } = {}) {
|
|
320
|
+
const summary = summarizeUsage([], { provider });
|
|
296
321
|
for (const candidate of [rotatedFilePath(filePath), filePath]) {
|
|
297
322
|
for await (const record of iterateUsageRecords(candidate, { warn })) {
|
|
323
|
+
if (provider && provider !== usageProvider(record)) continue;
|
|
298
324
|
const one = summarizeUsage([record]);
|
|
299
325
|
onRecord?.(record, one);
|
|
300
326
|
summary.requests += one.requests;
|
|
301
327
|
addUsageTotals(summary.totals, one.totals);
|
|
328
|
+
addUsageTotals(summary.providers, one.providers);
|
|
302
329
|
for (const [model, values] of Object.entries(one.byModel)) {
|
|
303
|
-
if (!summary.byModel
|
|
330
|
+
if (!Object.hasOwn(summary.byModel, model)) Object.defineProperty(summary.byModel, model, { value: { requests: 0 }, enumerable: true, configurable: true, writable: true });
|
|
304
331
|
addUsageTotals(summary.byModel[model], values);
|
|
305
332
|
}
|
|
306
333
|
}
|
|
@@ -330,21 +357,23 @@ export async function usageSummaryVersion(filePath) {
|
|
|
330
357
|
} catch { return null; } // Uncacheable metadata never replaces the normal read/error path.
|
|
331
358
|
}
|
|
332
359
|
|
|
333
|
-
export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = console.error, onRecord } = {}) {
|
|
334
|
-
if (
|
|
335
|
-
|
|
360
|
+
export async function summarizeUsageLogs(filePath = usageLogPath(), { warn = console.error, onRecord, provider = "" } = {}) {
|
|
361
|
+
if (provider && !["github", "m365"].includes(provider)) throw new Error("Usage provider must be github or m365");
|
|
362
|
+
if (onRecord || warn !== console.error) return summarizeUsageLogFiles(filePath, { warn, onRecord, provider });
|
|
363
|
+
const fileVersion = await usageSummaryVersion(filePath);
|
|
364
|
+
const version = fileVersion === null ? null : `${fileVersion}\0${provider}`;
|
|
336
365
|
if (version === null) {
|
|
337
366
|
cachedSummary = null;
|
|
338
|
-
return summarizeUsageLogFiles(filePath, { warn });
|
|
367
|
+
return summarizeUsageLogFiles(filePath, { warn, provider });
|
|
339
368
|
}
|
|
340
369
|
if (cachedSummary?.version === version) return structuredClone(await cachedSummary.promise);
|
|
341
370
|
const entry = { version, promise: null };
|
|
342
371
|
cachedSummary = entry;
|
|
343
372
|
entry.promise = (async () => {
|
|
344
373
|
let warned = false;
|
|
345
|
-
const summary = await summarizeUsageLogFiles(filePath, { warn(message) { warned = true; warn(message); } });
|
|
374
|
+
const summary = await summarizeUsageLogFiles(filePath, { provider, warn(message) { warned = true; warn(message); } });
|
|
346
375
|
const after = await usageSummaryVersion(filePath);
|
|
347
|
-
const retain = !warned && after ===
|
|
376
|
+
const retain = !warned && after === fileVersion && Object.keys(summary.byModel).length <= 128
|
|
348
377
|
&& Buffer.byteLength(JSON.stringify(summary)) <= SUMMARY_CACHE_MAX_BYTES;
|
|
349
378
|
if (!retain && cachedSummary === entry) cachedSummary = null;
|
|
350
379
|
return summary;
|
package/src/usage.mjs
CHANGED
|
@@ -7,6 +7,8 @@ export {
|
|
|
7
7
|
usageLogPath,
|
|
8
8
|
usageLogMaxBytes,
|
|
9
9
|
buildResponsesUsageRecord,
|
|
10
|
+
buildMessagesUsageRecord,
|
|
11
|
+
usageProvider,
|
|
10
12
|
recordUsage,
|
|
11
13
|
recordResponsesUsage,
|
|
12
14
|
flushUsageWritesForTests,
|
|
@@ -33,6 +35,8 @@ function cacheHitPercent(usage) {
|
|
|
33
35
|
|
|
34
36
|
function formatPlainUsageSummary(summary, filePath, { sanitize = false } = {}) {
|
|
35
37
|
const lines = [`Usage log: ${filePath}`];
|
|
38
|
+
if (summary.provider_filter) lines.push(`Provider: ${summary.provider_filter}`);
|
|
39
|
+
else if (summary.providers?.m365) lines.push(`Providers: GitHub ${fmt(summary.providers.github)} / M365 ${fmt(summary.providers.m365)} (combined totals; use --provider to separate)`);
|
|
36
40
|
if (summary.requests === 0) {
|
|
37
41
|
lines.push("No usage records yet.");
|
|
38
42
|
return (sanitize ? lines.map((line) => terminalCell(line, { fallback: "" })) : lines).join("\n");
|
|
@@ -103,7 +107,8 @@ function formatTableUsageSummary(summary, filePath, output) {
|
|
|
103
107
|
} else {
|
|
104
108
|
table.compact = false;
|
|
105
109
|
}
|
|
106
|
-
const lines = [`Usage log: ${safePath}`,
|
|
110
|
+
const lines = [`Usage log: ${safePath}`, ...(summary.provider_filter ? [`Provider: ${summary.provider_filter}`]
|
|
111
|
+
: summary.providers?.m365 ? [`Providers: GitHub ${fmt(summary.providers.github)} / M365 ${fmt(summary.providers.m365)} (combined totals; use --provider to separate)`] : []), "", table.output];
|
|
107
112
|
if (table.compact) {
|
|
108
113
|
lines.push(
|
|
109
114
|
"",
|
|
@@ -137,7 +142,8 @@ export async function printUsageSummary({
|
|
|
137
142
|
output = process.stdout,
|
|
138
143
|
log = console.log,
|
|
139
144
|
warn = console.error,
|
|
145
|
+
provider = "",
|
|
140
146
|
} = {}) {
|
|
141
|
-
const summary = await summarizeUsageLogs(filePath, { warn });
|
|
147
|
+
const summary = await summarizeUsageLogs(filePath, { warn, provider });
|
|
142
148
|
log(formatUsageSummary(summary, { filePath, format, output }));
|
|
143
149
|
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import { PassThrough, Writable } from "node:stream";
|
|
5
|
+
import { windowsPowerShellEnvironment } from "./windows-process.mjs";
|
|
6
|
+
|
|
7
|
+
function failure(code) {
|
|
8
|
+
return Object.assign(new Error(`Windows network failed (${code}); existing company routes were preserved`), { code });
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// Private, credit-based WinHTTP transport. Each consumer owns its worker and a
|
|
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 } = {}) {
|
|
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"];
|
|
17
|
+
const command = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
18
|
+
const source = fileURLToPath(new URL("./windows-prediction-network.cs", import.meta.url));
|
|
19
|
+
const child = spawnImpl(command, ["-NoProfile", "-NonInteractive", "-Command",
|
|
20
|
+
"$ErrorActionPreference='Stop';Add-Type -Path $env:CCDX_PREDICTION_NETWORK_SOURCE -ReferencedAssemblies System.dll,System.Core.dll,System.Web.Extensions.dll;[CCDXPredictionNetwork]::Run()"],
|
|
21
|
+
{ env: { ...windowsPowerShellEnvironment(env), CCDX_PREDICTION_NETWORK_SOURCE: source }, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, shell: false });
|
|
22
|
+
const requests = new Map();let sequence = 0, buffer = "", stopped = false, initialized = false, closing = false;
|
|
23
|
+
let resolveReady, rejectReady;
|
|
24
|
+
const ready = new Promise((resolve, reject) => { resolveReady = resolve;rejectReady = reject; });
|
|
25
|
+
const write = value => { if (!stopped && !child.stdin.destroyed) child.stdin.write(JSON.stringify(value) + "\n"); };
|
|
26
|
+
const stop = error => {
|
|
27
|
+
if(stopped)return;stopped=true;rejectReady(error);
|
|
28
|
+
for(const req of [...requests.values()])req.destroy(error);
|
|
29
|
+
child.stdin.destroy();child.kill();
|
|
30
|
+
if(initialized&&!closing)onFailure(error);
|
|
31
|
+
};
|
|
32
|
+
const cancelled = () => stop(failure("proxy_worker_cancelled"));
|
|
33
|
+
signal?.addEventListener("abort", cancelled, { once: true });
|
|
34
|
+
child.on("error", () => stop(failure("proxy_worker_start_failed")));
|
|
35
|
+
child.on("exit", () => stop(failure("proxy_worker_exited")));
|
|
36
|
+
// Consume, but never retain or log compiler stderr (it can include paths).
|
|
37
|
+
child.stderr.resume();child.stdin.on("error", () => stop(failure("proxy_worker_pipe_failed")));
|
|
38
|
+
child.stdout.setEncoding("utf8");
|
|
39
|
+
child.stdout.on("data", chunk => {
|
|
40
|
+
buffer += chunk;
|
|
41
|
+
if(buffer.length > 2*1024*1024)return stop(failure("proxy_worker_output_limit"));
|
|
42
|
+
let boundary;
|
|
43
|
+
while((boundary=buffer.indexOf("\n"))>=0) {
|
|
44
|
+
const line=buffer.slice(0,boundary);buffer=buffer.slice(boundary+1);let event;
|
|
45
|
+
try{event=JSON.parse(line);}catch{return stop(failure("proxy_worker_protocol_error"));}
|
|
46
|
+
if(event.type==="ready") {
|
|
47
|
+
if(event.pac!==null && typeof event.pac!=="string")return stop(failure("proxy_worker_protocol_error"));
|
|
48
|
+
const script=event.pac===null?null:Buffer.from(event.pac,"base64").toString("utf8").replace(/^\uFEFF/, "");
|
|
49
|
+
try{if(script!==null)validatePac(script);}catch(error){return stop(error);}
|
|
50
|
+
resolveReady(script);continue;
|
|
51
|
+
}
|
|
52
|
+
const req=requests.get(event.id);
|
|
53
|
+
if(!req){if(event.type==="error"&&!event.id)return stop(failure(/^winhttp_[a-z0-9_]+$/.test(event.code)?event.code:"proxy_worker_failed"));continue;}
|
|
54
|
+
req.frame(event);
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
write({autoDetect:settings.autoDetect===true,pac:settings.pac||"",...(target === "m365" ? {target,timeoutMs} : {})});
|
|
58
|
+
const timer=setTimeout(()=>stop(failure("proxy_wpad_timeout")),timeoutMs);
|
|
59
|
+
let script;
|
|
60
|
+
try{if(signal?.aborted)cancelled();script=await ready;}catch(error){stop(error);throw error;}finally{clearTimeout(timer);signal?.removeEventListener("abort",cancelled);}
|
|
61
|
+
initialized=true;
|
|
62
|
+
const requestImpl=(options,callback)=>{
|
|
63
|
+
const id=++sequence;let reply,done=false,started=false,uploadCallback;
|
|
64
|
+
const finish=()=>{clearTimeout(deadline);requests.delete(id);done=true;};
|
|
65
|
+
const deadline=setTimeout(()=>req.destroy(failure("proxy_request_timeout")),timeoutMs);
|
|
66
|
+
const start=()=>{
|
|
67
|
+
if(started)return;started=true;
|
|
68
|
+
const host=options.hostname;
|
|
69
|
+
if(!allowedHosts.includes(host)||!String(options.path).startsWith("/")||String(options.path).startsWith("//"))throw failure("proxy_target_invalid");
|
|
70
|
+
if(target === "m365" && !String(options.path).startsWith("/api/v1/llmapi/")) throw failure("proxy_target_invalid");
|
|
71
|
+
const headers=[];
|
|
72
|
+
for(const [name,value]of Object.entries(options.headers||{})){
|
|
73
|
+
if(!/^[!#$%&'*+.^_`|~0-9a-z-]+$/i.test(name))throw failure("proxy_headers_invalid");
|
|
74
|
+
for(const item of Array.isArray(value)?value:[value]){
|
|
75
|
+
if(/[\r\n]/.test(String(item)))throw failure("proxy_headers_invalid");headers.push(`${name}: ${item}`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const headerText=headers.join("\r\n")+"\r\n";
|
|
79
|
+
if(headerText.length>32768)throw failure("proxy_headers_limit");
|
|
80
|
+
if(requests.size>32)throw failure("proxy_admission_limit");
|
|
81
|
+
const rawLength=options.headers?.["content-length"];
|
|
82
|
+
const length=rawLength===undefined?(["GET","HEAD"].includes(options.method||"GET")?0:-1):Number(rawLength);
|
|
83
|
+
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});
|
|
85
|
+
};
|
|
86
|
+
const req=new Writable({highWaterMark:32*1024,autoDestroy:false,
|
|
87
|
+
write(chunk,_encoding,complete){
|
|
88
|
+
try{start();}catch(error){complete(error);req.destroy(error);return;}
|
|
89
|
+
let offset=0;
|
|
90
|
+
const next=()=>{if(offset>=chunk.length){uploadCallback=undefined;complete();return;}
|
|
91
|
+
const bytes=chunk.subarray(offset,offset+65536);offset+=bytes.length;
|
|
92
|
+
uploadCallback=next;write({op:"upload",id,body:bytes.toString("base64")});};next();
|
|
93
|
+
},
|
|
94
|
+
final(complete){try{start();write({op:"upload_end",id});complete();}catch(error){complete(error);req.destroy(error);}},
|
|
95
|
+
destroy(error,complete){if(!done){write({op:"cancel",id});finish();reply?.destroy(error);uploadCallback=undefined;}complete(error);},
|
|
96
|
+
});
|
|
97
|
+
req.setTimeout=(milliseconds,handler)=>{if(handler)req.once("timeout",handler);return req;};
|
|
98
|
+
req.frame=event=>{
|
|
99
|
+
deadline.refresh();
|
|
100
|
+
if(event.type==="headers"){
|
|
101
|
+
if(reply||typeof event.headers!=="string"||event.headers.length>65536)return req.destroy(failure("proxy_worker_protocol_error"));
|
|
102
|
+
const lines=event.headers.split("\r\n"),match=/^HTTP\/\S+ (\d{3})(?: (.*))?$/.exec(lines.shift());
|
|
103
|
+
if(!match)return req.destroy(failure("proxy_worker_protocol_error"));
|
|
104
|
+
reply=new PassThrough({highWaterMark:32*1024});reply.statusCode=Number(match[1]);reply.statusMessage=match[2]||"";reply.headers={};
|
|
105
|
+
for(const line of lines){const colon=line.indexOf(":");if(colon<1)continue;const name=line.slice(0,colon).toLowerCase(),value=line.slice(colon+1).trim();
|
|
106
|
+
if(name==="set-cookie")(reply.headers[name]||=[]).push(value);else reply.headers[name]=reply.headers[name]?reply.headers[name]+", "+value:value;}
|
|
107
|
+
reply.once("close",()=>{if(!done)req.destroy();});callback(reply);
|
|
108
|
+
}else if(event.type==="upload_ack"){if(!uploadCallback)return req.destroy(failure("proxy_worker_protocol_error"));uploadCallback();}
|
|
109
|
+
else if(event.type==="data"){
|
|
110
|
+
if(!reply||typeof event.body!=="string"||event.body.length>22000)return req.destroy(failure("proxy_worker_protocol_error"));
|
|
111
|
+
const ack=()=>write({op:"ack",id});if(reply.write(Buffer.from(event.body,"base64")))ack();else reply.once("drain",ack);
|
|
112
|
+
}else if(event.type==="end"){if(!reply)return req.destroy(failure("proxy_worker_protocol_error"));finish();reply.end();}
|
|
113
|
+
else if(event.type==="error")req.destroy(failure(/^winhttp_[a-z0-9_]+$/.test(event.code)?event.code:"proxy_request_failed"));
|
|
114
|
+
else req.destroy(failure("proxy_worker_protocol_error"));
|
|
115
|
+
};
|
|
116
|
+
requests.set(id,req);
|
|
117
|
+
if(stopped)queueMicrotask(()=>req.destroy(failure("proxy_worker_closed")));
|
|
118
|
+
else if(requests.size>32)queueMicrotask(()=>req.destroy(failure("proxy_admission_limit")));
|
|
119
|
+
return req;
|
|
120
|
+
};
|
|
121
|
+
return {script,requestImpl,healthy:()=>!stopped,close(){closing=true;stop(failure("proxy_worker_closed"));}};
|
|
122
|
+
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
//
|
|
1
|
+
// Consumer-scoped worker. Keep the filename/class compatible with an older
|
|
2
|
+
// still-running prediction bridge during package replacement.
|
|
3
|
+
// Windows owns PAC/WPAD, proxy authentication and TLS trust.
|
|
2
4
|
// Requests and response chunks exist only in anonymous pipes, never files.
|
|
3
5
|
using System;
|
|
4
6
|
using System.Collections.Generic;
|
|
@@ -28,6 +30,8 @@ public static class CCDXPredictionNetwork {
|
|
|
28
30
|
static readonly Dictionary<int, Work> active = new Dictionary<int, Work>();
|
|
29
31
|
static readonly JavaScriptSerializer json = new JavaScriptSerializer { MaxJsonLength=2*1024*1024 };
|
|
30
32
|
static IntPtr session;
|
|
33
|
+
static string target = "prediction";
|
|
34
|
+
static int requestTimeout = 30000;
|
|
31
35
|
class Work { public IntPtr handle; public ManualResetEventSlim ack = new ManualResetEventSlim(false); public BlockingCollection<byte[]> upload = new BlockingCollection<byte[]>(2); public bool cancelled; }
|
|
32
36
|
static void Check(bool ok) { if(!ok) throw new IOException("winhttp_" + Marshal.GetLastWin32Error()); }
|
|
33
37
|
static void Emit(object value) { lock(outputLock) { Console.Out.WriteLine(json.Serialize(value)); Console.Out.Flush(); } }
|
|
@@ -73,7 +77,7 @@ public static class CCDXPredictionNetwork {
|
|
|
73
77
|
IntPtr connection=IntPtr.Zero;
|
|
74
78
|
try {
|
|
75
79
|
var uri=new Uri((string)data["url"]);
|
|
76
|
-
if(uri.Scheme!="https" || uri.Port!=443 || uri.UserInfo.Length!=0 || uri.Fragment.Length!=0 || (uri.Host!="chatgpt.com"&&uri.Host!="ab.chatgpt.com")) throw new IOException("winhttp_target_invalid");
|
|
80
|
+
if(uri.Scheme!="https" || uri.Port!=443 || uri.UserInfo.Length!=0 || uri.Fragment.Length!=0 || (target=="m365" ? (uri.Host!="df.loki.delve.office.com" || !uri.AbsolutePath.StartsWith("/api/v1/llmapi/",StringComparison.Ordinal)) : (uri.Host!="chatgpt.com"&&uri.Host!="ab.chatgpt.com"))) throw new IOException("winhttp_target_invalid");
|
|
77
81
|
var method=(string)data["method"];
|
|
78
82
|
if(method!="GET"&&method!="POST"&&method!="HEAD"&&method!="PUT"&&method!="DELETE"&&method!="OPTIONS"&&method!="PATCH")throw new IOException("winhttp_method_invalid");
|
|
79
83
|
var headers=(string)data["headers"];
|
|
@@ -107,7 +111,7 @@ public static class CCDXPredictionNetwork {
|
|
|
107
111
|
while(true) {
|
|
108
112
|
Check(WinHttpReadData(request,buffer,(uint)buffer.Length,out read));if(read==0)break;
|
|
109
113
|
work.ack.Reset();Emit(new {id=id,type="data",body=Convert.ToBase64String(buffer,0,(int)read)});
|
|
110
|
-
if(!work.ack.Wait(
|
|
114
|
+
if(!work.ack.Wait(requestTimeout))throw new IOException("winhttp_consumer_timeout");
|
|
111
115
|
if(work.cancelled)return;
|
|
112
116
|
}
|
|
113
117
|
Emit(new {id=id,type="end"});
|
|
@@ -122,11 +126,14 @@ public static class CCDXPredictionNetwork {
|
|
|
122
126
|
}
|
|
123
127
|
public static void Run() {
|
|
124
128
|
Console.InputEncoding=new UTF8Encoding(false);Console.OutputEncoding=new UTF8Encoding(false);
|
|
125
|
-
session=WinHttpOpen("CCDX native prediction",4,null,null,0);
|
|
126
129
|
try {
|
|
127
|
-
Check(session!=IntPtr.Zero);Check(WinHttpSetTimeouts(session,10000,10000,30000,30000));
|
|
128
|
-
uint protocols=0x800;Check(WinHttpSetOption(session,84,ref protocols,4));
|
|
129
130
|
var initial=json.Deserialize<Dictionary<string,object>>(Console.ReadLine());
|
|
131
|
+
if(initial.ContainsKey("target")) target=(string)initial["target"];
|
|
132
|
+
if(target!="prediction"&&target!="m365")throw new IOException("winhttp_target_invalid");
|
|
133
|
+
if(target=="m365" && initial.ContainsKey("timeoutMs")) requestTimeout=(int)Math.Max(1000,Math.Min(int.MaxValue,Convert.ToInt64(initial["timeoutMs"])));
|
|
134
|
+
session=target=="m365"?WinHttpOpen("CCDX Microsoft 365",4,null,null,0):WinHttpOpen("CCDX native prediction",4,null,null,0);
|
|
135
|
+
Check(session!=IntPtr.Zero);Check(WinHttpSetTimeouts(session,10000,10000,requestTimeout,requestTimeout));
|
|
136
|
+
uint protocols=0x800;Check(WinHttpSetOption(session,84,ref protocols,4));
|
|
130
137
|
string pac=(string)initial["pac"];
|
|
131
138
|
if(string.IsNullOrWhiteSpace(pac)&&(bool)initial["autoDetect"]) {
|
|
132
139
|
IntPtr address;
|
|
@@ -1,10 +1,6 @@
|
|
|
1
|
-
import path from "node:path";
|
|
2
|
-
import { fileURLToPath } from "node:url";
|
|
3
|
-
import { spawn } from "node:child_process";
|
|
4
|
-
import { PassThrough, Writable } from "node:stream";
|
|
5
1
|
import { Script } from "node:vm";
|
|
6
|
-
import { windowsPowerShellEnvironment } from "./native-prediction-windows.mjs";
|
|
7
2
|
import { predictionProxyExpression } from "./prediction-pac.mjs";
|
|
3
|
+
import { startWindowsHttpNetwork } from "./windows-http-network.mjs";
|
|
8
4
|
|
|
9
5
|
function failure(code) {
|
|
10
6
|
return Object.assign(new Error(`Windows prediction network failed (${code}); existing company routes were preserved`), { code });
|
|
@@ -18,107 +14,7 @@ export function companyPredictionPac(script, port) {
|
|
|
18
14
|
return combined;
|
|
19
15
|
}
|
|
20
16
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
const command = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
25
|
-
const source = fileURLToPath(new URL("./windows-prediction-network.cs", import.meta.url));
|
|
26
|
-
const child = spawnImpl(command, ["-NoProfile", "-NonInteractive", "-Command",
|
|
27
|
-
"$ErrorActionPreference='Stop';Add-Type -Path $env:CCDX_PREDICTION_NETWORK_SOURCE -ReferencedAssemblies System.dll,System.Core.dll,System.Web.Extensions.dll;[CCDXPredictionNetwork]::Run()"],
|
|
28
|
-
{ env: { ...windowsPowerShellEnvironment(env), CCDX_PREDICTION_NETWORK_SOURCE: source }, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, shell: false });
|
|
29
|
-
const requests = new Map();let sequence = 0, buffer = "", stopped = false, initialized = false, closing = false;
|
|
30
|
-
let resolveReady, rejectReady;
|
|
31
|
-
const ready = new Promise((resolve, reject) => { resolveReady = resolve;rejectReady = reject; });
|
|
32
|
-
const write = value => { if (!stopped && !child.stdin.destroyed) child.stdin.write(JSON.stringify(value) + "\n"); };
|
|
33
|
-
const stop = error => {
|
|
34
|
-
if(stopped)return;stopped=true;rejectReady(error);
|
|
35
|
-
for(const req of [...requests.values()])req.destroy(error);
|
|
36
|
-
child.stdin.destroy();child.kill();
|
|
37
|
-
if(initialized&&!closing)onFailure(error);
|
|
38
|
-
};
|
|
39
|
-
child.on("error", () => stop(failure("proxy_worker_start_failed")));
|
|
40
|
-
child.on("exit", () => stop(failure("proxy_worker_exited")));
|
|
41
|
-
// Consume, but never retain or log compiler stderr (it can include paths).
|
|
42
|
-
child.stderr.resume();child.stdin.on("error", () => stop(failure("proxy_worker_pipe_failed")));
|
|
43
|
-
child.stdout.setEncoding("utf8");
|
|
44
|
-
child.stdout.on("data", chunk => {
|
|
45
|
-
buffer += chunk;
|
|
46
|
-
if(buffer.length > 2*1024*1024)return stop(failure("proxy_worker_output_limit"));
|
|
47
|
-
let boundary;
|
|
48
|
-
while((boundary=buffer.indexOf("\n"))>=0) {
|
|
49
|
-
const line=buffer.slice(0,boundary);buffer=buffer.slice(boundary+1);let event;
|
|
50
|
-
try{event=JSON.parse(line);}catch{return stop(failure("proxy_worker_protocol_error"));}
|
|
51
|
-
if(event.type==="ready") {
|
|
52
|
-
if(event.pac!==null && typeof event.pac!=="string")return stop(failure("proxy_worker_protocol_error"));
|
|
53
|
-
const script=event.pac===null?null:Buffer.from(event.pac,"base64").toString("utf8").replace(/^\uFEFF/, "");
|
|
54
|
-
try{if(script!==null)companyPredictionPac(script,1);}catch(error){return stop(error);}
|
|
55
|
-
resolveReady(script);continue;
|
|
56
|
-
}
|
|
57
|
-
const req=requests.get(event.id);
|
|
58
|
-
if(!req){if(event.type==="error"&&!event.id)return stop(failure(/^winhttp_[a-z0-9_]+$/.test(event.code)?event.code:"proxy_worker_failed"));continue;}
|
|
59
|
-
req.frame(event);
|
|
60
|
-
}
|
|
61
|
-
});
|
|
62
|
-
write({autoDetect:settings.autoDetect===true,pac:settings.pac||""});
|
|
63
|
-
const timer=setTimeout(()=>stop(failure("proxy_wpad_timeout")),timeoutMs);
|
|
64
|
-
let script;
|
|
65
|
-
try{script=await ready;}catch(error){stop(error);throw error;}finally{clearTimeout(timer);}
|
|
66
|
-
initialized=true;
|
|
67
|
-
const requestImpl=(options,callback)=>{
|
|
68
|
-
const id=++sequence;let reply,done=false,started=false,uploadCallback;
|
|
69
|
-
const finish=()=>{clearTimeout(deadline);requests.delete(id);done=true;};
|
|
70
|
-
const deadline=setTimeout(()=>req.destroy(failure("proxy_request_timeout")),timeoutMs);
|
|
71
|
-
const start=()=>{
|
|
72
|
-
if(started)return;started=true;
|
|
73
|
-
const host=options.hostname;
|
|
74
|
-
if(!["chatgpt.com","ab.chatgpt.com"].includes(host)||!String(options.path).startsWith("/")||String(options.path).startsWith("//"))throw failure("proxy_target_invalid");
|
|
75
|
-
const headers=[];
|
|
76
|
-
for(const [name,value]of Object.entries(options.headers||{})){
|
|
77
|
-
if(!/^[!#$%&'*+.^_`|~0-9a-z-]+$/i.test(name))throw failure("proxy_headers_invalid");
|
|
78
|
-
for(const item of Array.isArray(value)?value:[value]){
|
|
79
|
-
if(/[\r\n]/.test(String(item)))throw failure("proxy_headers_invalid");headers.push(`${name}: ${item}`);
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
const headerText=headers.join("\r\n")+"\r\n";
|
|
83
|
-
if(headerText.length>32768)throw failure("proxy_headers_limit");
|
|
84
|
-
if(requests.size>=32)throw failure("proxy_admission_limit");
|
|
85
|
-
const rawLength=options.headers?.["content-length"];
|
|
86
|
-
const length=rawLength===undefined?(["GET","HEAD"].includes(options.method||"GET")?0:-1):Number(rawLength);
|
|
87
|
-
if(!Number.isSafeInteger(length)||length < -1)throw failure("proxy_upload_length_invalid");
|
|
88
|
-
requests.set(id,req);write({op:"request",id,url:`https://${host}${options.path}`,method:options.method||"GET",headers:headerText,length});
|
|
89
|
-
};
|
|
90
|
-
const req=new Writable({highWaterMark:32*1024,autoDestroy:false,
|
|
91
|
-
write(chunk,_encoding,complete){
|
|
92
|
-
try{start();}catch(error){complete(error);return;}
|
|
93
|
-
let offset=0;
|
|
94
|
-
const next=()=>{if(offset>=chunk.length){uploadCallback=undefined;complete();return;}
|
|
95
|
-
const bytes=chunk.subarray(offset,offset+65536);offset+=bytes.length;
|
|
96
|
-
uploadCallback=next;write({op:"upload",id,body:bytes.toString("base64")});};next();
|
|
97
|
-
},
|
|
98
|
-
final(complete){try{start();write({op:"upload_end",id});complete();}catch(error){complete(error);}},
|
|
99
|
-
destroy(error,complete){if(!done){write({op:"cancel",id});finish();reply?.destroy(error);uploadCallback=undefined;}complete(error);},
|
|
100
|
-
});
|
|
101
|
-
req.setTimeout=(milliseconds,handler)=>{if(handler)req.once("timeout",handler);return req;};
|
|
102
|
-
req.frame=event=>{
|
|
103
|
-
deadline.refresh();
|
|
104
|
-
if(event.type==="headers"){
|
|
105
|
-
if(reply||typeof event.headers!=="string"||event.headers.length>65536)return req.destroy(failure("proxy_worker_protocol_error"));
|
|
106
|
-
const lines=event.headers.split("\r\n"),match=/^HTTP\/\S+ (\d{3})(?: (.*))?$/.exec(lines.shift());
|
|
107
|
-
if(!match)return req.destroy(failure("proxy_worker_protocol_error"));
|
|
108
|
-
reply=new PassThrough({highWaterMark:32*1024});reply.statusCode=Number(match[1]);reply.statusMessage=match[2]||"";reply.headers={};
|
|
109
|
-
for(const line of lines){const colon=line.indexOf(":");if(colon<1)continue;const name=line.slice(0,colon).toLowerCase(),value=line.slice(colon+1).trim();
|
|
110
|
-
if(name==="set-cookie")(reply.headers[name]||=[]).push(value);else reply.headers[name]=reply.headers[name]?reply.headers[name]+", "+value:value;}
|
|
111
|
-
reply.once("close",()=>{if(!done)req.destroy();});callback(reply);
|
|
112
|
-
}else if(event.type==="upload_ack"){if(!uploadCallback)return req.destroy(failure("proxy_worker_protocol_error"));uploadCallback();}
|
|
113
|
-
else if(event.type==="data"){
|
|
114
|
-
if(!reply||typeof event.body!=="string"||event.body.length>22000)return req.destroy(failure("proxy_worker_protocol_error"));
|
|
115
|
-
const ack=()=>write({op:"ack",id});if(reply.write(Buffer.from(event.body,"base64")))ack();else reply.once("drain",ack);
|
|
116
|
-
}else if(event.type==="end"){if(!reply)return req.destroy(failure("proxy_worker_protocol_error"));finish();reply.end();}
|
|
117
|
-
else if(event.type==="error")req.destroy(failure(/^winhttp_[a-z0-9_]+$/.test(event.code)?event.code:"proxy_request_failed"));
|
|
118
|
-
else req.destroy(failure("proxy_worker_protocol_error"));
|
|
119
|
-
};
|
|
120
|
-
if(stopped)queueMicrotask(()=>req.destroy(failure("proxy_worker_closed")));
|
|
121
|
-
return req;
|
|
122
|
-
};
|
|
123
|
-
return {script,requestImpl,pac:port=>companyPredictionPac(script,port),healthy:()=>!stopped,close(){closing=true;stop(failure("proxy_worker_closed"));}};
|
|
17
|
+
export async function startWindowsPredictionNetwork(options = {}) {
|
|
18
|
+
const network = await startWindowsHttpNetwork({ ...options, target: "prediction", validatePac: script => companyPredictionPac(script, 1) });
|
|
19
|
+
return { ...network, pac: port => companyPredictionPac(network.script, port) };
|
|
124
20
|
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
|
|
3
|
+
export function windowsPowerShellEnvironment(env = process.env) {
|
|
4
|
+
// PowerShell 7 can export a Core-only PSModulePath. Prefer the bundled
|
|
5
|
+
// Windows PowerShell modules for this child, retaining user module paths.
|
|
6
|
+
const modules = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "Modules");
|
|
7
|
+
return { ...env, PSModulePath: [modules, env.PSModulePath].filter(Boolean).join(";") };
|
|
8
|
+
}
|