@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
@@ -1,3 +1,4 @@
1
+ import { type DirEntry } from "./files.js";
1
2
  /**
2
3
  * THE INDEX FOR ONE WORKSPACE, created on demand and then kept.
3
4
  *
@@ -70,6 +71,10 @@ export declare class FileNameIndex {
70
71
  private scanned;
71
72
  private stopped;
72
73
  private incomplete;
74
+ private needsScan;
75
+ private generation;
76
+ private readonly removedDuringScan;
77
+ private readonly directoriesReadDuringScan;
73
78
  constructor(workspaceId: string, cwd?: string);
74
79
  /**
75
80
  * Whether the first pass has FINISHED.
@@ -85,6 +90,7 @@ export declare class FileNameIndex {
85
90
  get progress(): IndexProgress;
86
91
  /** Begin the background scan. Safe to call more than once; the second call is a no-op. */
87
92
  start(root: string): void;
93
+ markStale(): void;
88
94
  /**
89
95
  * WHY THE SCAN'S FAILURE IS RECORDED RATHER THAN THROWN.
90
96
  *
@@ -108,6 +114,8 @@ export declare class FileNameIndex {
108
114
  upsert(relativePath: string, kind?: "file" | "directory"): void;
109
115
  /** Forget a path that is gone. */
110
116
  remove(relativePath: string): void;
117
+ removeTree(path: string): void;
118
+ reconcileDirectory(directory: string, entries: DirEntry[]): void;
111
119
  /**
112
120
  * The query. A substring filter over an in-memory map - no filesystem access at all.
113
121
  *
@@ -32,8 +32,9 @@
32
32
  * replaces.
33
33
  */
34
34
  import { readdir } from "node:fs/promises";
35
- import { isAbsolute, relative, resolve, sep } from "node:path";
36
35
  import { createRootGuard, toRelative } from "./files.js";
36
+ import { belowPath, blockedBy, inScope, matchesDirectoryReads } from "./file-index.js";
37
+ import { explorerInternalPath } from "./workspace-file-operations.js";
37
38
  import { sessionScopeKey } from "./session-cwd.js";
38
39
  /**
39
40
  * THE INDEX FOR ONE WORKSPACE, created on demand and then kept.
@@ -54,14 +55,14 @@ export function ensureNameIndex(indexes, workspaceId, root, cwd = "") {
54
55
  }
55
56
  /** Keeps every root/subdirectory index for a workspace in step with one observed write. */
56
57
  export function recordWorkspacePath(indexes, workspaceId, workspaceRoot, path) {
57
- const absolute = resolve(workspaceRoot, path);
58
+ if (explorerInternalPath(path))
59
+ return;
58
60
  for (const index of indexes.values()) {
59
61
  if (index.workspaceId !== workspaceId)
60
62
  continue;
61
- const scoped = relative(resolve(workspaceRoot, index.cwd), absolute);
62
- if (!scoped || scoped === ".." || scoped.startsWith(`..${sep}`) || isAbsolute(scoped))
63
- continue;
64
- index.upsert(scoped.split(sep).join("/"));
63
+ const scoped = inScope(workspaceRoot, index.cwd, path);
64
+ if (scoped)
65
+ index.upsert(scoped);
65
66
  }
66
67
  }
67
68
  const MAX_DIRECTORIES = 20000;
@@ -115,6 +116,10 @@ export class FileNameIndex {
115
116
  scanned = 0;
116
117
  stopped = false;
117
118
  incomplete = false;
119
+ needsScan = false;
120
+ generation = 0;
121
+ removedDuringScan = new Set();
122
+ directoriesReadDuringScan = new Map();
118
123
  constructor(workspaceId, cwd = "") {
119
124
  this.workspaceId = workspaceId;
120
125
  this.cwd = cwd;
@@ -144,13 +149,21 @@ export class FileNameIndex {
144
149
  // The guard is "has a scan been started", NOT "are there any entries". An EMPTY workspace
145
150
  // finishes its scan with zero entries, and an emptiness test would restart the scan on every
146
151
  // request - so the answer to every query would be "still building" forever.
147
- if (this.started || this.building)
152
+ if (this.building)
153
+ return;
154
+ if (this.started) {
155
+ if (this.needsScan)
156
+ this.reset(root);
148
157
  return;
158
+ }
159
+ this.needsScan = false;
149
160
  this.started = true;
150
161
  this.root = root;
151
162
  this.building = true;
152
- void this.scan();
163
+ void this.scan(++this.generation);
153
164
  }
165
+ markStale() { if (this.started)
166
+ this.needsScan = true; }
154
167
  /**
155
168
  * WHY THE SCAN'S FAILURE IS RECORDED RATHER THAN THROWN.
156
169
  *
@@ -177,6 +190,8 @@ export class FileNameIndex {
177
190
  /** Rebuild from scratch. The ↻ button. */
178
191
  reset(root) {
179
192
  this.entries.clear();
193
+ this.removedDuringScan.clear();
194
+ this.directoriesReadDuringScan.clear();
180
195
  this.scanned = 0;
181
196
  this.incomplete = false;
182
197
  this.stopped = false;
@@ -201,6 +216,28 @@ export class FileNameIndex {
201
216
  this.entries.delete(path);
202
217
  // The directories that held it are still there; only the file itself is gone.
203
218
  }
219
+ removeTree(path) {
220
+ if (this.building)
221
+ this.removedDuringScan.add(path);
222
+ for (const key of this.entries.keys())
223
+ if (belowPath(key, path))
224
+ this.entries.delete(key);
225
+ }
226
+ reconcileDirectory(directory, entries) {
227
+ const present = new Map(entries.map(entry => [entry.path, entry]));
228
+ if (this.building)
229
+ this.directoriesReadDuringScan.set(directory, new Set(entries.filter(entry => !entry.symlink && entry.kind !== "symlink").map(entry => entry.path)));
230
+ for (const [path, existing] of this.entries) {
231
+ if (existing.directory !== directory)
232
+ continue;
233
+ const entry = present.get(path);
234
+ if (!entry || entry.symlink || entry.kind !== existing.kind)
235
+ this.removeTree(path);
236
+ }
237
+ for (const entry of entries)
238
+ if (!entry.symlink && entry.kind !== "symlink")
239
+ this.upsert(entry.path, entry.kind);
240
+ }
204
241
  /**
205
242
  * The query. A substring filter over an in-memory map - no filesystem access at all.
206
243
  *
@@ -264,13 +301,13 @@ export class FileNameIndex {
264
301
  * Symlinks are recorded but never followed - following one is how a scan becomes an infinite
265
302
  * walk, and a link inside the workspace is the one path the tree refuses to descend as well.
266
303
  */
267
- async scan() {
304
+ async scan(generation) {
268
305
  const started = Date.now();
269
306
  const guard = createRootGuard(this.root);
270
307
  const queue = [""];
271
308
  while (queue.length) {
272
- if (this.stopped)
273
- break;
309
+ if (this.stopped || generation !== this.generation)
310
+ return;
274
311
  const directory = queue.shift();
275
312
  if (this.scanned >= MAX_DIRECTORIES) {
276
313
  this.incomplete = true;
@@ -282,6 +319,8 @@ export class FileNameIndex {
282
319
  entries = await readdir(await guard(directory), { withFileTypes: true });
283
320
  }
284
321
  catch (error) {
322
+ if (generation !== this.generation || this.stopped)
323
+ return;
285
324
  // THE ROOT IS NOT ONE OF THE SKIPPABLE DIRECTORIES.
286
325
  //
287
326
  // A workspace whose directory is gone must answer 404 `workspace_missing`, and the reason is
@@ -305,10 +344,15 @@ export class FileNameIndex {
305
344
  this.incomplete = true;
306
345
  continue;
307
346
  }
347
+ if (generation !== this.generation || this.stopped)
348
+ return;
308
349
  for (const entry of entries) {
309
350
  if (entry.isSymbolicLink())
310
351
  continue;
311
352
  const relative = directory ? `${directory}/${entry.name}` : entry.name;
353
+ if (explorerInternalPath(this.cwd ? `${this.cwd}/${relative}` : relative) || blockedBy(relative, this.removedDuringScan)
354
+ || !matchesDirectoryReads(relative, this.directoriesReadDuringScan))
355
+ continue;
312
356
  if (entry.isDirectory()) {
313
357
  this.entries.set(relative, { path: relative, name: entry.name, directory, kind: "directory" });
314
358
  queue.push(relative);
@@ -328,9 +372,12 @@ export class FileNameIndex {
328
372
  await new Promise((resolve) => setTimeout(resolve, 0));
329
373
  }
330
374
  this.building = false;
375
+ this.removedDuringScan.clear();
376
+ this.directoriesReadDuringScan.clear();
331
377
  }
332
378
  /** Stop a running scan. Used when a workspace goes away. */
333
379
  stop() {
380
+ this.generation += 1;
334
381
  this.stopped = true;
335
382
  this.building = false;
336
383
  }
@@ -730,6 +730,10 @@ export function describe(error) {
730
730
  if (error instanceof FilesError)
731
731
  return { status: error.status, body: { error: error.message, code: error.code, ...(error.details ? { details: error.details } : {}) } };
732
732
  const code = error?.code;
733
+ if (code === "EEXIST" || code === "ENOTEMPTY")
734
+ return { status: 409, body: { error: "目标名称已存在。", code: "already_exists" } };
735
+ if (code === "EXDEV")
736
+ return { status: 409, body: { error: "这个位置位于另一文件系统,无法移动。", code: "different_filesystem" } };
733
737
  if (code === "EACCES" || code === "EPERM")
734
738
  return { status: 403, body: { error: "权限不足,无法访问该路径", code: "denied" } };
735
739
  if (code === "ELOOP")
@@ -8,7 +8,7 @@ import { gzip } from "node:zlib";
8
8
  import { promisify } from "node:util";
9
9
  import { homedir, networkInterfaces } from "node:os";
10
10
  import { basename, dirname, extname, join, relative, resolve } from "node:path";
11
- import { describe as describeFilesError, fileMeta, listDirectory, MAX_FILE_BYTES, readWorkspaceFile, resolveInsideRoot, toRelative, writeWorkspaceFile, } from "./files.js";
11
+ import { describe as describeFilesError, FilesError, fileMeta, listDirectory, MAX_FILE_BYTES, readWorkspaceFile, resolveInsideRoot, toRelative, writeWorkspaceFile, } from "./files.js";
12
12
  import { findUploadFile, MAX_UPLOAD_BODY_BYTES, saveUpload } from "./upload.js";
13
13
  import { describeThrown } from "./failure-text.js";
14
14
  import { checkDiskVersion } from "./version.js";
@@ -24,9 +24,12 @@ import { MAX_FEISHU_REQUEST_BYTES } from "./application/feishu-service.js";
24
24
  import { MAX_WEB_REQUEST_BYTES } from "./web.js";
25
25
  import { MAX_TOOL_BODY_BYTES } from "./tool-registry.js";
26
26
  import { claimUpdateSlot, getLastUpdateOutcome, isUpdateInFlight, packageUpdateArgs, recordUpdateOutcome, releaseUpdateSlot, shellArgs } from "./update.js";
27
- import { FileIndex } from "./file-index.js";
27
+ import { FileIndex, refreshWorkspaceIndex } from "./file-index.js";
28
28
  import { ensureNameIndex, recordWorkspacePath } from "./file-name-index.js";
29
- import { resolveSessionCwd, sessionScopeKey, workspacePathFromSession } from "./session-cwd.js";
29
+ import { resolveFileCwd, resolveSessionCwd, sessionScopeKey, workspacePathFromSession } from "./session-cwd.js";
30
+ import { explorerInternalPath, explorerPath, inspectWorkspaceUpload, listWorkspaceTrash, MAX_WORKSPACE_UPLOAD_BYTES, mutateWorkspaceTree, serializeWorkspaceWrite, uploadWorkspaceFile } from "./workspace-file-operations.js";
31
+ import { readWorkspaceDocumentPreview, respondWithWorkspaceFile } from "./workspace-file-response.js";
32
+ import { updateExplorerIndexes } from "./workspace-file-indexes.js";
30
33
  import { readMessageMedia } from "./message-media.js";
31
34
  import { MESSAGE_FRAME_CSP, MESSAGE_HTML_CSP } from "../shared/message-media.js";
32
35
  import { verifyDirectChildScope, verifyListParentScope, verifyReportTargetScope, verifySpawnParentScope } from "./session-tree-scope.js";
@@ -47,6 +50,19 @@ function nameIndexFor(context, workspaceId, root, cwd = "") {
47
50
  context.nameIndexes = indexes;
48
51
  return ensureNameIndex(indexes, workspaceId, root, cwd);
49
52
  }
53
+ async function readWorkspaceUpload(request) {
54
+ const chunks = [];
55
+ let length = 0;
56
+ for await (const chunk of request.iterator({ destroyOnReturn: false })) {
57
+ length += chunk.length;
58
+ if (length > MAX_WORKSPACE_UPLOAD_BYTES) {
59
+ request.resume();
60
+ throw new FilesError(413, "单个文件不能超过 32 MB。", "too_large");
61
+ }
62
+ chunks.push(chunk);
63
+ }
64
+ return Buffer.concat(chunks, length);
65
+ }
50
66
  const MIME_TYPES = {
51
67
  ".css": "text/css; charset=utf-8",
52
68
  ".html": "text/html; charset=utf-8",
@@ -63,15 +79,19 @@ const MIME_TYPES = {
63
79
  */
64
80
  function toolBrowserSdk() {
65
81
  return String.raw `(() => {
66
- const request = async (path, init) => {
67
- 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 });
68
87
  let body;
69
88
  try { body = await response.json(); } catch { body = { error: "Super Pi returned an unreadable response" }; }
70
89
  if (!response.ok) throw new Error(body && body.error ? body.error : "Tool request failed (HTTP " + response.status + ")");
71
90
  return body;
72
91
  };
73
92
  const api = {
74
- 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),
75
95
  get: (runId) => request("./api/runs/" + encodeURIComponent(runId), { method: "GET" }),
76
96
  cancel: (runId) => request("./api/runs/" + encodeURIComponent(runId), { method: "DELETE" }),
77
97
  wait: async (runId, { intervalMs = 250, signal } = {}) => {
@@ -90,7 +110,8 @@ function toolBrowserSdk() {
90
110
  // credentials, the model choice and the ceilings, and the tool only ever sees the text. It is a
91
111
  // completion, not an agent - the model that answers has no tools, no files and no session history.
92
112
  // Only a tool registered with permissions.llm may call it; otherwise the server refuses.
93
- 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),
94
115
  llmGet: (callId) => request("./api/llm/" + encodeURIComponent(callId), { method: "GET" }),
95
116
  llmCancel: (callId) => request("./api/llm/" + encodeURIComponent(callId), { method: "DELETE" }),
96
117
  llmWait: async (callId, { intervalMs = 400, signal } = {}) => {
@@ -494,13 +515,35 @@ export function createHttpServer(options) {
494
515
  response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", "access-control-allow-origin": "null", "vary": "Origin" });
495
516
  response.end(JSON.stringify(body));
496
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
+ }
497
540
  if (resource === "api/run") {
498
541
  if (!toolOrigin) {
499
542
  toolApi(403, { error: "tool runtime API is only available to the sandboxed tool frame" });
500
543
  return;
501
544
  }
502
545
  if (request.method === "OPTIONS") {
503
- 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");
504
547
  return;
505
548
  }
506
549
  if (request.method !== "POST") {
@@ -520,7 +563,7 @@ export function createHttpServer(options) {
520
563
  toolApi(404, { error: "python script is not registered" });
521
564
  return;
522
565
  }
523
- 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 });
524
567
  toolApi(202, run);
525
568
  }
526
569
  catch (error) {
@@ -595,7 +638,11 @@ export function createHttpServer(options) {
595
638
  }
596
639
  if (llmStart) {
597
640
  if (request.method === "OPTIONS") {
598
- 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) : []);
599
646
  return;
600
647
  }
601
648
  if (request.method !== "POST") {
@@ -610,7 +657,7 @@ export function createHttpServer(options) {
610
657
  const raw = asked.text;
611
658
  try {
612
659
  const body = JSON.parse(raw);
613
- 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 }));
614
661
  }
615
662
  catch (error) {
616
663
  toolApi(400, { error: describeThrown(error) || "模型调用失败,没有拿到失败原因。" });
@@ -1421,7 +1468,7 @@ export function createHttpServer(options) {
1421
1468
  }
1422
1469
  broadcaster.broadcastState();
1423
1470
  try {
1424
- execService.spawn(sessionId, cmd, cwd);
1471
+ execService.spawn(sessionId, cmd, cwd, conversationId);
1425
1472
  json(202, { sessionId, status: "running" });
1426
1473
  }
1427
1474
  catch (error) {
@@ -2415,6 +2462,83 @@ export function createHttpServer(options) {
2415
2462
  }
2416
2463
  return;
2417
2464
  }
2465
+ const explorerRoute = /^\/api\/files\/(tree|upload|upload-check|asset|document)$/.exec(url.pathname)?.[1];
2466
+ if (explorerRoute) {
2467
+ try {
2468
+ const workspaceId = url.searchParams.get("workspaceId")?.trim();
2469
+ const workspace = workspaceId ? store.workspace(workspaceId) : undefined;
2470
+ if (!workspaceId || !workspace)
2471
+ throw new FilesError(404, "请先选择有效工作区。", "no_workspace");
2472
+ const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
2473
+ const path = url.searchParams.get("path") ?? "";
2474
+ if (request.method === "GET" || request.method === "HEAD") {
2475
+ if (explorerRoute === "asset") {
2476
+ await respondWithWorkspaceFile(request, response, await explorerPath(workspace.path, root, path), url.searchParams.has("download"));
2477
+ return;
2478
+ }
2479
+ if (request.method === "GET" && explorerRoute === "document") {
2480
+ json(200, await readWorkspaceDocumentPreview(await explorerPath(workspace.path, root, path)));
2481
+ return;
2482
+ }
2483
+ if (request.method === "GET" && explorerRoute === "tree") {
2484
+ json(200, { entries: await listWorkspaceTrash(workspace.path, root) });
2485
+ return;
2486
+ }
2487
+ if (request.method === "GET" && explorerRoute === "upload-check") {
2488
+ json(200, await inspectWorkspaceUpload(workspace.path, root, path, url.searchParams.get("name") ?? ""));
2489
+ return;
2490
+ }
2491
+ }
2492
+ if (request.method !== "POST" || (explorerRoute !== "tree" && explorerRoute !== "upload")) {
2493
+ json(405, { error: "不支持此文件操作。", code: "method" });
2494
+ return;
2495
+ }
2496
+ const origin = request.headers.origin;
2497
+ const fetchSite = request.headers["sec-fetch-site"];
2498
+ if (!isLocalOrPrivateAddress(remote) || (origin && (fetchSite ? fetchSite !== "same-origin" : origin !== url.origin))) {
2499
+ throw new FilesError(403, "文件操作需要来自同源的本机或局域网请求。", "denied");
2500
+ }
2501
+ let mutate;
2502
+ if (explorerRoute === "upload") {
2503
+ const bytes = await readWorkspaceUpload(request);
2504
+ mutate = () => uploadWorkspaceFile(workspace.path, root, path, url.searchParams.get("name") ?? "", bytes, request.headers["if-match"]);
2505
+ }
2506
+ else {
2507
+ const result = await readRequestText(request, 16 * 1024);
2508
+ if (result.tooLarge)
2509
+ throw new FilesError(413, "文件操作请求过大。", "too_large");
2510
+ let body;
2511
+ try {
2512
+ body = JSON.parse(result.text);
2513
+ }
2514
+ catch {
2515
+ throw new FilesError(400, "需要有效的文件操作请求。", "bad_request");
2516
+ }
2517
+ if (!body || typeof body !== "object" || Array.isArray(body))
2518
+ throw new FilesError(400, "需要有效的文件操作请求。", "bad_request");
2519
+ mutate = () => mutateWorkspaceTree(workspace.path, root, body);
2520
+ }
2521
+ const outcome = await serializeWorkspaceWrite(workspace.path, async () => {
2522
+ const result = await mutate();
2523
+ const oldPath = result.previousPath && toRelative(workspace.path, resolve(root, result.previousPath));
2524
+ const newPath = toRelative(workspace.path, resolve(root, result.path));
2525
+ await updateExplorerIndexes(context, workspaceId, workspace.path, newPath, result.removed ? newPath : oldPath, !!result.directory, !!result.removed)
2526
+ .catch((error) => console.warn("Super Pi: file operation completed, but the file indexes could not be updated", error));
2527
+ broadcaster.broadcast({ type: "files.invalidated", workspaceId, paths: oldPath ? [oldPath, newPath] : [newPath] });
2528
+ return result;
2529
+ });
2530
+ json(200, outcome);
2531
+ }
2532
+ catch (error) {
2533
+ if (response.headersSent) {
2534
+ response.destroy();
2535
+ return;
2536
+ }
2537
+ const described = describeFilesError(error);
2538
+ json(described.status, described.body);
2539
+ }
2540
+ return;
2541
+ }
2418
2542
  if (url.pathname === "/api/files/diff") {
2419
2543
  const json = (status, body) => {
2420
2544
  response.writeHead(status, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify(body));
@@ -2431,7 +2555,8 @@ export function createHttpServer(options) {
2431
2555
  json(400, { error: "需要 path 参数", code: "bad_request" });
2432
2556
  return;
2433
2557
  }
2434
- const root = await resolveSessionCwd(workspace.path, url.searchParams.get("cwd"));
2558
+ const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
2559
+ await explorerPath(workspace.path, root, path);
2435
2560
  const workspaceRelativePath = await workspacePathFromSession(workspace.path, root, path);
2436
2561
  const requested = url.searchParams.get("base")?.trim();
2437
2562
  const preferred = requested === "git" || requested === "agent" ? requested : "auto";
@@ -2468,7 +2593,8 @@ export function createHttpServer(options) {
2468
2593
  json(404, { error: "找不到这个工作区——它可能已经被删除。", code: "no_workspace" });
2469
2594
  return;
2470
2595
  }
2471
- const root = await resolveSessionCwd(workspace.path, url.searchParams.get("cwd"));
2596
+ const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
2597
+ await explorerPath(workspace.path, root, "", true);
2472
2598
  const cwd = relative(resolve(workspace.path), root).replaceAll("\\", "/");
2473
2599
  const indexKey = sessionScopeKey(workspaceId, cwd);
2474
2600
  if (query.length > 256 || /[\r\n]/.test(query)) {
@@ -2519,7 +2645,8 @@ export function createHttpServer(options) {
2519
2645
  json(400, { error: "搜索内容过长。" });
2520
2646
  return;
2521
2647
  }
2522
- const root = await resolveInsideRoot(workspace.path, url.searchParams.get("cwd") ?? "");
2648
+ const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
2649
+ await explorerPath(workspace.path, root, "", true);
2523
2650
  const cwd = relative(resolve(workspace.path), root).replaceAll("\\", "/");
2524
2651
  const index = nameIndexFor(context, workspaceId, root, cwd);
2525
2652
  await index.waitUntilIndexed(4000);
@@ -2563,7 +2690,8 @@ export function createHttpServer(options) {
2563
2690
  json(404, { error: `找不到工作区「${workspaceId ?? "未指定"}」——它可能已经被删除。`, code: "no_workspace" });
2564
2691
  return;
2565
2692
  }
2566
- const root = await resolveSessionCwd(workspace.path, url.searchParams.get("cwd"));
2693
+ const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
2694
+ await explorerPath(workspace.path, root, "", true);
2567
2695
  const cwd = relative(resolve(workspace.path), root).replaceAll("\\", "/");
2568
2696
  const indexKey = sessionScopeKey(workspaceId, cwd);
2569
2697
  const indexes = context.fileIndexes ?? new Map();
@@ -2599,7 +2727,8 @@ export function createHttpServer(options) {
2599
2727
  json(404, { error: `找不到工作区「${workspaceId ?? "未指定"}」——它可能已经被删除。`, code: "no_workspace" });
2600
2728
  return;
2601
2729
  }
2602
- const root = await resolveSessionCwd(workspace.path, url.searchParams.get("cwd"));
2730
+ const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
2731
+ await explorerPath(workspace.path, root, "", true);
2603
2732
  const cwd = relative(resolve(workspace.path), root).replaceAll("\\", "/");
2604
2733
  const indexKey = sessionScopeKey(workspaceId, cwd);
2605
2734
  if (url.pathname === "/api/files") {
@@ -2647,12 +2776,34 @@ export function createHttpServer(options) {
2647
2776
  });
2648
2777
  return;
2649
2778
  }
2650
- const listing = await listDirectory(root, url.searchParams.get("path"));
2779
+ const requested = url.searchParams.get("path") ?? "";
2780
+ const listing = await serializeWorkspaceWrite(workspace.path, async () => {
2781
+ await explorerPath(workspace.path, root, requested, true);
2782
+ const listed = await listDirectory(root, requested);
2783
+ const allowed = await Promise.all(listed.entries.map(async (entry) => {
2784
+ if (explorerInternalPath(toRelative(workspace.path, resolve(root, entry.path))))
2785
+ return false;
2786
+ if (!entry.symlink || entry.outside)
2787
+ return true;
2788
+ return explorerPath(workspace.path, root, entry.path).then(() => true, () => false);
2789
+ }));
2790
+ listed.entries = listed.entries.filter((_, position) => allowed[position]);
2791
+ if (!listed.truncated) {
2792
+ context.fileIndexes?.get(indexKey)?.reconcileDirectory(listed.path, listed.entries);
2793
+ context.nameIndexes?.get(indexKey)?.reconcileDirectory(listed.path, listed.entries);
2794
+ }
2795
+ if (requested === "" && url.searchParams.get("revalidate") === "1") {
2796
+ context.fileIndexes?.get(indexKey)?.markStale();
2797
+ context.nameIndexes?.get(indexKey)?.markStale();
2798
+ }
2799
+ return listed;
2800
+ });
2651
2801
  json(200, { mode: "list", ...listing, maxEntries: 2000 });
2652
2802
  return;
2653
2803
  }
2654
2804
  if (request.method === "GET") {
2655
2805
  const rel = url.searchParams.get("path") ?? "";
2806
+ await explorerPath(workspace.path, root, rel, true);
2656
2807
  if (url.searchParams.get("meta") === "1") {
2657
2808
  const resolved = await resolveInsideRoot(root, rel);
2658
2809
  const meta = await fileMeta(resolved);
@@ -2696,13 +2847,19 @@ export function createHttpServer(options) {
2696
2847
  json(400, { error: "写入需要 path 与 content 两个字符串字段", code: "bad_request" });
2697
2848
  return;
2698
2849
  }
2699
- const outcome = await writeWorkspaceFile(root, parsed.path, parsed.content, parsed.baseEtag);
2700
- context.fileIndexes?.get(indexKey)?.recordFile(outcome.path, outcome.meta);
2701
- // The name index learns about the save too. A file the user just saved must be findable
2702
- // by name immediately, and the index is the thing the search reads - so this is where the
2703
- // index stays true without anybody re-scanning the tree.
2704
- if (context.nameIndexes)
2705
- recordWorkspacePath(context.nameIndexes, workspaceId, workspace.path, await workspacePathFromSession(workspace.path, root, outcome.path));
2850
+ await explorerPath(workspace.path, root, parsed.path, true);
2851
+ const { path, content, baseEtag } = parsed;
2852
+ const outcome = await serializeWorkspaceWrite(workspace.path, async () => {
2853
+ await explorerPath(workspace.path, root, path, true);
2854
+ const saved = await writeWorkspaceFile(root, path, content, baseEtag);
2855
+ const changedPath = await workspacePathFromSession(workspace.path, root, saved.path);
2856
+ context.fileIndexes?.get(indexKey)?.recordFile(saved.path, saved.meta);
2857
+ refreshWorkspaceIndex(context.fileIndexes, workspaceId, changedPath, workspace.path);
2858
+ if (context.nameIndexes)
2859
+ recordWorkspacePath(context.nameIndexes, workspaceId, workspace.path, changedPath);
2860
+ broadcaster.broadcast({ type: "files.invalidated", workspaceId, paths: [changedPath] });
2861
+ return saved;
2862
+ });
2706
2863
  json(200, outcome);
2707
2864
  return;
2708
2865
  }
@@ -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 {