@evandu/super-pi 0.1.224 → 0.1.226

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 (54) hide show
  1. package/dist/client/.super-pi-client-sources.json +12 -10
  2. package/dist/client/assets/{CodeMirrorEditor-CophJ9Eb.js → CodeMirrorEditor-CPx3FRkc.js} +2 -2
  3. package/dist/client/assets/{dist-CMPtWQjx.js → dist-BGy161xY.js} +1 -1
  4. package/dist/client/assets/{dist-D-s1GEbP.js → dist-BcRFLi-f.js} +1 -1
  5. package/dist/client/assets/{dist-C8FqYuNv.js → dist-Bd0vaQfP.js} +1 -1
  6. package/dist/client/assets/{dist-DBdR1Wph.js → dist-BhoawkM0.js} +1 -1
  7. package/dist/client/assets/{dist-CxeSxC9m.js → dist-BmCaXpyc.js} +1 -1
  8. package/dist/client/assets/{dist-BYjXg164.js → dist-Bwd9h3XI.js} +1 -1
  9. package/dist/client/assets/{dist-C3amppza.js → dist-C0ZllFZk.js} +1 -1
  10. package/dist/client/assets/{dist-ZuNGtw_8.js → dist-C5tVulbG.js} +1 -1
  11. package/dist/client/assets/{dist-ukIdoKjd.js → dist-CLLxHv6V.js} +1 -1
  12. package/dist/client/assets/{dist-D7On6h3N.js → dist-COJk6PBz.js} +1 -1
  13. package/dist/client/assets/{dist-BxcN7lnR.js → dist-Cof87msC.js} +1 -1
  14. package/dist/client/assets/{dist-CEbbDGoy.js → dist-CxjGmvQd.js} +1 -1
  15. package/dist/client/assets/{dist-C3BgT3PU.js → dist-DFNP-htp.js} +1 -1
  16. package/dist/client/assets/{dist-nSNA_ze3.js → dist-DFZitQ_p.js} +1 -1
  17. package/dist/client/assets/{dist-BGVYvXYo.js → dist-DKGCVyZl.js} +1 -1
  18. package/dist/client/assets/{dist-TcwefdPn.js → dist-DO-Ok2s5.js} +1 -1
  19. package/dist/client/assets/{dist-Clk6Knpv.js → dist-DUTy2lLM.js} +1 -1
  20. package/dist/client/assets/{dist-CFMeFXLU.js → dist-DdZFaGt2.js} +1 -1
  21. package/dist/client/assets/{dist-pVo8vQ15.js → dist-DeXOTgBM.js} +1 -1
  22. package/dist/client/assets/{dist-C0s45hG8.js → dist-Dm98rStJ.js} +1 -1
  23. package/dist/client/assets/{dist-i8fMtdTP.js → dist-RYlwHzIV.js} +1 -1
  24. package/dist/client/assets/{dist-Ch4dVwk4.js → dist-bizf5YwW.js} +1 -1
  25. package/dist/client/assets/index-DqNRh76b.css +1 -0
  26. package/dist/client/assets/index-FTyVhfLq.js +364 -0
  27. package/dist/client/index.html +2 -2
  28. package/dist/server/application/extension-ui-service.d.ts +6 -1
  29. package/dist/server/application/extension-ui-service.js +31 -2
  30. package/dist/server/application/run-service.d.ts +4 -1
  31. package/dist/server/application/run-service.js +58 -18
  32. package/dist/server/command-handler.js +11 -2
  33. package/dist/server/exec-service.d.ts +5 -2
  34. package/dist/server/exec-service.js +12 -2
  35. package/dist/server/http-server.js +40 -9
  36. package/dist/server/index.js +14 -9
  37. package/dist/server/persistence/app-state-repository.d.ts +3 -1
  38. package/dist/server/persistence/sqlite-state-repository.js +14 -1
  39. package/dist/server/store.d.ts +1 -0
  40. package/dist/server/store.js +49 -12
  41. package/dist/server/terminal.d.ts +26 -76
  42. package/dist/server/terminal.js +239 -172
  43. package/dist/server/tool-llm.d.ts +7 -0
  44. package/dist/server/tool-llm.js +8 -1
  45. package/dist/server/tool-runner.d.ts +7 -0
  46. package/dist/server/tool-runner.js +8 -1
  47. package/dist/server/types.d.ts +23 -75
  48. package/dist/server/ws-server.d.ts +7 -12
  49. package/dist/server/ws-server.js +23 -18
  50. package/dist/shared/terminal-protocol.d.ts +71 -0
  51. package/dist/shared/terminal-protocol.js +1 -0
  52. package/package.json +3 -1
  53. package/dist/client/assets/index-CoJT13t0.js +0 -105
  54. package/dist/client/assets/index-DK_mME9e.css +0 -1
@@ -8,8 +8,8 @@
8
8
  <link rel="alternate icon" href="/favicon.ico" />
9
9
  <link rel="apple-touch-icon" href="/favicon.svg" />
10
10
  <title>Super Pi</title>
11
- <script type="module" crossorigin src="/assets/index-CoJT13t0.js"></script>
12
- <link rel="stylesheet" crossorigin href="/assets/index-DK_mME9e.css">
11
+ <script type="module" crossorigin src="/assets/index-FTyVhfLq.js"></script>
12
+ <link rel="stylesheet" crossorigin href="/assets/index-DqNRh76b.css">
13
13
  </head>
14
14
  <body>
15
15
  <div id="root"></div>
@@ -1,5 +1,5 @@
1
1
  import type { ExtensionUiHost } from "../runtime.js";
2
- import type { ExtensionUiAnswer, ExtensionUiCloseReason } from "../types.js";
2
+ import type { ExtensionUiRequest, ExtensionUiAnswer, ExtensionUiCloseReason } from "../types.js";
3
3
  import type { EventBroadcaster } from "../server-context.js";
4
4
  /**
5
5
  * Service managing extension UI interactive prompts between Pi / subagents and connected clients.
@@ -16,6 +16,11 @@ export declare class ExtensionUiService {
16
16
  private readonly broadcaster;
17
17
  private readonly canAddressUser;
18
18
  private readonly pendingUi;
19
+ private readonly view;
20
+ snapshot(visible: Set<string>): {
21
+ conversationId: string;
22
+ request: ExtensionUiRequest;
23
+ }[];
19
24
  constructor(broadcaster: EventBroadcaster, canAddressUser?: (conversationId: string) => boolean);
20
25
  private uiKey;
21
26
  /**
@@ -13,6 +13,17 @@ export class ExtensionUiService {
13
13
  broadcaster;
14
14
  canAddressUser;
15
15
  pendingUi = new Map();
16
+ view = new Map();
17
+ snapshot(visible) {
18
+ const pending = [...this.pendingUi.values()].filter(item => visible.has(item.conversationId))
19
+ .map(({ conversationId, request }) => ({ conversationId, request }));
20
+ for (const [conversationId, requests] of this.view) {
21
+ if (visible.has(conversationId))
22
+ for (const request of requests.values())
23
+ pending.push({ conversationId, request });
24
+ }
25
+ return pending;
26
+ }
16
27
  constructor(broadcaster, canAddressUser = () => true) {
17
28
  this.broadcaster = broadcaster;
18
29
  this.canAddressUser = canAddressUser;
@@ -51,11 +62,14 @@ export class ExtensionUiService {
51
62
  * Cancels any pending UI requests for a given conversation.
52
63
  */
53
64
  cancelPendingUi(conversationId, reason) {
65
+ const cleared = reason !== "expired" && this.view.delete(conversationId);
54
66
  for (const [key, pending] of [...this.pendingUi]) {
55
67
  if (pending.conversationId === conversationId) {
56
68
  this.settleUi(key, { cancelled: true }, reason);
57
69
  }
58
70
  }
71
+ if (cleared)
72
+ this.broadcaster.broadcastState?.();
59
73
  }
60
74
  /**
61
75
  * Creates an ExtensionUiHost interface for a conversation or subagent run.
@@ -66,13 +80,28 @@ export class ExtensionUiService {
66
80
  notify: (request) => {
67
81
  if (!this.canAddressUser(conversationId))
68
82
  return;
69
- this.broadcaster.broadcast({ type: "extension.ui", conversationId, request: scoped(request) });
83
+ const shown = scoped(request);
84
+ if (request.method === "setStatus" || request.method === "setWidget" || request.method === "setTitle") {
85
+ const key = JSON.stringify([request.method, request.statusKey ?? request.widgetKey ?? ""]);
86
+ const view = this.view.get(conversationId) ?? new Map();
87
+ if ((request.method === "setStatus" && request.statusText === undefined)
88
+ || (request.method === "setWidget" && request.widgetLines === undefined)
89
+ || (request.method === "setTitle" && !request.title))
90
+ view.delete(key);
91
+ else
92
+ view.set(key, shown);
93
+ if (view.size)
94
+ this.view.set(conversationId, view);
95
+ else
96
+ this.view.delete(conversationId);
97
+ }
98
+ this.broadcaster.broadcast({ type: "extension.ui", conversationId, request: shown });
70
99
  },
71
100
  ask: async (request) => {
72
101
  if (!this.canAddressUser(conversationId))
73
102
  return { cancelled: true };
74
103
  return new Promise((resolve) => {
75
- const shown = scoped(request);
104
+ const shown = scoped(request.timeoutMs === undefined ? request : { ...request, deadlineAt: Date.now() + request.timeoutMs });
76
105
  const key = this.uiKey(conversationId, shown.requestId);
77
106
  // Only the Pi-declared `timeoutMs` is honoured. There is no safety net when Pi did not set
78
107
  // one: a question Pi chose to leave open is a question the model is waiting on, and a
@@ -91,6 +91,8 @@ export declare class RunService {
91
91
  setNameIndexes(indexes: Map<string, import("../file-name-index.js").FileNameIndex>): void;
92
92
  reviewMemoryBoundary(conversationId: string): void;
93
93
  private readonly activeRuns;
94
+ stoppingConversationIds(): string[];
95
+ private readonly acceptingSends;
94
96
  private readonly lengthContinuations;
95
97
  private readonly turnEventScopes;
96
98
  private readonly historyCutClaims;
@@ -441,7 +443,8 @@ export declare class RunService {
441
443
  mode?: MessageDeliveryMode;
442
444
  onAccepted?: (messageId: string) => void;
443
445
  }): Promise<void>;
444
- enqueueAndRun(conversationId: string, content: string, images?: MessageImage[], attachments?: Message["attachments"], clientId?: string, mode?: MessageDeliveryMode): Promise<void>;
446
+ acknowledgeAcceptedSend(conversationId: string, clientId: string | undefined): Promise<boolean>;
447
+ enqueueAndRun(conversationId: string, content: string, images?: MessageImage[], attachments?: Message["attachments"], clientId?: string, mode?: MessageDeliveryMode, onAccepted?: () => void): Promise<void>;
445
448
  enqueueReminder(conversationId: string, note: string): Promise<void>;
446
449
  private enqueueMessage;
447
450
  /**
@@ -170,6 +170,10 @@ export class RunService {
170
170
  this.memory?.review(conversation);
171
171
  }
172
172
  activeRuns = new Map();
173
+ stoppingConversationIds() {
174
+ return [...this.activeRuns].filter(([, controller]) => controller.signal.aborted).map(([id]) => id);
175
+ }
176
+ acceptingSends = new Map();
173
177
  lengthContinuations = new Map();
174
178
  turnEventScopes = new Map();
175
179
  historyCutClaims = new Map();
@@ -592,11 +596,31 @@ export class RunService {
592
596
  const existing = this.store.question(command.conversationId, command.messageId, command.callIndex);
593
597
  if (!existing)
594
598
  throw new Error("这个工具调用不是一个问题");
599
+ if (existing.status !== "pending")
600
+ return;
601
+ const answers = command.answers ?? [];
602
+ if (!command.cancelled) {
603
+ const seen = new Set();
604
+ if (!Array.isArray(answers) || !answers.length)
605
+ throw new Error("请选择至少一个选项。");
606
+ for (const answer of answers) {
607
+ const item = answer && existing.items.find(item => item.id === answer.id);
608
+ if (!item || seen.has(item.id) || !Array.isArray(answer.selected)
609
+ || (!item.multiple && answer.selected.length > 1) || new Set(answer.selected).size !== answer.selected.length
610
+ || answer.selected.some(option => !item.options.includes(option))
611
+ || (answer.note !== undefined && (!item.extraNote || typeof answer.note !== "string"))) {
612
+ throw new Error("答案与提问选项不匹配。");
613
+ }
614
+ seen.add(item.id);
615
+ }
616
+ if (!answers.some(answer => answer.selected.length))
617
+ throw new Error("请选择至少一个选项。");
618
+ }
595
619
  const calls = await this.store.updateToolCall(command.conversationId, command.messageId, command.callIndex, {
596
620
  question: {
597
621
  items: existing.items,
598
622
  status: command.cancelled ? "cancelled" : "answered",
599
- ...(command.cancelled ? {} : { answers: command.answers ?? [] }),
623
+ ...(command.cancelled ? {} : { answers }),
600
624
  },
601
625
  });
602
626
  this.broadcaster.broadcast({ type: "message.tools", conversationId: command.conversationId, messageId: command.messageId, toolCalls: calls });
@@ -1988,29 +2012,44 @@ export class RunService {
1988
2012
  this.broadcaster.broadcastState();
1989
2013
  }
1990
2014
  }
1991
- enqueueAndRun(conversationId, content, images, attachments, clientId, mode) {
1992
- return this.enqueueMessage(conversationId, content, { images, attachments, clientId, mode });
2015
+ async acknowledgeAcceptedSend(conversationId, clientId) {
2016
+ if (!clientId)
2017
+ return false;
2018
+ const pending = this.acceptingSends.get(JSON.stringify([conversationId, clientId]));
2019
+ if (pending)
2020
+ await pending;
2021
+ return this.store.hasAcceptedSend(conversationId, clientId);
2022
+ }
2023
+ enqueueAndRun(conversationId, content, images, attachments, clientId, mode, onAccepted) {
2024
+ if (!clientId)
2025
+ return this.enqueueMessage(conversationId, content, { images, attachments, mode });
2026
+ const key = JSON.stringify([conversationId, clientId]);
2027
+ const pending = this.acceptingSends.get(key);
2028
+ if (pending)
2029
+ return pending.then(() => { if (this.store.hasAcceptedSend(conversationId, clientId))
2030
+ onAccepted?.(); });
2031
+ if (this.store.hasAcceptedSend(conversationId, clientId)) {
2032
+ onAccepted?.();
2033
+ return Promise.resolve();
2034
+ }
2035
+ let accepted;
2036
+ const receipt = new Promise(resolve => { accepted = resolve; });
2037
+ const work = this.enqueueMessage(conversationId, content, {
2038
+ images, attachments, clientId, mode,
2039
+ accepted: () => { accepted(); onAccepted?.(); },
2040
+ });
2041
+ const admission = Promise.race([work, receipt]);
2042
+ this.acceptingSends.set(key, admission);
2043
+ void admission.finally(() => { if (this.acceptingSends.get(key) === admission)
2044
+ this.acceptingSends.delete(key); }).catch(() => { });
2045
+ return work;
1993
2046
  }
1994
2047
  enqueueReminder(conversationId, note) {
1995
2048
  return this.enqueueMessage(conversationId, note, { source: "session-reminder" });
1996
2049
  }
1997
- async enqueueMessage(conversationId, content, { images, attachments, clientId, mode, source }) {
2050
+ async enqueueMessage(conversationId, content, { images, attachments, clientId, mode, source, accepted }) {
1998
2051
  const deliveryMode = parseMessageDeliveryMode(mode);
1999
2052
  this.assertHistoryAvailable(conversationId);
2000
- /**
2001
- * A CLIENT ID THIS CONVERSATION ALREADY HAS IS A RESEND, NOT A SECOND MESSAGE.
2002
- *
2003
- * The browser retries a send whose socket dropped before the answer arrived (see
2004
- * `src/client/pending-operations.ts`), and it cannot know whether the first attempt reached this
2005
- * server. It usually did - the drop is a restart or a sleeping laptop, not a refusal - so without
2006
- * this guard the retry would be a second user message, answered twice, for words the person said
2007
- * once. The id is minted per compose by the browser, so a match cannot be a coincidence.
2008
- *
2009
- * Returning silently is the whole answer: the original message is already in the transcript, and
2010
- * the browser learns it from the state snapshot that arrives on connect.
2011
- */
2012
- if (clientId && this.store.hasMessage(conversationId, clientId))
2013
- return;
2014
2053
  this.memory?.cancel(conversationId);
2015
2054
  if (source || !isLengthContinuation(content)) {
2016
2055
  this.lengthContinuations.delete(conversationId);
@@ -2069,6 +2108,7 @@ export class RunService {
2069
2108
  throw error;
2070
2109
  }
2071
2110
  this.broadcaster.broadcastState();
2111
+ accepted?.();
2072
2112
  if (!reservedController) {
2073
2113
  // The turn that is running answers this message itself, through Pi's own follow-up queue, rather
2074
2114
  // than by a turn of its own once the running one is over. The message stays in the waiting list
@@ -87,7 +87,7 @@ export class CommandHandler {
87
87
  return;
88
88
  return;
89
89
  }
90
- if (command.type === "terminal.open" || command.type === "terminal.input" || command.type === "terminal.resize" || command.type === "terminal.close") {
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
93
  await this.terminalService.handle(command, remoteAddress, sendToSocket ?? (() => { }));
@@ -165,6 +165,7 @@ export class CommandHandler {
165
165
  }
166
166
  if (command.type === "workspace.delete") {
167
167
  await this.workspaceService.deleteWorkspace(command.workspaceId);
168
+ this.terminalService?.removeWorkspace(command.workspaceId);
168
169
  return;
169
170
  }
170
171
  if (command.type === "workspace.settings") {
@@ -268,6 +269,14 @@ export class CommandHandler {
268
269
  return;
269
270
  }
270
271
  if (command.type === "message.send") {
272
+ const accepted = () => {
273
+ if (command.clientId)
274
+ sendToSocket?.({ type: "message.accepted", conversationId: command.conversationId, clientId: command.clientId });
275
+ };
276
+ if (await this.runService.acknowledgeAcceptedSend?.(command.conversationId, command.clientId)) {
277
+ accepted();
278
+ return;
279
+ }
271
280
  // THE LOCK IS NOT ONLY A DRAWING. A child session's composer is locked in the interface, and
272
281
  // this is the half that makes the lock real: the reporting line only runs upwards, one level
273
282
  // at a time, so the reader does not talk to a child session directly - unless they deliberately
@@ -293,7 +302,7 @@ export class CommandHandler {
293
302
  // attachment lost it on arrival - the browser drew the attachment, the transcript never had it, and
294
303
  // the model was handed the bare prompt. Forwarded now because this is the one line that carries
295
304
  // every field of the send.
296
- await this.runService.enqueueAndRun(command.conversationId, command.content, command.images, command.attachments, command.clientId, command.mode);
305
+ await this.runService.enqueueAndRun(command.conversationId, command.content, command.images, command.attachments, command.clientId, command.mode, accepted);
297
306
  return;
298
307
  }
299
308
  if (command.type === "message.steer") {
@@ -5,7 +5,7 @@
5
5
  * collects its output, and fires an onComplete callback. It exists so the pi-task tool can run background
6
6
  * bash commands without going through the subagent dispatch machinery.
7
7
  */
8
- import type { ExecEvent } from "./types.js";
8
+ import type { AppState, ExecEvent } from "./types.js";
9
9
  export interface ExecSession {
10
10
  id: string;
11
11
  pid: number;
@@ -28,7 +28,10 @@ export declare class ExecService {
28
28
  enabled: boolean;
29
29
  reason?: string;
30
30
  };
31
- spawn(id: string, cmd: string, cwd: string): ExecSession;
31
+ spawn(id: string, cmd: string, cwd: string, conversationId?: string): ExecSession;
32
+ outputSnapshots(state: Pick<AppState, "conversations" | "backgroundTasks">, scope?: {
33
+ conversationId?: string;
34
+ }): ExecEvent[];
32
35
  kill(id: string): void;
33
36
  closeAll(): void;
34
37
  private flushStderr;
@@ -43,13 +43,14 @@ export class ExecService {
43
43
  return { enabled: false, reason: ptyLoadError() };
44
44
  return { enabled: true };
45
45
  }
46
- spawn(id, cmd, cwd) {
46
+ spawn(id, cmd, cwd, conversationId) {
47
47
  const pty = loadPty();
48
48
  if (!pty)
49
49
  throw new Error("node-pty is not available");
50
50
  // Determine shell to run the command.
51
51
  const shell = defaultShell();
52
52
  const active = {
53
+ conversationId,
53
54
  pty: pty.spawn(shell.file, [...shell.args, "-c", cmd], {
54
55
  name: "xterm-256color",
55
56
  cols: 80,
@@ -65,7 +66,7 @@ export class ExecService {
65
66
  active.stdout += data;
66
67
  if (active.stdout.length > MAX_BACKLOG_BYTES)
67
68
  active.stdout = active.stdout.slice(-MAX_BACKLOG_BYTES);
68
- this.broadcast({ type: "exec.output", sessionId: id, data });
69
+ this.broadcast({ type: "exec.output", sessionId: id, conversationId, data });
69
70
  });
70
71
  // Flush stderr via a periodic timer rather than a separate channel.
71
72
  // node-pty on Windows multiplexes both streams; on Unix they are separate.
@@ -89,6 +90,15 @@ export class ExecService {
89
90
  killed: false,
90
91
  };
91
92
  }
93
+ outputSnapshots(state, scope) {
94
+ const visible = new Set(state.conversations.map(conversation => conversation.id));
95
+ const ids = state.backgroundTasks.filter(task => visible.has(task.conversationId) && (!scope || task.conversationId === scope.conversationId)).map(task => task.id);
96
+ const maxPerTask = Math.min(128_000, Math.max(1, Math.floor(512_000 / Math.max(ids.length, 1))));
97
+ return ids.flatMap(id => {
98
+ const session = this.sessions.get(id);
99
+ return session ? [{ type: "exec.output", sessionId: id, conversationId: session.conversationId, data: session.stdout.slice(-maxPerTask), replace: true }] : [];
100
+ });
101
+ }
92
102
  kill(id) {
93
103
  const session = this.sessions.get(id);
94
104
  if (!session || session.killed)
@@ -79,15 +79,19 @@ const MIME_TYPES = {
79
79
  */
80
80
  function toolBrowserSdk() {
81
81
  return String.raw `(() => {
82
- const request = async (path, init) => {
83
- const response = await fetch(path, init);
82
+ const ownerId = new URLSearchParams(location.hash.slice(1)).get("super-pi-owner");
83
+ const request = async (path, init, owned = false) => {
84
+ const headers = new Headers(init.headers);
85
+ if (ownerId && owned) headers.set("x-super-pi-tool-owner", ownerId);
86
+ const response = await fetch(path, { ...init, headers });
84
87
  let body;
85
88
  try { body = await response.json(); } catch { body = { error: "Super Pi returned an unreadable response" }; }
86
89
  if (!response.ok) throw new Error(body && body.error ? body.error : "Tool request failed (HTTP " + response.status + ")");
87
90
  return body;
88
91
  };
89
92
  const api = {
90
- run: (params = {}) => request("./api/run", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ params }) }),
93
+ run: (params = {}) => request("./api/run", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ params }) }, true),
94
+ listRuns: () => request("./api/runs", { method: "GET" }, true),
91
95
  get: (runId) => request("./api/runs/" + encodeURIComponent(runId), { method: "GET" }),
92
96
  cancel: (runId) => request("./api/runs/" + encodeURIComponent(runId), { method: "DELETE" }),
93
97
  wait: async (runId, { intervalMs = 250, signal } = {}) => {
@@ -106,7 +110,8 @@ function toolBrowserSdk() {
106
110
  // credentials, the model choice and the ceilings, and the tool only ever sees the text. It is a
107
111
  // completion, not an agent - the model that answers has no tools, no files and no session history.
108
112
  // Only a tool registered with permissions.llm may call it; otherwise the server refuses.
109
- llm: (input = {}) => request("./api/llm", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(input) }),
113
+ llm: (input = {}) => request("./api/llm", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(input) }, true),
114
+ listLlmCalls: () => request("./api/llm", { method: "GET" }, true),
110
115
  llmGet: (callId) => request("./api/llm/" + encodeURIComponent(callId), { method: "GET" }),
111
116
  llmCancel: (callId) => request("./api/llm/" + encodeURIComponent(callId), { method: "DELETE" }),
112
117
  llmWait: async (callId, { intervalMs = 400, signal } = {}) => {
@@ -510,13 +515,35 @@ export function createHttpServer(options) {
510
515
  response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", "access-control-allow-origin": "null", "vary": "Origin" });
511
516
  response.end(JSON.stringify(body));
512
517
  };
518
+ const ownerHeader = request.headers["x-super-pi-tool-owner"];
519
+ const ownerId = typeof ownerHeader === "string" && /^[0-9a-f]{32}$/.test(ownerHeader) ? ownerHeader : undefined;
520
+ const toolPreflight = (methods) => response.writeHead(204, {
521
+ "access-control-allow-origin": "null", "access-control-allow-methods": methods,
522
+ "access-control-allow-headers": "content-type, x-super-pi-tool-owner", "access-control-max-age": "300", "vary": "Origin",
523
+ }).end();
524
+ if (resource === "api/runs") {
525
+ if (!toolOrigin) {
526
+ toolApi(403, { error: "tool runtime API is only available to the sandboxed tool frame" });
527
+ return;
528
+ }
529
+ if (request.method === "OPTIONS") {
530
+ toolPreflight("GET");
531
+ return;
532
+ }
533
+ if (request.method !== "GET") {
534
+ toolApi(405, { error: "method" });
535
+ return;
536
+ }
537
+ toolApi(200, ownerId ? toolRunner.list(id, ownerId) : []);
538
+ return;
539
+ }
513
540
  if (resource === "api/run") {
514
541
  if (!toolOrigin) {
515
542
  toolApi(403, { error: "tool runtime API is only available to the sandboxed tool frame" });
516
543
  return;
517
544
  }
518
545
  if (request.method === "OPTIONS") {
519
- response.writeHead(204, { "access-control-allow-origin": "null", "access-control-allow-methods": "POST", "access-control-allow-headers": "content-type", "access-control-max-age": "300", "vary": "Origin" }).end();
546
+ toolPreflight("POST");
520
547
  return;
521
548
  }
522
549
  if (request.method !== "POST") {
@@ -536,7 +563,7 @@ export function createHttpServer(options) {
536
563
  toolApi(404, { error: "python script is not registered" });
537
564
  return;
538
565
  }
539
- const run = toolRunner.start({ toolId: id, script: resolve(resolved.root, resolved.tool.script.path), cwd: resolved.root, definition: resolved.tool.script, params: body.params ?? {}, environment: resolved.tool.environment });
566
+ const run = toolRunner.start({ toolId: id, script: resolve(resolved.root, resolved.tool.script.path), cwd: resolved.root, definition: resolved.tool.script, params: body.params ?? {}, environment: resolved.tool.environment, ownerId });
540
567
  toolApi(202, run);
541
568
  }
542
569
  catch (error) {
@@ -611,7 +638,11 @@ export function createHttpServer(options) {
611
638
  }
612
639
  if (llmStart) {
613
640
  if (request.method === "OPTIONS") {
614
- response.writeHead(204, { "access-control-allow-origin": "null", "access-control-allow-methods": "POST", "access-control-allow-headers": "content-type", "access-control-max-age": "300", "vary": "Origin" }).end();
641
+ toolPreflight("GET, POST");
642
+ return;
643
+ }
644
+ if (request.method === "GET") {
645
+ toolApi(200, ownerId ? context.toolLlm.list(id, ownerId) : []);
615
646
  return;
616
647
  }
617
648
  if (request.method !== "POST") {
@@ -626,7 +657,7 @@ export function createHttpServer(options) {
626
657
  const raw = asked.text;
627
658
  try {
628
659
  const body = JSON.parse(raw);
629
- toolApi(202, context.toolLlm.start({ toolId: id, prompt: body.prompt ?? "", system: body.system, timeoutMs: body.timeoutMs }));
660
+ toolApi(202, context.toolLlm.start({ toolId: id, prompt: body.prompt ?? "", system: body.system, timeoutMs: body.timeoutMs, ownerId }));
630
661
  }
631
662
  catch (error) {
632
663
  toolApi(400, { error: describeThrown(error) || "模型调用失败,没有拿到失败原因。" });
@@ -1437,7 +1468,7 @@ export function createHttpServer(options) {
1437
1468
  }
1438
1469
  broadcaster.broadcastState();
1439
1470
  try {
1440
- execService.spawn(sessionId, cmd, cwd);
1471
+ execService.spawn(sessionId, cmd, cwd, conversationId);
1441
1472
  json(202, { sessionId, status: "running" });
1442
1473
  }
1443
1474
  catch (error) {
@@ -163,7 +163,9 @@ const runtime = process.env.SUPER_PI_RUNTIME === "welcome"
163
163
  : new PiRpcRuntime(join(dataDir, "pi-sessions"), undefined, { dir: initialAgentDirs, promptDir: agentPromptDir }, { endpoint: taskEndpoint, execEndpoint, todoEndpoint, workflowEndpoint, questionEndpoint, toolsEndpoint, documentsEndpoint, scheduledTaskEndpoint, orchestratorEndpoint, uploadsDir });
164
164
  // Closed workspaces stay in the store for reopening. Focused sockets receive all visible sidebar
165
165
  // summaries and only their selected transcript; legacy sockets retain the complete visible state.
166
- const broadcaster = new WsBroadcaster((scope) => store.clientState(scope));
166
+ let projectRuntime = (state) => state;
167
+ let replayRuntime = (_state, _scope) => [];
168
+ const broadcaster = new WsBroadcaster(scope => projectRuntime(store.clientState(scope)), (state, scope) => replayRuntime(state, scope));
167
169
  const memory = new ActiveMemory(join(dataDir, "memories"), store, runtime);
168
170
  process.env.SUPER_PI_MEMORY_ENDPOINT = `http://${internalHost}:${port}/api/memory/tool`;
169
171
  if (runtime instanceof PiRpcRuntime)
@@ -305,6 +307,16 @@ const terminalService = new TerminalService({
305
307
  */
306
308
  const execService = new ExecService((event) => broadcaster.broadcast(event), (sessionId, exitCode, stdout, stderr) => runService.enqueueExecResult(sessionId, exitCode, stdout, stderr));
307
309
  runService.setExecService(execService);
310
+ replayRuntime = (state, scope) => execService.outputSnapshots(state, scope);
311
+ projectRuntime = state => {
312
+ const visible = new Set(state.conversations.map(conversation => conversation.id));
313
+ return {
314
+ ...state,
315
+ sendReceipts: true,
316
+ extensionUi: extensionUiService.snapshot(visible),
317
+ stoppingConversationIds: runService.stoppingConversationIds().filter(id => visible.has(id)),
318
+ };
319
+ };
308
320
  /**
309
321
  * THE SCHEDULED TASKS, and the clock that fires them.
310
322
  *
@@ -424,14 +436,7 @@ const wsServer = new WsServer({
424
436
  catalogService,
425
437
  accessToken,
426
438
  rootDir,
427
- // Closing a tab must close its shells. Routed through the service rather than reaching into it so the
428
- // per-session bookkeeping (output flush, pending timer) still runs - `closeAll` is for shutdown, not
429
- // for one socket's worth of sessions.
430
- onSocketClose: (sessionIds) => {
431
- for (const sessionId of sessionIds) {
432
- terminalService.handle({ type: "terminal.close", sessionId }, "127.0.0.1", () => { });
433
- }
434
- },
439
+ onSocketClose: sender => terminalService.detach(sender),
435
440
  });
436
441
  httpServer.listen(port, host, () => {
437
442
  const displayHost = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
@@ -1,4 +1,4 @@
1
- import type { AppState, Message, SubagentRun } from "../types.js";
1
+ import type { AppState, Conversation, Message, SubagentRun } from "../types.js";
2
2
  /** A durable atomic update to a single streaming entity. */
3
3
  export type StateTransaction = {
4
4
  kind: "message.replace";
@@ -51,6 +51,8 @@ export type StateTransaction = {
51
51
  conversationId: string;
52
52
  messages: Message[];
53
53
  updatedAt: string;
54
+ acceptedSendId?: string;
55
+ metadata?: Omit<Conversation, "messages">;
54
56
  };
55
57
  /** Durable backing store for the application's in-memory state snapshot. */
56
58
  export interface AppStateRepository {
@@ -42,6 +42,7 @@ export class SqliteStateRepository {
42
42
  CREATE TABLE IF NOT EXISTS timestamps (conversation TEXT PRIMARY KEY, stamp TEXT NOT NULL);
43
43
  CREATE TABLE IF NOT EXISTS collections (name TEXT PRIMARY KEY, json TEXT NOT NULL);
44
44
  CREATE TABLE IF NOT EXISTS metadata (conversation TEXT PRIMARY KEY, json TEXT NOT NULL);
45
+ CREATE TABLE IF NOT EXISTS send_receipts (conversation TEXT NOT NULL, id TEXT NOT NULL, PRIMARY KEY(conversation,id));
45
46
  CREATE TABLE IF NOT EXISTS runs (id TEXT PRIMARY KEY, json TEXT NOT NULL);`);
46
47
  }
47
48
  async load() {
@@ -56,6 +57,7 @@ export class SqliteStateRepository {
56
57
  if (!Array.isArray(state.conversations))
57
58
  state.conversations = [];
58
59
  for (const conversation of state.conversations) {
60
+ const baseReceipts = conversation.acceptedSendIds ?? [];
59
61
  const metadata = this.db.prepare("SELECT json FROM metadata WHERE conversation=?").get(conversation.id);
60
62
  if (metadata) {
61
63
  const messages = conversation.messages;
@@ -93,6 +95,10 @@ export class SqliteStateRepository {
93
95
  const stamp = this.db.prepare("SELECT stamp FROM timestamps WHERE conversation=?").get(conversation.id);
94
96
  if (stamp?.stamp)
95
97
  conversation.updatedAt = String(stamp.stamp);
98
+ const receipts = this.db.prepare("SELECT id FROM send_receipts WHERE conversation=?").all(conversation.id);
99
+ if (baseReceipts.length || receipts.length) {
100
+ conversation.acceptedSendIds = [...new Set([...baseReceipts, ...(conversation.acceptedSendIds ?? []), ...receipts.map(item => String(item.id))])];
101
+ }
96
102
  }
97
103
  const runs = new Map(this.db.prepare("SELECT id,json FROM runs").all().map(r => [String(r.id), JSON.parse(String(r.json))]));
98
104
  /**
@@ -122,7 +128,7 @@ export class SqliteStateRepository {
122
128
  async save(state) {
123
129
  this.atomic(() => {
124
130
  this.db.prepare("INSERT INTO state VALUES(1,?) ON CONFLICT(id) DO UPDATE SET json=excluded.json").run(JSON.stringify(state));
125
- this.db.exec("DELETE FROM messages; DELETE FROM message_order; DELETE FROM runs; DELETE FROM timestamps; DELETE FROM collections; DELETE FROM metadata;");
131
+ this.db.exec("DELETE FROM messages; DELETE FROM message_order; DELETE FROM runs; DELETE FROM timestamps; DELETE FROM collections; DELETE FROM metadata; DELETE FROM send_receipts;");
126
132
  });
127
133
  }
128
134
  async commit(transaction) {
@@ -176,6 +182,13 @@ export class SqliteStateRepository {
176
182
  // yet, the base array is authoritative - that is the `load` contract - so this falls back to
177
183
  // the full write ONCE to materialise the order, and every later write is a diff.
178
184
  const conversationId = transaction.conversationId;
185
+ if (transaction.acceptedSendId) {
186
+ this.db.prepare("INSERT OR IGNORE INTO send_receipts VALUES(?,?)").run(conversationId, transaction.acceptedSendId);
187
+ }
188
+ if (transaction.metadata) {
189
+ this.db.prepare("INSERT INTO metadata VALUES(?,?) ON CONFLICT(conversation) DO UPDATE SET json=excluded.json")
190
+ .run(conversationId, JSON.stringify(transaction.metadata));
191
+ }
179
192
  const stored = new Map(this.db.prepare("SELECT id,json FROM messages WHERE conversation=?").all(conversationId)
180
193
  .map((row) => [String(row.id), String(row.json)]));
181
194
  const ordered = this.db.prepare("SELECT id,position FROM message_order WHERE conversation=? ORDER BY position").all(conversationId);
@@ -198,6 +198,7 @@ export declare class Store {
198
198
  * out, so nothing can mutate the store through it.
199
199
  */
200
200
  hasMessage(conversationId: string, messageId: string): boolean;
201
+ hasAcceptedSend(conversationId: string, clientId: string): boolean;
201
202
  /**
202
203
  * One conversation and its workspace, as DETACHED copies, without cloning the whole state.
203
204
  *