@evandu/super-pi 0.1.265 → 0.1.268

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.
@@ -8,7 +8,7 @@
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-DW2nd-Cf.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-BEIuDi2o.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
13
  <link rel="stylesheet" crossorigin href="/assets/index-Cl8iehsn.css">
14
14
  </head>
@@ -1626,7 +1626,7 @@ export function createHttpServer(options) {
1626
1626
  console.error(`Super Pi: ${message}`);
1627
1627
  };
1628
1628
  const listenPort = port ?? request.socket.localPort;
1629
- const restartEnv = { ...process.env, SUPER_PI_DATA_DIR: paths.dataDir, SUPER_PI_PORT: String(listenPort) };
1629
+ const restartEnv = { ...process.env, SUPER_PI_DATA_DIR: paths.dataDir, SUPER_PI_PORT: String(listenPort), SUPER_PI_UPDATE_OPERATION_ID: id };
1630
1630
  if (host)
1631
1631
  restartEnv.SUPER_PI_HOST = host;
1632
1632
  const restartNow = () => {
@@ -1,6 +1,7 @@
1
1
  import { request as httpRequest } from "node:http";
2
2
  import { request as httpsRequest } from "node:https";
3
3
  import { defaultServiceUrl } from "../shared/managed-servers.js";
4
+ import { injectToolFrameBridge } from "../shared/tool-frame-bridge.js";
4
5
  export function serviceOrigin(value) {
5
6
  const url = new URL(value);
6
7
  if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/")
@@ -48,6 +49,10 @@ function upstreamHeaders(request, target, key) {
48
49
  const result = { ...request.headers, host: target.host, origin: target.origin, authorization: `Bearer ${key}` };
49
50
  delete result.cookie;
50
51
  delete result["sec-websocket-protocol"];
52
+ if (target.pathname.startsWith("/tools/")) {
53
+ result.origin = "null";
54
+ result["accept-encoding"] = "identity";
55
+ }
51
56
  return result;
52
57
  }
53
58
  export function proxyThroughDirect(origin, key, path, request, response, basePath) {
@@ -55,6 +60,15 @@ export function proxyThroughDirect(origin, key, path, request, response, basePat
55
60
  const upstream = (target.protocol === "https:" ? httpsRequest : httpRequest)(target, { method: request.method, headers: upstreamHeaders(request, target, key) }, result => {
56
61
  const outgoing = { ...result.headers };
57
62
  delete outgoing["set-cookie"];
63
+ if (path.startsWith("/tools/") && String(outgoing["content-type"]).startsWith("text/html")) {
64
+ delete outgoing["content-length"];
65
+ let html = "";
66
+ result.setEncoding("utf8");
67
+ result.on("data", chunk => { html += chunk; if (html.length > 2 * 1024 * 1024)
68
+ result.destroy(); });
69
+ result.once("end", () => response.writeHead(result.statusCode ?? 502, outgoing).end(injectToolFrameBridge(html)));
70
+ return;
71
+ }
58
72
  if (path.startsWith("/api/message-artifact?") && target.searchParams.has("frame") && String(outgoing["content-type"]).startsWith("text/html")) {
59
73
  delete outgoing["content-length"];
60
74
  let html = "";
@@ -1,5 +1,6 @@
1
1
  import { request as httpRequest, Agent } from "node:http";
2
2
  import { sshForward } from "./managed-ssh.js";
3
+ import { injectToolFrameBridge } from "../shared/tool-frame-bridge.js";
3
4
  function headers(input, port, key, sameOrigin = false) {
4
5
  const next = { ...input, host: `127.0.0.1:${port}`, authorization: `Bearer ${key}` };
5
6
  delete next.cookie;
@@ -48,9 +49,23 @@ export async function tunnelJson(client, port, path, key, method = "GET") {
48
49
  }
49
50
  export function proxyThroughSsh(client, port, key, path, request, response, basePath = "", sameOrigin = false) {
50
51
  const agent = agentFor(client, port);
51
- const upstream = httpRequest({ hostname: "127.0.0.1", port, method: request.method, path, headers: headers(request.headers, port, key, sameOrigin), agent }, result => {
52
+ const outgoingHeaders = headers(request.headers, port, key, sameOrigin);
53
+ if (path.startsWith("/tools/")) {
54
+ outgoingHeaders.origin = "null";
55
+ outgoingHeaders["accept-encoding"] = "identity";
56
+ }
57
+ const upstream = httpRequest({ hostname: "127.0.0.1", port, method: request.method, path, headers: outgoingHeaders, agent }, result => {
52
58
  const outgoing = { ...result.headers };
53
59
  delete outgoing["set-cookie"];
60
+ if (path.startsWith("/tools/") && String(outgoing["content-type"]).startsWith("text/html")) {
61
+ delete outgoing["content-length"];
62
+ let html = "";
63
+ result.setEncoding("utf8");
64
+ result.on("data", chunk => { html += chunk; if (html.length > 2 * 1024 * 1024)
65
+ result.destroy(); });
66
+ result.once("end", () => { response.writeHead(result.statusCode ?? 502, outgoing).end(injectToolFrameBridge(html)); agent.destroy(); });
67
+ return;
68
+ }
54
69
  // The trusted artifact wrapper uses an origin-root URL; keep its inner frame on this backend.
55
70
  if (basePath && path.startsWith("/api/message-artifact?") && new URL(path, "http://localhost").searchParams.has("frame") && String(outgoing["content-type"]).startsWith("text/html")) {
56
71
  delete outgoing["content-length"];
@@ -1093,7 +1093,7 @@ export class PiRpcRuntime {
1093
1093
  }
1094
1094
  let preflight;
1095
1095
  const imagePayloads = this.options.uploadsDir && images?.length
1096
- ? await loadConversationImages(this.options.uploadsDir, conversation.id, images)
1096
+ ? await loadConversationImages(this.options.uploadsDir, conversation.id, images, { required: true })
1097
1097
  : undefined;
1098
1098
  const promptOptions = {
1099
1099
  ...(imagePayloads?.length ? { images: imagePayloads } : {}),
@@ -1716,7 +1716,7 @@ export class PiRpcRuntime {
1716
1716
  await onSessionFile?.(sessionFile);
1717
1717
  }
1718
1718
  const imagePayloads = this.options.uploadsDir && images?.length
1719
- ? await loadConversationImages(this.options.uploadsDir, conversation.id, images)
1719
+ ? await loadConversationImages(this.options.uploadsDir, conversation.id, images, { required: true })
1720
1720
  : undefined;
1721
1721
  // A STOP THAT ARRIVED WHILE THE CHILD WAS STARTING MUST NOT SEND THE PROMPT.
1722
1722
  //
@@ -2808,7 +2808,7 @@ export class PiRpcRuntime {
2808
2808
  if (this.activeTurns.has(conversationId)) {
2809
2809
  const session = await this.sessionFor(conversationId);
2810
2810
  const imagePayloads = this.options.uploadsDir && images?.length
2811
- ? await loadConversationImages(this.options.uploadsDir, conversationId, images)
2811
+ ? await loadConversationImages(this.options.uploadsDir, conversationId, images, { required: true })
2812
2812
  : undefined;
2813
2813
  if (!session.followUp)
2814
2814
  throw new SteerUnavailableError(`会话 ${conversationId} 的 Pi 不支持排队消息`);
@@ -2879,7 +2879,7 @@ export class PiRpcRuntime {
2879
2879
  if (this.activeTurns.has(conversationId)) {
2880
2880
  const session = await this.sessionFor(conversationId);
2881
2881
  const imagePayloads = this.options.uploadsDir && images?.length
2882
- ? await loadConversationImages(this.options.uploadsDir, conversationId, images)
2882
+ ? await loadConversationImages(this.options.uploadsDir, conversationId, images, { required: true })
2883
2883
  : undefined;
2884
2884
  try {
2885
2885
  await session.prompt(message, { ...(imagePayloads?.length ? { images: imagePayloads } : {}), streamingBehavior: "steer" });
@@ -2894,7 +2894,7 @@ export class PiRpcRuntime {
2894
2894
  throw new SteerUnavailableError(`会话 ${conversationId} 的 Pi 进程已结束`);
2895
2895
  const id = `steer_${++this.steerSeq}`;
2896
2896
  const imagePayloads = this.options.uploadsDir && images?.length
2897
- ? await loadConversationImages(this.options.uploadsDir, conversationId, images)
2897
+ ? await loadConversationImages(this.options.uploadsDir, conversationId, images, { required: true })
2898
2898
  : undefined;
2899
2899
  const answer = new Promise((resolve, reject) => {
2900
2900
  const timer = setTimeout(() => {
@@ -32,4 +32,6 @@ export declare function findUploadFile(uploadsDir: string, conversationId: strin
32
32
  export declare function deleteConversationUploads(uploadsDir: string, conversationId: string): Promise<void>;
33
33
  /** Gives each fork its own copy of the local images referenced by its history. */
34
34
  export declare function copyForkUploads(uploadsDir: string, conversationId: string, forkedId: string, images: MessageImage[]): Promise<void>;
35
- export declare function loadConversationImages(uploadsDir: string, conversationId: string, images: MessageImage[]): Promise<PiImageContent[]>;
35
+ export declare function loadConversationImages(uploadsDir: string, conversationId: string, images: MessageImage[], options?: {
36
+ required?: boolean;
37
+ }): Promise<PiImageContent[]>;
@@ -158,7 +158,7 @@ export async function copyForkUploads(uploadsDir, conversationId, forkedId, imag
158
158
  await copyFile(source, join(target, basename(file.filePath)));
159
159
  }
160
160
  }
161
- export async function loadConversationImages(uploadsDir, conversationId, images) {
161
+ export async function loadConversationImages(uploadsDir, conversationId, images, options = {}) {
162
162
  const result = [];
163
163
  for (const img of images) {
164
164
  const found = await findUploadFile(uploadsDir, conversationId, img.id);
@@ -173,5 +173,7 @@ export async function loadConversationImages(uploadsDir, conversationId, images)
173
173
  }
174
174
  }
175
175
  }
176
+ if (options.required && result.length !== images.length)
177
+ throw new Error("部分图片附件不存在或已损坏,请重新上传后发送;本次没有向模型发送缺少图片的请求。");
176
178
  return result;
177
179
  }
@@ -0,0 +1,2 @@
1
+ /** Scoped tool requests cross the opaque frame boundary without exposing owner credentials. */
2
+ export declare function injectToolFrameBridge(html: string): string;
@@ -0,0 +1,27 @@
1
+ /** Scoped tool requests cross the opaque frame boundary without exposing owner credentials. */
2
+ export function injectToolFrameBridge(html) {
3
+ const script = String.raw `<script>(()=>{
4
+ const nativeFetch=window.fetch.bind(window), root=new URL('./',location.href), owner=new URLSearchParams(location.hash.slice(1)).get('super-pi-owner');
5
+ if(!owner || parent===window)return;
6
+ const pending=new Map();
7
+ addEventListener('message',event=>{const data=event.data;if(event.source!==parent||data?.type!=='super-pi-tool-response')return;const entry=pending.get(data.id);if(!entry)return;pending.delete(data.id);clearTimeout(entry.timer);entry.cleanup();if(data.error)entry.reject(new Error(data.error));else entry.resolve(new Response(data.body,{status:data.status,headers:data.headers}));});
8
+ window.fetch=async(input,init={})=>{
9
+ const request=new Request(input,init), url=new URL(request.url);
10
+ if(url.origin!==root.origin||!url.pathname.startsWith(root.pathname+'api/'))return nativeFetch(input,init);
11
+ if(request.signal.aborted)throw new DOMException('Aborted','AbortError');
12
+ const id=crypto.randomUUID?.()??Array.from(crypto.getRandomValues(new Uint8Array(16)),n=>n.toString(16).padStart(2,'0')).join(''), body=['GET','HEAD'].includes(request.method)?undefined:await request.text();
13
+ return new Promise((resolve,reject)=>{
14
+ const abort=()=>{const entry=pending.get(id);if(entry){clearTimeout(entry.timer);pending.delete(id);entry.cleanup();reject(new DOMException('Aborted','AbortError'));}};
15
+ const cleanup=()=>request.signal.removeEventListener('abort',abort);
16
+ const timer=setTimeout(()=>{pending.delete(id);cleanup();reject(new Error('Super Pi tool request timed out'));},30000);
17
+ pending.set(id,{resolve,reject,timer,cleanup});request.signal.addEventListener('abort',abort,{once:true});
18
+ parent.postMessage({type:'super-pi-tool-request',id,owner,path:url.pathname.slice(root.pathname.length)+url.search,method:request.method,body},'*');
19
+ });
20
+ };
21
+ })();</script>`;
22
+ if (/<head(?:\s[^>]*)?>/i.test(html))
23
+ return html.replace(/<head(?:\s[^>]*)?>/i, match => match + script);
24
+ if (/<!doctype[^>]*>/i.test(html))
25
+ return html.replace(/<!doctype[^>]*>/i, match => match + script);
26
+ return script + html;
27
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evandu/super-pi",
3
- "version": "0.1.265",
3
+ "version": "0.1.268",
4
4
  "description": "Web control plane and companion for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -21,6 +21,7 @@
21
21
  "bin",
22
22
  "scripts/restart-server.mjs",
23
23
  "scripts/restart-process.mjs",
24
+ "scripts/restart-lock.mjs",
24
25
  "README.md",
25
26
  "assets/knowledge-model",
26
27
  "scripts/patch-brace-expansion.mjs",
@@ -49,6 +50,10 @@
49
50
  "pack:server": "npm run build && node scripts/pack-server.mjs"
50
51
  },
51
52
  "check:logic": [
53
+ "scripts/desktop-relaunch.test.mjs",
54
+ "scripts/workbench-memory.test.mjs",
55
+ "scripts/desktop-application.test.mjs",
56
+ "scripts/desktop-notifications.test.mjs",
52
57
  "scripts/published-server-update.test.mjs",
53
58
  "scripts/reader-recovery-scope.test.mjs",
54
59
  "scripts/managed-direct.test.mjs",
@@ -314,6 +319,8 @@
314
319
  "scripts/session-reminder-pmo-rights.test.mjs"
315
320
  ],
316
321
  "check:browser": [
322
+ "scripts/remote-tool-runtime-browser.test.mjs",
323
+ "scripts/remote-image-paste-browser.test.mjs",
317
324
  "scripts/service-port-probe-browser.test.mjs",
318
325
  "scripts/update-multi-server-browser.test.mjs",
319
326
  "scripts/remote-queue-reconciliation-browser.test.mjs",
@@ -466,6 +473,7 @@
466
473
  "@earendil-works/pi-coding-agent": "1.5.2",
467
474
  "@electron-internal/extract-zip": "1.0.8",
468
475
  "@electron/get": "5.1.0",
476
+ "@electron/packager": "20.3.0",
469
477
  "@git-diff-view/react": "^0.1.8",
470
478
  "@types/diff": "^5.2.3",
471
479
  "@xterm/addon-fit": "^0.11.0",
@@ -24,7 +24,7 @@ export async function packServer(root, destination) {
24
24
  const manifest = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
25
25
  const files = (manifest.files ?? []).filter(file => file !== "desktop" && file !== "scripts/pack-server.mjs");
26
26
  for (const file of files) { try { await cp(join(root, file), join(staging, file), { recursive: true }); } catch (error) { if (error.code !== "ENOENT") throw error; } }
27
- const dependencies = Object.fromEntries(Object.entries(manifest.dependencies ?? {}).filter(([name]) => !["electron", "ssh2", "@electron/get", "@electron-internal/extract-zip"].includes(name)));
27
+ const dependencies = Object.fromEntries(Object.entries(manifest.dependencies ?? {}).filter(([name]) => !["electron", "ssh2", "@electron/get", "@electron-internal/extract-zip", "@electron/packager"].includes(name)));
28
28
  const server = { ...manifest, name: "@evandu/super-pi-server", description: "Super Pi remote execution service, without the desktop runtime", files, dependencies, devDependencies: undefined, scripts: undefined, bin: { "super-pi": "bin/super-pi.js", super_pi: "bin/super-pi.js", "super-pi-server": "bin/super-pi.js" } };
29
29
  await writeFile(join(staging, "package.json"), `${JSON.stringify(server, null, 2)}\n`);
30
30
  await mkdir(destination, { recursive: true });
@@ -0,0 +1,23 @@
1
+ import { mkdirSync, readFileSync, writeFileSync, rmSync, statSync } from 'node:fs';
2
+ import { join, resolve } from 'node:path';
3
+
4
+ /** Serialize the service helper and native supervisor without holding a live server open. */
5
+ export async function acquireRestartLock(directory, timeout = 180_000) {
6
+ const root = resolve(directory), path = join(root, 'restart-service.lock');
7
+ mkdirSync(root, { recursive: true });
8
+ const deadline = Date.now() + timeout;
9
+ for (;;) {
10
+ try {
11
+ mkdirSync(path); writeFileSync(join(path, 'owner.json'), JSON.stringify({ pid: process.pid }));
12
+ return () => { try { if (JSON.parse(readFileSync(join(path, 'owner.json'), 'utf8')).pid === process.pid) rmSync(path, { recursive: true, force: true }); } catch { /* Another owner must not be removed. */ } };
13
+ } catch (error) {
14
+ if (error.code !== 'EEXIST') throw error;
15
+ try {
16
+ const owner = JSON.parse(readFileSync(join(path, 'owner.json'), 'utf8'));
17
+ try { process.kill(owner.pid, 0); } catch (failure) { if (failure.code === 'ESRCH') { rmSync(path, { recursive: true, force: true }); continue; } }
18
+ } catch { try { if (Date.now() - statSync(path).mtimeMs > 30_000) { rmSync(path, { recursive: true, force: true }); continue; } } catch {} }
19
+ if (Date.now() >= deadline) throw new Error('另一项服务重启尚未结束,请查看重启日志。');
20
+ await new Promise(done => setTimeout(done, 200));
21
+ }
22
+ }
23
+ }
@@ -1,9 +1,10 @@
1
1
  import { spawn, execFile } from "node:child_process";
2
- import { openSync, readFileSync } from "node:fs";
2
+ import { openSync, readFileSync, writeFileSync, renameSync } from "node:fs";
3
3
  import { homedir, platform } from "node:os";
4
4
  import { join, resolve } from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  import { readProcessCommandLine } from "./restart-process.mjs";
7
+ import { acquireRestartLock } from "./restart-lock.mjs";
7
8
 
8
9
  const execFileAsync = promisify(execFile);
9
10
 
@@ -30,6 +31,20 @@ const allowedEntries = [entry, "src/server/index.ts"];
30
31
  * `cmd.includes(candidate)` never matched and the script refused to kill its own server. */
31
32
  const normalisePath = (value) => value.replace(/[\\/]+/g, "/").toLowerCase();
32
33
  const waitMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
34
+ const dataDirectory = process.env.SUPER_PI_DATA_DIR || join(homedir(), '.super-pi');
35
+ const releaseRestart = await acquireRestartLock(dataDirectory);
36
+ process.once('exit', releaseRestart);
37
+ // A second helper for this same accepted operation must not restart its healthy successor.
38
+ if (process.env.SUPER_PI_UPDATE_OPERATION_ID) {
39
+ try {
40
+ const operation = JSON.parse(readFileSync(join(dataDirectory, 'update-status.json'), 'utf8'));
41
+ const response = await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(1500) });
42
+ const health = await response.json();
43
+ let finished;
44
+ try { finished = JSON.parse(readFileSync(join(dataDirectory, 'restart-service-completed.json'), 'utf8')); } catch {}
45
+ if (response.ok && health.service === 'super-pi' && operation.id === process.env.SUPER_PI_UPDATE_OPERATION_ID && (operation.phase === 'completed' || finished?.id === operation.id && finished.version === operation.targetVersion) && health.runningVersion === operation.targetVersion) process.exit(0);
46
+ } catch { /* No healthy successor yet; this helper owns recovery. */ }
47
+ }
33
48
  async function pidsOnPort() {
34
49
  if (platform() === "win32") {
35
50
  const { stdout } = await execFileAsync("netstat", ["-ano", "-p", "TCP"]);
@@ -96,7 +111,13 @@ while (Date.now() < deadline) {
96
111
  try {
97
112
  const response = await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(2_000) });
98
113
  const body = await response.json();
99
- if (response.ok && body.status === "ok" && body.service === "super-pi") { console.log("Server ready: /api/health passed."); process.exit(0); }
114
+ if (response.ok && body.status === "ok" && body.service === "super-pi") {
115
+ if (process.env.SUPER_PI_UPDATE_OPERATION_ID) {
116
+ const file = join(dataDirectory, 'restart-service-completed.json'), temporary = `${file}.${process.pid}.tmp`;
117
+ writeFileSync(temporary, JSON.stringify({ id: process.env.SUPER_PI_UPDATE_OPERATION_ID, version: body.runningVersion })); renameSync(temporary, file);
118
+ }
119
+ console.log("Server ready: /api/health passed."); process.exit(0);
120
+ }
100
121
  } catch { /* The replacement is still starting. */ }
101
122
  await waitMs(200);
102
123
  }