@evandu/super-pi 0.1.198 → 0.1.200

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.
@@ -0,0 +1 @@
1
+ export function npmInstallPrefix(rootDir: string, platform?: string): string | undefined;
@@ -0,0 +1,10 @@
1
+ /** Infer npm's global prefix from this package's installation root, not its node_modules parent. */
2
+ export function npmInstallPrefix(rootDir, platform = process.platform) {
3
+ const match = rootDir.match(/^(.*)[\\/]node_modules[\\/]@evandu[\\/]super-pi[\\/]?$/i);
4
+ if (!match) return undefined;
5
+ const parent = match[1];
6
+ // Unix global packages live in <prefix>/lib/node_modules; Windows omits lib.
7
+ // Passing the Unix lib directory as --prefix would install into lib/lib/node_modules.
8
+ if (platform !== "win32" && /[\\/]lib$/.test(parent)) return parent.slice(0, -4) || "/";
9
+ return parent;
10
+ }
package/bin/super-pi.js CHANGED
@@ -6,12 +6,13 @@ import { homedir } from "node:os";
6
6
  import { dirname, join, resolve } from "node:path";
7
7
  import { promisify } from "node:util";
8
8
  import { pathToFileURL } from "node:url";
9
+ import { npmInstallPrefix } from "./npm-prefix.js";
9
10
 
10
11
  const execFileAsync = promisify(execFile);
11
12
  const root = resolve(import.meta.dirname, "..");
12
13
  const entry = resolve(root, "dist/server/index.js");
13
- const prefix = root.match(/^(.*)[\\/]node_modules[\\/]/i)?.[1];
14
14
  const platform = process.env.SUPER_PI_AUTOSTART_PLATFORM ?? process.platform;
15
+ const prefix = npmInstallPrefix(root, platform);
15
16
  const home = process.env.SUPER_PI_AUTOSTART_HOME ?? homedir();
16
17
 
17
18
  /**
@@ -40,5 +40,5 @@
40
40
  "src/client/types.ts": "0d32fd568f188507ce2b48266f44fa20da1bcf436090893b1ff0c164ed0f3132",
41
41
  "src/client/vite-env.d.ts": "65996936fbb042915f7b74a200fcdde7e410f32a669b1ab9597cfaa4b0faddb5"
42
42
  },
43
- "recordedAt": "2026-11-12T14:53:27.683Z"
43
+ "recordedAt": "2026-11-12T16:26:03.231Z"
44
44
  }
@@ -81,7 +81,7 @@ interface PiSdk {
81
81
  findById(cwd: string, id: string, sessionDir?: string): string | undefined;
82
82
  };
83
83
  ModelRuntime: {
84
- create(): Promise<{
84
+ create(options?: Record<string, unknown>): Promise<{
85
85
  getModel?: (provider: string, modelId: string) => unknown;
86
86
  getAvailable?: () => Promise<unknown[]>;
87
87
  getModels?: () => unknown[];
@@ -92,6 +92,9 @@ interface PiSdk {
92
92
  getError?: () => string | undefined;
93
93
  }>;
94
94
  };
95
+ AuthStorage?: {
96
+ create(path?: string): object;
97
+ };
95
98
  SettingsManager: {
96
99
  create(cwd: string, agentDir: string): {
97
100
  getDefaultProvider?: () => string | undefined;
@@ -28,7 +28,7 @@ import { open, readdir } from "node:fs/promises";
28
28
  import { StringDecoder } from "node:string_decoder";
29
29
  import { dirname, join, resolve } from "node:path";
30
30
  import { createModelResolver } from "./model-context-window.js";
31
- import { installProviderProxy } from "./provider-proxy.js";
31
+ import { installProviderProxy, proxyCredentialStore } from "./provider-proxy.js";
32
32
  import { fileURLToPath, pathToFileURL } from "node:url";
33
33
  const traceSession = (conversationId, phase, startedAt, extra = "") => {
34
34
  if (process.env.SUPER_PI_TRACE_LATENCY !== "1")
@@ -65,7 +65,12 @@ async function loadSdk() {
65
65
  // before anything can report the real reason. The name is written out in full here so a reader
66
66
  // can see exactly which package is being loaded.
67
67
  const specifier = ["@earendil-works", "pi-coding-agent"].join("/");
68
- sdkPromise = import(/* @vite-ignore */ specifier).then((mod) => mod, (error) => {
68
+ sdkPromise = import(/* @vite-ignore */ specifier).then(async (mod) => {
69
+ // Pi 0.86.1 accepts a CredentialStore but exports its file-store constructor only from core.
70
+ const storageUrl = new URL("./core/auth-storage.js", import.meta.resolve(specifier)).href;
71
+ const storage = await import(/* @vite-ignore */ storageUrl);
72
+ return { ...mod, AuthStorage: storage.AuthStorage };
73
+ }, (error) => {
69
74
  const reason = error instanceof Error ? error.message : String(error);
70
75
  sdkFailure = `Super Pi could not load Pi's SDK (@earendil-works/pi-coding-agent): ${reason}. Reinstall Super Pi (npm i -g @evandu/super-pi) so that Pi comes with it, or install it next to Super Pi with \`npm install @earendil-works/pi-coding-agent\`.`;
71
76
  throw new Error(sdkFailure);
@@ -88,7 +93,9 @@ async function loadSdk() {
88
93
  export async function createSdkCatalog(cwd) {
89
94
  const sdk = await loadSdk();
90
95
  const agentDir = defaultAgentDir();
91
- const modelRuntime = await sdk.ModelRuntime.create();
96
+ const credentials = sdk.AuthStorage ? proxyCredentialStore(sdk.AuthStorage.create(join(agentDir, "auth.json"))) : undefined;
97
+ const modelRuntime = await sdk.ModelRuntime.create(credentials ? { credentials } : undefined);
98
+ await installProviderProxy(modelRuntime, agentDir);
92
99
  const settingsManager = sdk.SettingsManager.create(cwd, agentDir);
93
100
  const models = (await modelRuntime.getAvailable?.()) ?? modelRuntime.getModels?.() ?? [];
94
101
  const levelsByModel = new Map();
@@ -291,8 +298,9 @@ export async function createPiSession(creation) {
291
298
  ? sdk.SessionManager.inMemory(creation.cwd, { id: creation.sessionId })
292
299
  : await resolveSessionManager(sdk, creation);
293
300
  traceSession(creation.sessionId, "sdk.transcript.ready", startedAt, `bytes=${transcriptBytes(sessionManager)}`);
294
- const modelRuntime = await sdk.ModelRuntime.create();
295
- installProviderProxy(modelRuntime);
301
+ const credentials = sdk.AuthStorage ? proxyCredentialStore(sdk.AuthStorage.create(join(agentDir, "auth.json"))) : undefined;
302
+ const modelRuntime = await sdk.ModelRuntime.create(credentials ? { credentials } : undefined);
303
+ await installProviderProxy(modelRuntime, agentDir);
296
304
  traceSession(creation.sessionId, "sdk.model-runtime", startedAt);
297
305
  // THE MODEL IS RESOLVED, NOT PASSED THROUGH. Pi's SDK takes a whole Model object - the provider's
298
306
  // configuration, the endpoint, the capability list - and Super Pi only knows the pair
@@ -2,7 +2,9 @@
2
2
  export declare function readProviderProxyEnv(agentDir: string, providerId?: string): Promise<Record<string, string>>;
3
3
  type Env = Record<string, string | undefined>;
4
4
  /** Apply scoped proxy values without changing the server's process environment. */
5
- export declare function providerProxyFetch(env: Env | undefined): typeof fetch | undefined;
6
- /** Pi's SDK accepts a fetch per request, but its OpenAI adapters do not use env proxies themselves. */
7
- export declare function installProviderProxy(runtime: unknown): void;
5
+ export declare function providerProxyFetch(env: Env | undefined, baseFetch?: typeof fetch): typeof fetch | undefined;
6
+ /** Keep Pi's own cross-process credential lock, and preserve scoped env on OAuth rotation/login. */
7
+ export declare function proxyCredentialStore<T extends object>(store: T): T;
8
+ /** Read provider routing independently of Pi's auth result: OAuth resolution omits credential.env. */
9
+ export declare function installProviderProxy(runtime: unknown, agentDir?: string): Promise<void>;
8
10
  export {};
@@ -1,6 +1,7 @@
1
1
  import { EnvHttpProxyAgent } from "undici";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
+ import { AsyncLocalStorage } from "node:async_hooks";
4
5
  /** Read only proxy keys; provider secrets must never become child process environment variables. */
5
6
  export async function readProviderProxyEnv(agentDir, providerId) {
6
7
  const read = async (file) => {
@@ -29,7 +30,7 @@ export async function readProviderProxyEnv(agentDir, providerId) {
29
30
  }
30
31
  const agents = new Map();
31
32
  /** Apply scoped proxy values without changing the server's process environment. */
32
- export function providerProxyFetch(env) {
33
+ export function providerProxyFetch(env, baseFetch = globalThis.fetch) {
33
34
  if (!env || !["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"].some(key => env[key] !== undefined))
34
35
  return undefined;
35
36
  const value = (key) => env[key.toLowerCase()] ?? env[key] ?? process.env[key.toLowerCase()] ?? process.env[key];
@@ -61,13 +62,87 @@ export function providerProxyFetch(env) {
61
62
  }
62
63
  agents.set(key, agent);
63
64
  }
64
- return (input, init) => globalThis.fetch(input, { ...init, dispatcher: agent });
65
+ return (input, init) => baseFetch(input, { ...init, dispatcher: agent });
65
66
  }
66
- /** Pi's SDK accepts a fetch per request, but its OpenAI adapters do not use env proxies themselves. */
67
- export function installProviderProxy(runtime) {
67
+ const authFetchScope = new AsyncLocalStorage();
68
+ let scopedFetch;
69
+ let baseAuthFetch;
70
+ /** OAuth adapters call global fetch. Route only the current async auth operation through its proxy. */
71
+ async function withAuthProxy(env, operation, providerId) {
72
+ const active = authFetchScope.getStore();
73
+ env = mergeEnv(env, providerId && active?.providerId === providerId ? active.env : undefined);
74
+ if (!Object.keys(env).some(key => /^(http_proxy|https_proxy|all_proxy|no_proxy)$/i.test(key))) {
75
+ if (active && providerId && active.providerId !== providerId)
76
+ return authFetchScope.run({ fetch: baseAuthFetch, providerId, env }, operation);
77
+ return operation();
78
+ }
79
+ if (globalThis.fetch !== scopedFetch) {
80
+ const original = globalThis.fetch;
81
+ baseAuthFetch = original;
82
+ scopedFetch = (input, init) => (authFetchScope.getStore()?.fetch ?? original)(input, init);
83
+ globalThis.fetch = scopedFetch;
84
+ }
85
+ const requestFetch = providerProxyFetch(env, baseAuthFetch);
86
+ return authFetchScope.run({ fetch: requestFetch, providerId, env }, operation);
87
+ }
88
+ function mergeEnv(...layers) {
89
+ const merged = {};
90
+ for (const layer of layers) {
91
+ Object.assign(merged, layer);
92
+ for (const key of ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY"]) {
93
+ const value = layer?.[key.toLowerCase()] ?? layer?.[key];
94
+ if (value !== undefined)
95
+ merged[key] = merged[key.toLowerCase()] = value;
96
+ }
97
+ }
98
+ return merged;
99
+ }
100
+ /** Keep Pi's own cross-process credential lock, and preserve scoped env on OAuth rotation/login. */
101
+ export function proxyCredentialStore(store) {
102
+ return new Proxy(store, {
103
+ get(target, property) {
104
+ const value = Reflect.get(target, property);
105
+ if (property === "modify" && typeof value === "function") {
106
+ return (providerId, modify, options) => value.call(target, providerId, (current) => withAuthProxy(current?.env, async () => {
107
+ const next = await modify(current);
108
+ if (next?.type === "oauth" && current?.env)
109
+ return { ...next, env: { ...current.env, ...next.env } };
110
+ return next;
111
+ }, providerId), options);
112
+ }
113
+ return typeof value === "function" ? value.bind(target) : value;
114
+ },
115
+ });
116
+ }
117
+ /** Read provider routing independently of Pi's auth result: OAuth resolution omits credential.env. */
118
+ export async function installProviderProxy(runtime, agentDir) {
68
119
  const target = runtime;
69
120
  if (typeof target.getAuth !== "function")
70
121
  return;
122
+ let stored = {};
123
+ if (agentDir) {
124
+ try {
125
+ stored = JSON.parse(await readFile(join(agentDir, "auth.json"), "utf8"));
126
+ }
127
+ catch (error) {
128
+ if (error.code !== "ENOENT")
129
+ throw error;
130
+ }
131
+ }
132
+ const providerEnv = (model) => stored[typeof model === "string" ? model : model?.provider ?? ""]?.env;
133
+ const getAuth = target.getAuth.bind(target);
134
+ target.getAuth = (model, options) => {
135
+ const env = mergeEnv(providerEnv(model), options?.env);
136
+ return withAuthProxy(env, async () => {
137
+ const auth = await getAuth(model, Object.keys(env).length ? { ...options, env } : options);
138
+ const resolvedEnv = mergeEnv(providerEnv(model), auth?.env, options?.env);
139
+ return auth && Object.keys(resolvedEnv).length ? { ...auth, env: resolvedEnv } : auth;
140
+ }, typeof model === "string" ? model : model?.provider);
141
+ };
142
+ const login = target.login;
143
+ if (typeof login === "function") {
144
+ target.login = (providerId, ...args) => withAuthProxy(providerEnv(providerId), () => login.call(target, providerId, ...args), providerId);
145
+ }
71
146
  for (const method of ["stream", "streamSimple", "streamDeferred"]) {
72
147
  const original = target[method];
73
148
  if (typeof original !== "function")
@@ -76,13 +151,23 @@ export function installProviderProxy(runtime) {
76
151
  // These SDK adapters reject injected fetch implementations; preserve their native transport.
77
152
  if (["bedrock-converse-stream", "google-generative-ai", "google-vertex"].includes(model?.api ?? ""))
78
153
  return original.call(target, model, context, options);
154
+ const env = mergeEnv(providerEnv(model), options?.env);
155
+ const routed = { ...options, ...(Object.keys(env).length ? { env } : {}) };
156
+ const hasProxy = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"].some(key => env[key]);
157
+ if (model?.api === "openai-codex-responses" && hasProxy && env.NO_PROXY !== "*") {
158
+ if (options?.transport && !["auto", "sse"].includes(options.transport))
159
+ throw new Error("Codex 配置代理时当前仅支持 SSE 传输,请将 transport 设为 sse 或 auto");
160
+ routed.transport = "sse";
161
+ }
79
162
  if (options?.fetch)
80
- return original.call(target, model, context, options);
163
+ return original.call(target, model, context, routed);
81
164
  const requestFetch = async (input, init) => {
82
- const auth = await target.getAuth(model);
83
- return (providerProxyFetch(auth?.env) ?? globalThis.fetch)(input, init);
165
+ const auth = await target.getAuth(model, { env });
166
+ // Provider requests select their own routing, even when launched inside another auth callback.
167
+ const transport = globalThis.fetch === scopedFetch ? baseAuthFetch : globalThis.fetch;
168
+ return (providerProxyFetch(mergeEnv(auth?.env, env), transport) ?? transport)(input, init);
84
169
  };
85
- return original.call(target, model, context, { ...options, fetch: requestFetch });
170
+ return original.call(target, model, context, { ...routed, fetch: requestFetch });
86
171
  };
87
172
  }
88
173
  }
@@ -33,7 +33,7 @@ export declare function shellArgs(args: string[]): string[];
33
33
  * The fetch options are there because the tarball is ~32 MB: npm's default
34
34
  * 5 minute timeout fails on a slow line and the update looks broken.
35
35
  */
36
- export declare function packageUpdateArgs(rootDir: string, version?: string): {
36
+ export declare function packageUpdateArgs(rootDir: string, version?: string, platform?: NodeJS.Platform): {
37
37
  args: string[];
38
38
  prefix?: string;
39
39
  };
@@ -1,4 +1,4 @@
1
- import { sep } from "node:path";
1
+ import { npmInstallPrefix } from "../../bin/npm-prefix.js";
2
2
  /**
3
3
  * Quote an argument for a shell on Windows.
4
4
  *
@@ -38,16 +38,13 @@ export function shellArgs(args) {
38
38
  * The fetch options are there because the tarball is ~32 MB: npm's default
39
39
  * 5 minute timeout fails on a slow line and the update looks broken.
40
40
  */
41
- export function packageUpdateArgs(rootDir, version) {
42
- const marker = `${sep}node_modules${sep}`;
43
- const lower = rootDir.toLowerCase();
44
- const index = lower.lastIndexOf(marker);
41
+ export function packageUpdateArgs(rootDir, version, platform = process.platform) {
42
+ const prefix = npmInstallPrefix(rootDir, platform);
45
43
  // THE VERSION THE USER CONFIRMED. The check reads the registry directly while npm resolves
46
44
  // "latest" from its own cache, so the two can disagree: the dialog promises vX and the
47
45
  // install silently lands on vY. Pinning the version the dialog showed removes that gap.
48
46
  const target = version ? `@evandu/super-pi@${version}` : "@evandu/super-pi";
49
- if (index >= 0) {
50
- const prefix = rootDir.slice(0, index);
47
+ if (prefix !== undefined) {
51
48
  return { prefix, args: ["install", "-g", "--prefix", prefix, "--fetch-timeout=900000", "--fetch-retries=8", "--fetch-retry-maxtimeout=120000", target] };
52
49
  }
53
50
  return { args: ["install", "-g", "--fetch-timeout=900000", "--fetch-retries=8", "--fetch-retry-maxtimeout=120000", target] };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evandu/super-pi",
3
- "version": "0.1.198",
3
+ "version": "0.1.200",
4
4
  "description": "Web control plane and companion for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -195,6 +195,7 @@
195
195
  "scripts/settings-default-model.test.mjs",
196
196
  "scripts/provider-registry.test.mjs",
197
197
  "scripts/provider-pi-reads.test.mjs",
198
+ "scripts/provider-oauth-proxy.test.mjs",
198
199
  "scripts/session-extension-credentials.test.mjs",
199
200
  "scripts/active-memory.test.mjs",
200
201
  "scripts/layered-memory.test.mjs",