@evandu/super-pi 0.1.223 → 0.1.225

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 (69) hide show
  1. package/dist/client/.super-pi-client-sources.json +12 -8
  2. package/dist/client/assets/{CodeMirrorEditor-Due3YL4A.js → CodeMirrorEditor-OLbwCzUh.js} +2 -2
  3. package/dist/client/assets/{dist-B3qtMidG.js → dist-BQImRXFO.js} +1 -1
  4. package/dist/client/assets/{dist-BJ5mZEGq.js → dist-BUOU8RAm.js} +1 -1
  5. package/dist/client/assets/{dist-BZGq856v.js → dist-BdrKprbZ.js} +1 -1
  6. package/dist/client/assets/{dist-DCVXoyno.js → dist-BffuhHE1.js} +1 -1
  7. package/dist/client/assets/{dist-B2XX-bBx.js → dist-C8-e07vM.js} +1 -1
  8. package/dist/client/assets/{dist-2kMlRtqo.js → dist-C8naDDXu.js} +1 -1
  9. package/dist/client/assets/{dist-JSFnHR0P.js → dist-C9f0Riun.js} +1 -1
  10. package/dist/client/assets/{dist-1hXEE44f.js → dist-CB9Qr9C6.js} +1 -1
  11. package/dist/client/assets/{dist-DSCSHwdP.js → dist-CIEDxNn7.js} +1 -1
  12. package/dist/client/assets/{dist-CRrYz-2t.js → dist-CIsUvpC9.js} +1 -1
  13. package/dist/client/assets/{dist-BHlGN5Cp.js → dist-CKA2u-s7.js} +1 -1
  14. package/dist/client/assets/{dist-D2n9-vIx.js → dist-COIAnYiN.js} +1 -1
  15. package/dist/client/assets/{dist-BvUexO6W.js → dist-CXpar2cD.js} +1 -1
  16. package/dist/client/assets/{dist-CMws1R9h.js → dist-CZu3CzDX.js} +1 -1
  17. package/dist/client/assets/{dist-BJ_pU8qp.js → dist-CaePDjkH.js} +1 -1
  18. package/dist/client/assets/{dist-CA52X7jm.js → dist-Cro2exEx.js} +1 -1
  19. package/dist/client/assets/{dist-BXTbngmK.js → dist-CxJkT0iM.js} +1 -1
  20. package/dist/client/assets/{dist-BaUqm3zx.js → dist-D53uN01l.js} +1 -1
  21. package/dist/client/assets/{dist-DOJKt6Px.js → dist-D9kySnbi.js} +1 -1
  22. package/dist/client/assets/{dist-Cw21UX77.js → dist-MARoODS1.js} +1 -1
  23. package/dist/client/assets/{dist-Po3GdueN.js → dist-ot9lBE7N.js} +1 -1
  24. package/dist/client/assets/{dist-CQIMZ_7M.js → dist-sv2AtsDR.js} +1 -1
  25. package/dist/client/assets/index-B0m5CXCB.js +105 -0
  26. package/dist/client/assets/index-DK_mME9e.css +1 -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 +102 -35
  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/file-index.d.ts +13 -1
  36. package/dist/server/file-index.js +108 -12
  37. package/dist/server/file-name-index.d.ts +8 -0
  38. package/dist/server/file-name-index.js +58 -11
  39. package/dist/server/files.js +4 -0
  40. package/dist/server/http-server.js +182 -25
  41. package/dist/server/index.js +14 -9
  42. package/dist/server/persistence/app-state-repository.d.ts +3 -1
  43. package/dist/server/persistence/sqlite-state-repository.js +14 -1
  44. package/dist/server/session-cwd.d.ts +2 -0
  45. package/dist/server/session-cwd.js +16 -1
  46. package/dist/server/store.d.ts +1 -0
  47. package/dist/server/store.js +49 -12
  48. package/dist/server/terminal.d.ts +26 -76
  49. package/dist/server/terminal.js +239 -172
  50. package/dist/server/tool-llm.d.ts +7 -0
  51. package/dist/server/tool-llm.js +8 -1
  52. package/dist/server/tool-runner.d.ts +7 -0
  53. package/dist/server/tool-runner.js +8 -1
  54. package/dist/server/types.d.ts +27 -75
  55. package/dist/server/workspace-file-indexes.d.ts +2 -0
  56. package/dist/server/workspace-file-indexes.js +61 -0
  57. package/dist/server/workspace-file-operations.d.ts +36 -0
  58. package/dist/server/workspace-file-operations.js +281 -0
  59. package/dist/server/workspace-file-response.d.ts +3 -0
  60. package/dist/server/workspace-file-response.js +79 -0
  61. package/dist/server/ws-server.d.ts +7 -12
  62. package/dist/server/ws-server.js +23 -18
  63. package/dist/shared/terminal-protocol.d.ts +71 -0
  64. package/dist/shared/terminal-protocol.js +1 -0
  65. package/dist/shared/workspace-file-preview.d.ts +4 -0
  66. package/dist/shared/workspace-file-preview.js +28 -0
  67. package/package.json +2 -1
  68. package/dist/client/assets/index-DHdzZ1mf.js +0 -103
  69. package/dist/client/assets/index-OmaD3l6r.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-DHdzZ1mf.js"></script>
12
- <link rel="stylesheet" crossorigin href="/assets/index-OmaD3l6r.css">
11
+ <script type="module" crossorigin src="/assets/index-B0m5CXCB.js"></script>
12
+ <link rel="stylesheet" crossorigin href="/assets/index-DK_mME9e.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
  /**
@@ -9,12 +9,15 @@ import { formatTurnFailure, isLengthExceededError } from "../turn-failure.js";
9
9
  import { isLengthContinuation, lengthContinuationText, MAX_LENGTH_CONTINUATIONS, buildLengthContinuationPrompt } from "../length-continuation.js";
10
10
  import { describeThrownWithStack } from "../failure-text.js";
11
11
  import { toWorkspaceRelative } from "../files.js";
12
- import { refreshWorkspaceIndex } from "../file-index.js";
12
+ import { inScope, refreshWorkspaceIndex } from "../file-index.js";
13
13
  import { resolveSessionCwd } from "../session-cwd.js";
14
14
  import { CHILD_QUESTION_LOCK_REASON, isChildSession } from "../../shared/child-session-lock.js";
15
15
  import { execFile } from "node:child_process";
16
16
  import { promisify } from "node:util";
17
17
  import { randomUUID } from "node:crypto";
18
+ import { isAbsolute, resolve } from "node:path";
19
+ import { lstat } from "node:fs/promises";
20
+ import { explorerPath, serializeWorkspaceWrite } from "../workspace-file-operations.js";
18
21
  const execFileAsync = promisify(execFile);
19
22
  /**
20
23
  * Validates a caller-supplied delivery mode without silently falling back on bogus values.
@@ -167,6 +170,10 @@ export class RunService {
167
170
  this.memory?.review(conversation);
168
171
  }
169
172
  activeRuns = new Map();
173
+ stoppingConversationIds() {
174
+ return [...this.activeRuns].filter(([, controller]) => controller.signal.aborted).map(([id]) => id);
175
+ }
176
+ acceptingSends = new Map();
170
177
  lengthContinuations = new Map();
171
178
  turnEventScopes = new Map();
172
179
  historyCutClaims = new Map();
@@ -589,11 +596,31 @@ export class RunService {
589
596
  const existing = this.store.question(command.conversationId, command.messageId, command.callIndex);
590
597
  if (!existing)
591
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
+ }
592
619
  const calls = await this.store.updateToolCall(command.conversationId, command.messageId, command.callIndex, {
593
620
  question: {
594
621
  items: existing.items,
595
622
  status: command.cancelled ? "cancelled" : "answered",
596
- ...(command.cancelled ? {} : { answers: command.answers ?? [] }),
623
+ ...(command.cancelled ? {} : { answers }),
597
624
  },
598
625
  });
599
626
  this.broadcaster.broadcast({ type: "message.tools", conversationId: command.conversationId, messageId: command.messageId, toolCalls: calls });
@@ -1392,6 +1419,7 @@ export class RunService {
1392
1419
  * back as a path with one space.
1393
1420
  */
1394
1421
  const fileWritePaths = new Map();
1422
+ let runCwd = workspace.path;
1395
1423
  const onFileWrite = (path, _toolName, toolCallId) => {
1396
1424
  if (!acceptsEvent("file.write"))
1397
1425
  return;
@@ -1410,17 +1438,16 @@ export class RunService {
1410
1438
  // it right, while the name index stored the absolute path with its leading slash stripped
1411
1439
  // (`home/me/project/src/a.ts`) - an entry that matched by name and then pointed at a file that
1412
1440
  // does not exist.
1413
- const relative = toWorkspaceRelative(workspace.path, path);
1414
- tracker.record(workspace.id, relative, { root: workspace.path, conversationId: conversation.id });
1415
- refreshWorkspaceIndex(this.fileIndexes, workspace.id, relative, workspace.path);
1416
- // The name index learns about the write as well, so the file the agent just created is
1417
- // findable by name straight away rather than after the next background scan. It goes through
1418
- // the SAME `ensureNameIndex` the HTTP layer uses, so there is one index per workspace rather
1419
- // than one per layer.
1420
- if (this.nameIndexes) {
1421
- ensureNameIndex(this.nameIndexes, workspace.id, workspace.path);
1422
- recordWorkspacePath(this.nameIndexes, workspace.id, workspace.path, relative);
1441
+ let relative;
1442
+ try {
1443
+ relative = toWorkspaceRelative(workspace.path, isAbsolute(path) ? path : resolve(runCwd, path));
1444
+ }
1445
+ catch {
1446
+ return;
1423
1447
  }
1448
+ if (!relative)
1449
+ return;
1450
+ tracker.record(workspace.id, relative, { root: workspace.path, conversationId: conversation.id });
1424
1451
  if (toolCallId)
1425
1452
  fileWritePaths.set(toolCallId, relative);
1426
1453
  this.broadcastFileChanges(workspace.id);
@@ -1524,14 +1551,37 @@ export class RunService {
1524
1551
  const writtenPath = call.id ? fileWritePaths.get(call.id) : undefined;
1525
1552
  if (writtenPath) {
1526
1553
  this.fileChanges?.confirm(workspace.id, writtenPath, workspace.path);
1527
- refreshWorkspaceIndex(this.fileIndexes, workspace.id, writtenPath, workspace.path);
1528
- if (this.nameIndexes) {
1529
- ensureNameIndex(this.nameIndexes, workspace.id, workspace.path);
1530
- recordWorkspacePath(this.nameIndexes, workspace.id, workspace.path, writtenPath);
1531
- }
1532
1554
  if (call.id)
1533
1555
  fileWritePaths.delete(call.id);
1534
1556
  this.broadcastFileChanges(workspace.id);
1557
+ void serializeWorkspaceWrite(workspace.path, async () => {
1558
+ const target = await explorerPath(workspace.path, workspace.path, writtenPath);
1559
+ const info = await lstat(target).catch((error) => {
1560
+ if (error.code !== "ENOENT" && error.code !== "ENOTDIR")
1561
+ throw error;
1562
+ });
1563
+ refreshWorkspaceIndex(this.fileIndexes, workspace.id, writtenPath, workspace.path);
1564
+ if (this.nameIndexes && info?.isFile()) {
1565
+ ensureNameIndex(this.nameIndexes, workspace.id, workspace.path);
1566
+ recordWorkspacePath(this.nameIndexes, workspace.id, workspace.path, writtenPath);
1567
+ }
1568
+ else if (!info)
1569
+ for (const index of this.nameIndexes?.values() ?? []) {
1570
+ if (index.workspaceId !== workspace.id)
1571
+ continue;
1572
+ const target = inScope(workspace.path, index.cwd, writtenPath);
1573
+ if (target)
1574
+ index.removeTree(target);
1575
+ }
1576
+ this.broadcaster.broadcast({ type: "files.invalidated", workspaceId: workspace.id, paths: [writtenPath] });
1577
+ }).catch((error) => {
1578
+ if (error && typeof error === "object" && "status" in error && error.status === 403)
1579
+ return;
1580
+ console.warn("Super Pi: could not update the workspace file tree", error);
1581
+ });
1582
+ }
1583
+ else if (/^(bash|powershell|shell|command|apply_patch|write|edit)$/i.test(call.name)) {
1584
+ this.broadcaster.broadcast({ type: "files.invalidated", workspaceId: workspace.id });
1535
1585
  }
1536
1586
  const index = call.id ? rowByToolCallId.get(call.id) : undefined;
1537
1587
  if (index === undefined)
@@ -1605,11 +1655,12 @@ export class RunService {
1605
1655
  return pendingTools;
1606
1656
  };
1607
1657
  try {
1658
+ runCwd = await resolveSessionCwd(workspace.path, conversation.cwd);
1608
1659
  for await (const delta of this.runtime.answer({
1609
1660
  conversation,
1610
1661
  prompt,
1611
1662
  signal: controller.signal,
1612
- cwd: await resolveSessionCwd(workspace.path, conversation.cwd),
1663
+ cwd: runCwd,
1613
1664
  host: {
1614
1665
  notify: (request) => { if (acceptsEvent("ui.notify"))
1615
1666
  uiHost.notify(request); },
@@ -1961,29 +2012,44 @@ export class RunService {
1961
2012
  this.broadcaster.broadcastState();
1962
2013
  }
1963
2014
  }
1964
- enqueueAndRun(conversationId, content, images, attachments, clientId, mode) {
1965
- 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;
1966
2046
  }
1967
2047
  enqueueReminder(conversationId, note) {
1968
2048
  return this.enqueueMessage(conversationId, note, { source: "session-reminder" });
1969
2049
  }
1970
- async enqueueMessage(conversationId, content, { images, attachments, clientId, mode, source }) {
2050
+ async enqueueMessage(conversationId, content, { images, attachments, clientId, mode, source, accepted }) {
1971
2051
  const deliveryMode = parseMessageDeliveryMode(mode);
1972
2052
  this.assertHistoryAvailable(conversationId);
1973
- /**
1974
- * A CLIENT ID THIS CONVERSATION ALREADY HAS IS A RESEND, NOT A SECOND MESSAGE.
1975
- *
1976
- * The browser retries a send whose socket dropped before the answer arrived (see
1977
- * `src/client/pending-operations.ts`), and it cannot know whether the first attempt reached this
1978
- * server. It usually did - the drop is a restart or a sleeping laptop, not a refusal - so without
1979
- * this guard the retry would be a second user message, answered twice, for words the person said
1980
- * once. The id is minted per compose by the browser, so a match cannot be a coincidence.
1981
- *
1982
- * Returning silently is the whole answer: the original message is already in the transcript, and
1983
- * the browser learns it from the state snapshot that arrives on connect.
1984
- */
1985
- if (clientId && this.store.hasMessage(conversationId, clientId))
1986
- return;
1987
2053
  this.memory?.cancel(conversationId);
1988
2054
  if (source || !isLengthContinuation(content)) {
1989
2055
  this.lengthContinuations.delete(conversationId);
@@ -2042,6 +2108,7 @@ export class RunService {
2042
2108
  throw error;
2043
2109
  }
2044
2110
  this.broadcaster.broadcastState();
2111
+ accepted?.();
2045
2112
  if (!reservedController) {
2046
2113
  // The turn that is running answers this message itself, through Pi's own follow-up queue, rather
2047
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)
@@ -1,4 +1,8 @@
1
- import { type FileMeta } from "./files.js";
1
+ import { type DirEntry, type FileMeta } from "./files.js";
2
+ export declare function belowPath(path: string, parent: string): boolean;
3
+ export declare function inScope(workspaceRoot: string, cwd: string, path: string): string | undefined;
4
+ export declare function blockedBy(path: string, blocked: ReadonlySet<string>): boolean;
5
+ export declare function matchesDirectoryReads(path: string, snapshots: ReadonlyMap<string, ReadonlySet<string>>): boolean;
2
6
  export type IndexedFile = {
3
7
  path: string;
4
8
  kind: "file" | "directory";
@@ -40,12 +44,17 @@ export declare class FileIndex {
40
44
  private root;
41
45
  private queue;
42
46
  private building;
47
+ private needsScan;
43
48
  private skipped;
49
+ private readonly touched;
50
+ private readonly removedDuringScan;
51
+ private readonly directoriesReadDuringScan;
44
52
  version: number;
45
53
  builtAt: number;
46
54
  complete: boolean;
47
55
  constructor(workspaceId: string, broadcast: (event: FileIndexEvent) => void, cwd?: string);
48
56
  start(root: string): void;
57
+ markStale(): void;
49
58
  stop(): void;
50
59
  snapshot(since?: number): FileIndexSnapshot;
51
60
  /**
@@ -66,6 +75,9 @@ export declare class FileIndex {
66
75
  * caller's file API operation has already passed the sole containment guard and read this metadata. */
67
76
  recordFile(path: string, meta: FileMeta, mtimeMs?: number): void;
68
77
  remove(path: string): void;
78
+ removeTree(path: string): void;
79
+ recordEntries(entries: Pick<IndexedFile, "path" | "kind">[]): void;
80
+ reconcileDirectory(directory: string, entries: DirEntry[]): void;
69
81
  private scan;
70
82
  private publish;
71
83
  }
@@ -1,6 +1,34 @@
1
1
  import { readdir, stat } from "node:fs/promises";
2
- import { resolve } from "node:path";
2
+ import { isAbsolute, relative, resolve, sep } from "node:path";
3
3
  import { SEARCH_SKIP_DIRS, createRootGuard, fileMeta, isTextName, toRelative, toWorkspaceRelative } from "./files.js";
4
+ export function belowPath(path, parent) {
5
+ return !parent || path === parent || path.startsWith(`${parent}/`);
6
+ }
7
+ export function inScope(workspaceRoot, cwd, path) {
8
+ const local = relative(resolve(workspaceRoot, cwd), resolve(workspaceRoot, path));
9
+ if (local === ".." || local.startsWith(`..${sep}`) || isAbsolute(local))
10
+ return;
11
+ return local.split(sep).join("/");
12
+ }
13
+ export function blockedBy(path, blocked) {
14
+ if (blocked.has(""))
15
+ return true;
16
+ for (let prefix = path; prefix; prefix = prefix.slice(0, Math.max(0, prefix.lastIndexOf("/")))) {
17
+ if (blocked.has(prefix))
18
+ return true;
19
+ }
20
+ return false;
21
+ }
22
+ export function matchesDirectoryReads(path, snapshots) {
23
+ for (let entry = path; entry;) {
24
+ const parent = entry.slice(0, Math.max(0, entry.lastIndexOf("/")));
25
+ const present = snapshots.get(parent);
26
+ if (present && !present.has(entry))
27
+ return false;
28
+ entry = parent;
29
+ }
30
+ return true;
31
+ }
4
32
  const MAX_DIRECTORIES = 4000;
5
33
  const MAX_FILES = 30000;
6
34
  const MAX_MS = 4000;
@@ -19,7 +47,11 @@ export class FileIndex {
19
47
  root = "";
20
48
  queue = [];
21
49
  building = false;
50
+ needsScan = false;
22
51
  skipped = [];
52
+ touched = new Set();
53
+ removedDuringScan = new Set();
54
+ directoriesReadDuringScan = new Map();
23
55
  version = 0;
24
56
  builtAt = 0;
25
57
  complete = false;
@@ -29,20 +61,39 @@ export class FileIndex {
29
61
  this.cwd = cwd;
30
62
  }
31
63
  start(root) {
32
- if (this.building || this.builtAt)
64
+ if (this.building || (this.builtAt && !this.needsScan))
33
65
  return;
66
+ const replacing = !!this.builtAt;
67
+ this.needsScan = false;
34
68
  this.root = root;
35
69
  this.building = true;
70
+ this.complete = false;
71
+ this.skipped = [];
36
72
  this.queue = [""];
37
- void this.scan();
73
+ void this.scan(replacing);
38
74
  }
75
+ markStale() { if (this.root)
76
+ this.needsScan = true; }
39
77
  stop() { }
40
78
  snapshot(since) {
41
79
  const valid = Number.isFinite(since) && since !== undefined;
42
- const deltas = valid ? this.history.filter((item) => item.version > since) : [];
80
+ const changed = new Map();
81
+ const removed = new Set();
82
+ if (valid)
83
+ for (const item of this.history) {
84
+ if (item.version <= since)
85
+ continue;
86
+ for (const entry of item.changed) {
87
+ removed.delete(entry.path);
88
+ changed.set(entry.path, entry);
89
+ }
90
+ for (const path of item.removed) {
91
+ changed.delete(path);
92
+ removed.add(path);
93
+ }
94
+ }
43
95
  return { version: this.version, builtAt: this.builtAt, complete: this.complete, skipped: this.skipped,
44
- changed: valid ? deltas.flatMap((item) => item.changed) : [...this.entries.values()],
45
- removed: valid ? deltas.flatMap((item) => item.removed) : [] };
96
+ changed: valid ? [...changed.values()] : [...this.entries.values()], removed: [...removed] };
46
97
  }
47
98
  /**
48
99
  * ONE FILE, REFRESHED.
@@ -83,7 +134,7 @@ export class FileIndex {
83
134
  catch (error) {
84
135
  const code = error.code;
85
136
  if (code === "ENOENT" || code === "ENOTDIR")
86
- this.remove(key);
137
+ this.removeTree(key);
87
138
  else
88
139
  throw error;
89
140
  }
@@ -98,7 +149,39 @@ export class FileIndex {
98
149
  }
99
150
  remove(path) { if (this.entries.delete(path))
100
151
  this.publish([], [path]); }
101
- async scan() {
152
+ removeTree(path) {
153
+ if (this.building)
154
+ this.removedDuringScan.add(path);
155
+ const removed = [...this.entries.keys()].filter(key => belowPath(key, path));
156
+ for (const key of removed)
157
+ this.entries.delete(key);
158
+ this.publish([], removed);
159
+ }
160
+ recordEntries(entries) {
161
+ const changed = [];
162
+ for (const { path, kind } of entries) {
163
+ if (!path || path.split("/").some((segment, i, all) => SEARCH_SKIP_DIRS.has(segment) && (i < all.length - 1 || kind === "directory")))
164
+ continue;
165
+ if (this.entries.get(path)?.kind === kind)
166
+ continue;
167
+ changed.push({ path, kind, size: null, mtimeMs: null, etag: null, text: kind === "file" ? isTextName(path) : null });
168
+ }
169
+ this.publish(changed, []);
170
+ }
171
+ reconcileDirectory(directory, entries) {
172
+ const present = new Map(entries.map(entry => [entry.path, entry]));
173
+ if (this.building)
174
+ this.directoriesReadDuringScan.set(directory, new Set(entries.filter(entry => !entry.symlink && entry.kind !== "symlink").map(entry => entry.path)));
175
+ for (const [path, existing] of this.entries) {
176
+ if (path.slice(0, Math.max(0, path.lastIndexOf("/"))) !== directory)
177
+ continue;
178
+ const entry = present.get(path);
179
+ if (!entry || entry.symlink || entry.kind !== existing.kind)
180
+ this.removeTree(path);
181
+ }
182
+ this.recordEntries(entries.flatMap(entry => !entry.symlink && entry.kind !== "symlink" ? [{ path: entry.path, kind: entry.kind }] : []));
183
+ }
184
+ async scan(replacing) {
102
185
  const started = Date.now();
103
186
  let dirs = 0;
104
187
  let files = 0;
@@ -151,14 +234,25 @@ export class FileIndex {
151
234
  this.builtAt = Date.now();
152
235
  // Quick Open does not need per-directory progress. One final batch bounds WS traffic and keeps the
153
236
  // existing on-demand tree interactive throughout the scan (including dependency directories).
154
- this.publish(changed, [], true);
237
+ const scanned = changed.filter(entry => !this.touched.has(entry.path) && !blockedBy(entry.path, this.removedDuringScan)
238
+ && matchesDirectoryReads(entry.path, this.directoriesReadDuringScan));
239
+ const found = replacing && !incomplete ? new Set(scanned.map(entry => entry.path)) : undefined;
240
+ const removed = found ? [...this.entries.keys()].filter(path => !this.touched.has(path) && !found.has(path)) : [];
241
+ for (const path of removed)
242
+ this.entries.delete(path);
243
+ this.publish(scanned, removed, true, replacing);
244
+ this.touched.clear();
245
+ this.removedDuringScan.clear();
246
+ this.directoriesReadDuringScan.clear();
155
247
  }
156
- publish(changed, removed, force = false) {
248
+ publish(changed, removed, force = false, invalidateMetadata = false) {
157
249
  changed = changed.map((entry) => {
158
250
  // A targeted stat may race the cheap directory walk. Do not let the later readdir-only result erase
159
251
  // metadata that was already paid for and verified.
160
252
  const previous = this.entries.get(entry.path);
161
- const merged = previous?.kind === entry.kind && entry.size === null ? { ...entry, size: previous.size, mtimeMs: previous.mtimeMs, etag: previous.etag } : entry;
253
+ if (this.building)
254
+ this.touched.add(entry.path);
255
+ const merged = !invalidateMetadata && previous?.kind === entry.kind && entry.size === null ? { ...entry, size: previous.size, mtimeMs: previous.mtimeMs, etag: previous.etag } : entry;
162
256
  this.entries.set(entry.path, merged);
163
257
  return merged;
164
258
  });
@@ -192,7 +286,9 @@ export function refreshWorkspaceIndex(indexes, workspaceId, path, workspaceRoot)
192
286
  for (const index of indexes?.values() ?? []) {
193
287
  if (index.workspaceId !== workspaceId)
194
288
  continue;
195
- const target = workspaceRoot && index.cwd ? resolve(workspaceRoot, path) : path;
289
+ const target = workspaceRoot ? inScope(workspaceRoot, index.cwd, path) : path;
290
+ if (!target)
291
+ continue;
196
292
  void index.refresh(target).catch((error) => {
197
293
  console.warn(`Super Pi: the file index did not refresh ${path}: ${error instanceof Error ? error.message : "unknown error"}`);
198
294
  });