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
|
@@ -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
|
+
}
|