@zllf/pi-provider-proxy 0.2.1 → 0.2.3
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 +6 -2
- package/package.json +1 -1
- package/src/codex-sse.js +127 -0
- package/src/connection-demand.js +81 -0
- package/src/connection-retry.js +40 -0
- package/src/extension.js +8 -4
- package/src/routing.js +65 -21
- package/src/session-http.js +93 -29
- package/src/transport.js +72 -29
package/README.md
CHANGED
|
@@ -14,15 +14,19 @@ pi install npm:@zllf/pi-provider-proxy
|
|
|
14
14
|
pi update npm:@zllf/pi-provider-proxy
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
在已打开的 Pi 会话中运行 `/reload`,然后输入 `/proxy`。也可以用 `pi install git:github.com/Zllf/pi-provider-proxy@v0.2.
|
|
17
|
+
在已打开的 Pi 会话中运行 `/reload`,然后输入 `/proxy`。也可以用 `pi install git:github.com/Zllf/pi-provider-proxy@v0.2.3` 固定 GitHub 版本。要求 Node.js 22.19 或更高版本,已在 Pi 1.7.0 验证。
|
|
18
18
|
|
|
19
19
|
## 配置代理
|
|
20
20
|
|
|
21
|
-
1. 在 `/proxy` 中选择「共享代理配置」→「添加配置」,起个简称,再粘贴完整地址,例如 `
|
|
21
|
+
1. 在 `/proxy` 中选择「共享代理配置」→「添加配置」,起个简称,再粘贴完整地址,例如 `socks5://127.0.0.1:1080`。`socks5` 在本机解析目标域名,`socks5h` 由代理解析。
|
|
22
22
|
2. 在「选择服务商」中选中目标,再用「更改服务商路由」选择代理、直连或继承 Pi 设置。修改从下一次请求生效。
|
|
23
23
|
3. 如果希望额度查询、自动命名等扩展也走当前模型的出口,在 `/proxy` 打开「Pi 网络跟随当前模型」。切换模型或更改绑定时,新请求立即使用新的出口。开关默认关闭。
|
|
24
24
|
4. 用「测试路由」检查能否连到服务商。收到 `401` 表示已收到目标站点的响应,账号权限可通过实际对话验证。
|
|
25
25
|
|
|
26
|
+
同一 Pi 会话内,同一服务商的多轮模型请求会复用代理连接。每个目标站点最多并发使用 4 条连接,空闲连接最长保留 90 秒,实际时长取决于上游。换代理后,新请求使用新路由,已开始的回答继续走原连接。SOCKS5 建连时限为 20 秒,调用方可以设置更短的请求期限。
|
|
27
|
+
|
|
28
|
+
扩展接管的连接在请求发出前遇到重置时,会在同一路由上静默补试,最多 3 次。补试在首次建连后的 5 秒内启动,耗尽后按原有方式报告最后一次错误。调用方发起的新请求有自己的补试次数。
|
|
29
|
+
|
|
26
30
|
**带密码的代理**可以直接粘贴 `socks5://用户名:密码@主机:端口`。输入时显示星号,完整地址以明文保存在 `~/.pi/agent/provider-proxy.json`,macOS 和 Linux 文件权限为 `0600`。也可以用 `$NAME` 引用保存完整地址的环境变量。
|
|
27
31
|
|
|
28
32
|
## 支持范围
|
package/package.json
CHANGED
package/src/codex-sse.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
const TAIL_TIMEOUT_MS = 350;
|
|
2
|
+
const TAIL_BYTE_LIMIT = 32 * 1024;
|
|
3
|
+
|
|
4
|
+
async function drainTail(reader, pendingRead, signals, byteBody) {
|
|
5
|
+
// Cancelling a Web Streams reader settles its pending reads immediately, even
|
|
6
|
+
// if the underlying source takes longer to finish its own cancellation.
|
|
7
|
+
const stop = reason => { void reader.cancel(reason).catch(() => {}); };
|
|
8
|
+
const onAbort = event => stop(event.target.reason);
|
|
9
|
+
const deadline = performance.now() + TAIL_TIMEOUT_MS;
|
|
10
|
+
const timer = setTimeout(stop, TAIL_TIMEOUT_MS);
|
|
11
|
+
try {
|
|
12
|
+
for (const signal of signals) signal.addEventListener('abort', onAbort, { once: true });
|
|
13
|
+
let remaining = TAIL_BYTE_LIMIT;
|
|
14
|
+
if (pendingRead) {
|
|
15
|
+
const { done, value } = await pendingRead;
|
|
16
|
+
if (done) return;
|
|
17
|
+
remaining -= value.byteLength;
|
|
18
|
+
}
|
|
19
|
+
// Fetch byte streams accept a caller-sized buffer. Even a large queued
|
|
20
|
+
// chunk can supply at most the remaining budget to a new drain read.
|
|
21
|
+
let buffer;
|
|
22
|
+
if (byteBody && remaining > 0) {
|
|
23
|
+
reader.releaseLock();
|
|
24
|
+
reader = byteBody.getReader({ mode: 'byob' });
|
|
25
|
+
buffer = new ArrayBuffer(remaining);
|
|
26
|
+
}
|
|
27
|
+
while (remaining > 0 && performance.now() < deadline) {
|
|
28
|
+
const { done, value } = buffer
|
|
29
|
+
? await reader.read(new Uint8Array(buffer, 0, remaining))
|
|
30
|
+
: await reader.read();
|
|
31
|
+
if (done) return;
|
|
32
|
+
remaining -= value.byteLength;
|
|
33
|
+
if (buffer) buffer = value.buffer;
|
|
34
|
+
}
|
|
35
|
+
stop();
|
|
36
|
+
} finally {
|
|
37
|
+
clearTimeout(timer);
|
|
38
|
+
for (const signal of signals) signal.removeEventListener('abort', onAbort);
|
|
39
|
+
reader.releaseLock();
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function codexBody(body, signals) {
|
|
44
|
+
// Undici supplies a byte stream. An injected fetch may supply a default
|
|
45
|
+
// stream whose chunks (such as pooled Buffers) must not be transferred.
|
|
46
|
+
let type;
|
|
47
|
+
try {
|
|
48
|
+
body.getReader({ mode: 'byob' }).releaseLock();
|
|
49
|
+
type = 'bytes';
|
|
50
|
+
} catch { /* Default streams only support a default reader. */ }
|
|
51
|
+
const reader = body.getReader();
|
|
52
|
+
let pendingRead;
|
|
53
|
+
let cancelling = false;
|
|
54
|
+
return new ReadableStream({
|
|
55
|
+
type,
|
|
56
|
+
start(controller) {
|
|
57
|
+
reader.closed.then(async () => {
|
|
58
|
+
// A last read may deliver bytes in the same turn that the source closes.
|
|
59
|
+
await pendingRead;
|
|
60
|
+
if (cancelling) return;
|
|
61
|
+
try {
|
|
62
|
+
controller.close();
|
|
63
|
+
controller.byobRequest?.respond(0);
|
|
64
|
+
} catch (error) { controller.error(error); } // e.g. a partial BYOB element at EOF
|
|
65
|
+
finally { reader.releaseLock(); }
|
|
66
|
+
}, error => {
|
|
67
|
+
if (cancelling) return;
|
|
68
|
+
controller.error(error);
|
|
69
|
+
reader.releaseLock();
|
|
70
|
+
});
|
|
71
|
+
},
|
|
72
|
+
async pull(controller) {
|
|
73
|
+
pendingRead = reader.read();
|
|
74
|
+
try {
|
|
75
|
+
const { done, value } = await pendingRead;
|
|
76
|
+
if (!done && !cancelling) controller.enqueue(value);
|
|
77
|
+
} finally { pendingRead = undefined; }
|
|
78
|
+
},
|
|
79
|
+
async cancel(reason) {
|
|
80
|
+
cancelling = true;
|
|
81
|
+
const aborted = signals.find(signal => signal.aborted);
|
|
82
|
+
if (reason === undefined && !aborted) {
|
|
83
|
+
return drainTail(reader, pendingRead, signals, type === 'bytes' ? body : undefined);
|
|
84
|
+
}
|
|
85
|
+
try { await reader.cancel(reason !== undefined ? reason : aborted.reason); }
|
|
86
|
+
finally { reader.releaseLock(); }
|
|
87
|
+
},
|
|
88
|
+
}, { highWaterMark: 0 }); // Pull only when the consumer requests bytes.
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function withFetchMetadata(wrapped, original) {
|
|
92
|
+
// Response's public constructor cannot set these fetch-owned properties. Keep
|
|
93
|
+
// the original header guard (network response headers are immutable).
|
|
94
|
+
const clone = wrapped.clone.bind(wrapped);
|
|
95
|
+
Object.defineProperties(wrapped, {
|
|
96
|
+
url: { value: original.url },
|
|
97
|
+
redirected: { value: original.redirected },
|
|
98
|
+
type: { value: original.type },
|
|
99
|
+
headers: { value: original.headers },
|
|
100
|
+
clone: { value: () => withFetchMetadata(clone(), original) },
|
|
101
|
+
});
|
|
102
|
+
return wrapped;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function isCodexSse(response, input, init) {
|
|
106
|
+
if (!response.ok || !response.body) return false;
|
|
107
|
+
const mime = response.headers.get('content-type');
|
|
108
|
+
if (mime !== null) return /^text\/event-stream\s*(?:;|$)/i.test(mime);
|
|
109
|
+
// Pi treats successful POSTs to its Codex responses endpoint as SSE even
|
|
110
|
+
// when the server omits Content-Type. Match the requested path, ignoring query.
|
|
111
|
+
const method = init?.method ?? input?.method ?? 'GET';
|
|
112
|
+
return method.toUpperCase() === 'POST' &&
|
|
113
|
+
URL.parse(input?.url ?? input)?.pathname.endsWith('/codex/responses');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Fetch adapter for a single Codex model stream. Pi passes its header signal
|
|
117
|
+
* to fetch and separately uses the logical request signal in the SSE parser. */
|
|
118
|
+
export function codexFetch(baseFetch, logicalSignal) {
|
|
119
|
+
return async (input, init) => {
|
|
120
|
+
const response = await baseFetch(input, init);
|
|
121
|
+
if (!isCodexSse(response, input, init)) return response;
|
|
122
|
+
|
|
123
|
+
const signals = [...new Set([init?.signal ?? input?.signal, logicalSignal].filter(Boolean))];
|
|
124
|
+
const wrapped = new response.constructor(codexBody(response.body, signals), response);
|
|
125
|
+
return response.type === 'default' ? wrapped : withFetchMetadata(wrapped, response);
|
|
126
|
+
};
|
|
127
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import UnwrapHandler from 'undici/lib/handler/unwrap-handler.js';
|
|
2
|
+
import { errors } from 'undici';
|
|
3
|
+
|
|
4
|
+
const originalConnectError = Symbol('original connection error');
|
|
5
|
+
const forwardedCallbacks = ['onBodySent', 'onRequestSent', 'onResponseStarted', 'onHeaders', 'onData'];
|
|
6
|
+
|
|
7
|
+
export function terminalConnectError(error) {
|
|
8
|
+
// Undici reconnects for these codes instead of failing the pending request.
|
|
9
|
+
if (error?.code !== 'UND_ERR_SOCKET' && error?.code !== 'UND_ERR_INFO') return error;
|
|
10
|
+
return Object.assign(new Error(error.message), { [originalConnectError]: error });
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function createConnectionDemand() {
|
|
14
|
+
const origins = new Map();
|
|
15
|
+
|
|
16
|
+
function attach(dispatcher) {
|
|
17
|
+
const dispatch = dispatcher.dispatch.bind(dispatcher);
|
|
18
|
+
dispatcher.dispatch = (options, incoming) => {
|
|
19
|
+
const handler = UnwrapHandler.unwrap(incoming);
|
|
20
|
+
if (typeof handler.onConnect !== 'function' || typeof handler.onError !== 'function') {
|
|
21
|
+
return dispatch(options, incoming);
|
|
22
|
+
}
|
|
23
|
+
const origin = new URL(options.origin).origin;
|
|
24
|
+
origins.set(origin, (origins.get(origin) ?? 0) + 1);
|
|
25
|
+
let pending = true;
|
|
26
|
+
let cancelled;
|
|
27
|
+
let abortRequest;
|
|
28
|
+
function release() {
|
|
29
|
+
if (!pending) return;
|
|
30
|
+
pending = false;
|
|
31
|
+
const remaining = origins.get(origin) - 1;
|
|
32
|
+
if (remaining) origins.set(origin, remaining);
|
|
33
|
+
else origins.delete(origin);
|
|
34
|
+
}
|
|
35
|
+
const wrapped = {
|
|
36
|
+
onConnect(abort) {
|
|
37
|
+
release();
|
|
38
|
+
abortRequest = abort;
|
|
39
|
+
// Fail this unwritten request without closing a socket another request can use.
|
|
40
|
+
if (cancelled) throw cancelled;
|
|
41
|
+
},
|
|
42
|
+
onError(error) {
|
|
43
|
+
release();
|
|
44
|
+
return handler.onError(cancelled ?? error?.[originalConnectError] ?? error);
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
for (const name of forwardedCallbacks) {
|
|
48
|
+
if (typeof handler[name] === 'function') wrapped[name] = handler[name].bind(handler);
|
|
49
|
+
}
|
|
50
|
+
for (const name of ['onComplete', 'onUpgrade']) {
|
|
51
|
+
if (typeof handler[name] === 'function') {
|
|
52
|
+
wrapped[name] = (...args) => {
|
|
53
|
+
release();
|
|
54
|
+
return handler[name](...args);
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
// Fetch only provides cancellation through this callback, so register it before socket setup.
|
|
60
|
+
handler.onConnect(reason => {
|
|
61
|
+
release();
|
|
62
|
+
cancelled ??= reason ?? new errors.RequestAbortedError();
|
|
63
|
+
abortRequest?.(cancelled);
|
|
64
|
+
});
|
|
65
|
+
} catch (error) {
|
|
66
|
+
release();
|
|
67
|
+
handler.onError(error);
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
if (cancelled) {
|
|
71
|
+
handler.onError(cancelled);
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
try { return dispatch(options, wrapped); }
|
|
75
|
+
catch (error) { release(); throw error; }
|
|
76
|
+
};
|
|
77
|
+
return dispatcher;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return { attach, waiting: origin => origins.has(origin) };
|
|
81
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { errors } from 'undici';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { terminalConnectError } from './connection-demand.js';
|
|
4
|
+
|
|
5
|
+
const resetCodes = new Set(['ECONNRESET', 'SOCKS_RESET', 'UND_ERR_SOCKET']);
|
|
6
|
+
const retryDelays = [100, 200, 400];
|
|
7
|
+
// An individual handshake keeps its protocol timeout. This window limits retry starts.
|
|
8
|
+
const resetWindowMs = 5_000;
|
|
9
|
+
|
|
10
|
+
/** Call only during connection setup, before handing a socket to the request. */
|
|
11
|
+
export async function retryConnection(connect, { signal, active = () => true, retrySocksTimeout = false } = {}) {
|
|
12
|
+
const start = performance.now();
|
|
13
|
+
for (let attempt = 0; ; attempt++) {
|
|
14
|
+
signal?.throwIfAborted();
|
|
15
|
+
try { return await connect(); }
|
|
16
|
+
catch (error) {
|
|
17
|
+
signal?.throwIfAborted();
|
|
18
|
+
const wait = retryDelays[attempt];
|
|
19
|
+
const earlyReset = resetCodes.has(error.code) && performance.now() - start + wait <= resetWindowMs;
|
|
20
|
+
const oauthTimeout = attempt === 0 && retrySocksTimeout && error.code === 'SOCKS_TIMEOUT';
|
|
21
|
+
if (wait === undefined || !active() || (!earlyReset && !oauthTimeout)) throw error;
|
|
22
|
+
try { await delay(wait, undefined, { signal }); }
|
|
23
|
+
catch { signal?.throwIfAborted(); throw error; }
|
|
24
|
+
if (!active()) throw error;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function retryConnector(connect, { active, retrySocksTimeout }) {
|
|
30
|
+
return (parameters, callback) => {
|
|
31
|
+
if (!active()) return callback(new errors.RequestAbortedError());
|
|
32
|
+
retryConnection(() => new Promise((resolve, reject) => {
|
|
33
|
+
connect(parameters, (error, socket) => error ? reject(error) : resolve(socket));
|
|
34
|
+
}), { active, retrySocksTimeout, signal: parameters.signal }).then(socket => {
|
|
35
|
+
if (active()) return callback(null, socket);
|
|
36
|
+
socket.destroy();
|
|
37
|
+
callback(new errors.RequestAbortedError());
|
|
38
|
+
}, error => callback(active() ? terminalConnectError(error) : new errors.RequestAbortedError()));
|
|
39
|
+
};
|
|
40
|
+
}
|
package/src/extension.js
CHANGED
|
@@ -9,7 +9,7 @@ import { wrapCodexAuth } from './oauth.js';
|
|
|
9
9
|
import { createSessionNetwork } from './session-network.js';
|
|
10
10
|
import { createSessionHttp } from './session-http.js';
|
|
11
11
|
import { beforeModelListeners } from './model-events.js';
|
|
12
|
-
import {
|
|
12
|
+
import { createModelRoutes, probeEndpoint } from './routing.js';
|
|
13
13
|
|
|
14
14
|
const nativeIds = new Set(['openai-codex', 'anthropic', 'openai', 'deepseek', 'openrouter']);
|
|
15
15
|
const compatibleApis = new Set(['openai-completions', 'openai-responses', 'anthropic-messages']);
|
|
@@ -67,6 +67,7 @@ export default function providerProxy(pi, HostRunner = ExtensionRunner) {
|
|
|
67
67
|
return store;
|
|
68
68
|
};
|
|
69
69
|
const installed = new Set();
|
|
70
|
+
const modelRoutes = createModelRoutes(id => checked().route(id));
|
|
70
71
|
const blocked = new Set();
|
|
71
72
|
const sessionNetwork = createSessionNetwork();
|
|
72
73
|
const sessionHttp = createSessionHttp();
|
|
@@ -90,6 +91,7 @@ export default function providerProxy(pi, HostRunner = ExtensionRunner) {
|
|
|
90
91
|
function block(id, error) {
|
|
91
92
|
if (blocked.has(id)) return;
|
|
92
93
|
pi.registerProvider(blockedProvider(id, builtins.find(p => p.id === id), error));
|
|
94
|
+
modelRoutes.retire(id);
|
|
93
95
|
blocked.add(id);
|
|
94
96
|
}
|
|
95
97
|
function activate(id) {
|
|
@@ -100,12 +102,12 @@ export default function providerProxy(pi, HostRunner = ExtensionRunner) {
|
|
|
100
102
|
pi.registerProvider({
|
|
101
103
|
...native,
|
|
102
104
|
auth: id === 'openai-codex' ? wrapCodexAuth(native.auth, route) : native.auth,
|
|
103
|
-
stream:
|
|
104
|
-
streamSimple:
|
|
105
|
+
stream: modelRoutes.wrap(id, native.stream),
|
|
106
|
+
streamSimple: modelRoutes.wrap(id, native.streamSimple),
|
|
105
107
|
});
|
|
106
108
|
} else {
|
|
107
109
|
// Omit the model list so Pi retains its models.json catalog and auth.
|
|
108
|
-
pi.registerProvider(id, { api, streamSimple:
|
|
110
|
+
pi.registerProvider(id, { api, streamSimple: modelRoutes.wrap(id, getApiProvider(api).streamSimple) });
|
|
109
111
|
}
|
|
110
112
|
installed.add(id);
|
|
111
113
|
}
|
|
@@ -150,6 +152,7 @@ export default function providerProxy(pi, HostRunner = ExtensionRunner) {
|
|
|
150
152
|
releaseEarlyListener?.();
|
|
151
153
|
releaseEarlyListener = undefined;
|
|
152
154
|
activeProvider = undefined;
|
|
155
|
+
modelRoutes.dispose();
|
|
153
156
|
sessionNetwork.dispose();
|
|
154
157
|
sessionHttp.dispose();
|
|
155
158
|
});
|
|
@@ -171,6 +174,7 @@ export default function providerProxy(pi, HostRunner = ExtensionRunner) {
|
|
|
171
174
|
}
|
|
172
175
|
}
|
|
173
176
|
checked().save(next);
|
|
177
|
+
modelRoutes.refresh();
|
|
174
178
|
for (const id of blocked) {
|
|
175
179
|
if (Object.hasOwn(next.bindings, id)) continue;
|
|
176
180
|
pi.unregisterProvider(id);
|
package/src/routing.js
CHANGED
|
@@ -1,25 +1,69 @@
|
|
|
1
|
-
import { createTransport } from './transport.js';
|
|
1
|
+
import { createTransport, SOCKS_HANDSHAKE_TIMEOUT_MS } from './transport.js';
|
|
2
2
|
import { problem } from './config.js';
|
|
3
|
+
import { codexFetch } from './codex-sse.js';
|
|
3
4
|
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
export function
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
5
|
+
// The stream lease covers retries and all response events. Once a binding is
|
|
6
|
+
// retired, only streams that already hold its transport may keep using it.
|
|
7
|
+
export function createModelRoutes(resolveRoute) {
|
|
8
|
+
const pools = new Map();
|
|
9
|
+
let disposed = false;
|
|
10
|
+
|
|
11
|
+
function closeIfIdle(entry) {
|
|
12
|
+
if (entry.retired && entry.users === 0) void entry.transport.close().catch(() => {});
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function retire(id) {
|
|
16
|
+
const entry = pools.get(id);
|
|
17
|
+
if (!entry) return;
|
|
18
|
+
pools.delete(id);
|
|
19
|
+
entry.retired = true;
|
|
20
|
+
closeIfIdle(entry);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function currentRoute(id) {
|
|
24
|
+
let route;
|
|
25
|
+
try { route = resolveRoute(id); }
|
|
26
|
+
catch (error) { retire(id); throw error; }
|
|
27
|
+
const entry = pools.get(id);
|
|
28
|
+
if (entry && entry.route !== route) retire(id);
|
|
29
|
+
return route;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function wrap(id, delegate) {
|
|
33
|
+
return (model, transcript, options) => {
|
|
34
|
+
if (disposed) throw new Error('Model proxy session is closed.');
|
|
35
|
+
const route = currentRoute(id);
|
|
36
|
+
if (route === undefined) return delegate(model, transcript, options);
|
|
37
|
+
let entry = pools.get(id);
|
|
38
|
+
if (!entry) {
|
|
39
|
+
entry = { route, transport: createTransport(route, { modelPool: true }), users: 0, retired: false };
|
|
40
|
+
pools.set(id, entry);
|
|
41
|
+
}
|
|
42
|
+
entry.users++;
|
|
43
|
+
const release = () => { entry.users--; closeIfIdle(entry); };
|
|
44
|
+
try {
|
|
45
|
+
const codex = model.api === 'openai-codex-responses';
|
|
46
|
+
const stream = delegate(model, transcript, {
|
|
47
|
+
...options, fetch: codex ? codexFetch(entry.transport.fetch, options?.signal) : entry.transport.fetch,
|
|
48
|
+
...(codex ? { transport: 'sse' } : {}),
|
|
49
|
+
});
|
|
50
|
+
stream.result().then(release, release);
|
|
51
|
+
return stream;
|
|
52
|
+
} catch (error) { release(); throw error; }
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
wrap, retire,
|
|
58
|
+
refresh() {
|
|
59
|
+
for (const id of pools.keys()) {
|
|
60
|
+
try { currentRoute(id); } catch { /* Next request reports the configuration error. */ }
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
dispose() {
|
|
64
|
+
disposed = true;
|
|
65
|
+
for (const id of pools.keys()) retire(id);
|
|
66
|
+
},
|
|
23
67
|
};
|
|
24
68
|
}
|
|
25
69
|
|
|
@@ -31,7 +75,7 @@ export async function probeEndpoint(endpoint, route) {
|
|
|
31
75
|
origin = url.origin;
|
|
32
76
|
} catch { throw problem('NO_ENDPOINT'); }
|
|
33
77
|
const transport = route === undefined ? undefined : createTransport(route);
|
|
34
|
-
const signal = AbortSignal.timeout(6000);
|
|
78
|
+
const signal = AbortSignal.timeout(route?.startsWith('socks5') ? SOCKS_HANDSHAKE_TIMEOUT_MS + 5000 : 6000);
|
|
35
79
|
const start = performance.now();
|
|
36
80
|
try {
|
|
37
81
|
const response = await (transport?.fetch ?? globalThis.fetch)(origin, {
|
package/src/session-http.js
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import dns from 'node:dns';
|
|
2
|
+
import { addAbortListener, once } from 'node:events';
|
|
2
3
|
import http from 'node:http';
|
|
3
4
|
import https from 'node:https';
|
|
4
5
|
import { isIP } from 'node:net';
|
|
5
6
|
import { buildConnector, Client } from 'undici';
|
|
6
|
-
import {
|
|
7
|
+
import { retryConnection } from './connection-retry.js';
|
|
7
8
|
import { isLoopbackHost } from './local-target.js';
|
|
8
|
-
import { validateProxyUrl } from './transport.js';
|
|
9
|
+
import { openSocks, SOCKS_HANDSHAKE_TIMEOUT_MS, socksFailure, validateProxyUrl } from './transport.js';
|
|
9
10
|
|
|
10
11
|
const handshakeTimeout = 10_000;
|
|
12
|
+
const connectionOptions = Symbol('session connection options');
|
|
11
13
|
|
|
12
14
|
function httpTunnel(proxy) {
|
|
13
15
|
const headers = {};
|
|
@@ -17,7 +19,7 @@ function httpTunnel(proxy) {
|
|
|
17
19
|
}
|
|
18
20
|
// The CONNECT Host header names the destination. Verify outer TLS against the proxy.
|
|
19
21
|
const connect = buildConnector({ rejectUnauthorized: true });
|
|
20
|
-
return async ({ host, port }) => {
|
|
22
|
+
return async ({ host, port }, signal) => {
|
|
21
23
|
const authority = `${isIP(host) === 6 ? `[${host}]` : host}:${port}`;
|
|
22
24
|
// A successful CONNECT detaches the socket from this one-use client.
|
|
23
25
|
const client = new Client(proxy.origin, {
|
|
@@ -25,7 +27,8 @@ function httpTunnel(proxy) {
|
|
|
25
27
|
});
|
|
26
28
|
try {
|
|
27
29
|
const { socket, statusCode } = await client.connect({
|
|
28
|
-
path: authority, headers: { ...headers, host: authority },
|
|
30
|
+
path: authority, headers: { ...headers, host: authority },
|
|
31
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(handshakeTimeout)]),
|
|
29
32
|
});
|
|
30
33
|
if (statusCode === 200) return socket;
|
|
31
34
|
socket.destroy();
|
|
@@ -36,49 +39,102 @@ function httpTunnel(proxy) {
|
|
|
36
39
|
};
|
|
37
40
|
}
|
|
38
41
|
|
|
42
|
+
function lookupDestination(lookup, host, family, signal) {
|
|
43
|
+
signal.throwIfAborted();
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
const abort = addAbortListener(signal, () => reject(signal.reason));
|
|
46
|
+
function done(error, address) {
|
|
47
|
+
abort[Symbol.dispose]();
|
|
48
|
+
if (error) reject(error);
|
|
49
|
+
else resolve(address);
|
|
50
|
+
}
|
|
51
|
+
try { lookup(host, { family }, done); }
|
|
52
|
+
catch (error) { done(error); }
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
39
56
|
function socksTunnel(url) {
|
|
40
57
|
const proxy = {
|
|
41
58
|
type: 5, host: url.hostname.replace(/^\[|\]$/g, ''), port: Number(url.port || 1080),
|
|
42
59
|
userId: decodeURIComponent(url.username), password: decodeURIComponent(url.password),
|
|
43
60
|
};
|
|
44
|
-
return async ({ host, port, lookup = dns.lookup, family = 0 }) => {
|
|
61
|
+
return async ({ host, port, lookup = dns.lookup, family = 0 }, signal) => {
|
|
45
62
|
if (url.protocol === 'socks5:' && !isIP(host)) {
|
|
46
|
-
host = await
|
|
47
|
-
lookup(host, { family }, (error, address) => error ? reject(error) : resolve(address));
|
|
48
|
-
});
|
|
63
|
+
host = await lookupDestination(lookup, host, family, signal);
|
|
49
64
|
}
|
|
50
65
|
if (Buffer.byteLength(host) > 255) throw new Error('SOCKS destination name is too long.');
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
66
|
+
signal.throwIfAborted();
|
|
67
|
+
try {
|
|
68
|
+
return await openSocks({
|
|
69
|
+
command: 'connect', proxy, destination: { host, port: Number(port) }, timeout: SOCKS_HANDSHAKE_TIMEOUT_MS,
|
|
70
|
+
}, signal);
|
|
71
|
+
} catch (error) { throw socksFailure(error); }
|
|
55
72
|
};
|
|
56
73
|
}
|
|
57
74
|
|
|
58
|
-
function remoteAgent(core, tunnel) {
|
|
75
|
+
function remoteAgent(core, tunnel, timeout) {
|
|
59
76
|
// One-use sockets let an old route drain naturally, including upgrades and streams.
|
|
60
77
|
const agent = new core.Agent();
|
|
61
|
-
|
|
62
|
-
const
|
|
78
|
+
const open = agent.createConnection.bind(agent);
|
|
79
|
+
const secure = core === https;
|
|
63
80
|
agent.createConnection = (options, callback) => {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
81
|
+
const request = options[connectionOptions];
|
|
82
|
+
const deadline = AbortSignal.timeout(timeout);
|
|
83
|
+
const signal = AbortSignal.any([request.signal, deadline]);
|
|
84
|
+
let tunnelFailure;
|
|
85
|
+
async function connect() {
|
|
86
|
+
let socket;
|
|
87
|
+
if (tunnel) {
|
|
88
|
+
try { socket = await tunnel(options, signal); }
|
|
89
|
+
catch (error) {
|
|
90
|
+
signal.throwIfAborted();
|
|
91
|
+
tunnelFailure = error;
|
|
92
|
+
throw error;
|
|
71
93
|
}
|
|
94
|
+
if (!secure) return socket;
|
|
72
95
|
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
96
|
+
try {
|
|
97
|
+
signal.throwIfAborted();
|
|
98
|
+
socket = open(socket ? { ...options, socket } : options);
|
|
99
|
+
await once(socket, secure ? 'secureConnect' : 'connect', { signal });
|
|
100
|
+
return socket;
|
|
101
|
+
} catch (error) { socket?.destroy(); throw error; }
|
|
102
|
+
}
|
|
103
|
+
retryConnection(connect, { signal }).then(socket => callback(null, socket), error => {
|
|
104
|
+
if (error === deadline.reason) {
|
|
105
|
+
callback(Object.assign(new Error('Connection timed out.'), { code: 'ETIMEDOUT' }));
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
// Preserve the existing redaction for errors from proxy negotiation.
|
|
109
|
+
callback(error === tunnelFailure ? new Error('Session proxy connection failed.') : error);
|
|
77
110
|
});
|
|
78
111
|
};
|
|
79
112
|
return agent;
|
|
80
113
|
}
|
|
81
114
|
|
|
115
|
+
function pendingConnection(req) {
|
|
116
|
+
const connection = new AbortController();
|
|
117
|
+
const descriptor = Object.getOwnPropertyDescriptor(req, 'destroy');
|
|
118
|
+
const destroy = req.destroy;
|
|
119
|
+
function cancel(error, ...args) {
|
|
120
|
+
const result = destroy.call(this, error, ...args);
|
|
121
|
+
if (this === req && req.destroyed) connection.abort(error ?? Object.assign(new Error('socket hang up'), { code: 'ECONNRESET' }));
|
|
122
|
+
return result;
|
|
123
|
+
}
|
|
124
|
+
function release() {
|
|
125
|
+
req.removeListener('socket', release);
|
|
126
|
+
req.removeListener('close', release);
|
|
127
|
+
if (Object.getOwnPropertyDescriptor(req, 'destroy')?.value !== cancel) return;
|
|
128
|
+
if (descriptor) Object.defineProperty(req, 'destroy', descriptor);
|
|
129
|
+
else delete req.destroy;
|
|
130
|
+
}
|
|
131
|
+
// Node emits close only after the agent's connection callback, so observe destroy while it is pending.
|
|
132
|
+
Object.defineProperty(req, 'destroy', { configurable: true, writable: true, value: cancel });
|
|
133
|
+
req.once('socket', release);
|
|
134
|
+
req.once('close', release);
|
|
135
|
+
return connection;
|
|
136
|
+
}
|
|
137
|
+
|
|
82
138
|
function hasProxyAuthorization(req, headers) {
|
|
83
139
|
if (req.hasHeader('proxy-authorization')) return true;
|
|
84
140
|
if (!Array.isArray(headers)) return false;
|
|
@@ -100,12 +156,16 @@ function install(core) {
|
|
|
100
156
|
if (active && !local && hasProxyAuthorization(req, options.headers)) {
|
|
101
157
|
return req.onSocket(null, new Error('Set proxy credentials on the proxy URL.'));
|
|
102
158
|
}
|
|
159
|
+
if (active && !local) {
|
|
160
|
+
if (req.destroyed) return req.onSocket(null);
|
|
161
|
+
options = { ...options, [connectionOptions]: pendingConnection(req) };
|
|
162
|
+
}
|
|
103
163
|
req.agent = delegate;
|
|
104
164
|
delegate.addRequest(req, options);
|
|
105
165
|
};
|
|
106
166
|
core.globalAgent = router;
|
|
107
167
|
return {
|
|
108
|
-
configure(blocked, tunnel) { remote = blocked ? undefined : remoteAgent(core, tunnel); },
|
|
168
|
+
configure(blocked, tunnel, timeout) { remote = blocked ? undefined : remoteAgent(core, tunnel, timeout); },
|
|
109
169
|
restore() {
|
|
110
170
|
active = false;
|
|
111
171
|
remote = undefined;
|
|
@@ -125,17 +185,21 @@ export function createSessionHttp() {
|
|
|
125
185
|
set(route) {
|
|
126
186
|
if (route === undefined) return restore();
|
|
127
187
|
let tunnel;
|
|
188
|
+
let timeout = handshakeTimeout;
|
|
128
189
|
let blocked = route instanceof Error;
|
|
129
190
|
if (!blocked && route !== 'direct') {
|
|
130
191
|
try {
|
|
131
192
|
const url = new URL(validateProxyUrl(route));
|
|
132
|
-
|
|
193
|
+
if (url.protocol.startsWith('socks')) {
|
|
194
|
+
tunnel = socksTunnel(url);
|
|
195
|
+
timeout = SOCKS_HANDSHAKE_TIMEOUT_MS;
|
|
196
|
+
} else tunnel = httpTunnel(url);
|
|
133
197
|
} catch {
|
|
134
198
|
blocked = true;
|
|
135
199
|
}
|
|
136
200
|
}
|
|
137
201
|
installed ??= [install(http), install(https)];
|
|
138
|
-
for (const binding of installed) binding.configure(blocked, tunnel);
|
|
202
|
+
for (const binding of installed) binding.configure(blocked, tunnel, timeout);
|
|
139
203
|
},
|
|
140
204
|
dispose: restore,
|
|
141
205
|
};
|
package/src/transport.js
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
import { lookup } from 'node:dns/promises';
|
|
2
|
-
import {
|
|
2
|
+
import { addAbortListener, once } from 'node:events';
|
|
3
|
+
import { connect as openTcp, isIP } from 'node:net';
|
|
3
4
|
import { domainToASCII } from 'node:url';
|
|
4
|
-
import { Agent, Pool, ProxyAgent, Request as UndiciRequest, buildConnector, fetch as dispatchFetch } from 'undici';
|
|
5
|
+
import { Agent, Client, Pool, ProxyAgent, Request as UndiciRequest, buildConnector, fetch as dispatchFetch } from 'undici';
|
|
5
6
|
import { SocksClient } from 'socks';
|
|
7
|
+
import { createConnectionDemand } from './connection-demand.js';
|
|
8
|
+
import { retryConnector } from './connection-retry.js';
|
|
9
|
+
|
|
10
|
+
export const SOCKS_HANDSHAKE_TIMEOUT_MS = 20_000;
|
|
11
|
+
const modelPoolOptions = { connections: 4, keepAliveTimeout: 90_000, keepAliveMaxTimeout: 90_000 };
|
|
6
12
|
|
|
7
13
|
function invalidProxy() {
|
|
8
14
|
return new TypeError('Invalid proxy URL (expected an HTTP, HTTPS, SOCKS5, or SOCKS5H proxy authority).');
|
|
@@ -31,7 +37,7 @@ export function validateProxyUrl(value) {
|
|
|
31
37
|
}
|
|
32
38
|
}
|
|
33
39
|
|
|
34
|
-
function socksFailure(error) {
|
|
40
|
+
export function socksFailure(error) {
|
|
35
41
|
// SocksClientError also holds the plaintext proxy credentials. Copy only a code.
|
|
36
42
|
const msg = error?.message ?? '';
|
|
37
43
|
let code = 'SOCKS_CONNECT';
|
|
@@ -41,7 +47,28 @@ function socksFailure(error) {
|
|
|
41
47
|
return Object.assign(new Error('SOCKS proxy connection failed.'), { code });
|
|
42
48
|
}
|
|
43
49
|
|
|
44
|
-
function
|
|
50
|
+
export async function openSocks(options, signal) {
|
|
51
|
+
if (!signal) return (await SocksClient.createConnection(options)).socket;
|
|
52
|
+
signal.throwIfAborted();
|
|
53
|
+
const { host, port } = options.proxy;
|
|
54
|
+
const socket = openTcp({ host, port });
|
|
55
|
+
const abort = addAbortListener(signal, () => socket.destroy());
|
|
56
|
+
try {
|
|
57
|
+
await once(socket, 'connect', { signal });
|
|
58
|
+
socket.setNoDelay(true);
|
|
59
|
+
await SocksClient.createConnection({ ...options, existing_socket: socket });
|
|
60
|
+
signal.throwIfAborted();
|
|
61
|
+
return socket;
|
|
62
|
+
} catch (error) {
|
|
63
|
+
socket.destroy();
|
|
64
|
+
signal.throwIfAborted();
|
|
65
|
+
throw error;
|
|
66
|
+
} finally {
|
|
67
|
+
abort[Symbol.dispose]();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function socksConnector(url) {
|
|
45
72
|
const proxy = {
|
|
46
73
|
type: 5,
|
|
47
74
|
host: url.hostname.replace(/^\[|\]$/g, ''),
|
|
@@ -58,42 +85,57 @@ function socksAgent(url, retryHandshake) {
|
|
|
58
85
|
const secured = protocol === 'https:';
|
|
59
86
|
const options = {
|
|
60
87
|
command: 'connect', proxy, destination: { host, port: Number(port || (secured ? 443 : 80)) },
|
|
61
|
-
timeout:
|
|
88
|
+
timeout: SOCKS_HANDSHAKE_TIMEOUT_MS, set_tcp_nodelay: true,
|
|
62
89
|
};
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
return (await SocksClient.createConnection(options)).socket;
|
|
66
|
-
} catch (error) {
|
|
67
|
-
const failure = socksFailure(error);
|
|
68
|
-
// Only establish a tunnel again. No OAuth POST has been sent at this point.
|
|
69
|
-
if (!retryHandshake || attempt > 0 || !['SOCKS_TIMEOUT', 'SOCKS_RESET'].includes(failure.code)) throw failure;
|
|
70
|
-
}
|
|
71
|
-
}
|
|
90
|
+
try { return (await SocksClient.createConnection(options)).socket; }
|
|
91
|
+
catch (error) { throw socksFailure(error); }
|
|
72
92
|
}
|
|
73
93
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
}
|
|
82
|
-
}
|
|
94
|
+
async function connectOnce(options) {
|
|
95
|
+
const socket = await tunnel(options);
|
|
96
|
+
if (options.protocol !== 'https:') return socket;
|
|
97
|
+
try {
|
|
98
|
+
// Use the original hostname for SNI and certificate checks after local DNS resolution.
|
|
99
|
+
return await new Promise((resolve, reject) => tlsConnect({ ...options, httpSocket: socket },
|
|
100
|
+
(error, secured) => error ? reject(error) : resolve(secured)));
|
|
101
|
+
} catch (error) { socket.destroy(); throw error; }
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return (options, callback) => { connectOnce(options).then(socket => callback(null, socket), callback); };
|
|
83
105
|
}
|
|
84
106
|
|
|
85
|
-
export function createRouteDispatcher(route,
|
|
86
|
-
|
|
107
|
+
export function createRouteDispatcher(route, retrySocksTimeout = false, modelPool = false) {
|
|
108
|
+
const poolOptions = modelPool ? modelPoolOptions : {};
|
|
109
|
+
const demand = createConnectionDemand();
|
|
110
|
+
let dispatcher;
|
|
111
|
+
function factory(origin, options) {
|
|
112
|
+
const key = new URL(origin).origin;
|
|
113
|
+
const Dispatcher = options.connections === 1 ? Client : Pool;
|
|
114
|
+
const connect = retryConnector(options.connect, {
|
|
115
|
+
active: () => !dispatcher.destroyed && demand.waiting(key), retrySocksTimeout,
|
|
116
|
+
});
|
|
117
|
+
return new Dispatcher(origin, { ...options, connect });
|
|
118
|
+
}
|
|
119
|
+
if (route === 'direct') {
|
|
120
|
+
dispatcher = new Agent({ ...poolOptions, factory, connect: buildConnector({ rejectUnauthorized: true }) });
|
|
121
|
+
return demand.attach(dispatcher);
|
|
122
|
+
}
|
|
87
123
|
const url = new URL(validateProxyUrl(route));
|
|
88
|
-
if (url.protocol.startsWith('socks'))
|
|
124
|
+
if (url.protocol.startsWith('socks')) {
|
|
125
|
+
dispatcher = new Agent({ ...poolOptions, factory, connect: socksConnector(url) });
|
|
126
|
+
return demand.attach(dispatcher);
|
|
127
|
+
}
|
|
89
128
|
|
|
90
129
|
let token;
|
|
91
130
|
if (url.username || url.password) {
|
|
92
131
|
const basic = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`;
|
|
93
132
|
token = `Basic ${Buffer.from(basic).toString('base64')}`;
|
|
94
133
|
}
|
|
95
|
-
|
|
134
|
+
dispatcher = new ProxyAgent({
|
|
135
|
+
...poolOptions,
|
|
96
136
|
uri: url.origin, token, proxyTunnel: true,
|
|
137
|
+
// Retry the whole CONNECT and origin TLS setup before handing off its socket.
|
|
138
|
+
factory,
|
|
97
139
|
// ProxyAgent passes even an IP literal as SNI. Let the connector derive SNI
|
|
98
140
|
// from the proxy host, omitting it for IPs while TLS still verifies their SAN.
|
|
99
141
|
clientFactory: (origin, { connect }) => new Pool(origin, {
|
|
@@ -101,11 +143,12 @@ export function createRouteDispatcher(route, retryHandshake = false) {
|
|
|
101
143
|
}),
|
|
102
144
|
proxyTls: { rejectUnauthorized: true }, requestTls: { rejectUnauthorized: true },
|
|
103
145
|
});
|
|
146
|
+
return demand.attach(dispatcher);
|
|
104
147
|
}
|
|
105
148
|
|
|
106
149
|
/** Owns one dispatcher. Call close() on retirement to terminate outstanding requests. */
|
|
107
|
-
export function createTransport(route, { retrySocksHandshake = false } = {}) {
|
|
108
|
-
const dispatcher = createRouteDispatcher(route, retrySocksHandshake);
|
|
150
|
+
export function createTransport(route, { retrySocksHandshake = false, modelPool = false } = {}) {
|
|
151
|
+
const dispatcher = createRouteDispatcher(route, retrySocksHandshake, modelPool);
|
|
109
152
|
let closing;
|
|
110
153
|
return {
|
|
111
154
|
async fetch(input, init) {
|