@evandu/super-pi 0.1.270 → 0.1.272

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.
@@ -1,3 +1,12 @@
1
+ const recordedFailures = new WeakSet();
2
+ export function recordedTurnFailure(error) {
3
+ const failure = error instanceof Error ? error : new Error(String(error));
4
+ recordedFailures.add(failure);
5
+ return failure;
6
+ }
7
+ export function isRecordedTurnFailure(error) {
8
+ return error instanceof Error && recordedFailures.has(error);
9
+ }
1
10
  /**
2
11
  * Translates a thrown error from the turn loop into a sentence a person reads.
3
12
  *
@@ -22,6 +31,8 @@ export function formatTurnFailure(error) {
22
31
  if (controllerAborted(error))
23
32
  return "本轮任务已停止。";
24
33
  const raw = error instanceof Error ? error.message : typeof error === "string" ? error : "";
34
+ if (/^(本地模型通道|模型通道在回复完成前断开)/.test(raw))
35
+ return raw;
25
36
  const lower = raw.toLowerCase();
26
37
  // PROVIDER QUOTA / RATE LIMIT - the only reason the user is in this branch is because Pi was
27
38
  // answering them a moment ago and now the model will not let it. The action is "wait or change
@@ -2143,6 +2143,7 @@ export type ServerEvent = {
2143
2143
  } | {
2144
2144
  type: "error";
2145
2145
  message: string;
2146
+ recordedTurnFailure?: boolean;
2146
2147
  } | {
2147
2148
  type: "extension.ui";
2148
2149
  conversationId: string;
@@ -2,6 +2,7 @@ import { isBrowserAuthorized } from "./browser-access.js";
2
2
  import { WebSocket, WebSocketServer } from "ws";
3
3
  import { isAuthorized, isLoopbackAddress } from "./http-server.js";
4
4
  import { describeThrown, describeThrownWithStack } from "./failure-text.js";
5
+ import { isRecordedTurnFailure } from "./turn-failure.js";
5
6
  /**
6
7
  * A WebSocket is a live transport, not an unbounded queue. `ws.send()` only
7
8
  * copies bytes into the socket's userland buffer; a browser that is frozen or
@@ -607,6 +608,7 @@ export class WsServer {
607
608
  safeSend(socket, JSON.stringify({
608
609
  type: "error",
609
610
  message: reason || "服务端没有说明这次失败的原因。",
611
+ ...(isRecordedTurnFailure(error) ? { recordedTurnFailure: true } : {}),
610
612
  }));
611
613
  }
612
614
  finally {
@@ -36,13 +36,17 @@ export interface ManagedServerProfile {
36
36
  deployedAt?: string;
37
37
  remoteRoot?: string;
38
38
  serviceUrl?: string;
39
+ allowServiceTunnel?: boolean;
39
40
  transport?: "direct" | "ssh";
40
41
  serviceError?: string;
42
+ sshError?: string;
43
+ modelError?: string;
41
44
  serviceHost?: ServiceListenHost;
42
45
  deployedServiceHost?: ServiceListenHost;
43
46
  ssh: "offline" | "connecting" | "online" | "needsTrust" | "awaitingVerification";
44
47
  service: "unknown" | "offline" | "online";
45
48
  modelChannel: "offline" | "online";
49
+ modelChannelPaused?: boolean;
46
50
  phase: "idle" | "connecting" | "needsTrust" | "awaitingVerification" | "deploying" | "ready" | "failed";
47
51
  verification?: SshVerification;
48
52
  existingService?: {
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "superPi": {
4
4
  "managedDirectListener": true
5
5
  },
6
- "version": "0.1.270",
6
+ "version": "0.1.272",
7
7
  "description": "Web control plane and companion for Pi",
8
8
  "license": "MIT",
9
9
  "type": "module",
@@ -1,5 +1,6 @@
1
1
  import { spawn, execFile } from "node:child_process";
2
- import { openSync, readFileSync, writeFileSync, renameSync } from "node:fs";
2
+ import { closeSync, openSync, readFileSync, writeFileSync, renameSync } from "node:fs";
3
+ import { createConnection, isIPv6 } from "node:net";
3
4
  import { homedir, platform } from "node:os";
4
5
  import { join, resolve } from "node:path";
5
6
  import { promisify } from "node:util";
@@ -24,6 +25,9 @@ function savedPort() {
24
25
  // as an argument and never sets this variable, so the script looked at 3080 and never found the
25
26
  // running server it was supposed to replace.
26
27
  const port = Number(process.env.SUPER_PI_PORT ?? savedPort() ?? 3080);
28
+ const bindHost = process.env.SUPER_PI_HOST;
29
+ const probeHost = !bindHost || bindHost === "0.0.0.0" ? "127.0.0.1" : bindHost === "::" ? "::1" : bindHost;
30
+ const origin = `http://${isIPv6(probeHost) ? `[${probeHost}]` : probeHost}:${port}`;
27
31
  const entry = "dist/server/index.js";
28
32
  const allowedEntries = [entry, "src/server/index.ts"];
29
33
  /** Compare paths the way Windows reports them. A command line on Windows contains BACKSLASHES
@@ -32,38 +36,78 @@ const allowedEntries = [entry, "src/server/index.ts"];
32
36
  const normalisePath = (value) => value.replace(/[\\/]+/g, "/").toLowerCase();
33
37
  const waitMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
34
38
  const dataDirectory = process.env.SUPER_PI_DATA_DIR || join(homedir(), '.super-pi');
39
+ const gracefulOnly = process.env.SUPER_PI_RESTART_GRACEFUL_ONLY === "1";
40
+ const expectedVersion = process.env.SUPER_PI_RESTART_EXPECTED_VERSION;
41
+ async function readHealth(timeout) {
42
+ try {
43
+ const response = await fetch(`${origin}/api/health`, { headers: { connection: "close" }, signal: AbortSignal.timeout(timeout) });
44
+ return response.ok ? await response.json() : undefined;
45
+ } catch { return undefined; }
46
+ }
35
47
  const releaseRestart = await acquireRestartLock(dataDirectory);
36
48
  process.once('exit', releaseRestart);
37
49
  // A second helper for this same accepted operation must not restart its healthy successor.
38
50
  if (process.env.SUPER_PI_UPDATE_OPERATION_ID) {
39
51
  try {
40
52
  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();
53
+ const health = await readHealth(1500);
43
54
  let finished;
44
55
  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);
56
+ if (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
57
  } catch { /* No healthy successor yet; this helper owns recovery. */ }
47
58
  }
48
59
  async function pidsOnPort() {
49
60
  if (platform() === "win32") {
50
61
  const { stdout } = await execFileAsync("netstat", ["-ano", "-p", "TCP"]);
51
- return [...new Set(stdout.split(/\r?\n/).filter((line) => line.includes(`:${port}`) && /LISTENING\s+\d+/.test(line)).map((line) => line.trim().split(/\s+/).at(-1)))];
62
+ return [...new Set(stdout.split(/\r?\n/).map(line => line.trim().split(/\s+/)).filter(([, local, , state]) => state === "LISTENING" && local.endsWith(`:${port}`)).map(fields => fields.at(-1)))];
52
63
  }
53
64
  try { const { stdout } = await execFileAsync("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-t"]); return stdout.trim().split(/\s+/).filter(Boolean); }
54
- catch { const { stdout } = await execFileAsync("sh", ["-c", `ss -lptn 'sport = :${port}' 2>/dev/null`]); return [...new Set([...stdout.matchAll(/pid=(\d+)/g)].map((match) => match[1]))]; }
65
+ catch (error) {
66
+ if (error.code === 1 && !error.stdout?.trim() && !error.stderr?.trim()) return [];
67
+ if (platform() !== "linux") throw error;
68
+ const { stdout } = await execFileAsync("ss", ["-lptn", "sport", "=", `:${port}`]);
69
+ return [...new Set([...stdout.matchAll(/pid=(\d+)/g)].map((match) => match[1]))];
70
+ }
55
71
  }
56
72
  async function commandLine(pid) {
57
73
  return readProcessCommandLine(pid);
58
74
  }
59
75
  async function requestShutdown() {
60
- const headers = {};
76
+ const headers = { connection: "close" };
61
77
  if (process.env.SUPER_PI_ACCESS_TOKEN) headers.authorization = `Bearer ${process.env.SUPER_PI_ACCESS_TOKEN}`;
62
- try { return (await fetch(`http://127.0.0.1:${port}/api/shutdown`, { method: "POST", headers, signal: AbortSignal.timeout(2000) })).status; }
78
+ try { return (await fetch(`${origin}/api/shutdown`, { method: "POST", headers, signal: AbortSignal.timeout(2000) })).status; }
63
79
  catch { return null; }
64
80
  }
65
81
  async function waitForPortRelease(timeoutMs) {
66
- for (let elapsed = 0; elapsed < timeoutMs; elapsed += 100) { if (!(await pidsOnPort()).length) return true; await waitMs(100); }
82
+ const deadline = Date.now() + timeoutMs;
83
+ do { if (!(await pidsOnPort()).length) return true; await waitMs(100); } while (Date.now() < deadline);
84
+ return false;
85
+ }
86
+
87
+ function portReleased() {
88
+ return new Promise(resolve => {
89
+ const socket = createConnection({ host: probeHost, port });
90
+ socket.setTimeout(1000);
91
+ const done = released => { socket.destroy(); resolve(released); };
92
+ socket.once("error", error => done(error.code === "ECONNREFUSED"));
93
+ socket.once("connect", () => done(false));
94
+ socket.once("timeout", () => done(false));
95
+ });
96
+ }
97
+
98
+ async function stopGracefully() {
99
+ if (await portReleased()) return true;
100
+ const health = await readHealth(2000);
101
+ if (health?.service !== "super-pi") {
102
+ console.error(`Port ${port} is occupied by a service that did not identify itself as Super Pi.`);
103
+ return false;
104
+ }
105
+ const status = await requestShutdown();
106
+ if (status >= 200 && status < 300) {
107
+ const deadline = Date.now() + 20_000;
108
+ do { if (await portReleased()) return true; await waitMs(200); } while (Date.now() < deadline);
109
+ }
110
+ console.error(`Super Pi did not release port ${port} after a graceful shutdown request (HTTP ${status ?? "no response"}).`);
67
111
  return false;
68
112
  }
69
113
  // On Windows a detached, console-less node.exe has no window to receive WM_CLOSE, so plain
@@ -75,12 +119,12 @@ async function forceKill(pid) {
75
119
  }
76
120
  async function stopConflicts() {
77
121
  const pids = await pidsOnPort(); if (!pids.length) { console.log(`Port ${port} is free.`); return true; }
78
- for (const pid of pids) { const cmd = await commandLine(pid); console.log(`Port ${port} is occupied by PID ${pid}: ${cmd}`); if (!allowedEntries.some((candidate) => normalisePath(cmd).includes(normalisePath(candidate)))) { console.error(`Refusing to kill non-super-pi process on port ${port}: ${cmd}`); process.exitCode = 2; return false; } }
122
+ for (const pid of pids) { const cmd = await commandLine(pid); if (!allowedEntries.some((candidate) => normalisePath(cmd).includes(normalisePath(candidate)))) { console.error(`Refusing to stop non-Super Pi process on port ${port} (PID ${pid}).`); return false; } }
79
123
  const status = await requestShutdown();
80
124
  if (status !== null && status >= 200 && status < 300) {
81
125
  console.log(`Graceful shutdown accepted (HTTP ${status}); waiting for port ${port} to release...`);
82
126
  if (await waitForPortRelease(3000)) { console.log(`Port ${port} released after graceful shutdown.`); return true; }
83
- console.log(`Graceful shutdown did not release port ${port} within 3s.`);
127
+ console.log(`Graceful shutdown did not release port ${port} in time.`);
84
128
  } else {
85
129
  console.log(`Graceful shutdown unavailable (HTTP ${status ?? "no response"}); the running server may predate the shutdown endpoint.`);
86
130
  }
@@ -88,11 +132,19 @@ async function stopConflicts() {
88
132
  if (await waitForPortRelease(2000)) { console.log(`Port ${port} released after force kill.`); return true; }
89
133
  console.error(`Port ${port} is still occupied after force kill.`); process.exitCode = 1; return false;
90
134
  }
91
- if (await stopConflicts() === false) process.exit(2);
135
+ if (!await (gracefulOnly ? stopGracefully() : stopConflicts())) process.exit(2);
92
136
  console.log(`Starting ${entry} on port ${port}...`);
93
137
  const logPath = process.env.SUPER_PI_LOG ?? "restart-server.log";
94
138
  const logFd = openSync(logPath, "a");
95
- const child = spawn(process.execPath, [entry], { stdio: ["ignore", logFd, logFd], detached: true, env: process.env });
139
+ const serverEnv = { ...process.env };
140
+ delete serverEnv.SUPER_PI_RESTART_EXPECTED_VERSION;
141
+ delete serverEnv.SUPER_PI_RESTART_GRACEFUL_ONLY;
142
+ delete serverEnv.SUPER_PI_UPDATE_OPERATION_ID;
143
+ let child;
144
+ try { child = spawn(process.execPath, [entry], { stdio: ["ignore", logFd, logFd], detached: true, env: serverEnv, windowsHide: true }); }
145
+ finally { closeSync(logFd); }
146
+ let startupError;
147
+ child.once("error", error => { startupError = error.message; });
96
148
  child.unref();
97
149
  // HOW LONG THE NEW SERVER MAY TAKE TO BECOME REACHABLE.
98
150
  //
@@ -108,17 +160,18 @@ child.unref();
108
160
  const READINESS_BUDGET_MS = 120000;
109
161
  const deadline = Date.now() + READINESS_BUDGET_MS;
110
162
  while (Date.now() < deadline) {
111
- try {
112
- const response = await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(2_000) });
113
- const body = await response.json();
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);
163
+ const body = await readHealth(2_000);
164
+ if (body?.status === "ok" && body.service === "super-pi" && (!expectedVersion || body.runningVersion === expectedVersion)) {
165
+ if (process.env.SUPER_PI_UPDATE_OPERATION_ID) {
166
+ const file = join(dataDirectory, 'restart-service-completed.json'), temporary = `${file}.${process.pid}.tmp`;
167
+ writeFileSync(temporary, JSON.stringify({ id: process.env.SUPER_PI_UPDATE_OPERATION_ID, version: body.runningVersion })); renameSync(temporary, file);
120
168
  }
121
- } catch { /* The replacement is still starting. */ }
169
+ console.log("Server ready: /api/health passed."); process.exit(0);
170
+ }
171
+ if (startupError || child.exitCode !== null || child.signalCode !== null) {
172
+ console.error(`Server exited before becoming ready (${startupError ?? child.exitCode ?? child.signalCode}). See ${logPath}.`);
173
+ process.exit(1);
174
+ }
122
175
  await waitMs(200);
123
176
  }
124
177
  console.error(`Server did not become reachable within ${READINESS_BUDGET_MS}ms. It is STILL RUNNING - do not kill it, a slow start still ends up serving. See ${logPath}:`); try { console.error(readFileSync(logPath, "utf8").slice(-8000)); } catch {}