@evandu/super-pi 0.1.199 → 0.1.201

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.
Files changed (38) hide show
  1. package/agents/super-pi-task/core.ts +1 -0
  2. package/dist/client/.super-pi-client-sources.json +7 -6
  3. package/dist/client/assets/{CodeMirrorEditor-U3KDceIT.js → CodeMirrorEditor-vxQIyy7b.js} +2 -2
  4. package/dist/client/assets/{dist-B3Mq2G-v.js → dist-4SH20Tbv.js} +1 -1
  5. package/dist/client/assets/{dist-CHT_b-1Q.js → dist-B-IVJoQx.js} +1 -1
  6. package/dist/client/assets/{dist-D7SBQneC.js → dist-B131Snro.js} +1 -1
  7. package/dist/client/assets/{dist-CAbji9OL.js → dist-B9Xymme_.js} +1 -1
  8. package/dist/client/assets/{dist-IDDdx_gZ.js → dist-BA_txYZC.js} +1 -1
  9. package/dist/client/assets/{dist-BZvAhJP1.js → dist-BBL_GRBs.js} +1 -1
  10. package/dist/client/assets/{dist-DhbOXLqT.js → dist-BOiDpbIK.js} +1 -1
  11. package/dist/client/assets/{dist-D4HLkTu7.js → dist-B_slddW0.js} +1 -1
  12. package/dist/client/assets/{dist-C8rmoSBN.js → dist-C6WoehaJ.js} +1 -1
  13. package/dist/client/assets/{dist-BVe_Uv1h.js → dist-C6vEFxfz.js} +1 -1
  14. package/dist/client/assets/{dist-BRsrFxrS.js → dist-CPrZlJdM.js} +1 -1
  15. package/dist/client/assets/{dist-BvsEwUNz.js → dist-D9xg8iqu.js} +1 -1
  16. package/dist/client/assets/{dist-BPxhWZry.js → dist-DAYkQ0P3.js} +1 -1
  17. package/dist/client/assets/{dist-CnxhfY0a.js → dist-DDjw1OJ2.js} +1 -1
  18. package/dist/client/assets/{dist-CcQPELVv.js → dist-DEKddEF2.js} +1 -1
  19. package/dist/client/assets/{dist-BNPrsqKa.js → dist-DEROl11F.js} +1 -1
  20. package/dist/client/assets/{dist-ZcXCK1RB.js → dist-DRZYzTGl.js} +1 -1
  21. package/dist/client/assets/{dist-Dikq_PJ3.js → dist-Dbqc2GHg.js} +1 -1
  22. package/dist/client/assets/{dist-CGNj_nWe.js → dist-DcgxyyHo.js} +1 -1
  23. package/dist/client/assets/{dist-e4yYl6NS.js → dist-DqP_0JTb.js} +1 -1
  24. package/dist/client/assets/{dist-McDiPyAf.js → dist-IjAxSRZT.js} +1 -1
  25. package/dist/client/assets/{dist-CBJ6RIS3.js → dist-p340hSe4.js} +1 -1
  26. package/dist/client/assets/{index-BXQjUHV_.css → index-Df8Zo6Xu.css} +1 -1
  27. package/dist/client/assets/{index-B2DCZtoX.js → index-fsBZreVZ.js} +42 -42
  28. package/dist/client/index.html +2 -2
  29. package/dist/server/http-server.js +49 -0
  30. package/dist/server/message-media.d.ts +7 -0
  31. package/dist/server/message-media.js +54 -0
  32. package/dist/server/pi-session.d.ts +4 -1
  33. package/dist/server/pi-session.js +13 -5
  34. package/dist/server/provider-proxy.d.ts +5 -3
  35. package/dist/server/provider-proxy.js +93 -8
  36. package/dist/shared/message-media.d.ts +12 -0
  37. package/dist/shared/message-media.js +27 -0
  38. package/package.json +4 -1
@@ -8,8 +8,8 @@
8
8
  <link rel="alternate icon" href="/favicon.ico" />
9
9
  <link rel="apple-touch-icon" href="/favicon.svg" />
10
10
  <title>Super Pi</title>
11
- <script type="module" crossorigin src="/assets/index-B2DCZtoX.js"></script>
12
- <link rel="stylesheet" crossorigin href="/assets/index-BXQjUHV_.css">
11
+ <script type="module" crossorigin src="/assets/index-fsBZreVZ.js"></script>
12
+ <link rel="stylesheet" crossorigin href="/assets/index-Df8Zo6Xu.css">
13
13
  </head>
14
14
  <body>
15
15
  <div id="root"></div>
@@ -26,6 +26,8 @@ import { claimUpdateSlot, getLastUpdateOutcome, isUpdateInFlight, packageUpdateA
26
26
  import { FileIndex } from "./file-index.js";
27
27
  import { ensureNameIndex, recordWorkspacePath } from "./file-name-index.js";
28
28
  import { resolveSessionCwd, sessionScopeKey, workspacePathFromSession } from "./session-cwd.js";
29
+ import { readMessageMedia } from "./message-media.js";
30
+ import { MESSAGE_FRAME_CSP, MESSAGE_HTML_CSP } from "../shared/message-media.js";
29
31
  import { verifyDirectChildScope, verifyListParentScope, verifyReportTargetScope, verifySpawnParentScope } from "./session-tree-scope.js";
30
32
  import { CHILD_SESSION_LOCK_REASON } from "../shared/child-session-lock.js";
31
33
  import { MAX_CONTENT_DEPTH, MAX_CONTENT_FILE_BYTES, MAX_CONTENT_RESULTS, searchByContent } from "./content-search.js";
@@ -2342,6 +2344,53 @@ export function createHttpServer(options) {
2342
2344
  }
2343
2345
  return;
2344
2346
  }
2347
+ if (url.pathname === "/api/message-artifact") {
2348
+ try {
2349
+ if (request.method !== "GET" && request.method !== "HEAD") {
2350
+ response.writeHead(405, { allow: "GET, HEAD" }).end();
2351
+ return;
2352
+ }
2353
+ const workspaceId = url.searchParams.get("workspaceId");
2354
+ const conversationId = url.searchParams.get("conversationId");
2355
+ const workspace = workspaceId ? store.workspace(workspaceId) : undefined;
2356
+ const conversation = conversationId ? store.conversation(conversationId) : undefined;
2357
+ if (!workspace || !conversation || conversation.workspaceId !== workspaceId) {
2358
+ response.writeHead(404, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ error: "找不到对应的工作区和会话", code: "no_artifact_scope" }));
2359
+ return;
2360
+ }
2361
+ const root = await resolveInsideRoot(workspace.path, conversation.cwd ?? "");
2362
+ const artifact = await readMessageMedia(root, url.searchParams.get("path") ?? "");
2363
+ response.setHeader("cache-control", "no-store");
2364
+ response.setHeader("x-content-type-options", "nosniff");
2365
+ response.setHeader("referrer-policy", "no-referrer");
2366
+ if (url.searchParams.has("meta")) {
2367
+ const body = JSON.stringify({ path: artifact.path, kind: artifact.kind, mime: artifact.mime, bytes: artifact.bytes.length });
2368
+ response.writeHead(200, { "content-type": "application/json; charset=utf-8" }).end(request.method === "HEAD" ? undefined : body);
2369
+ return;
2370
+ }
2371
+ if (url.searchParams.has("frame") && artifact.kind === "html") {
2372
+ const contentUrl = new URL(url);
2373
+ contentUrl.searchParams.delete("frame");
2374
+ contentUrl.searchParams.delete("download");
2375
+ const escapeAttribute = (value) => value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
2376
+ const body = `<!doctype html><html><head><meta charset="utf-8"><title>HTML preview</title><style>html,body,iframe{margin:0;width:100%;height:100%;border:0;display:block}</style></head><body><iframe title="Interactive content" sandbox="allow-scripts" referrerpolicy="no-referrer" csp="${escapeAttribute(MESSAGE_HTML_CSP)}" src="${escapeAttribute(contentUrl.pathname + contentUrl.search)}"></iframe></body></html>`;
2377
+ response.writeHead(200, { "content-type": "text/html; charset=utf-8", "content-security-policy": `${MESSAGE_FRAME_CSP}; sandbox allow-scripts` }).end(request.method === "HEAD" ? undefined : body);
2378
+ return;
2379
+ }
2380
+ response.setHeader("content-security-policy", artifact.kind === "html"
2381
+ ? `${MESSAGE_HTML_CSP}; sandbox allow-scripts`
2382
+ : "default-src 'none'; style-src 'unsafe-inline'; sandbox");
2383
+ if (url.searchParams.has("download"))
2384
+ response.setHeader("content-disposition", `attachment; filename*=UTF-8''${encodeURIComponent(artifact.path.split("/").pop() ?? "artifact")}`);
2385
+ response.writeHead(200, { "content-type": artifact.mime, "content-length": artifact.bytes.length });
2386
+ response.end(request.method === "HEAD" ? undefined : artifact.bytes);
2387
+ }
2388
+ catch (error) {
2389
+ const described = describeFilesError(error);
2390
+ response.writeHead(described.status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }).end(request.method === "HEAD" ? undefined : JSON.stringify(described.body));
2391
+ }
2392
+ return;
2393
+ }
2345
2394
  if (url.pathname === "/api/files/diff") {
2346
2395
  const json = (status, body) => {
2347
2396
  response.writeHead(status, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify(body));
@@ -0,0 +1,7 @@
1
+ /** Resolve against the conversation cwd, including canonical containment for absolute paths and links. */
2
+ export declare function readMessageMedia(root: string, requested: string): Promise<{
3
+ kind: import("../shared/message-media.js").MessageMediaKind;
4
+ mime: string;
5
+ path: string;
6
+ bytes: Buffer<ArrayBuffer>;
7
+ }>;
@@ -0,0 +1,54 @@
1
+ import { open, realpath } from "node:fs/promises";
2
+ import { isAbsolute, relative } from "node:path";
3
+ import { FilesError, resolveInsideRoot } from "./files.js";
4
+ import { localMessageMedia, MAX_MESSAGE_MEDIA_BYTES, messageMediaType } from "../shared/message-media.js";
5
+ /** Resolve against the conversation cwd, including canonical containment for absolute paths and links. */
6
+ export async function readMessageMedia(root, requested) {
7
+ if (!localMessageMedia(requested))
8
+ throw new FilesError(415, "只支持本地图片或 HTML 文件", "unsupported_artifact");
9
+ try {
10
+ const canonicalRoot = await realpath(root);
11
+ const input = requested.replace(/\\/g, "/");
12
+ const candidate = isAbsolute(input) ? relative(canonicalRoot, await realpath(input)) : input;
13
+ const checked = await resolveInsideRoot(canonicalRoot, candidate);
14
+ const path = await realpath(checked);
15
+ await resolveInsideRoot(canonicalRoot, relative(canonicalRoot, path));
16
+ const type = messageMediaType(path);
17
+ if (!type || type.kind !== messageMediaType(requested)?.kind) {
18
+ throw new FilesError(415, "文件实际类型不支持预览", "unsupported_artifact");
19
+ }
20
+ const file = await open(path, "r");
21
+ try {
22
+ const info = await file.stat();
23
+ if (!info.isFile())
24
+ throw new FilesError(400, "预览路径不是文件", "not_a_file");
25
+ if (info.size > MAX_MESSAGE_MEDIA_BYTES)
26
+ throw new FilesError(413, "预览文件超过 20 MB", "too_large");
27
+ // Bound the read even if another process grows the file after stat.
28
+ const bytes = Buffer.alloc(info.size + 1);
29
+ let bytesRead = 0;
30
+ while (bytesRead < bytes.length) {
31
+ const chunk = await file.read(bytes, bytesRead, bytes.length - bytesRead, bytesRead);
32
+ if (!chunk.bytesRead)
33
+ break;
34
+ bytesRead += chunk.bytesRead;
35
+ }
36
+ if (bytesRead > info.size)
37
+ throw new FilesError(409, "文件正在变化,请重新加载", "artifact_changed");
38
+ return { ...type, path: relative(canonicalRoot, path).replace(/\\/g, "/"), bytes: bytes.subarray(0, bytesRead) };
39
+ }
40
+ finally {
41
+ await file.close();
42
+ }
43
+ }
44
+ catch (error) {
45
+ if (error instanceof FilesError)
46
+ throw error;
47
+ const code = error.code;
48
+ if (code === "ENOENT" || code === "ENOTDIR")
49
+ throw new FilesError(404, "预览文件不存在,可能尚未生成或已被移动", "not_found");
50
+ if (code === "EACCES" || code === "EPERM")
51
+ throw new FilesError(403, "没有权限读取预览文件", "denied");
52
+ throw error;
53
+ }
54
+ }
@@ -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
  }
@@ -0,0 +1,12 @@
1
+ /** Only workspace-backed artifacts are embedded automatically; remote images remain links. */
2
+ export type MessageMediaKind = "image" | "html";
3
+ export declare const MESSAGE_HTML_CSP = "default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; form-action 'none'; base-uri 'none'";
4
+ /** The trusted outer document also prevents the untrusted child from navigating to another origin. */
5
+ export declare const MESSAGE_FRAME_CSP: string;
6
+ export declare const MAX_MESSAGE_MEDIA_BYTES: number;
7
+ export declare function messageMediaType(path: string): {
8
+ kind: MessageMediaKind;
9
+ mime: string;
10
+ } | undefined;
11
+ export declare function localMessageMedia(path: string): MessageMediaKind | undefined;
12
+ export declare function messageMediaUrl(workspaceId: string, conversationId: string, path: string): string;
@@ -0,0 +1,27 @@
1
+ export const MESSAGE_HTML_CSP = "default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; connect-src 'none'; frame-src 'none'; object-src 'none'; form-action 'none'; base-uri 'none'";
2
+ /** The trusted outer document also prevents the untrusted child from navigating to another origin. */
3
+ export const MESSAGE_FRAME_CSP = MESSAGE_HTML_CSP.replace("frame-src 'none'", "frame-src 'self'");
4
+ export const MAX_MESSAGE_MEDIA_BYTES = 20 * 1024 * 1024;
5
+ const TYPES = {
6
+ png: { kind: "image", mime: "image/png" },
7
+ jpg: { kind: "image", mime: "image/jpeg" },
8
+ jpeg: { kind: "image", mime: "image/jpeg" },
9
+ gif: { kind: "image", mime: "image/gif" },
10
+ webp: { kind: "image", mime: "image/webp" },
11
+ svg: { kind: "image", mime: "image/svg+xml" },
12
+ html: { kind: "html", mime: "text/html; charset=utf-8" },
13
+ htm: { kind: "html", mime: "text/html; charset=utf-8" },
14
+ };
15
+ export function messageMediaType(path) {
16
+ return TYPES[/\.([a-z]+)$/i.exec(path)?.[1].toLowerCase() ?? ""];
17
+ }
18
+ export function localMessageMedia(path) {
19
+ if (!path || /[\u0000-\u001f\u007f]/.test(path) || /^[\\/]{2}/.test(path))
20
+ return;
21
+ if (/^[a-z][a-z\d+.-]*:/i.test(path) && !/^[a-z]:[\\/]/i.test(path))
22
+ return;
23
+ return messageMediaType(path)?.kind;
24
+ }
25
+ export function messageMediaUrl(workspaceId, conversationId, path) {
26
+ return `/api/message-artifact?${new URLSearchParams({ workspaceId, conversationId, path })}`;
27
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evandu/super-pi",
3
- "version": "0.1.199",
3
+ "version": "0.1.201",
4
4
  "description": "Web control plane and companion for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -43,6 +43,7 @@
43
43
  "test": "node scripts/test.mjs"
44
44
  },
45
45
  "check:logic": [
46
+ "scripts/message-media.test.mjs",
46
47
  "scripts/update-args.test.mjs",
47
48
  "scripts/update-restart.test.mjs",
48
49
  "scripts/update-restart-budget.test.mjs",
@@ -195,6 +196,7 @@
195
196
  "scripts/settings-default-model.test.mjs",
196
197
  "scripts/provider-registry.test.mjs",
197
198
  "scripts/provider-pi-reads.test.mjs",
199
+ "scripts/provider-oauth-proxy.test.mjs",
198
200
  "scripts/session-extension-credentials.test.mjs",
199
201
  "scripts/active-memory.test.mjs",
200
202
  "scripts/layered-memory.test.mjs",
@@ -275,6 +277,7 @@
275
277
  "scripts/session-reminder-pmo-rights.test.mjs"
276
278
  ],
277
279
  "check:browser": [
280
+ "scripts/message-media-browser.test.mjs",
278
281
  "scripts/update-button-browser.test.mjs",
279
282
  "scripts/interrupt-browser.test.mjs",
280
283
  "scripts/revert-browser.test.mjs",