@zllf/pi-provider-proxy 0.2.0 → 0.2.2

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 CHANGED
@@ -14,15 +14,17 @@ 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.0` 固定 GitHub 版本。要求 Node.js 22.19 或更高版本,已在 Pi 1.7.0 验证。
17
+ 在已打开的 Pi 会话中运行 `/reload`,然后输入 `/proxy`。也可以用 `pi install git:github.com/Zllf/pi-provider-proxy@v0.2.2` 固定 GitHub 版本。要求 Node.js 22.19 或更高版本,已在 Pi 1.7.0 验证。
18
18
 
19
19
  ## 配置代理
20
20
 
21
- 1. 在 `/proxy` 中选择「共享代理配置」→「添加配置」,起个简称,再粘贴完整地址,例如 `socks5h://127.0.0.1:1080`。`socks5h` 由代理解析目标域名,`socks5` 在本机解析。
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
+
26
28
  **带密码的代理**可以直接粘贴 `socks5://用户名:密码@主机:端口`。输入时显示星号,完整地址以明文保存在 `~/.pi/agent/provider-proxy.json`,macOS 和 Linux 文件权限为 `0600`。也可以用 `$NAME` 引用保存完整地址的环境变量。
27
29
 
28
30
  ## 支持范围
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zllf/pi-provider-proxy",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Per-provider HTTP and SOCKS routes for the Pi terminal",
5
5
  "type": "module",
6
6
  "repository": {
@@ -26,7 +26,7 @@
26
26
  ],
27
27
  "pi": {
28
28
  "extensions": [
29
- "./src/extension.js"
29
+ "./src/entry.cjs"
30
30
  ]
31
31
  },
32
32
  "scripts": {
@@ -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
+ }
package/src/entry.cjs ADDED
@@ -0,0 +1,6 @@
1
+ // Resolve Pi's runner through the extension loader. A native ESM import in a
2
+ // source checkout can instead resolve the separate development SDK instance.
3
+ const { ExtensionRunner } = require('@earendil-works/pi-coding-agent');
4
+ const providerProxy = require('./extension.js').default;
5
+
6
+ module.exports = pi => providerProxy(pi, ExtensionRunner);
package/src/extension.js CHANGED
@@ -2,13 +2,14 @@ import { join } from 'node:path';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
4
4
  import { getApiProvider } from '@earendil-works/pi-ai/compat';
5
- import { getAgentDir } from '@earendil-works/pi-coding-agent';
5
+ import { ExtensionRunner, getAgentDir } from '@earendil-works/pi-coding-agent';
6
6
  import { openConfig, problem } from './config.js';
7
7
  import { registerMenu } from './menu.js';
8
8
  import { wrapCodexAuth } from './oauth.js';
9
9
  import { createSessionNetwork } from './session-network.js';
10
10
  import { createSessionHttp } from './session-http.js';
11
- import { probeEndpoint, routedStream } from './routing.js';
11
+ import { beforeModelListeners } from './model-events.js';
12
+ import { createModelRoutes, probeEndpoint } from './routing.js';
12
13
 
13
14
  const nativeIds = new Set(['openai-codex', 'anthropic', 'openai', 'deepseek', 'openrouter']);
14
15
  const compatibleApis = new Set(['openai-completions', 'openai-responses', 'anthropic-messages']);
@@ -54,7 +55,7 @@ function blockedProvider(id, native, error) {
54
55
  };
55
56
  }
56
57
 
57
- export default function providerProxy(pi) {
58
+ export default function providerProxy(pi, HostRunner = ExtensionRunner) {
58
59
  const dir = getAgentDir();
59
60
  const builtins = builtinProviders();
60
61
  const catalog = supportedCatalog(dir, builtins);
@@ -66,6 +67,7 @@ export default function providerProxy(pi) {
66
67
  return store;
67
68
  };
68
69
  const installed = new Set();
70
+ const modelRoutes = createModelRoutes(id => checked().route(id));
69
71
  const blocked = new Set();
70
72
  const sessionNetwork = createSessionNetwork();
71
73
  const sessionHttp = createSessionHttp();
@@ -89,6 +91,7 @@ export default function providerProxy(pi) {
89
91
  function block(id, error) {
90
92
  if (blocked.has(id)) return;
91
93
  pi.registerProvider(blockedProvider(id, builtins.find(p => p.id === id), error));
94
+ modelRoutes.retire(id);
92
95
  blocked.add(id);
93
96
  }
94
97
  function activate(id) {
@@ -99,12 +102,12 @@ export default function providerProxy(pi) {
99
102
  pi.registerProvider({
100
103
  ...native,
101
104
  auth: id === 'openai-codex' ? wrapCodexAuth(native.auth, route) : native.auth,
102
- stream: routedStream(native.stream, route),
103
- streamSimple: routedStream(native.streamSimple, route),
105
+ stream: modelRoutes.wrap(id, native.stream),
106
+ streamSimple: modelRoutes.wrap(id, native.streamSimple),
104
107
  });
105
108
  } else {
106
109
  // Omit the model list so Pi retains its models.json catalog and auth.
107
- pi.registerProvider(id, { api, streamSimple: routedStream(getApiProvider(api).streamSimple, route) });
110
+ pi.registerProvider(id, { api, streamSimple: modelRoutes.wrap(id, getApiProvider(api).streamSimple) });
108
111
  }
109
112
  installed.add(id);
110
113
  }
@@ -128,19 +131,37 @@ export default function providerProxy(pi) {
128
131
  }
129
132
  }
130
133
  }
131
- pi.on('model_select', (event, ctx) => selectProvider(event.model?.provider, ctx));
134
+ const prepared = new WeakSet();
135
+ let releaseEarlyListener;
136
+ function prepareModel(event, ctx) {
137
+ if (prepared.has(event)) return;
138
+ selectProvider((event.type === 'model_select' ? event.model : ctx.model)?.provider, ctx);
139
+ prepared.add(event);
140
+ }
141
+ function configureEarlyListener() {
142
+ if (store?.read().followModel) {
143
+ releaseEarlyListener ??= beforeModelListeners(HostRunner.prototype, commandHandler, prepareModel);
144
+ } else {
145
+ releaseEarlyListener?.();
146
+ releaseEarlyListener = undefined;
147
+ }
148
+ }
149
+ pi.on('model_select', prepareModel);
132
150
  pi.on('before_agent_start', (_event, ctx) => selectProvider(ctx.model?.provider, ctx));
133
151
  pi.on('session_shutdown', () => {
152
+ releaseEarlyListener?.();
153
+ releaseEarlyListener = undefined;
134
154
  activeProvider = undefined;
155
+ modelRoutes.dispose();
135
156
  sessionNetwork.dispose();
136
157
  sessionHttp.dispose();
137
158
  });
138
- pi.on('session_start', (_event, ctx) => {
139
- selectProvider(ctx.model?.provider, ctx);
159
+ pi.on('session_start', (event, ctx) => {
160
+ prepareModel(event, ctx);
140
161
  if (loadError) ctx.ui.notify(loadError.message, 'error');
141
162
  else if (blocked.size) ctx.ui.notify(`${[...blocked].join(', ')} — ${problem('STALE_BINDING').message}`, 'warning');
142
163
  });
143
- registerMenu(pi, {
164
+ const commandHandler = registerMenu(pi, {
144
165
  read: () => checked().read(),
145
166
  save: next => {
146
167
  // Register before publishing. Until save succeeds, each wrapper still reads the old snapshot.
@@ -153,12 +174,14 @@ export default function providerProxy(pi) {
153
174
  }
154
175
  }
155
176
  checked().save(next);
177
+ modelRoutes.refresh();
156
178
  for (const id of blocked) {
157
179
  if (Object.hasOwn(next.bindings, id)) continue;
158
180
  pi.unregisterProvider(id);
159
181
  installed.delete(id);
160
182
  blocked.delete(id);
161
183
  }
184
+ configureEarlyListener();
162
185
  applySessionRoute();
163
186
  },
164
187
  providers: ctx => {
@@ -172,4 +195,5 @@ export default function providerProxy(pi) {
172
195
  return probeEndpoint(model?.baseUrl, checked().route(id));
173
196
  },
174
197
  });
198
+ configureEarlyListener();
175
199
  }
@@ -10,7 +10,7 @@ export function isLoopbackHost(hostname) {
10
10
  try {
11
11
  const authority = isIP(host) === 6 ? `[${host}]` : host;
12
12
  const canonical = new URL(`http://${authority}`).hostname;
13
- return canonical === '0.0.0.0' || canonical.startsWith('127.') ||
13
+ return canonical === '0.0.0.0' || (isIP(canonical) === 4 && canonical.startsWith('127.')) ||
14
14
  canonical === '[::1]' || canonical === '[::]' || /^\[::ffff:7f[\da-f]{2}:[\da-f]{1,4}\]$/.test(canonical);
15
15
  } catch { return false; }
16
16
  }
package/src/menu.js CHANGED
@@ -133,7 +133,7 @@ async function testRoute(services, ctx, provider, language) {
133
133
  export function registerMenu(pi, services, detect = deviceLanguage) {
134
134
  const language = detect();
135
135
  const text = messages(language);
136
- pi.registerCommand('proxy', {
136
+ const command = {
137
137
  description: text.title,
138
138
  async handler(_args, ctx) {
139
139
  if (!ctx.hasUI) return;
@@ -206,5 +206,7 @@ export function registerMenu(pi, services, detect = deviceLanguage) {
206
206
  }
207
207
  }
208
208
  },
209
- });
209
+ };
210
+ pi.registerCommand('proxy', command);
211
+ return command.handler;
210
212
  }
@@ -0,0 +1,39 @@
1
+ // Pi 1.7 awaits extension listeners in install order. These two events need
2
+ // the model's route before *any* listener can issue or await its first request.
3
+ // Match on the owning command function (unique per factory/session), using the
4
+ // host-exported runner so this also works with Pi's bundled CLI.
5
+ const bridgeKey = Symbol.for('@zllf/pi-provider-proxy.model-events.v1');
6
+
7
+ function installBridge(prototype) {
8
+ const original = prototype.emit;
9
+ const owners = new WeakMap();
10
+ const bridge = { owners, count: 0, dispose };
11
+ function emit(event, ...args) {
12
+ if (event.type === 'session_start' || event.type === 'model_select') {
13
+ const command = this.getCommand('proxy');
14
+ // Pi namespaces commands with duplicate names, e.g. /proxy:1.
15
+ const commands = command ? [command] : this.getRegisteredCommands().filter(c => c.name === 'proxy');
16
+ for (const { handler } of commands) {
17
+ const prepare = owners.get(handler);
18
+ if (prepare) prepare(event, this.createContext());
19
+ }
20
+ }
21
+ return original.call(this, event, ...args);
22
+ }
23
+ function dispose() {
24
+ if (bridge.count === 0 && prototype.emit === emit) prototype.emit = original;
25
+ }
26
+ Object.defineProperty(emit, bridgeKey, { value: bridge });
27
+ prototype.emit = emit;
28
+ return bridge;
29
+ }
30
+
31
+ export function beforeModelListeners(prototype, commandHandler, prepare) {
32
+ const bridge = prototype.emit[bridgeKey] ?? installBridge(prototype);
33
+ bridge.owners.set(commandHandler, prepare);
34
+ bridge.count++;
35
+ return () => {
36
+ if (bridge.owners.delete(commandHandler)) bridge.count--;
37
+ bridge.dispose();
38
+ };
39
+ }
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
- // Each logical stream owns its connections through retries and body consumption.
5
- // Editing/deleting a profile can therefore never disrupt an existing stream.
6
- export function routedStream(delegate, getRoute) {
7
- return (model, transcript, options) => {
8
- const route = getRoute();
9
- if (route === undefined) return delegate(model, transcript, options);
10
- const transport = createTransport(route);
11
- try {
12
- const stream = delegate(model, transcript, {
13
- ...options, fetch: transport.fetch,
14
- ...(model.api === 'openai-codex-responses' ? { transport: 'sse' } : {}),
15
- });
16
- const retire = () => transport.close().catch(() => {});
17
- stream.result().then(retire, retire);
18
- return stream;
19
- } catch (error) {
20
- void transport.close().catch(() => {});
21
- throw error;
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, {
@@ -5,7 +5,7 @@ import { isIP } from 'node:net';
5
5
  import { buildConnector, Client } from 'undici';
6
6
  import { SocksClient } from 'socks';
7
7
  import { isLoopbackHost } from './local-target.js';
8
- import { validateProxyUrl } from './transport.js';
8
+ import { SOCKS_HANDSHAKE_TIMEOUT_MS, validateProxyUrl } from './transport.js';
9
9
 
10
10
  const handshakeTimeout = 10_000;
11
11
 
@@ -49,7 +49,7 @@ function socksTunnel(url) {
49
49
  }
50
50
  if (Buffer.byteLength(host) > 255) throw new Error('SOCKS destination name is too long.');
51
51
  const { socket } = await SocksClient.createConnection({
52
- command: 'connect', proxy, destination: { host, port: Number(port) }, timeout: handshakeTimeout,
52
+ command: 'connect', proxy, destination: { host, port: Number(port) }, timeout: SOCKS_HANDSHAKE_TIMEOUT_MS,
53
53
  });
54
54
  return socket;
55
55
  };
@@ -16,6 +16,12 @@ function rejectDispatch(handler, error) {
16
16
  return false;
17
17
  }
18
18
 
19
+ function dispatchRoute(route, options, handler) {
20
+ if (route.error) return rejectDispatch(handler, route.error);
21
+ // Our pinned 7.30 dispatcher accepts both legacy and modern handlers.
22
+ return route.dispatcher.dispatch(options, handler);
23
+ }
24
+
19
25
  class SessionDispatcher extends Dispatcher {
20
26
  #original;
21
27
  #adapt;
@@ -33,26 +39,46 @@ class SessionDispatcher extends Dispatcher {
33
39
 
34
40
  dispatch(options, handler) {
35
41
  const route = this.#state.route;
36
- // A reference captured while enabled can still be used after unhooking.
37
- if (!route || isLoopbackHost(new URL(options.origin).hostname)) {
38
- return this.#original.dispatch(options, this.#adapt(handler));
39
- }
40
- if (route.error) return rejectDispatch(handler, route.error);
41
- // Our pinned 7.30 dispatcher accepts both legacy and modern handlers.
42
- return route.dispatcher.dispatch(options, handler);
42
+ if (route && !isLoopbackHost(new URL(options.origin).hostname)) return dispatchRoute(route, options, handler);
43
+ return this.#original.dispatch(options, this.#adapt(handler));
43
44
  }
44
45
  }
45
46
 
46
47
  function restore(hooks) {
47
- for (const { key, descriptor, installed } of hooks) {
48
- if (globalThis[key] !== installed) continue;
49
- if (descriptor) Object.defineProperty(globalThis, key, descriptor);
50
- else delete globalThis[key];
48
+ for (const { target, key, descriptor, installed } of hooks) {
49
+ if (Object.getOwnPropertyDescriptor(target, key)?.value !== installed) continue;
50
+ if (descriptor) Object.defineProperty(target, key, descriptor);
51
+ else delete target[key];
52
+ }
53
+ }
54
+
55
+ // Pi 1.7 replaces BOTH non-configurable data slots after session_start and on
56
+ // idle-timeout changes. Its .1 adapter calls .2.dispatch on the host agent.
57
+ // Take the prototype from the running host (Pi can have its own Undici copy).
58
+ // Shadow dispatch on that class only, and delegate every other instance.
59
+ function installPiDispatcher(state, host, adapter) {
60
+ const target = host && Object.getPrototypeOf(host);
61
+ const adapterType = adapter && Object.getPrototypeOf(adapter)?.constructor;
62
+ // Pi 1.7's CLI bundle emits EnvHttpProxyAgent2 and _Dispatcher1Wrapper.
63
+ if (!/^EnvHttpProxyAgent\d*$/.test(target?.constructor?.name) || !/^_?Dispatcher1Wrapper\d*$/.test(adapterType?.name)) return;
64
+ // Only shadow the inherited method on a stock, extensible class prototype.
65
+ // Respect instance/class overrides and fall back to the slot facades there.
66
+ if (Object.hasOwn(host, 'dispatch') || Object.hasOwn(target, 'dispatch') || !Object.isExtensible(target)) return;
67
+ const dispatch = target.dispatch;
68
+ function installed(options, handler) {
69
+ if (this === globalThis[modern] && state.route && !isLoopbackHost(new URL(options.origin).hostname)) {
70
+ return dispatchRoute(state.route, options, handler);
71
+ }
72
+ return dispatch.call(this, options, handler);
51
73
  }
74
+ Object.defineProperty(target, 'dispatch', { configurable: true, writable: true, value: installed });
75
+ return { target, key: 'dispatch', installed };
52
76
  }
53
77
 
54
78
  function install(state) {
55
79
  const previous = { [legacy]: globalThis[legacy], [modern]: globalThis[modern] };
80
+ const piHook = installPiDispatcher(state, previous[modern], previous[legacy]);
81
+ if (piHook) return [piHook];
56
82
  const hooks = [];
57
83
  try {
58
84
  for (const key of [legacy, modern]) {
@@ -68,7 +94,7 @@ function install(state) {
68
94
  Object.defineProperty(globalThis, key, descriptor ? { value: installed } : {
69
95
  value: installed, configurable: true, writable: true,
70
96
  });
71
- hooks.push({ key, descriptor, installed });
97
+ hooks.push({ target: globalThis, key, descriptor, installed });
72
98
  }
73
99
  return hooks;
74
100
  } catch (error) {
package/src/transport.js CHANGED
@@ -4,6 +4,10 @@ import { domainToASCII } from 'node:url';
4
4
  import { Agent, Pool, ProxyAgent, Request as UndiciRequest, buildConnector, fetch as dispatchFetch } from 'undici';
5
5
  import { SocksClient } from 'socks';
6
6
 
7
+ export const SOCKS_HANDSHAKE_TIMEOUT_MS = 20_000;
8
+ const modelPoolOptions = { connections: 4, keepAliveTimeout: 90_000, keepAliveMaxTimeout: 90_000 };
9
+ const earlyResetWindowMs = 5_000;
10
+
7
11
  function invalidProxy() {
8
12
  return new TypeError('Invalid proxy URL (expected an HTTP, HTTPS, SOCKS5, or SOCKS5H proxy authority).');
9
13
  }
@@ -41,7 +45,7 @@ function socksFailure(error) {
41
45
  return Object.assign(new Error('SOCKS proxy connection failed.'), { code });
42
46
  }
43
47
 
44
- function socksAgent(url, retryHandshake) {
48
+ function socksAgent(url, retrySocksHandshake, modelPool) {
45
49
  const proxy = {
46
50
  type: 5,
47
51
  host: url.hostname.replace(/^\[|\]$/g, ''),
@@ -58,34 +62,46 @@ function socksAgent(url, retryHandshake) {
58
62
  const secured = protocol === 'https:';
59
63
  const options = {
60
64
  command: 'connect', proxy, destination: { host, port: Number(port || (secured ? 443 : 80)) },
61
- timeout: 10_000, set_tcp_nodelay: true,
65
+ timeout: SOCKS_HANDSHAKE_TIMEOUT_MS, set_tcp_nodelay: true,
62
66
  };
63
- for (let attempt = 0; ; attempt++) {
64
- try {
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
- }
67
+ try { return (await SocksClient.createConnection(options)).socket; }
68
+ catch (error) { throw socksFailure(error); }
69
+ }
70
+
71
+ async function connectOnce(options) {
72
+ const socket = await tunnel(options);
73
+ if (options.protocol !== 'https:') return socket;
74
+ try {
75
+ // Use the original hostname for SNI and certificate checks after local DNS resolution.
76
+ return await new Promise((resolve, reject) => tlsConnect({ ...options, httpSocket: socket },
77
+ (error, secured) => error ? reject(error) : resolve(secured)));
78
+ } catch (error) { socket.destroy(); throw error; }
79
+ }
80
+
81
+ async function connect(options) {
82
+ const start = performance.now();
83
+ try { return await connectOnce(options); }
84
+ catch (error) {
85
+ const retryOAuth = retrySocksHandshake && ['SOCKS_TIMEOUT', 'SOCKS_RESET'].includes(error.code);
86
+ const earlyModelReset = modelPool && performance.now() - start <= earlyResetWindowMs &&
87
+ ['SOCKS_RESET', 'ECONNRESET'].includes(error.code);
88
+ if (!retryOAuth && !earlyModelReset) throw error;
89
+ // Undici receives a socket only after connect resolves. No HTTP bytes have been sent.
90
+ return connectOnce(options);
71
91
  }
72
92
  }
73
93
 
74
94
  return new Agent({
75
- connect(options, callback) {
76
- tunnel(options).then(socket => {
77
- if (options.protocol !== 'https:') return callback(null, socket);
78
- // Verify against the original destination hostname, even after local DNS lookup.
79
- tlsConnect({ ...options, httpSocket: socket }, callback);
80
- }, callback);
81
- },
95
+ ...(modelPool && modelPoolOptions),
96
+ connect(options, callback) { connect(options).then(socket => callback(null, socket), callback); },
82
97
  });
83
98
  }
84
99
 
85
- export function createRouteDispatcher(route, retryHandshake = false) {
86
- if (route === 'direct') return new Agent({ connect: { rejectUnauthorized: true } });
100
+ export function createRouteDispatcher(route, retryHandshake = false, modelPool = false) {
101
+ const poolOptions = modelPool ? modelPoolOptions : {};
102
+ if (route === 'direct') return new Agent({ ...poolOptions, connect: { rejectUnauthorized: true } });
87
103
  const url = new URL(validateProxyUrl(route));
88
- if (url.protocol.startsWith('socks')) return socksAgent(url, retryHandshake);
104
+ if (url.protocol.startsWith('socks')) return socksAgent(url, retryHandshake, modelPool);
89
105
 
90
106
  let token;
91
107
  if (url.username || url.password) {
@@ -93,6 +109,7 @@ export function createRouteDispatcher(route, retryHandshake = false) {
93
109
  token = `Basic ${Buffer.from(basic).toString('base64')}`;
94
110
  }
95
111
  return new ProxyAgent({
112
+ ...poolOptions,
96
113
  uri: url.origin, token, proxyTunnel: true,
97
114
  // ProxyAgent passes even an IP literal as SNI. Let the connector derive SNI
98
115
  // from the proxy host, omitting it for IPs while TLS still verifies their SAN.
@@ -104,8 +121,8 @@ export function createRouteDispatcher(route, retryHandshake = false) {
104
121
  }
105
122
 
106
123
  /** Owns one dispatcher. Call close() on retirement to terminate outstanding requests. */
107
- export function createTransport(route, { retrySocksHandshake = false } = {}) {
108
- const dispatcher = createRouteDispatcher(route, retrySocksHandshake);
124
+ export function createTransport(route, { retrySocksHandshake = false, modelPool = false } = {}) {
125
+ const dispatcher = createRouteDispatcher(route, retrySocksHandshake, modelPool);
109
126
  let closing;
110
127
  return {
111
128
  async fetch(input, init) {