@evandu/super-pi 0.1.258 → 0.1.260

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 (53) hide show
  1. package/README.md +42 -0
  2. package/agents/super-pi-managed-model/index.ts +9 -0
  3. package/bin/npm-prefix.js +1 -1
  4. package/bin/super-pi.js +4 -3
  5. package/desktop/icon.png +0 -0
  6. package/desktop/launch.cjs +14 -0
  7. package/desktop/login-item.cjs +7 -0
  8. package/desktop/main.cjs +104 -0
  9. package/desktop/preload.cjs +9 -0
  10. package/desktop/runtime.cjs +107 -0
  11. package/dist/client/.super-pi-client-sources.json +33 -28
  12. package/dist/client/assets/CodeMirrorEditor-mi9rGUce.js +2 -0
  13. package/dist/client/assets/{GitDiffEditor-BOtWl74Z.js → GitDiffEditor-FQBfGxOY.js} +3 -3
  14. package/dist/client/assets/index-Cn7hdrDw.js +350 -0
  15. package/dist/client/assets/{index-JchFQmlF.css → index-UfzqdECL.css} +1 -1
  16. package/dist/client/index.html +2 -2
  17. package/dist/server/browser-access.d.ts +34 -0
  18. package/dist/server/browser-access.js +89 -0
  19. package/dist/server/command-handler.d.ts +1 -1
  20. package/dist/server/command-handler.js +3 -3
  21. package/dist/server/http-server.js +90 -36
  22. package/dist/server/index.js +9 -0
  23. package/dist/server/managed-http-tunnel.d.ts +6 -0
  24. package/dist/server/managed-http-tunnel.js +85 -0
  25. package/dist/server/managed-http.d.ts +4 -0
  26. package/dist/server/managed-http.js +85 -0
  27. package/dist/server/managed-model-adapter.d.ts +17 -0
  28. package/dist/server/managed-model-adapter.js +75 -0
  29. package/dist/server/managed-model-gateway.d.ts +49 -0
  30. package/dist/server/managed-model-gateway.js +73 -0
  31. package/dist/server/managed-servers.d.ts +55 -0
  32. package/dist/server/managed-servers.js +396 -0
  33. package/dist/server/managed-ssh.d.ts +26 -0
  34. package/dist/server/managed-ssh.js +73 -0
  35. package/dist/server/manager-vault.d.ts +11 -0
  36. package/dist/server/manager-vault.js +67 -0
  37. package/dist/server/provider-proxy.js +2 -0
  38. package/dist/server/remote-bootstrap.d.ts +17 -0
  39. package/dist/server/remote-bootstrap.js +119 -0
  40. package/dist/server/runtime.js +2 -2
  41. package/dist/server/server-context.d.ts +2 -0
  42. package/dist/server/terminal.d.ts +2 -2
  43. package/dist/server/terminal.js +6 -6
  44. package/dist/server/update.d.ts +1 -0
  45. package/dist/server/update.js +13 -2
  46. package/dist/server/ws-server.d.ts +5 -0
  47. package/dist/server/ws-server.js +29 -4
  48. package/dist/shared/managed-servers.d.ts +36 -0
  49. package/dist/shared/managed-servers.js +1 -0
  50. package/package.json +23 -4
  51. package/scripts/pack-server.mjs +44 -0
  52. package/dist/client/assets/CodeMirrorEditor-CyVU-MC_.js +0 -2
  53. package/dist/client/assets/index-Ba79LA0t.js +0 -349
@@ -8,9 +8,9 @@
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-Ba79LA0t.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-Cn7hdrDw.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
- <link rel="stylesheet" crossorigin href="/assets/index-JchFQmlF.css">
13
+ <link rel="stylesheet" crossorigin href="/assets/index-UfzqdECL.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
@@ -0,0 +1,34 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ export declare const isBrowserAuthorized: (request: object) => boolean;
3
+ /** Owner-issued browser access is separate from per-turn agent capabilities. */
4
+ export declare class BrowserAccess {
5
+ private readonly path;
6
+ private id;
7
+ private key?;
8
+ private readonly leases;
9
+ private readonly revoked;
10
+ onRevoke(listener: () => void): () => boolean;
11
+ private invalidate;
12
+ constructor(path: string);
13
+ private save;
14
+ private matches;
15
+ status(): {
16
+ id: `${string}-${string}-${string}-${string}-${string}`;
17
+ protocol: number;
18
+ enabled: boolean;
19
+ };
20
+ rotate(): {
21
+ id: `${string}-${string}-${string}-${string}-${string}`;
22
+ protocol: number;
23
+ enabled: boolean;
24
+ key: string;
25
+ };
26
+ revoke(): {
27
+ id: `${string}-${string}-${string}-${string}-${string}`;
28
+ protocol: number;
29
+ enabled: boolean;
30
+ };
31
+ lease(origin: string): string;
32
+ authorize(request: IncomingMessage, websocket?: boolean): boolean;
33
+ cors(request: IncomingMessage, response: ServerResponse): "local" | "allowed" | "denied" | "preflight";
34
+ }
@@ -0,0 +1,89 @@
1
+ import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ const authorized = new WeakSet();
4
+ export const isBrowserAuthorized = (request) => authorized.has(request);
5
+ const assetPath = (path) => /^\/api\/files\/(?:open-)?asset$/.test(path) || path === "/api/message-artifact" || path.startsWith("/api/upload/");
6
+ /** Owner-issued browser access is separate from per-turn agent capabilities. */
7
+ export class BrowserAccess {
8
+ path;
9
+ id = randomUUID();
10
+ key;
11
+ leases = new Map();
12
+ revoked = new Set();
13
+ onRevoke(listener) { this.revoked.add(listener); return () => this.revoked.delete(listener); }
14
+ invalidate() { this.leases.clear(); for (const listener of this.revoked)
15
+ listener(); }
16
+ constructor(path) {
17
+ this.path = path;
18
+ if (existsSync(path)) {
19
+ const stored = JSON.parse(readFileSync(path, "utf8"));
20
+ if (typeof stored.id === "string")
21
+ this.id = stored.id;
22
+ if (typeof stored.key === "string")
23
+ this.key = stored.key;
24
+ }
25
+ else
26
+ this.save();
27
+ }
28
+ save() { writeFileSync(this.path, JSON.stringify({ id: this.id, key: this.key }), { mode: 0o600 }); }
29
+ matches(key) {
30
+ if (!key || !this.key)
31
+ return false;
32
+ const a = Buffer.from(key), b = Buffer.from(this.key);
33
+ return a.length === b.length && timingSafeEqual(a, b);
34
+ }
35
+ status() { return { id: this.id, protocol: 1, enabled: Boolean(this.key) }; }
36
+ rotate() { this.key = randomBytes(32).toString("base64url"); this.invalidate(); this.save(); return { ...this.status(), key: this.key }; }
37
+ revoke() { this.key = undefined; this.invalidate(); this.save(); return this.status(); }
38
+ lease(origin) {
39
+ for (const [key, entry] of this.leases)
40
+ if (entry.expires < Date.now())
41
+ this.leases.delete(key);
42
+ if (this.leases.size >= 128)
43
+ this.leases.delete(this.leases.keys().next().value);
44
+ const ticket = randomBytes(24).toString("base64url");
45
+ this.leases.set(ticket, { origin, expires: Date.now() + 30 * 60_000 });
46
+ return ticket;
47
+ }
48
+ authorize(request, websocket = false) {
49
+ let key = request.headers.authorization?.replace(/^Bearer /, "");
50
+ if (websocket) {
51
+ const protocol = request.headers["sec-websocket-protocol"]?.split(",").map(item => item.trim()).find(item => item.startsWith("super-pi-key."));
52
+ if (protocol)
53
+ key = protocol.slice("super-pi-key.".length);
54
+ }
55
+ if (!this.matches(key)) {
56
+ const url = new URL(request.url ?? "/", "http://localhost");
57
+ const lease = this.leases.get(url.searchParams.get("browserAsset") ?? "");
58
+ if (websocket || request.method !== "GET" || !assetPath(url.pathname) || !lease || lease.expires < Date.now())
59
+ return false;
60
+ }
61
+ authorized.add(request);
62
+ return true;
63
+ }
64
+ cors(request, response) {
65
+ const origin = request.headers.origin;
66
+ if (!origin || origin === "null")
67
+ return "local";
68
+ let parsed;
69
+ try {
70
+ parsed = new URL(origin);
71
+ }
72
+ catch {
73
+ return "denied";
74
+ }
75
+ if (!["http:", "https:"].includes(parsed.protocol))
76
+ return "denied";
77
+ if (parsed.host === request.headers.host)
78
+ return "local";
79
+ response.setHeader("access-control-allow-origin", parsed.origin);
80
+ response.setHeader("vary", "Origin");
81
+ response.setHeader("access-control-expose-headers", "etag, content-disposition, content-length, last-modified, x-request-id");
82
+ if (request.method === "OPTIONS") {
83
+ response.setHeader("access-control-allow-methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS");
84
+ response.setHeader("access-control-allow-headers", "authorization, content-type, x-request-id, if-match, if-none-match, range");
85
+ return "preflight";
86
+ }
87
+ return this.authorize(request) ? "allowed" : "denied";
88
+ }
89
+ }
@@ -82,7 +82,7 @@ export declare class CommandHandler {
82
82
  claimRevert(conversationId: string): void;
83
83
  /** The other half of `claimRevert`. Safe to call for a conversation nothing claimed. */
84
84
  releaseRevert(conversationId: string): void;
85
- handleCommand(command: ClientCommand, sendToSocket?: SocketSender, remoteAddress?: string): Promise<string | void>;
85
+ handleCommand(command: ClientCommand, sendToSocket?: SocketSender, remoteAddress?: string, browserAuthorized?: boolean): Promise<string | void>;
86
86
  /**
87
87
  * The scheduled-task service, or a refusal.
88
88
  *
@@ -77,20 +77,20 @@ export class CommandHandler {
77
77
  releaseRevert(conversationId) {
78
78
  this.conversationService.releaseRevert(conversationId);
79
79
  }
80
- async handleCommand(command, sendToSocket, remoteAddress) {
80
+ async handleCommand(command, sendToSocket, remoteAddress, browserAuthorized = false) {
81
81
  if ("conversationId" in command && typeof command.conversationId === "string"
82
82
  && command.type !== "conversation.warm.delete" && this.conversationService.isWarmSession?.(command.conversationId)) {
83
83
  throw new Error("预热快照只能通过项目派发使用");
84
84
  }
85
85
  if (command.type === "terminal.shell.set") {
86
- if (!this.terminalService || !(await this.terminalService.setShell(command.command, remoteAddress)))
86
+ if (!this.terminalService || !(await this.terminalService.setShell(command.command, remoteAddress, browserAuthorized)))
87
87
  return;
88
88
  return;
89
89
  }
90
90
  if (command.type === "terminal.sync" || command.type === "terminal.detach" || command.type === "terminal.open" || command.type === "terminal.input" || command.type === "terminal.resize" || command.type === "terminal.close") {
91
91
  if (!this.terminalService)
92
92
  return;
93
- await this.terminalService.handle(command, remoteAddress, sendToSocket ?? (() => { }));
93
+ await this.terminalService.handle(command, remoteAddress, sendToSocket ?? (() => { }), browserAuthorized);
94
94
  return;
95
95
  }
96
96
  if (command.type === "model.rules.set") {
@@ -1,7 +1,9 @@
1
+ import { handleManagedHttp } from "./managed-http.js";
1
2
  import { createReadStream, existsSync } from "node:fs";
2
3
  import { matchPathMentions } from "../shared/file-mentions.js";
3
4
  import { spawn } from "node:child_process";
4
5
  import { randomUUID } from "node:crypto";
6
+ import { BrowserAccess, isBrowserAuthorized } from "./browser-access.js";
5
7
  import { NativeToolsService, NativeToolsError } from "./native-tools-service.js";
6
8
  import { once } from "node:events";
7
9
  import { readdir, realpath, rm, stat } from "node:fs/promises";
@@ -249,7 +251,7 @@ export function parseServerArgs(argv) {
249
251
  * Checks whether an incoming HTTP request satisfies access token authorization.
250
252
  */
251
253
  export function isAuthorized(request, accessToken) {
252
- return !accessToken || request.headers.authorization === `Bearer ${accessToken}`;
254
+ return isBrowserAuthorized(request) || !accessToken || request.headers.authorization === `Bearer ${accessToken}`;
253
255
  }
254
256
  /**
255
257
  * A signal that fires when the caller goes away, so work started on its behalf can stop.
@@ -362,6 +364,7 @@ export function createHttpServer(options) {
362
364
  const gitDrafts = new Set();
363
365
  const manageWorktree = createWorktreeService(context);
364
366
  const explicitFileOpen = createExplicitFileOpen();
367
+ const browserAccess = context.browserAccess ??= new BrowserAccess(join(paths.dataDir, "browser-access.json"));
365
368
  const nativeTools = new NativeToolsService(paths.dataDir, () => context.runtime?.reloadNativeTools?.());
366
369
  let tracker;
367
370
  const getUpdateTracker = () => tracker ??= new UpdateTracker(join(paths.dataDir ?? rootDir, "update-status.json"), rootDir);
@@ -385,6 +388,16 @@ export function createHttpServer(options) {
385
388
  try {
386
389
  // Internal tools use a narrow per-run capability, never the global management token.
387
390
  const requestPath = request.url?.split("?")[0] ?? "";
391
+ const cross = browserAccess.cors(request, response);
392
+ if (cross === "preflight") {
393
+ response.writeHead(204).end();
394
+ return;
395
+ }
396
+ if (cross === "denied") {
397
+ response.writeHead(401, { "content-type": "application/json" }).end(JSON.stringify({ error: "远程浏览器未获授权,请检查服务器连接密钥。" }));
398
+ return;
399
+ }
400
+ browserAccess.authorize(request);
388
401
  // Tool REGISTRATION is checked after its JSON body is parsed: an agent proves its turn capability
389
402
  // there, while an interactive browser uses the ordinary server access token. Reading and DELETING
390
403
  // the registry have no such second channel, so they are NOT exempted here and fall through to the
@@ -413,6 +426,43 @@ export function createHttpServer(options) {
413
426
  const url = new URL(request.url ?? "/", `http://${request.headers.host ?? "localhost"}`);
414
427
  const remote = request.socket.remoteAddress ?? "";
415
428
  const json = (status, body) => { response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }); response.end(JSON.stringify(body)); };
429
+ if (await handleManagedHttp(context, request, response, url))
430
+ return;
431
+ if (url.pathname === "/api/browser-access") {
432
+ if (request.method === "GET") {
433
+ json(200, { ...browserAccess.status(), ...(isBrowserAuthorized(request) ? { assetLease: browserAccess.lease(String(request.headers.origin ?? url.origin)) } : {}) });
434
+ return;
435
+ }
436
+ if (request.method !== "POST") {
437
+ json(405, { error: "仅支持 GET / POST" });
438
+ return;
439
+ }
440
+ if (!isBrowserAuthorized(request) && (!isLocalOrPrivateAddress(remote) || (request.headers.origin && request.headers.origin !== url.origin))) {
441
+ json(403, { error: "请在此服务器的本地或局域网设置中管理连接密钥。" });
442
+ return;
443
+ }
444
+ let body = "";
445
+ for await (const part of request) {
446
+ body += part;
447
+ if (body.length > 1024) {
448
+ json(413, { error: "请求过大" });
449
+ return;
450
+ }
451
+ }
452
+ try {
453
+ const action = JSON.parse(body).action;
454
+ if (action === "rotate")
455
+ json(200, browserAccess.rotate());
456
+ else if (action === "revoke")
457
+ json(200, browserAccess.revoke());
458
+ else
459
+ json(400, { error: "未知的连接授权操作" });
460
+ }
461
+ catch {
462
+ json(400, { error: "连接授权请求格式不正确" });
463
+ }
464
+ return;
465
+ }
416
466
  if (url.pathname === "/api/group-chats" && context.groupChatService) {
417
467
  const groups = context.groupChatService;
418
468
  const workspaceId = url.searchParams.get("workspaceId") ?? "";
@@ -917,7 +967,7 @@ export function createHttpServer(options) {
917
967
  return;
918
968
  }
919
969
  const origin = request.headers.origin;
920
- if (origin && origin !== url.origin) {
970
+ if (!isBrowserAuthorized(request) && origin && origin !== url.origin) {
921
971
  response.writeHead(403).end("Origin not allowed");
922
972
  return;
923
973
  }
@@ -992,7 +1042,7 @@ export function createHttpServer(options) {
992
1042
  const remote = request.socket.remoteAddress;
993
1043
  const origin = request.headers.origin;
994
1044
  const fetchSite = request.headers["sec-fetch-site"];
995
- if (!isLocalOrPrivateAddress(remote) || (origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
1045
+ if ((!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote)) || (!isBrowserAuthorized(request) && origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
996
1046
  json(403, { error: "外部工具管理只允许本机或局域网的同源请求。" });
997
1047
  return;
998
1048
  }
@@ -1108,7 +1158,7 @@ export function createHttpServer(options) {
1108
1158
  const remote = request.socket.remoteAddress;
1109
1159
  const origin = request.headers.origin;
1110
1160
  const fetchSite = request.headers["sec-fetch-site"];
1111
- if (!isLocalOrPrivateAddress(remote) || (origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
1161
+ if ((!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote)) || (!isBrowserAuthorized(request) && origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
1112
1162
  json(403, { error: "供应商授权只允许本机或局域网的同源请求。" });
1113
1163
  return;
1114
1164
  }
@@ -1180,7 +1230,7 @@ export function createHttpServer(options) {
1180
1230
  return;
1181
1231
  }
1182
1232
  const origin = request.headers.origin;
1183
- if (origin && origin !== url.origin) {
1233
+ if (!isBrowserAuthorized(request) && origin && origin !== url.origin) {
1184
1234
  response.writeHead(403).end("Origin not allowed");
1185
1235
  return;
1186
1236
  }
@@ -1216,7 +1266,7 @@ export function createHttpServer(options) {
1216
1266
  return;
1217
1267
  }
1218
1268
  const origin = request.headers.origin;
1219
- if (origin && origin !== url.origin) {
1269
+ if (!isBrowserAuthorized(request) && origin && origin !== url.origin) {
1220
1270
  response.writeHead(403).end("Origin not allowed");
1221
1271
  return;
1222
1272
  }
@@ -1255,7 +1305,7 @@ export function createHttpServer(options) {
1255
1305
  if (url.pathname === "/api/tavily/settings") {
1256
1306
  const origin = request.headers.origin;
1257
1307
  const fetchSite = request.headers["sec-fetch-site"];
1258
- if (!isLocalOrPrivateAddress(remote) || (origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
1308
+ if ((!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote)) || (!isBrowserAuthorized(request) && origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
1259
1309
  json(403, { error: "Tavily 凭据设置只允许本机或局域网的同源请求。" });
1260
1310
  return;
1261
1311
  }
@@ -1307,7 +1357,7 @@ export function createHttpServer(options) {
1307
1357
  return;
1308
1358
  }
1309
1359
  const origin = request.headers.origin;
1310
- if (origin && origin !== url.origin) {
1360
+ if (!isBrowserAuthorized(request) && origin && origin !== url.origin) {
1311
1361
  response.writeHead(403).end("Origin not allowed");
1312
1362
  return;
1313
1363
  }
@@ -1348,7 +1398,7 @@ export function createHttpServer(options) {
1348
1398
  return;
1349
1399
  }
1350
1400
  const origin = request.headers.origin;
1351
- if (origin && origin !== url.origin) {
1401
+ if (!isBrowserAuthorized(request) && origin && origin !== url.origin) {
1352
1402
  response.writeHead(403).end("Origin not allowed");
1353
1403
  return;
1354
1404
  }
@@ -1421,7 +1471,7 @@ export function createHttpServer(options) {
1421
1471
  json(405, { error: "这个接口只接受 POST 请求。" });
1422
1472
  return;
1423
1473
  }
1424
- if (!isLocalOrPrivateAddress(remote)) {
1474
+ if ((!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
1425
1475
  json(403, { error: "连接飞书账号只允许来自本机或局域网的请求。" });
1426
1476
  return;
1427
1477
  }
@@ -1448,7 +1498,7 @@ export function createHttpServer(options) {
1448
1498
  response.writeHead(503).end();
1449
1499
  return;
1450
1500
  }
1451
- if (!isLocalOrPrivateAddress(remote)) {
1501
+ if ((!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
1452
1502
  json(403, { error: "测试飞书连接只允许来自本机或局域网的请求。" });
1453
1503
  return;
1454
1504
  }
@@ -1457,7 +1507,7 @@ export function createHttpServer(options) {
1457
1507
  return;
1458
1508
  }
1459
1509
  if (url.pathname === "/api/shutdown") {
1460
- if (request.method !== "POST" || !isLocalOrPrivateAddress(remote)) {
1510
+ if (request.method !== "POST" || (!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
1461
1511
  response.writeHead(403, { "content-type": "text/plain; charset=utf-8" }).end("Shutdown requires a loopback or private network POST");
1462
1512
  return;
1463
1513
  }
@@ -1467,10 +1517,14 @@ export function createHttpServer(options) {
1467
1517
  return;
1468
1518
  }
1469
1519
  if (url.pathname === "/api/update" && request.method === "POST") {
1470
- if (!isLocalOrPrivateAddress(remote)) {
1520
+ if ((!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
1471
1521
  json(403, { error: "只允许从本机或局域网更新服务。" });
1472
1522
  return;
1473
1523
  }
1524
+ if (process.env.SUPER_PI_MANAGED_CONFIG) {
1525
+ json(409, { error: "此服务由本地入口托管,请在本地设置的「服务器连接 → SSH 托管」中重新部署以升级。" });
1526
+ return;
1527
+ }
1474
1528
  let body = {};
1475
1529
  try {
1476
1530
  const input = await readRequestText(request, 4096);
@@ -1581,7 +1635,7 @@ export function createHttpServer(options) {
1581
1635
  return;
1582
1636
  }
1583
1637
  if ((url.pathname === "/api/update-status" || url.pathname === "/api/update-check") && request.method === "GET") {
1584
- if (!isLocalOrPrivateAddress(remote)) {
1638
+ if ((!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
1585
1639
  json(403, { error: "只允许从本机或局域网查看更新。" });
1586
1640
  return;
1587
1641
  }
@@ -1608,7 +1662,7 @@ export function createHttpServer(options) {
1608
1662
  if (url.pathname === "/api/health") {
1609
1663
  const version = checkDiskVersion(rootDir);
1610
1664
  response.writeHead(200, { "content-type": "application/json; charset=utf-8" })
1611
- .end(JSON.stringify({ status: "ok", service: "super-pi", ...version }));
1665
+ .end(JSON.stringify({ status: "ok", service: "super-pi", manager: Boolean(context.managedServers), managed: Boolean(process.env.SUPER_PI_MANAGED_CONFIG), ...version }));
1612
1666
  return;
1613
1667
  }
1614
1668
  /**
@@ -1658,7 +1712,7 @@ export function createHttpServer(options) {
1658
1712
  }
1659
1713
  const origin = request.headers.origin;
1660
1714
  const fetchSite = request.headers["sec-fetch-site"];
1661
- if (!isLocalOrPrivateAddress(remote) || (origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
1715
+ if ((!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote)) || (!isBrowserAuthorized(request) && origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
1662
1716
  json(403, { error: "工作树操作需要来自同源的本机或局域网请求" });
1663
1717
  return;
1664
1718
  }
@@ -1737,7 +1791,7 @@ export function createHttpServer(options) {
1737
1791
  // keys to somebody's repository. The server listens on 0.0.0.0 by default and the global
1738
1792
  // access token is OPTIONAL (`isAuthorized` passes everyone when there is none), so this
1739
1793
  // predicate IS the boundary for every other write endpoint in this file (ledger TEST-042).
1740
- if (!isLocalOrPrivateAddress(remote)) {
1794
+ if ((!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
1741
1795
  json(403, { error: "Git 写操作只允许来自本机或局域网的请求。" });
1742
1796
  return;
1743
1797
  }
@@ -1923,7 +1977,7 @@ export function createHttpServer(options) {
1923
1977
  return;
1924
1978
  }
1925
1979
  if (url.pathname === "/api/subagent/dispatch") {
1926
- if (request.method !== "POST" || !isLocalOrPrivateAddress(remote)) {
1980
+ if (request.method !== "POST" || (!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
1927
1981
  response.writeHead(403, { "content-type": "text/plain; charset=utf-8" }).end("Sub-agent dispatch requires a loopback or private network POST");
1928
1982
  return;
1929
1983
  }
@@ -1964,7 +2018,7 @@ export function createHttpServer(options) {
1964
2018
  * Result is delivered via WebSocket exec.exit event and injected into the conversation.
1965
2019
  */
1966
2020
  if (url.pathname === "/api/exec") {
1967
- if (request.method !== "POST" || !isLocalOrPrivateAddress(remote)) {
2021
+ if (request.method !== "POST" || (!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
1968
2022
  response.writeHead(403, { "content-type": "text/plain; charset=utf-8" }).end("Exec requires a loopback or private network POST");
1969
2023
  return;
1970
2024
  }
@@ -2060,7 +2114,7 @@ export function createHttpServer(options) {
2060
2114
  return;
2061
2115
  }
2062
2116
  if (url.pathname === "/api/workflow/run") {
2063
- if (request.method !== "POST" || !isLocalOrPrivateAddress(remote)) {
2117
+ if (request.method !== "POST" || (!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
2064
2118
  response.writeHead(403, { "content-type": "text/plain; charset=utf-8" }).end("Workflow dispatch requires a loopback or private network POST");
2065
2119
  return;
2066
2120
  }
@@ -2096,7 +2150,7 @@ export function createHttpServer(options) {
2096
2150
  return;
2097
2151
  }
2098
2152
  if (url.pathname === "/api/todos") {
2099
- if (request.method !== "POST" || !isLocalOrPrivateAddress(remote)) {
2153
+ if (request.method !== "POST" || (!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
2100
2154
  response.writeHead(403, { "content-type": "text/plain; charset=utf-8" }).end("Todo writes require a loopback or private network POST");
2101
2155
  return;
2102
2156
  }
@@ -2140,7 +2194,7 @@ export function createHttpServer(options) {
2140
2194
  // THE AGENT'S DOOR TO THE SCHEDULED TASKS, and the same shape as `/api/todos`: exempt from the
2141
2195
  // global token because the caller proves itself with a per-conversation capability instead, and
2142
2196
  // restricted to loopback or a private network for the same reason `/api/todos` is.
2143
- if (request.method !== "POST" || !isLocalOrPrivateAddress(remote)) {
2197
+ if (request.method !== "POST" || (!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
2144
2198
  response.writeHead(403, { "content-type": "text/plain; charset=utf-8" }).end("Scheduled task writes require a loopback or private network POST");
2145
2199
  return;
2146
2200
  }
@@ -2243,7 +2297,7 @@ export function createHttpServer(options) {
2243
2297
  return;
2244
2298
  }
2245
2299
  if (url.pathname === "/api/projects" || url.pathname.startsWith("/api/projects/")) {
2246
- if (!isLocalOrPrivateAddress(remote)) {
2300
+ if ((!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
2247
2301
  json(403, { error: "项目控制面板只允许本机或私网访问" });
2248
2302
  return;
2249
2303
  }
@@ -2420,7 +2474,7 @@ export function createHttpServer(options) {
2420
2474
  return;
2421
2475
  }
2422
2476
  if (url.pathname === "/api/orchestrator") {
2423
- if (request.method !== "POST" || !isLocalOrPrivateAddress(remote)) {
2477
+ if (request.method !== "POST" || (!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
2424
2478
  response.writeHead(403, { "content-type": "text/plain; charset=utf-8" }).end("Orchestrator requires a loopback or private network POST");
2425
2479
  return;
2426
2480
  }
@@ -2793,7 +2847,7 @@ export function createHttpServer(options) {
2793
2847
  // would mean either the browser gets a dispatch credential it must not have, or the agent
2794
2848
  // loses the proof that it is the agent.
2795
2849
  if (url.pathname === "/api/orchestrator/stop") {
2796
- if (request.method !== "POST" || !isLocalOrPrivateAddress(remote)) {
2850
+ if (request.method !== "POST" || (!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
2797
2851
  response.writeHead(403, { "content-type": "text/plain; charset=utf-8" }).end("Stopping a session requires a loopback or private network POST");
2798
2852
  return;
2799
2853
  }
@@ -2850,7 +2904,7 @@ export function createHttpServer(options) {
2850
2904
  const json = (status, payload) => {
2851
2905
  response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }).end(JSON.stringify(payload));
2852
2906
  };
2853
- if (request.method !== "GET" || !isLocalOrPrivateAddress(remote)) {
2907
+ if (request.method !== "GET" || (!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
2854
2908
  json(403, { error: "Usage readout requires a local/private GET request." });
2855
2909
  return;
2856
2910
  }
@@ -2877,7 +2931,7 @@ export function createHttpServer(options) {
2877
2931
  return;
2878
2932
  }
2879
2933
  if (url.pathname === "/api/orchestrator/status" && request.method === "GET") {
2880
- if (!isLocalOrPrivateAddress(remote)) {
2934
+ if ((!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
2881
2935
  response.writeHead(403).end();
2882
2936
  return;
2883
2937
  }
@@ -2920,7 +2974,7 @@ export function createHttpServer(options) {
2920
2974
  return;
2921
2975
  }
2922
2976
  if (url.pathname === "/api/orchestrator/list" && request.method === "GET") {
2923
- if (!isLocalOrPrivateAddress(remote)) {
2977
+ if ((!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
2924
2978
  response.writeHead(403).end();
2925
2979
  return;
2926
2980
  }
@@ -2961,7 +3015,7 @@ export function createHttpServer(options) {
2961
3015
  return;
2962
3016
  }
2963
3017
  if (url.pathname === "/api/question") {
2964
- if (request.method !== "POST" || !isLocalOrPrivateAddress(remote)) {
3018
+ if (request.method !== "POST" || (!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
2965
3019
  response.writeHead(403).end();
2966
3020
  return;
2967
3021
  }
@@ -3055,8 +3109,8 @@ export function createHttpServer(options) {
3055
3109
  try {
3056
3110
  const origin = request.headers.origin;
3057
3111
  const fetchSite = request.headers["sec-fetch-site"];
3058
- if (!isLocalOrPrivateAddress(remote) || (fetchSite && fetchSite !== "same-origin" && fetchSite !== "none")
3059
- || (origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
3112
+ if ((!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote)) || (!isBrowserAuthorized(request) && fetchSite && fetchSite !== "same-origin" && fetchSite !== "none")
3113
+ || (!isBrowserAuthorized(request) && origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
3060
3114
  throw new FilesError(403, "打开外部文件需要来自同源的本机或局域网请求。", "denied");
3061
3115
  }
3062
3116
  const workspaceId = url.searchParams.get("workspaceId")?.trim();
@@ -3138,7 +3192,7 @@ export function createHttpServer(options) {
3138
3192
  }
3139
3193
  const origin = request.headers.origin;
3140
3194
  const fetchSite = request.headers["sec-fetch-site"];
3141
- if (!isLocalOrPrivateAddress(remote) || (origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
3195
+ if ((!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote)) || (!isBrowserAuthorized(request) && origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
3142
3196
  throw new FilesError(403, "文件操作需要来自同源的本机或局域网请求。", "denied");
3143
3197
  }
3144
3198
  let mutate;
@@ -3507,7 +3561,7 @@ export function createHttpServer(options) {
3507
3561
  }
3508
3562
  if (request.method === "PUT") {
3509
3563
  const remoteAddr = request.socket.remoteAddress ?? "";
3510
- if (!isLocalOrPrivateAddress(remoteAddr)) {
3564
+ if (!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remoteAddr)) {
3511
3565
  json(403, { error: "保存文件需要从本机或局域网发起。", code: "not_loopback" });
3512
3566
  return;
3513
3567
  }
@@ -3629,7 +3683,7 @@ export function createHttpServer(options) {
3629
3683
  return;
3630
3684
  }
3631
3685
  if (url.pathname === "/api/upload") {
3632
- if (request.method !== "POST" || !isLocalOrPrivateAddress(remote)) {
3686
+ if (request.method !== "POST" || (!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
3633
3687
  response.writeHead(403, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ error: "上传需要从本机或局域网发起。" }));
3634
3688
  return;
3635
3689
  }
@@ -3684,7 +3738,7 @@ export function createHttpServer(options) {
3684
3738
  return;
3685
3739
  }
3686
3740
  if (url.pathname.startsWith("/api/upload/")) {
3687
- if (request.method !== "GET" || !isLocalOrPrivateAddress(remote)) {
3741
+ if (request.method !== "GET" || (!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote))) {
3688
3742
  response.writeHead(403, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ error: "读取上传的图片需要从本机或局域网发起。" }));
3689
3743
  return;
3690
3744
  }
@@ -3761,7 +3815,7 @@ export function createHttpServer(options) {
3761
3815
  // an unexpected throw became an unhandled rejection and left clients with
3762
3816
  // a socket that simply hung. Preserve the real reason in the detached
3763
3817
  // server log and give the caller a bounded, correlatable response.
3764
- console.error(`Super Pi HTTP request failed requestId=${requestId} method=${request.method ?? "?"} url=${request.url ?? "?"}:`, describeThrown(error));
3818
+ console.error(`Super Pi HTTP request failed requestId=${requestId} method=${request.method ?? "?"} url=${request.url?.replace(/([?&]browserAsset=)[^&]*/g, "$1[redacted]") ?? "?"}:`, describeThrown(error));
3765
3819
  if (response.headersSent) {
3766
3820
  response.destroy();
3767
3821
  }
@@ -431,6 +431,7 @@ async function shutdown(reason) {
431
431
  // those sessions hold their working directory open, which is the lock that made a deleted workspace
432
432
  // fail to go away.
433
433
  await runtime.disposeSessions?.();
434
+ await serverContext.managedServers?.close();
434
435
  // The capabilities die AFTER the sessions that carry them: a session that is still alive could
435
436
  // otherwise use a credential the server has already forgotten about.
436
437
  releaseAllCapabilities();
@@ -445,6 +446,12 @@ async function shutdown(reason) {
445
446
  process.on("SIGINT", () => { void shutdown("SIGINT").finally(() => process.exit(0)); });
446
447
  process.on("SIGTERM", () => { void shutdown("SIGTERM").finally(() => process.exit(0)); });
447
448
  // ------------------------------------------------------------- Transports & startup
449
+ const fullPackage = JSON.parse(readFileSync(join(rootDir, "package.json"), "utf8")).name !== "@evandu/super-pi-server";
450
+ if (fullPackage && !process.env.SUPER_PI_MANAGED_CONFIG && process.env.SUPER_PI_DISABLE_MANAGER !== "1") {
451
+ const { ManagedServers } = await import("./managed-servers.js");
452
+ serverContext.managedServers = new ManagedServers(join(dataDir, "manager"), rootDir, () => store.defaultModel());
453
+ await serverContext.managedServers.initialize();
454
+ }
448
455
  const httpServer = createHttpServer({ context: serverContext, onShutdown: shutdown, port, host });
449
456
  const wsServer = new WsServer({
450
457
  httpServer,
@@ -454,6 +461,8 @@ const wsServer = new WsServer({
454
461
  accessToken,
455
462
  rootDir,
456
463
  onSocketClose: sender => terminalService.detach(sender),
464
+ browserAccess: serverContext.browserAccess,
465
+ managedServers: serverContext.managedServers,
457
466
  });
458
467
  httpServer.listen(port, host, () => {
459
468
  const displayHost = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
@@ -0,0 +1,6 @@
1
+ import { type IncomingMessage, type ServerResponse } from "node:http";
2
+ import type { Duplex } from "node:stream";
3
+ import type { Client } from "ssh2";
4
+ export declare function tunnelJson(client: Client, port: number, path: string, key: string, method?: string): Promise<any>;
5
+ export declare function proxyThroughSsh(client: Client, port: number, key: string, path: string, request: IncomingMessage, response: ServerResponse, basePath?: string): void;
6
+ export declare function proxyWebSocketThroughSsh(client: Client, port: number, key: string, path: string, request: IncomingMessage, socket: Duplex, head: Buffer): Promise<void>;