@evandu/super-pi 0.1.273 → 0.1.275

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 (97) hide show
  1. package/agents/group-rsi.md +18 -0
  2. package/agents/super-pi-documents/index.ts +16 -1
  3. package/agents/super-pi-task/core.ts +8 -8
  4. package/bin/completion.js +19 -5
  5. package/bin/render-presentation.ps1 +35 -0
  6. package/bin/super-pi.js +3 -0
  7. package/desktop/main.cjs +16 -9
  8. package/desktop/notifications.cjs +2 -1
  9. package/desktop/relaunch.cjs +5 -2
  10. package/desktop/restart-handoff.cjs +35 -0
  11. package/desktop/runtime.cjs +28 -4
  12. package/dist/client/.super-pi-client-sources.json +34 -19
  13. package/dist/client/assets/CodeMirrorEditor-DJgZdigq.js +2 -0
  14. package/dist/client/assets/{GitDiffEditor-CpoDDQrA.css → GitDiffEditor-DIRyUxnb.css} +1 -1
  15. package/dist/client/assets/GitDiffEditor-lOnvlR42.js +29 -0
  16. package/dist/client/assets/{dist-DGBjhKI9.js → dist-AW5lyI3I.js} +1 -1
  17. package/dist/client/assets/dist-B3-a6uF0.js +7 -0
  18. package/dist/client/assets/dist-BGxkyh6e.js +1 -0
  19. package/dist/client/assets/dist-BJxfd7yb.js +11 -0
  20. package/dist/client/assets/{dist-BvjUKkwy.js → dist-BRVQKlcp.js} +1 -1
  21. package/dist/client/assets/dist-BV64A9Ji.js +1 -0
  22. package/dist/client/assets/{dist-BlRuQIg1.js → dist-BXAOrsjq.js} +1 -1
  23. package/dist/client/assets/dist-CKF2Jksy.js +1 -0
  24. package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
  25. package/dist/client/assets/{dist-i79xiXVk.js → dist-Cus6_oaF.js} +2 -2
  26. package/dist/client/assets/dist-Cx00EZKR.js +23 -0
  27. package/dist/client/assets/dist-D71y2EI1.js +1 -0
  28. package/dist/client/assets/dist-Dc1MBGAG.js +1 -0
  29. package/dist/client/assets/dist-Dds-qLxY.js +9 -0
  30. package/dist/client/assets/dist-DeD9copn.js +1 -0
  31. package/dist/client/assets/dist-DuvGReu-.js +6 -0
  32. package/dist/client/assets/{dist-D5u1uPmZ.js → dist-Dvb0SqcK.js} +2 -2
  33. package/dist/client/assets/dist-J6XWqRpB.js +3 -0
  34. package/dist/client/assets/{dist-CQncCwUc.js → dist-QzbOCAU6.js} +1 -1
  35. package/dist/client/assets/{dist-DjI7p99D.js → dist-moiMRpw_.js} +1 -1
  36. package/dist/client/assets/dist-scBkrwv-.js +2 -0
  37. package/dist/client/assets/index-BWm699nV.js +350 -0
  38. package/dist/client/assets/index-CnNljc5p.css +1 -0
  39. package/dist/client/index.html +2 -2
  40. package/dist/server/agents.d.ts +1 -1
  41. package/dist/server/agents.js +10 -3
  42. package/dist/server/application/conversation-service.d.ts +1 -1
  43. package/dist/server/application/conversation-service.js +3 -2
  44. package/dist/server/application/document-service.d.ts +134 -0
  45. package/dist/server/application/document-service.js +9 -0
  46. package/dist/server/application/group-chat-service.d.ts +17 -0
  47. package/dist/server/application/group-chat-service.js +168 -3
  48. package/dist/server/application/group-rsi.d.ts +13 -0
  49. package/dist/server/application/group-rsi.js +69 -0
  50. package/dist/server/application/worktree-service.js +6 -2
  51. package/dist/server/http-server.js +54 -3
  52. package/dist/server/index.js +15 -2
  53. package/dist/server/managed-http.js +2 -1
  54. package/dist/server/managed-model-adapter.d.ts +4 -0
  55. package/dist/server/managed-model-relay.d.ts +1 -1
  56. package/dist/server/managed-model-relay.js +18 -15
  57. package/dist/server/managed-servers.d.ts +10 -1
  58. package/dist/server/managed-servers.js +63 -4
  59. package/dist/server/presentations/brief.d.ts +49 -0
  60. package/dist/server/presentations/brief.js +132 -0
  61. package/dist/server/presentations/inspect.d.ts +15 -0
  62. package/dist/server/presentations/inspect.js +30 -0
  63. package/dist/server/presentations/native.d.ts +8 -0
  64. package/dist/server/presentations/native.js +33 -0
  65. package/dist/server/presentations/render.d.ts +16 -0
  66. package/dist/server/presentations/render.js +152 -0
  67. package/dist/server/presentations/service.d.ts +176 -0
  68. package/dist/server/presentations/service.js +155 -0
  69. package/dist/server/remote-bootstrap.d.ts +11 -0
  70. package/dist/server/remote-bootstrap.js +105 -29
  71. package/dist/server/runtime.js +3 -2
  72. package/dist/shared/group-chat.d.ts +40 -0
  73. package/dist/shared/message-source-link.d.ts +1 -0
  74. package/dist/shared/message-source-link.js +4 -0
  75. package/dist/shared/workspace-file-preview.d.ts +1 -1
  76. package/dist/shared/workspace-file-preview.js +2 -0
  77. package/package.json +5 -1
  78. package/skills/presentation/SKILL.md +23 -1
  79. package/skills/presentation/references/spec.md +15 -0
  80. package/dist/client/assets/CodeMirrorEditor-D8MjtASz.js +0 -2
  81. package/dist/client/assets/GitDiffEditor-DFJmhUHc.js +0 -29
  82. package/dist/client/assets/dist-3qQVP6l8.js +0 -6
  83. package/dist/client/assets/dist-CZ4PyxQu.js +0 -9
  84. package/dist/client/assets/dist-CfTFp0AF.js +0 -2
  85. package/dist/client/assets/dist-CxmJXjJI.js +0 -1
  86. package/dist/client/assets/dist-D8HpMxmZ.js +0 -1
  87. package/dist/client/assets/dist-DRBIy9A1.js +0 -1
  88. package/dist/client/assets/dist-Dcww9FSw.js +0 -1
  89. package/dist/client/assets/dist-DlPa5gNa.js +0 -7
  90. package/dist/client/assets/dist-DxPJ1PN-.js +0 -1
  91. package/dist/client/assets/dist-HXD8sSA4.js +0 -23
  92. package/dist/client/assets/dist-LbeLCeoq.js +0 -1
  93. package/dist/client/assets/dist-ONdtnupI.js +0 -1
  94. package/dist/client/assets/dist-YqmXusLA.js +0 -11
  95. package/dist/client/assets/dist-ZAR1Tu2c.js +0 -3
  96. package/dist/client/assets/index-Bqutm6qV.js +0 -350
  97. package/dist/client/assets/index-DV3qc1Hh.css +0 -1
@@ -38,6 +38,7 @@ import { updateIsActive } from "../shared/update-status.js";
38
38
  import { FileIndex, refreshWorkspaceIndex } from "./file-index.js";
39
39
  import { ensureNameIndex, QUICK_OPEN_PAGE_SIZE, recordWorkspacePath } from "./file-name-index.js";
40
40
  import { resolveFileCwd, sessionScopeKey, workspacePathFromSession } from "./session-cwd.js";
41
+ import { presentationAsset, readPresentation } from "./presentations/service.js";
41
42
  import { explorerInternalPath, explorerPath, inspectWorkspaceUpload, listWorkspaceTrash, MAX_WORKSPACE_UPLOAD_BYTES, mutateWorkspaceTree, serializeWorkspaceWrite, uploadWorkspaceFile } from "./workspace-file-operations.js";
42
43
  import { readWorkspaceDocumentPreview, respondWithWorkspaceFile } from "./workspace-file-response.js";
43
44
  import { createExplicitFileOpen } from "./explicit-file-open.js";
@@ -571,6 +572,10 @@ export function createHttpServer(options) {
571
572
  json(200, await groups.configure(workspaceId, roomId, body));
572
573
  return;
573
574
  }
575
+ if (typeof body?.action === "string" && body.action.startsWith("rsi.")) {
576
+ json(200, await groups.updateRsi(workspaceId, roomId, body));
577
+ return;
578
+ }
574
579
  if (body?.action === "clone.resolve") {
575
580
  json(200, await groups.resolveClone(workspaceId, roomId, body));
576
581
  return;
@@ -1359,9 +1364,11 @@ export function createHttpServer(options) {
1359
1364
  response.writeHead(403, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ error: verdict.message }));
1360
1365
  return;
1361
1366
  }
1362
- const result = body.action === "write"
1363
- ? await context.documentService.write(conversationId, String(body.path ?? ""), String(body.content ?? ""), typeof body.title === "string" ? body.title : undefined, typeof body.baseEtag === "string" ? body.baseEtag : undefined)
1364
- : await context.documentService.read(conversationId, String(body.path ?? ""));
1367
+ const result = typeof body.action === "string" && body.action.startsWith("presentation_")
1368
+ ? await context.documentService.presentation(conversationId, body)
1369
+ : body.action === "write"
1370
+ ? await context.documentService.write(conversationId, String(body.path ?? ""), String(body.content ?? ""), typeof body.title === "string" ? body.title : undefined, typeof body.baseEtag === "string" ? body.baseEtag : undefined)
1371
+ : await context.documentService.read(conversationId, String(body.path ?? ""));
1365
1372
  response.writeHead(200, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify(result));
1366
1373
  }
1367
1374
  catch (error) {
@@ -1369,6 +1376,32 @@ export function createHttpServer(options) {
1369
1376
  }
1370
1377
  return;
1371
1378
  }
1379
+ if (url.pathname === "/api/presentations" || url.pathname === "/api/presentations/asset") {
1380
+ if (request.method !== "GET") {
1381
+ json(405, { error: "不支持此操作" });
1382
+ return;
1383
+ }
1384
+ try {
1385
+ const workspaceId = url.searchParams.get("workspaceId")?.trim();
1386
+ const workspace = workspaceId ? store.workspace(workspaceId) : undefined;
1387
+ if (!workspace || workspace.closedAt)
1388
+ throw new Error("请先选择有效工作区");
1389
+ const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
1390
+ const path = url.searchParams.get("path");
1391
+ if (!path)
1392
+ throw new Error("缺少 path");
1393
+ if (url.pathname.endsWith("/asset")) {
1394
+ const asset = await presentationAsset(root, path, url.searchParams.get("asset") ?? "");
1395
+ response.writeHead(200, { "content-type": asset.type, "cache-control": "no-store", "x-content-type-options": "nosniff", "content-security-policy": "default-src 'none'; style-src 'none'; sandbox" }).end(asset.bytes);
1396
+ }
1397
+ else
1398
+ json(200, await readPresentation(root, path));
1399
+ }
1400
+ catch (error) {
1401
+ json(400, { error: error instanceof Error ? error.message : String(error) });
1402
+ }
1403
+ return;
1404
+ }
1372
1405
  if (url.pathname === "/api/tavily/settings") {
1373
1406
  const origin = request.headers.origin;
1374
1407
  const fetchSite = request.headers["sec-fetch-site"];
@@ -1443,6 +1476,15 @@ export function createHttpServer(options) {
1443
1476
  return;
1444
1477
  }
1445
1478
  const body = raw ? JSON.parse(raw) : {};
1479
+ const entryConfig = await readManagedModelConfig();
1480
+ if (entryConfig?.entryIntegrations) {
1481
+ if (!entryConfig.entryIntegrations.web) {
1482
+ json(503, { error: "请在入口设置中连接 Tavily。" });
1483
+ return;
1484
+ }
1485
+ await remoteModelRelay.invoke(request, response, "/integration/web", raw);
1486
+ return;
1487
+ }
1446
1488
  const result = body.action === "search"
1447
1489
  ? await context.web.search(String(body.query ?? ""), Number(body.limit ?? 5), abortedAs(request))
1448
1490
  : body.action === "fetch"
@@ -1488,6 +1530,15 @@ export function createHttpServer(options) {
1488
1530
  return;
1489
1531
  }
1490
1532
  const body = raw ? JSON.parse(raw) : {};
1533
+ const entryConfig = await readManagedModelConfig();
1534
+ if (entryConfig?.entryIntegrations) {
1535
+ if (!entryConfig.entryIntegrations.feishu) {
1536
+ json(503, { error: "入口未提供飞书连接。" });
1537
+ return;
1538
+ }
1539
+ await remoteModelRelay.invoke(request, response, "/integration/feishu", raw);
1540
+ return;
1541
+ }
1491
1542
  json(200, await context.feishu.tool(body));
1492
1543
  }
1493
1544
  catch (error) {
@@ -44,6 +44,7 @@ import { ToolRunner } from "./tool-runner.js";
44
44
  import { ToolLlmService } from "./tool-llm.js";
45
45
  import { WebService } from "./web.js";
46
46
  import { TavilyService } from "./tavily.js";
47
+ import { readManagedModelConfig } from "./managed-model-adapter.js";
47
48
  // ------------------------------------------------------------- Environment & paths
48
49
  const rootDir = resolve(import.meta.dirname, "../..");
49
50
  initRunningVersion(rootDir);
@@ -201,7 +202,8 @@ process.env.SUPER_PI_FEISHU_ENDPOINT = `http://${internalHost}:${port}/api/feish
201
202
  const tavily = new TavilyService(join(dataDir, "tavily.json"));
202
203
  const web = new WebService(tavily);
203
204
  process.env.SUPER_PI_WEB_ENDPOINT = `http://${internalHost}:${port}/api/web/tool`;
204
- process.env.SUPER_PI_WEB_ENABLED = tavily.configured ? "1" : "0";
205
+ const entryIntegrations = (await readManagedModelConfig())?.entryIntegrations;
206
+ process.env.SUPER_PI_WEB_ENABLED = (entryIntegrations ? entryIntegrations.web : tavily.configured) ? "1" : "0";
205
207
  const extensionUiService = new ExtensionUiService(broadcaster, id => {
206
208
  const { parentConversationId, parent } = store.childSessionFacts(id);
207
209
  return !isChildSession(parentConversationId, parent);
@@ -449,7 +451,18 @@ process.on("SIGTERM", () => { void shutdown("SIGTERM").finally(() => process.exi
449
451
  const fullPackage = JSON.parse(readFileSync(join(rootDir, "package.json"), "utf8")).name !== "@evandu/super-pi-server";
450
452
  if (fullPackage && !process.env.SUPER_PI_MANAGED_CONFIG && process.env.SUPER_PI_DISABLE_MANAGER !== "1") {
451
453
  const { ManagedServers } = await import("./managed-servers.js");
452
- serverContext.managedServers = new ManagedServers(join(dataDir, "manager"), rootDir, () => store.defaultModel());
454
+ serverContext.managedServers = new ManagedServers(join(dataDir, "manager"), rootDir, () => store.defaultModel(), {
455
+ available: () => ({ web: tavily.configured, feishu: true }),
456
+ invoke: async (kind, body, signal) => {
457
+ if (kind === "feishu")
458
+ return feishu.tool(body);
459
+ if (body.action === "search")
460
+ return web.search(String(body.query ?? ""), Number(body.limit ?? 5), signal);
461
+ if (body.action === "fetch")
462
+ return web.fetch(String(body.url ?? ""), signal);
463
+ throw new Error("未知网页工具操作");
464
+ },
465
+ });
453
466
  await serverContext.managedServers.initialize();
454
467
  }
455
468
  const httpServer = createHttpServer({ context: serverContext, onShutdown: shutdown, port, host });
@@ -44,8 +44,9 @@ export async function handleManagedHttp(context, request, response, url) {
44
44
  const path = process.env.SUPER_PI_MANAGED_CONFIG;
45
45
  const temp = path + "." + randomUUID() + ".tmp";
46
46
  try {
47
- await writeFile(temp, JSON.stringify({ ...config, models: catalog.models, defaultModel: catalog.defaultModel, endpoint: `http://127.0.0.1:${request.socket.localPort}/api/managed-model/invoke` }), { mode: 0o600 });
47
+ await writeFile(temp, JSON.stringify({ ...config, models: catalog.models, defaultModel: catalog.defaultModel, entryIntegrations: catalog.entryIntegrations, endpoint: `http://127.0.0.1:${request.socket.localPort}/api/managed-model/invoke` }), { mode: 0o600 });
48
48
  await rename(temp, path);
49
+ process.env.SUPER_PI_WEB_ENABLED = catalog.entryIntegrations?.web === true ? "1" : "0";
49
50
  }
50
51
  finally {
51
52
  await rm(temp, { force: true });
@@ -1,5 +1,9 @@
1
1
  import type { Model } from "@earendil-works/pi-ai";
2
2
  export interface ManagedModelConfig {
3
+ entryIntegrations?: {
4
+ web: boolean;
5
+ feishu: boolean;
6
+ };
3
7
  endpoint: string;
4
8
  token: string;
5
9
  models: Model<string>[];
@@ -6,7 +6,7 @@ export declare class ModelRelay {
6
6
  private waiting;
7
7
  close(): void;
8
8
  attach(socket: WebSocket): void;
9
- invoke(request: IncomingMessage, response: ServerResponse): Promise<void>;
9
+ invoke(request: IncomingMessage, response: ServerResponse, path?: string, payload?: string): Promise<void>;
10
10
  }
11
11
  export declare const remoteModelRelay: ModelRelay;
12
12
  export declare function connectModelRelay(origin: string, key: string, gatewayPort: number, modelToken: string): WebSocket;
@@ -34,12 +34,12 @@ export class ModelRelay {
34
34
  if (this.socket !== socket)
35
35
  return;
36
36
  try {
37
- const { id, type, data, status } = JSON.parse(raw.toString());
37
+ const { id, type, data, status, contentType } = JSON.parse(raw.toString());
38
38
  const response = this.requests.get(id);
39
39
  if (!response)
40
40
  return;
41
41
  if (type === "start")
42
- response.writeHead(status, { "content-type": "application/x-ndjson", "cache-control": "no-store" });
42
+ response.writeHead(status, { "content-type": contentType === "application/json" ? contentType : "application/x-ndjson", "cache-control": "no-store" });
43
43
  else if (type === "data") {
44
44
  if (response.writableLength > maxRequest)
45
45
  response.destroy();
@@ -63,7 +63,7 @@ export class ModelRelay {
63
63
  }
64
64
  });
65
65
  }
66
- async invoke(request, response) {
66
+ async invoke(request, response, path = "/model", payload) {
67
67
  // Allow the manager's next health poll to reconnect after a service restart.
68
68
  if (this.socket?.readyState !== WebSocket.OPEN && this.waiting.size < maxConcurrent) {
69
69
  await new Promise(resolve => {
@@ -87,14 +87,17 @@ export class ModelRelay {
87
87
  }
88
88
  const parts = [];
89
89
  let size = 0;
90
- for await (const chunk of request) {
91
- size += chunk.length;
92
- if (size > maxRequest) {
93
- response.writeHead(413).end();
94
- return;
90
+ if (payload !== undefined)
91
+ parts.push(Buffer.from(payload));
92
+ else
93
+ for await (const chunk of request) {
94
+ size += chunk.length;
95
+ if (size > maxRequest) {
96
+ response.writeHead(413).end();
97
+ return;
98
+ }
99
+ parts.push(chunk);
95
100
  }
96
- parts.push(chunk);
97
- }
98
101
  if (this.socket !== socket || socket.readyState !== WebSocket.OPEN || this.requests.size >= maxConcurrent || socket.bufferedAmount > maxRequest) {
99
102
  response.writeHead(503).end();
100
103
  return;
@@ -105,7 +108,7 @@ export class ModelRelay {
105
108
  if (this.requests.delete(id) && socket.readyState === WebSocket.OPEN)
106
109
  socket.send(JSON.stringify({ type: "cancel", id }));
107
110
  });
108
- socket.send(JSON.stringify({ id, type: "request", body: Buffer.concat(parts).toString("base64") }), error => { if (error)
111
+ socket.send(JSON.stringify({ id, type: "request", path, body: Buffer.concat(parts).toString("base64") }), error => { if (error)
109
112
  response.destroy(); });
110
113
  }
111
114
  }
@@ -145,20 +148,20 @@ export function connectModelRelay(origin, key, gatewayPort, modelToken) {
145
148
  socket.terminate();
146
149
  return;
147
150
  }
148
- const { id, type, body } = message;
151
+ const { id, type, body, path = "/model" } = message;
149
152
  if (type === "cancel") {
150
153
  active.get(id)?.abort();
151
154
  return;
152
155
  }
153
- if (type !== "request" || typeof id !== "string" || typeof body !== "string" || active.has(id) || active.size >= maxConcurrent) {
156
+ if (type !== "request" || typeof id !== "string" || typeof body !== "string" || !["/model", "/integration/web", "/integration/feishu"].includes(path) || active.has(id) || active.size >= maxConcurrent) {
154
157
  socket.terminate();
155
158
  return;
156
159
  }
157
160
  const controller = new AbortController();
158
161
  active.set(id, controller);
159
162
  try {
160
- const result = await fetch(`http://127.0.0.1:${gatewayPort}/model`, { method: "POST", redirect: "error", headers: { authorization: `Bearer ${modelToken}`, "content-type": "application/json" }, body: Buffer.from(body, "base64"), signal: controller.signal });
161
- await send({ id, type: "start", status: result.status });
163
+ const result = await fetch(`http://127.0.0.1:${gatewayPort}${path}`, { method: "POST", redirect: "error", headers: { authorization: `Bearer ${modelToken}`, "content-type": "application/json" }, body: Buffer.from(body, "base64"), signal: controller.signal });
164
+ await send({ id, type: "start", status: result.status, contentType: result.headers.get("content-type") });
162
165
  const reader = result.body?.getReader();
163
166
  if (reader)
164
167
  for (;;) {
@@ -2,10 +2,18 @@ import { type IncomingMessage, type ServerResponse } from "node:http";
2
2
  import type { Duplex } from "node:stream";
3
3
  import type { Client } from "ssh2";
4
4
  import type { ManagedServerInput, ManagedServerProfile, SshVerification } from "../shared/managed-servers.js";
5
+ interface EntryIntegrations {
6
+ available(): {
7
+ web: boolean;
8
+ feishu: boolean;
9
+ };
10
+ invoke(kind: "web" | "feishu", body: Record<string, unknown>, signal: AbortSignal): Promise<unknown>;
11
+ }
5
12
  export declare class ManagedServers {
6
13
  private readonly directory;
7
14
  private readonly packageRoot;
8
15
  private readonly defaultModel;
16
+ private readonly integrations?;
9
17
  private readonly records;
10
18
  private readonly clients;
11
19
  private readonly secrets;
@@ -30,7 +38,7 @@ export declare class ManagedServers {
30
38
  constructor(directory: string, packageRoot: string, defaultModel: () => {
31
39
  provider: string;
32
40
  modelId: string;
33
- } | undefined);
41
+ } | undefined, integrations?: EntryIntegrations | undefined);
34
42
  initialize(): Promise<void>;
35
43
  list(): {
36
44
  id: string;
@@ -129,3 +137,4 @@ export declare class ManagedServers {
129
137
  upgrade(id: string, path: string, request: IncomingMessage, socket: Duplex, head: Buffer): Promise<void>;
130
138
  close(): Promise<void>;
131
139
  }
140
+ export {};
@@ -19,6 +19,7 @@ export class ManagedServers {
19
19
  directory;
20
20
  packageRoot;
21
21
  defaultModel;
22
+ integrations;
22
23
  records = new Map();
23
24
  clients = new Map();
24
25
  secrets = new Map();
@@ -40,10 +41,11 @@ export class ManagedServers {
40
41
  maintaining = false;
41
42
  persistence = Promise.resolve();
42
43
  artifact;
43
- constructor(directory, packageRoot, defaultModel) {
44
+ constructor(directory, packageRoot, defaultModel, integrations) {
44
45
  this.directory = directory;
45
46
  this.packageRoot = packageRoot;
46
47
  this.defaultModel = defaultModel;
48
+ this.integrations = integrations;
47
49
  this.vault = new ManagerVault(join(directory, "credentials"));
48
50
  }
49
51
  async initialize() {
@@ -83,7 +85,45 @@ export class ManagedServers {
83
85
  const expected = Buffer.from(token);
84
86
  return supplied.length === expected.length && timingSafeEqual(supplied, expected);
85
87
  });
86
- if (request.url !== "/model" || !valid) {
88
+ if (!valid) {
89
+ response.writeHead(403).end();
90
+ return;
91
+ }
92
+ if (["/integration/web", "/integration/feishu"].includes(request.url ?? "") && this.integrations) {
93
+ const kind = request.url === "/integration/web" ? "web" : "feishu";
94
+ const controller = new AbortController();
95
+ response.once("close", () => { if (!response.writableEnded)
96
+ controller.abort(); });
97
+ void (async () => {
98
+ try {
99
+ if (request.method !== "POST" || !this.integrations.available()[kind]) {
100
+ response.writeHead(503).end();
101
+ return;
102
+ }
103
+ const parts = [];
104
+ let size = 0;
105
+ for await (const part of request) {
106
+ size += part.length;
107
+ if (size > 4 * 1024 * 1024) {
108
+ response.writeHead(413).end();
109
+ return;
110
+ }
111
+ parts.push(part);
112
+ }
113
+ const body = JSON.parse(Buffer.concat(parts).toString("utf8"));
114
+ if (!body || typeof body !== "object" || Array.isArray(body))
115
+ throw new Error("入口服务请求格式无效");
116
+ const result = await this.integrations.invoke(kind, body, controller.signal);
117
+ response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(result));
118
+ }
119
+ catch (cause) {
120
+ if (!response.headersSent)
121
+ response.writeHead(400, { "content-type": "application/json" }).end(JSON.stringify({ error: cause instanceof Error ? cause.message : "入口服务调用失败" }));
122
+ }
123
+ })();
124
+ return;
125
+ }
126
+ if (request.url !== "/model") {
87
127
  response.writeHead(403).end();
88
128
  return;
89
129
  }
@@ -358,7 +398,7 @@ export class ManagedServers {
358
398
  if (reload && entry.profile.modelTransport === "direct" && relay?.readyState !== WebSocket.OPEN)
359
399
  throw new Error("服务端口的模型通道正在连接,请稍后重试");
360
400
  if (reload && entry.installation && secret && relay?.readyState === WebSocket.OPEN && entry.profile.serviceUrl) {
361
- const body = JSON.stringify({ models: await this.gateway.catalog(force), defaultModel: this.defaultModel() });
401
+ const body = JSON.stringify({ models: await this.gateway.catalog(force), defaultModel: this.defaultModel(), entryIntegrations: this.integrations?.available() });
362
402
  const hash = createHash("sha256").update(body).digest("hex");
363
403
  if (!force && this.syncedRelays.get(relay) === hash)
364
404
  return;
@@ -659,7 +699,26 @@ export class ManagedServers {
659
699
  if ((state.conversations ?? []).some((conversation) => ["running", "waiting", "awaiting_background"].includes(conversation.status)))
660
700
  throw new Error("远端仍有进行中的任务,请完成后再重新部署");
661
701
  }
662
- const installation = await installRemote({ client, id, archive: artifact.path, archiveHash: artifact.shasum, cacheDir: join(this.directory, "cache"), progress: (step, output) => this.progress(entry, step, output) });
702
+ let installation = entry.installation;
703
+ let reusable = false;
704
+ if (installation && installation.archiveHash && installation.archiveHash === artifact.shasum) {
705
+ try {
706
+ const files = [posix.join(installation.packageRoot, "dist/server/index.js"), posix.join(installation.packageRoot, "dist/client/index.html"), posix.join(installation.packageRoot, "agents/super-pi-managed-model/index.ts"), installation.piCommand];
707
+ const probe = `import{readFileSync,accessSync}from'node:fs';import{fileURLToPath}from'node:url';const[v,m]=process.versions.node.split('.').map(Number);if(!(v>22||(v===22&&m>=19)))throw Error('Unsupported Node runtime');const pkg=JSON.parse(readFileSync(${JSON.stringify(posix.join(installation.packageRoot, "package.json"))},'utf8'));if(pkg.name!=='@evandu/super-pi-server'||pkg.version!==${JSON.stringify(artifact.version)})throw Error('Unexpected installation');for(const file of ${JSON.stringify(files)})accessSync(file);accessSync(fileURLToPath(import.meta.resolve('@earendil-works/pi-coding-agent')));`;
708
+ await sshExec(client, `cd ${sh(installation.packageRoot)} && ${sh(installation.node)} --input-type=module -e ${sh(probe)}`);
709
+ reusable = true;
710
+ this.progress(entry, "复用已完成的同版本远端安装");
711
+ }
712
+ catch {
713
+ delete installation.archiveHash;
714
+ this.progress(entry, "已有安装不完整,正在修复");
715
+ await this.persist();
716
+ }
717
+ }
718
+ if (!reusable)
719
+ installation = await installRemote({ client, id, archive: artifact.path, archiveHash: artifact.shasum, cacheDir: join(this.directory, "cache"), progress: (step, output) => this.progress(entry, step, output) });
720
+ if (!installation)
721
+ throw new Error("远端安装未完成");
663
722
  entry.installation = installation;
664
723
  entry.profile.remoteRoot = installation.root;
665
724
  entry.profile.identity ??= randomUUID();
@@ -0,0 +1,49 @@
1
+ import { type PresentationSpec } from "./schema.js";
2
+ export type SlideBrief = {
3
+ id: string;
4
+ title: string;
5
+ layout?: "cover" | "body" | "comparison" | "chart" | "table" | "timeline" | "metrics";
6
+ subtitle?: string;
7
+ bullets?: string[];
8
+ columns?: {
9
+ title: string;
10
+ bullets: string[];
11
+ }[];
12
+ chart?: {
13
+ type: "bar" | "column" | "line" | "area" | "pie" | "doughnut";
14
+ categories: string[];
15
+ series: {
16
+ name: string;
17
+ values: number[];
18
+ }[];
19
+ };
20
+ table?: (string | number | boolean | null)[][];
21
+ steps?: {
22
+ title: string;
23
+ body: string;
24
+ }[];
25
+ metrics?: {
26
+ label: string;
27
+ value: string;
28
+ detail?: string;
29
+ }[];
30
+ notes?: string;
31
+ source?: string;
32
+ };
33
+ export type PresentationBrief = {
34
+ title: string;
35
+ author?: string;
36
+ data?: Record<string, unknown>;
37
+ slides: SlideBrief[];
38
+ };
39
+ export type PresentationSource = {
40
+ kind: "brief";
41
+ brief: PresentationBrief;
42
+ } | {
43
+ kind: "spec";
44
+ spec: PresentationSpec;
45
+ };
46
+ export declare function safeJson(text: string): any;
47
+ export declare function compile(source: PresentationSource): PresentationSpec;
48
+ /** Stable slide IDs make a local revision independent of pagination. */
49
+ export declare function patchSource(source: PresentationSource, patch: any): PresentationSource;
@@ -0,0 +1,132 @@
1
+ import { validatePresentationSpec } from "./schema.js";
2
+ const object = (v) => !!v && typeof v === "object" && !Array.isArray(v);
3
+ const forbidden = new Set(["__proto__", "prototype", "constructor"]);
4
+ export function safeJson(text) {
5
+ return JSON.parse(text, (key, value) => { if (forbidden.has(key))
6
+ throw new Error("不支持的 JSON 属性"); return value; });
7
+ }
8
+ function bind(value, data, depth = 0) {
9
+ if (depth > 24)
10
+ throw new Error("数据引用或对象嵌套过深");
11
+ const lookup = (key) => {
12
+ let found = data;
13
+ for (const part of key.split(".")) {
14
+ if (forbidden.has(part) || (!object(found) && !Array.isArray(found)) || !Object.hasOwn(found, part))
15
+ throw new Error(`数据引用不存在:${key}`);
16
+ found = found[part];
17
+ }
18
+ return found;
19
+ };
20
+ if (object(value) && Object.keys(value).length === 1 && typeof value.$ref === "string")
21
+ return bind(lookup(value.$ref), data, depth + 1);
22
+ if (typeof value === "string")
23
+ return value.replace(/\{\{([\w.-]+)\}\}/g, (_match, key) => {
24
+ const found = lookup(key);
25
+ if (!["string", "number", "boolean"].includes(typeof found))
26
+ throw new Error(`数据引用必须为标量:${key}`);
27
+ return String(found);
28
+ });
29
+ if (Array.isArray(value))
30
+ return value.map(item => bind(item, data, depth + 1));
31
+ if (object(value))
32
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, bind(item, data, depth + 1)]));
33
+ return value;
34
+ }
35
+ export function compile(source) {
36
+ let spec;
37
+ if (source.kind === "spec")
38
+ spec = source.spec;
39
+ else {
40
+ const brief = source.brief;
41
+ if (!object(brief) || typeof brief.title !== "string" || !Array.isArray(brief.slides) || !brief.slides.length || brief.slides.length > 200)
42
+ throw new Error("brief 需要 title 和 1–200 个 slides");
43
+ spec = { version: 1, canvas: { width: 13.333, height: 7.5 }, metadata: { title: brief.title, author: brief.author, language: "zh-CN" }, slides: [] };
44
+ for (const [index, original] of brief.slides.entries()) {
45
+ const slide = bind(original, brief.data ?? {});
46
+ if (!object(slide) || typeof slide.id !== "string" || typeof slide.title !== "string")
47
+ throw new Error(`第 ${index + 1} 页需要 id/title`);
48
+ const elements = [];
49
+ const text = (key, content, x, y, width, height, size = 22, bold = false, color = "233047") => {
50
+ if (typeof content !== "string")
51
+ throw new Error(`第 ${index + 1} 页 ${key} 必须为文字`);
52
+ elements.push({ id: `${slide.id}-${key}`, type: "text", x, y, width, height, text: content, fontSize: size, fontFamily: "Noto Sans SC", bold, color });
53
+ };
54
+ text("number", `${String(index + 1).padStart(2, "0")} / ${brief.slides.length}`, .6, 7.05, 2, .22, 10, false, "52627A");
55
+ text("title", slide.title, .65, slide.layout === "cover" ? 1.6 : .5, 12, slide.layout === "cover" ? 1.6 : .9, slide.layout === "cover" ? 36 : 28, true);
56
+ if (slide.source)
57
+ text("source", slide.source, 2.7, 7.02, 10, .3, 10, false, "52627A");
58
+ const bullets = (items, x, y, width, height, key) => text(key, items.map(item => `• ${item}`).join("\n\n"), x, y, width, height, 22);
59
+ const layout = slide.layout ?? (slide.chart ? "chart" : slide.table ? "table" : "body");
60
+ if (layout === "cover")
61
+ text("subtitle", slide.subtitle ?? "", .7, 3.7, 11.9, 1.5, 24, false, "52627A");
62
+ else if (layout === "body")
63
+ bullets(slide.bullets ?? [slide.subtitle ?? ""], .75, 1.75, 11.8, 4.85, "body");
64
+ else if (layout === "comparison") {
65
+ if (!slide.columns?.length || slide.columns.length > 3)
66
+ throw new Error("comparison 需要 1–3 个 columns");
67
+ const w = 12 / slide.columns.length;
68
+ slide.columns.forEach((col, i) => { text(`col-${i}`, col.title, .7 + w * i, 1.65, w - .35, .7, 24, true, "245BA8"); bullets(col.bullets, .7 + w * i, 2.6, w - .4, 3.9, `body-${i}`); });
69
+ }
70
+ else if (layout === "chart") {
71
+ if (!slide.chart)
72
+ throw new Error("chart 页面缺少 chart 数据");
73
+ elements.push({ id: `${slide.id}-chart`, type: "chart", x: .8, y: 1.6, width: 11.7, height: slide.subtitle ? 4.5 : 5.1, chart: slide.chart.type, categories: slide.chart.categories, series: slide.chart.series, showLegend: true, showValues: true });
74
+ if (slide.subtitle)
75
+ text("takeaway", slide.subtitle, .8, 6.25, 11.7, .6, 18);
76
+ }
77
+ else if (layout === "table") {
78
+ if (!slide.table?.length)
79
+ throw new Error("table 页面缺少 table");
80
+ elements.push({ id: `${slide.id}-table`, type: "table", x: .75, y: 1.65, width: 11.8, height: 5, rows: slide.table, headerRows: 1 });
81
+ }
82
+ else if (layout === "timeline" || layout === "metrics") {
83
+ const entries = layout === "timeline" ? slide.steps?.map(step => ({ label: step.title, value: step.body })) : slide.metrics;
84
+ if (!entries?.length || entries.length > 5)
85
+ throw new Error(`${layout} 需要 1–5 项`);
86
+ const w = 12 / entries.length;
87
+ entries.forEach((item, i) => {
88
+ text(`label-${i}`, item.label, .7 + w * i, 1.9, w - .35, 1, 20, true, "245BA8");
89
+ text(`value-${i}`, item.value, .7 + w * i, 3.05, w - .35, 2.1, layout === "metrics" ? 30 : 22, layout === "metrics");
90
+ if ("detail" in item && typeof item.detail === "string")
91
+ text(`detail-${i}`, item.detail, .7 + w * i, 5.4, w - .35, 1.1, 16);
92
+ });
93
+ }
94
+ else
95
+ throw new Error(`不支持的 layout:${layout}`);
96
+ spec.slides.push({ id: slide.id, title: slide.title, notes: slide.notes, background: "F8FAFD", elements });
97
+ }
98
+ }
99
+ const result = validatePresentationSpec(spec);
100
+ if (!result.valid)
101
+ throw new Error(JSON.stringify(result.diagnostics));
102
+ if (!spec.slides.length || spec.canvas.width > 56 || spec.canvas.height > 56)
103
+ throw new Error("页面数或画布大小非法");
104
+ return spec;
105
+ }
106
+ /** Stable slide IDs make a local revision independent of pagination. */
107
+ export function patchSource(source, patch) {
108
+ if (!object(patch))
109
+ throw new Error("patch 必须为对象");
110
+ const copy = structuredClone(source);
111
+ const deck = copy.kind === "brief" ? copy.brief : copy.spec;
112
+ if (patch.data !== undefined) {
113
+ if (copy.kind !== "brief" || !object(patch.data))
114
+ throw new Error("data 补丁仅用于 brief");
115
+ copy.brief.data = { ...copy.brief.data, ...patch.data };
116
+ }
117
+ if (patch.slides !== undefined) {
118
+ if (!object(patch.slides))
119
+ throw new Error("slides 补丁格式为 {页面ID: 字段补丁}");
120
+ for (const [id, changes] of Object.entries(patch.slides)) {
121
+ const index = deck.slides.findIndex(slide => slide.id === id);
122
+ if (index < 0 || !object(changes) || (changes.id !== undefined && changes.id !== id))
123
+ throw new Error(`页面补丁非法:${id}`);
124
+ Object.assign(deck.slides[index], changes);
125
+ }
126
+ }
127
+ const unknown = Object.keys(patch).filter(key => key !== "data" && key !== "slides");
128
+ if (unknown.length)
129
+ throw new Error(`不支持的补丁字段:${unknown.join(",")}`);
130
+ compile(copy);
131
+ return copy;
132
+ }
@@ -0,0 +1,15 @@
1
+ /** Inspect generated OOXML rather than making the model write a ZIP/XML checker for every deck. */
2
+ export declare function inspectPptx(bytes: Buffer): Promise<{
3
+ slides: number;
4
+ notes: number;
5
+ nativeCharts: number;
6
+ nativeTables: number;
7
+ editableTextShapes: number;
8
+ embeddedWorkbooks: number;
9
+ canvasInches: {
10
+ width: number;
11
+ height: number;
12
+ } | undefined;
13
+ relationships: string;
14
+ verification: string;
15
+ }>;
@@ -0,0 +1,30 @@
1
+ import { posix } from "node:path";
2
+ /** Inspect generated OOXML rather than making the model write a ZIP/XML checker for every deck. */
3
+ export async function inspectPptx(bytes) {
4
+ const { unzipSync, strFromU8 } = await import("fflate");
5
+ const files = unzipSync(bytes);
6
+ const names = Object.keys(files);
7
+ const slideNames = names.filter(name => /^ppt\/slides\/slide\d+\.xml$/.test(name));
8
+ const notes = names.filter(name => /^ppt\/notesSlides\/notesSlide\d+\.xml$/.test(name));
9
+ const charts = names.filter(name => /^ppt\/charts\/chart\d+\.xml$/.test(name));
10
+ const tables = slideNames.reduce((sum, name) => sum + (strFromU8(files[name]).match(/<a:tbl>/g)?.length ?? 0), 0);
11
+ const textShapes = slideNames.reduce((sum, name) => sum + (strFromU8(files[name]).match(/<p:sp>/g)?.length ?? 0), 0);
12
+ const missing = [];
13
+ for (const name of names.filter(name => name.endsWith(".rels"))) {
14
+ const directory = posix.dirname(name).replace(/(?:^|\/)\_rels$/, "");
15
+ for (const relation of strFromU8(files[name]).matchAll(/<Relationship\b[^>]*\/>/g)) {
16
+ if (/TargetMode="External"/.test(relation[0]))
17
+ continue;
18
+ const target = /\bTarget="([^"]+)"/.exec(relation[0])?.[1];
19
+ if (!target)
20
+ throw new Error("PPTX 包含缺少 Target 的关系");
21
+ const member = posix.normalize(target.startsWith("/") ? target.slice(1) : posix.join(directory, target));
22
+ if (!Object.hasOwn(files, member))
23
+ missing.push(`${name}: ${member}`);
24
+ }
25
+ }
26
+ if (!slideNames.length || missing.length)
27
+ throw new Error(`PPTX 结构检查失败:${missing.join("; ") || "没有页面"}`);
28
+ const size = /<p:sldSz\b[^>]*\bcx="(\d+)"[^>]*\bcy="(\d+)"/.exec(strFromU8(files["ppt/presentation.xml"]));
29
+ return { slides: slideNames.length, notes: notes.length, nativeCharts: charts.length, nativeTables: tables, editableTextShapes: textShapes, embeddedWorkbooks: names.filter(name => /^ppt\/embeddings\/.*\.xlsx$/.test(name)).length, canvasInches: size ? { width: Number(size[1]) / 914400, height: Number(size[2]) / 914400 } : undefined, relationships: "complete", verification: "OOXML structure; native rendering is reported separately" };
30
+ }
@@ -0,0 +1,8 @@
1
+ export type NativeResult = {
2
+ pages: Buffer[];
3
+ engine: string;
4
+ } | {
5
+ reason: string;
6
+ };
7
+ /** Native rendering is optional and serialized; a failed engine never masquerades as verified. */
8
+ export declare function nativePreview(path: string, count: number): Promise<NativeResult>;