@zllf/pi-provider-proxy 0.2.0 → 0.2.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 CHANGED
@@ -14,7 +14,7 @@ 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.1` 固定 GitHub 版本。要求 Node.js 22.19 或更高版本,已在 Pi 1.7.0 验证。
18
18
 
19
19
  ## 配置代理
20
20
 
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.1",
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": {
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,12 +2,13 @@ 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 { beforeModelListeners } from './model-events.js';
11
12
  import { probeEndpoint, routedStream } from './routing.js';
12
13
 
13
14
  const nativeIds = new Set(['openai-codex', 'anthropic', 'openai', 'deepseek', 'openrouter']);
@@ -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);
@@ -128,19 +129,36 @@ export default function providerProxy(pi) {
128
129
  }
129
130
  }
130
131
  }
131
- pi.on('model_select', (event, ctx) => selectProvider(event.model?.provider, ctx));
132
+ const prepared = new WeakSet();
133
+ let releaseEarlyListener;
134
+ function prepareModel(event, ctx) {
135
+ if (prepared.has(event)) return;
136
+ selectProvider((event.type === 'model_select' ? event.model : ctx.model)?.provider, ctx);
137
+ prepared.add(event);
138
+ }
139
+ function configureEarlyListener() {
140
+ if (store?.read().followModel) {
141
+ releaseEarlyListener ??= beforeModelListeners(HostRunner.prototype, commandHandler, prepareModel);
142
+ } else {
143
+ releaseEarlyListener?.();
144
+ releaseEarlyListener = undefined;
145
+ }
146
+ }
147
+ pi.on('model_select', prepareModel);
132
148
  pi.on('before_agent_start', (_event, ctx) => selectProvider(ctx.model?.provider, ctx));
133
149
  pi.on('session_shutdown', () => {
150
+ releaseEarlyListener?.();
151
+ releaseEarlyListener = undefined;
134
152
  activeProvider = undefined;
135
153
  sessionNetwork.dispose();
136
154
  sessionHttp.dispose();
137
155
  });
138
- pi.on('session_start', (_event, ctx) => {
139
- selectProvider(ctx.model?.provider, ctx);
156
+ pi.on('session_start', (event, ctx) => {
157
+ prepareModel(event, ctx);
140
158
  if (loadError) ctx.ui.notify(loadError.message, 'error');
141
159
  else if (blocked.size) ctx.ui.notify(`${[...blocked].join(', ')} — ${problem('STALE_BINDING').message}`, 'warning');
142
160
  });
143
- registerMenu(pi, {
161
+ const commandHandler = registerMenu(pi, {
144
162
  read: () => checked().read(),
145
163
  save: next => {
146
164
  // Register before publishing. Until save succeeds, each wrapper still reads the old snapshot.
@@ -159,6 +177,7 @@ export default function providerProxy(pi) {
159
177
  installed.delete(id);
160
178
  blocked.delete(id);
161
179
  }
180
+ configureEarlyListener();
162
181
  applySessionRoute();
163
182
  },
164
183
  providers: ctx => {
@@ -172,4 +191,5 @@ export default function providerProxy(pi) {
172
191
  return probeEndpoint(model?.baseUrl, checked().route(id));
173
192
  },
174
193
  });
194
+ configureEarlyListener();
175
195
  }
@@ -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
+ }
@@ -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) {