@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
@@ -25,12 +25,10 @@
25
25
  * 2. NETWORK SCOPE. Even enabled, a command is refused unless the WebSocket arrived from loopback or
26
26
  * an RFC 1918 / link-local / ULA address (`isLocalOrPrivateAddress`, the same predicate the file
27
27
  * endpoints use). A request that arrives from a routed or proxied address is refused by name.
28
- * 3. THE BROWSER NEVER CHOOSES THE WORKING DIRECTORY. `terminal.open` carries a WORKSPACE ID and
29
- * nothing else; this file resolves the id against the store and spawns in that workspace's path.
30
- * A browser that asked for `C:\` or `/etc` gets its own workspace's directory instead, because
31
- * there is no code path on which a client-supplied path reaches `spawn`.
32
- * 4. BOUNDED SESSIONS. `MAX_SESSIONS` live shells, capped so a loop of reconnects cannot accumulate
33
- * processes.
28
+ * 3. WORKSPACE SCOPE. The server resolves a workspace ID and validates the relative starting directory.
29
+ * 4. BOUNDED SESSIONS. Shells and retained output count toward fixed limits.
30
+ * 5. REATTACHMENT. Browser ownership scopes session discovery; only a subscribed socket may
31
+ * address a slot. Losing a subscription does not end the shell.
34
32
  *
35
33
  * What is NOT here is a per-command allowlist. A terminal that refuses `rm` or `curl` is not a terminal,
36
34
  * and pretending otherwise would be worse than the honest version: with (1) and (2) the operator has
@@ -49,10 +47,11 @@
49
47
  * only way to get them. The cost is a native module, and it is paid only by operators who set
50
48
  */
51
49
  import { createRequire } from "node:module";
50
+ import { randomUUID } from "node:crypto";
52
51
  import { existsSync, accessSync, constants } from "node:fs";
53
52
  import { delimiter, join } from "node:path";
54
- import { isLocalOrPrivateAddress } from "./http-server.js";
55
- import { resolveSessionCwd } from "./session-cwd.js";
53
+ import { MAX_TERMINAL_SLOTS } from "../shared/terminal-protocol.js";
54
+ import { resolveFileCwd } from "./session-cwd.js";
56
55
  let ptyModule;
57
56
  let ptyLoadFailure;
58
57
  /**
@@ -237,26 +236,24 @@ const MAX_ROWS = 200;
237
236
  */
238
237
  const FLUSH_INTERVAL_MS = 16;
239
238
  const MAX_CHUNK_BYTES = 64 * 1024;
240
- /** Hard per-session backlog. Beyond this the session is considered runaway and is killed. */
239
+ /** Maximum pending output and retained replay history, measured in UTF-16 code units. */
241
240
  const MAX_BACKLOG_BYTES = 4 * 1024 * 1024;
242
- /**
243
- * The terminal is built in; node-pty availability is checked when a session opens.
244
- */
241
+ const MAX_HISTORY = 256 * 1024;
242
+ /** The terminal is built in. Native PTY availability is checked on use. */
245
243
  export function isTerminalEnabled(env = process.env) {
246
244
  void env;
247
245
  return true;
248
246
  }
249
- /** The sentence a browser shows when the terminal is missing. Says WHICH of the three gates closed. */
250
247
  export function terminalDisabledReason(_env = process.env) {
251
- // The raw native error is logged when it happens (loadPty); the browser gets a sentence it can act on.
252
248
  if (ptyLoadFailure)
253
249
  return "终端组件(node-pty)没有加载成功,请重新安装依赖或重启 Super Pi。";
254
250
  return "";
255
251
  }
256
252
  export class TerminalService {
257
- sessions = new Map();
253
+ groups = new Map();
254
+ subscriptions = new Map();
255
+ closing = false;
258
256
  workspaceFor;
259
- /** Whether a command from this peer is allowed to touch a shell at all. */
260
257
  isTrustedPeer;
261
258
  configuredShell;
262
259
  saveConfiguredShell;
@@ -284,203 +281,273 @@ export class TerminalService {
284
281
  await this.saveConfiguredShell(shell);
285
282
  return true;
286
283
  }
287
- /**
288
- * WHY THE PEER CHECK LIVES ON EVERY COMMAND AND NOT ONLY ON `open`.
289
- *
290
- * The obvious implementation authorises `terminal.open` and then trusts the session. That leaves a
291
- * live shell reachable by a socket opened BEFORE the address changed - and, on this server, the
292
- * browser is same-origin on whatever host it was opened from, so a user who tunnels in, opens a
293
- * terminal, and then forwards their port to a colleague has silently widened the audience for every
294
- * keystroke that follows.
295
- *
296
- * `isTrustedPeer` is re-evaluated per command. It is a pure function of the socket's remote address,
297
- * so the cost is one predicate per keystroke and the guarantee is that no session outlives its
298
- * socket's authorisation.
299
- */
300
284
  assertUsable(remoteAddress, send) {
301
- if (!this.enabled) {
302
- send({ type: "terminal.status", enabled: false, reason: terminalDisabledReason() });
285
+ if (!this.isTrustedPeer(remoteAddress)) {
286
+ send({ type: "terminal.error", message: "终端只接受来自本机或局域网地址的连接。" });
303
287
  return false;
304
288
  }
305
- if (!loadPty()) {
289
+ if (this.closing || !this.enabled || !loadPty()) {
306
290
  send({ type: "terminal.status", enabled: false, reason: terminalDisabledReason() });
307
291
  return false;
308
292
  }
309
- if (!isLocalOrPrivateAddress(remoteAddress)) {
310
- // Named explicitly rather than folded into the disabled message: the operator who enabled the
311
- // terminal and is reaching it from a non-private address needs to know which of the gates closed.
312
- send({ type: "terminal.error", sessionId: "", message: "终端只接受来自本机或局域网地址的连接。" });
313
- return false;
314
- }
315
293
  return true;
316
294
  }
317
295
  async handle(command, remoteAddress, send) {
296
+ if (command.type === "terminal.detach") {
297
+ this.detach(send);
298
+ return;
299
+ }
318
300
  if (!this.assertUsable(remoteAddress, send))
319
301
  return;
302
+ if (command.type === "terminal.sync") {
303
+ await this.sync(command, send);
304
+ return;
305
+ }
306
+ const subscription = this.subscriptions.get(send);
307
+ if (!subscription?.ready) {
308
+ if (command.type !== "terminal.resize")
309
+ send({ type: "terminal.error", message: "终端尚未连接,请刷新页面后重试。" });
310
+ return;
311
+ }
312
+ const { group } = subscription;
320
313
  if (command.type === "terminal.open") {
321
- if (this.sessions.has(command.sessionId))
322
- return;
323
- if (this.sessions.size >= MAX_SESSIONS) {
324
- // The count is in the message because the shells eating the budget are usually the BACKGROUND
325
- // ones of other sessions - a parent session's children included, each of which has its own
326
- // panel with its own terminals. The user sees three terminals in this panel and a refusal,
327
- // and has no way to guess that the sessions they left open still hold shells.
328
- send({
329
- type: "terminal.error",
330
- sessionId: command.sessionId,
331
- message: `终端会话已达上限(服务器最多 ${MAX_SESSIONS} 个,当前已有 ${this.sessions.size} 个在运行)。切换会话后仍在后台运行的终端也计入其中(包括 session 树里的子会话),请到对应的会话里关闭一个再试。`,
332
- });
333
- return;
334
- }
335
- // The workspace id is the ONLY thing the browser supplies, and it is resolved here. A client that
336
- // sends a path instead gets nothing - there is no overload that accepts one.
337
- const workspace = this.workspaceFor(command.workspaceId);
338
- if (!workspace) {
339
- send({ type: "terminal.error", sessionId: command.sessionId, message: "工作区不存在,无法打开终端。" });
340
- return;
314
+ try {
315
+ const activate = await this.open(group, subscription.cwd, command);
316
+ for (const [peer, view] of this.subscriptions) {
317
+ if (view.ready && view.group === group)
318
+ this.sendSessions(peer, group, false, peer === send ? activate : undefined);
319
+ }
341
320
  }
342
- const cwd = await resolveSessionCwd(workspace.path, command.cwd);
343
- // A workspace whose directory was deleted or renamed must not spawn a shell in `process.cwd()`,
344
- // which would silently run the terminal in the SERVER's directory instead of an error.
345
- if (!existsSync(cwd)) {
346
- send({ type: "terminal.error", sessionId: command.sessionId, message: `会话工作目录不存在:${cwd}` });
347
- return;
321
+ catch (error) {
322
+ send({ type: "terminal.error", sessionId: command.sessionId, message: this.errorMessage(error) });
348
323
  }
349
- const pty = loadPty();
350
- const shell = defaultShell(process.env, this.configuredShell());
351
- const child = pty.spawn(shell.file, shell.args, {
352
- // `xterm-256color` is what makes a shell enable colour and line editing; the client understands
353
- // the same terminfo name, so the two ends agree on what the escape sequences mean.
354
- name: "xterm-256color",
355
- cols: clamp(command.cols, MIN_COLS, MAX_COLS, 80),
356
- rows: clamp(command.rows, MIN_ROWS, MAX_ROWS, 24),
357
- cwd,
358
- env: { ...process.env, TERM: "xterm-256color" },
359
- });
360
- const session = { pty: child, closed: false, killed: false, pending: "" };
361
- this.sessions.set(command.sessionId, session);
362
- child.onData((data) => this.enqueue(session, command.sessionId, data, send));
363
- child.onExit(({ exitCode }) => {
364
- // Drain everything still queued before reporting the exit: each flush sends at most
365
- // MAX_CHUNK_BYTES and re-queues the remainder, so a large final burst takes several
366
- // passes. Without the loop, the exit would cut off output the shell already produced.
367
- while (session.pending)
368
- this.flush(session, command.sessionId, send);
369
- this.sessions.delete(command.sessionId);
370
- // A killed shell on Windows reports 0xC0000139 (STATUS_ENTRYPOINT_NOT_FOUND) because that is how
371
- // ConPTY tears down, not because a command failed. Reporting it verbatim would tell the user a
372
- // command exited with a status no program can produce, so a session WE killed reports 0.
373
- if (session.closed && session.killed)
374
- return;
375
- session.closed = true;
376
- send({ type: "terminal.exit", sessionId: command.sessionId, exitCode: session.killed ? 0 : exitCode });
377
- });
378
324
  return;
379
325
  }
380
- // A RESIZE IS A LAYOUT HINT, NOT A COMMAND, AND IT IS THE ONE THAT ARRIVES TOO EARLY TO REPORT ON.
381
- // The client measures its own box in a layout effect, which runs before the effects that open the
382
- // session - so on every mount the panel sends a `terminal.resize` for a session this server has not
383
- // been told about yet. Answering that with 「会话已结束,请重新打开」 is how a perfectly working
384
- // terminal ended up wearing a death notice: the shell started normally a moment later and its prompt
385
- // was on screen, underneath a banner claiming it had exited. Nothing is lost by dropping a resize for
386
- // a session that does not exist - the open carries the measurement too, and the next resize after it
387
- // carries anything the panel has learned since.
388
- if (command.type === "terminal.resize" && !this.sessions.has(command.sessionId))
389
- return;
390
- const session = this.sessions.get(command.sessionId);
326
+ const session = group.sessions.get(command.sessionId);
391
327
  if (!session) {
392
- send({ type: "terminal.error", sessionId: command.sessionId, message: "终端会话已结束,请重新打开。" });
328
+ if (command.type === "terminal.resize")
329
+ return;
330
+ send({ type: "terminal.error", sessionId: command.sessionId, message: "终端会话已关闭或不属于当前视图。" });
331
+ this.sendSessions(send, group, false);
332
+ return;
333
+ }
334
+ if (command.type === "terminal.close") {
335
+ while (session.pending)
336
+ this.flush(group, session);
337
+ group.sessions.delete(session.slot.id);
338
+ this.stop(session);
339
+ this.publish(group, { type: "terminal.exit", sessionId: session.slot.id, exitCode: 0 });
340
+ this.publish(group, { type: "terminal.sessions", ...group.scope, sessions: this.slots(group), replay: false });
393
341
  return;
394
342
  }
343
+ if (!session.pty)
344
+ return;
395
345
  if (command.type === "terminal.input") {
396
- // A keystroke is at most a few bytes; the cap exists to stop a client from using `terminal.input`
397
- // as an unbounded write into a shell, not to limit typing.
398
- if (command.data.length > 64 * 1024)
399
- return;
400
- session.pty.write(command.data);
346
+ if (typeof command.data === "string" && command.data.length <= 64 * 1024)
347
+ session.pty.write(command.data);
401
348
  return;
402
349
  }
403
- if (command.type === "terminal.resize") {
404
- try {
405
- session.pty.resize(clamp(command.cols, MIN_COLS, MAX_COLS, 80), clamp(command.rows, MIN_ROWS, MAX_ROWS, 24));
406
- }
407
- catch {
408
- // A resize against a shell that exited between the lookup and here is not an error worth a
409
- // message; the exit event is already on its way.
350
+ const cols = clamp(command.cols, MIN_COLS, MAX_COLS, session.slot.cols);
351
+ const rows = clamp(command.rows, MIN_ROWS, MAX_ROWS, session.slot.rows);
352
+ if (cols === session.slot.cols && rows === session.slot.rows)
353
+ return;
354
+ try {
355
+ session.pty.resize(cols, rows);
356
+ Object.assign(session.slot, { cols, rows });
357
+ this.publish(group, { type: "terminal.size", sessionId: session.slot.id, cols, rows });
358
+ }
359
+ catch {
360
+ // The PTY can exit before a layout hint arrives.
361
+ }
362
+ }
363
+ async sync(command, send) {
364
+ const { ownerId, workspaceId, conversationId, cwd } = command;
365
+ this.detach(send);
366
+ if (typeof ownerId !== "string" || !/^[0-9a-f]{32}$/.test(ownerId)
367
+ || typeof workspaceId !== "string" || !this.workspaceFor(workspaceId)
368
+ || (conversationId !== undefined && (typeof conversationId !== "string" || conversationId.length > 200))) {
369
+ send({ type: "terminal.error", message: "终端的浏览器标识或工作区无效。" });
370
+ return;
371
+ }
372
+ const key = JSON.stringify([ownerId, workspaceId, conversationId]);
373
+ let group = this.groups.get(key);
374
+ if (!group) {
375
+ group = { key, scope: { workspaceId, conversationId }, initialized: false, creating: 0, sessions: new Map() };
376
+ this.groups.set(key, group);
377
+ }
378
+ const subscription = { group, cwd, ready: false };
379
+ this.subscriptions.set(send, subscription);
380
+ try {
381
+ if (command.initialize === false)
382
+ group.initialized = true;
383
+ if (!group.initialized)
384
+ await this.open(group, cwd, command, true);
385
+ }
386
+ catch (error) {
387
+ if (this.subscriptions.get(send) === subscription) {
388
+ this.detach(send);
389
+ send({ type: "terminal.error", message: this.errorMessage(error) });
410
390
  }
411
391
  return;
412
392
  }
413
- // terminal.close
414
- this.kill(command.sessionId, session, send);
393
+ if (this.subscriptions.get(send) !== subscription)
394
+ return;
395
+ subscription.ready = true;
396
+ this.sendSessions(send, group, true);
397
+ // No await between the snapshot and replay. Live output starts after this baseline.
398
+ for (const session of group.sessions.values()) {
399
+ send({ type: "terminal.replay", sessionId: session.slot.id, data: session.history });
400
+ }
401
+ }
402
+ async open(group, cwd, size, initial = false) {
403
+ group.creating += 1;
404
+ try {
405
+ return await this.spawn(group, cwd, size, initial);
406
+ }
407
+ finally {
408
+ group.creating -= 1;
409
+ this.pruneEmptyGroup(group);
410
+ }
415
411
  }
416
- enqueue(session, sessionId, data, send) {
417
- session.pending += data;
418
- // Flush when a chunk arrives while no timer is pending, so output appears at interactive latency
419
- // rather than waiting for the next chunk that may never come.
420
- if (session.timer)
412
+ async spawn(group, cwd, size, initial) {
413
+ const workspace = this.workspaceFor(group.scope.workspaceId);
414
+ if (!workspace)
415
+ throw new Error("工作区不存在,无法打开终端。");
416
+ if (cwd !== undefined && typeof cwd !== "string")
417
+ throw new Error("会话目录无效。");
418
+ const directory = await resolveFileCwd(workspace.path, cwd);
419
+ if (this.closing || this.groups.get(group.key) !== group)
420
+ throw new Error("终端工作区已关闭,无法打开终端。");
421
+ if (!existsSync(directory))
422
+ throw new Error("会话工作目录不存在,无法打开终端。");
423
+ // Filesystem resolution yields to other sockets. Recheck creation and capacity before spawning.
424
+ if (initial && group.initialized)
421
425
  return;
422
- session.timer = setTimeout(() => this.flush(session, sessionId, send), FLUSH_INTERVAL_MS);
426
+ const previous = size.sessionId ? group.sessions.get(size.sessionId) : undefined;
427
+ if (size.sessionId && !previous)
428
+ throw new Error("终端会话已关闭。");
429
+ if (previous?.pty)
430
+ return previous.slot.id;
431
+ const count = [...this.groups.values()].reduce((total, item) => total + item.sessions.size, 0);
432
+ if (!previous && (group.sessions.size >= MAX_TERMINAL_SLOTS || count >= MAX_SESSIONS)) {
433
+ throw new Error(`终端数量已达上限(每个会话最多 ${MAX_TERMINAL_SLOTS} 个,服务端最多 ${MAX_SESSIONS} 个)。请关闭不用的终端后重试。`);
434
+ }
435
+ let title = 1;
436
+ const used = new Set([...group.sessions.values()].map(session => session.slot.title));
437
+ while (used.has(String(title)))
438
+ title += 1;
439
+ const slot = {
440
+ id: previous?.slot.id ?? randomUUID(),
441
+ title: previous?.slot.title ?? String(title),
442
+ cols: clamp(size.cols, MIN_COLS, MAX_COLS, 80),
443
+ rows: clamp(size.rows, MIN_ROWS, MAX_ROWS, 24),
444
+ };
445
+ const shell = defaultShell(process.env, this.configuredShell());
446
+ const child = loadPty().spawn(shell.file, shell.args, {
447
+ name: "xterm-256color", cols: slot.cols, rows: slot.rows, cwd: directory,
448
+ env: { ...process.env, TERM: "xterm-256color" },
449
+ });
450
+ const session = { slot, pty: child, history: "", pending: "" };
451
+ group.sessions.set(slot.id, session);
452
+ group.initialized = true;
453
+ child.onData(data => {
454
+ if (session.pty !== child)
455
+ return;
456
+ session.pending += data;
457
+ session.timer ??= setTimeout(() => this.flush(group, session), FLUSH_INTERVAL_MS);
458
+ });
459
+ child.onExit(({ exitCode }) => {
460
+ while (session.pending && session.pty === child)
461
+ this.flush(group, session);
462
+ if (session.pty !== child)
463
+ return;
464
+ session.pty = undefined;
465
+ this.recordExit(group, session, exitCode);
466
+ });
467
+ return slot.id;
468
+ }
469
+ slots(group) {
470
+ return [...group.sessions.values()].map(session => session.slot);
423
471
  }
424
- flush(session, sessionId, send) {
425
- if (session.timer) {
426
- clearTimeout(session.timer);
427
- session.timer = undefined;
472
+ sendSessions(send, group, replay, activate) {
473
+ send({ type: "terminal.sessions", ...group.scope, sessions: this.slots(group), replay, activate });
474
+ }
475
+ publish(group, event) {
476
+ for (const [send, view] of this.subscriptions) {
477
+ if (view.ready && view.group === group)
478
+ send(event);
428
479
  }
480
+ }
481
+ flush(group, session) {
482
+ clearTimeout(session.timer);
483
+ session.timer = undefined;
429
484
  if (!session.pending)
430
485
  return;
431
486
  if (session.pending.length > MAX_BACKLOG_BYTES) {
432
- this.kill(sessionId, session, send);
433
- send({ type: "terminal.error", sessionId, message: "输出量过大,已停止该终端会话。" });
487
+ this.stop(session);
488
+ this.recordExit(group, session, 1, "输出量过大,已停止该终端会话。");
434
489
  return;
435
490
  }
436
- let data = session.pending;
437
- session.pending = "";
438
- if (data.length > MAX_CHUNK_BYTES) {
439
- // The ceiling bounds ONE FRAME, not the queue: the remainder is older data, so it goes back to
440
- // the FRONT of the pending buffer and the timer is re-armed so the next flush sends it. Dropping
441
- // it here would silently lose terminal output - the exact corruption the queue exists to avoid.
442
- session.pending = data.slice(MAX_CHUNK_BYTES) + session.pending;
443
- data = data.slice(0, MAX_CHUNK_BYTES);
444
- session.timer = setTimeout(() => this.flush(session, sessionId, send), FLUSH_INTERVAL_MS);
445
- }
446
- send({ type: "terminal.output", sessionId, data });
491
+ const data = session.pending.slice(0, MAX_CHUNK_BYTES);
492
+ session.pending = session.pending.slice(data.length);
493
+ if (session.pending)
494
+ session.timer = setTimeout(() => this.flush(group, session), FLUSH_INTERVAL_MS);
495
+ session.history = (session.history + data).slice(-MAX_HISTORY);
496
+ this.publish(group, { type: "terminal.output", sessionId: session.slot.id, data });
447
497
  }
448
- kill(sessionId, session, send) {
449
- // Drain the backlog before teardown so closing a terminal does not discard output the shell
450
- // already produced; each flush sends at most MAX_CHUNK_BYTES per frame.
451
- while (session.pending)
452
- this.flush(session, sessionId, send);
453
- session.closed = true;
454
- session.killed = true;
455
- if (session.timer) {
456
- clearTimeout(session.timer);
457
- session.timer = undefined;
458
- }
459
- this.sessions.delete(sessionId);
498
+ recordExit(group, session, exitCode, reason) {
499
+ Object.assign(session.slot, { exitCode, reason });
500
+ this.publish(group, { type: "terminal.exit", sessionId: session.slot.id, exitCode, reason });
501
+ }
502
+ stop(session) {
503
+ const child = session.pty;
504
+ session.pty = undefined;
505
+ session.pending = "";
506
+ clearTimeout(session.timer);
507
+ session.timer = undefined;
460
508
  try {
461
- session.pty.kill();
509
+ child?.kill();
462
510
  }
463
- catch {
464
- // A shell that already exited makes `kill()` throw on some platforms. The session is removed
465
- // either way, so there is nothing left to leak.
511
+ catch { /* The shell may already be gone. */ }
512
+ }
513
+ errorMessage(error) {
514
+ return error instanceof Error ? error.message : "无法打开终端。";
515
+ }
516
+ /** Losing a reader never changes a shell or its output history. */
517
+ detach(send) {
518
+ const view = this.subscriptions.get(send);
519
+ this.subscriptions.delete(send);
520
+ if (view)
521
+ this.pruneEmptyGroup(view.group);
522
+ }
523
+ pruneEmptyGroup(group) {
524
+ if (group.sessions.size || group.creating || this.groups.get(group.key) !== group)
525
+ return;
526
+ if ([...this.subscriptions.values()].some(view => view.group === group))
527
+ return;
528
+ this.groups.delete(group.key);
529
+ }
530
+ removeWorkspace(workspaceId) {
531
+ for (const [key, group] of this.groups) {
532
+ if (group.scope.workspaceId !== workspaceId)
533
+ continue;
534
+ this.groups.delete(key);
535
+ for (const session of group.sessions.values())
536
+ this.stop(session);
537
+ for (const [send, view] of this.subscriptions) {
538
+ if (view.group === group)
539
+ this.detach(send);
540
+ }
466
541
  }
467
- send({ type: "terminal.exit", sessionId, exitCode: 0 });
468
542
  }
469
- /** Every shell, for shutdown. Exits without reporting anything - the server is going away. */
470
543
  closeAll() {
471
- for (const [sessionId, session] of this.sessions) {
472
- session.closed = true;
473
- session.killed = true;
474
- if (session.timer)
475
- clearTimeout(session.timer);
476
- try {
477
- session.pty.kill();
478
- }
479
- catch {
480
- /* already gone */
481
- }
482
- this.sessions.delete(sessionId);
544
+ this.closing = true;
545
+ for (const group of this.groups.values()) {
546
+ for (const session of group.sessions.values())
547
+ this.stop(session);
483
548
  }
549
+ this.groups.clear();
550
+ this.subscriptions.clear();
484
551
  }
485
552
  }
486
553
  function clamp(value, min, max, fallback) {
@@ -43,6 +43,7 @@ export type ToolLlmRequest = {
43
43
  prompt: string;
44
44
  system?: string;
45
45
  timeoutMs?: number;
46
+ ownerId?: string;
46
47
  };
47
48
  /** 32KB of prompt is a paragraph of a book; more than that is a tool trying to move a transcript. */
48
49
  export declare const MAX_TOOL_LLM_PROMPT_BYTES = 32000;
@@ -59,6 +60,12 @@ export declare class ToolLlmService {
59
60
  * tool asking a question there should be told the machine cannot answer it. */
60
61
  get available(): boolean;
61
62
  start(request: ToolLlmRequest): ToolLlmRun;
63
+ list(toolId: string, ownerId: string): {
64
+ id: string;
65
+ status: ToolLlmStatus;
66
+ startedAt: string;
67
+ finishedAt: string | undefined;
68
+ }[];
62
69
  get(id: string, toolId: string): ToolLlmRun | undefined;
63
70
  cancel(id: string, toolId: string): ToolLlmRun | undefined;
64
71
  wait(id: string, toolId: string, signal?: AbortSignal): Promise<ToolLlmRun>;
@@ -60,7 +60,7 @@ export class ToolLlmService {
60
60
  // a Pi process and a model call alive.
61
61
  const timer = setTimeout(() => controller.abort(), timeoutMs);
62
62
  timer.unref();
63
- const active = { run, controller, timer };
63
+ const active = { run, ownerId: request.ownerId, controller, timer };
64
64
  this.runs.set(id, active);
65
65
  void (async () => {
66
66
  try {
@@ -101,6 +101,13 @@ export class ToolLlmService {
101
101
  })();
102
102
  return copy(run);
103
103
  }
104
+ list(toolId, ownerId) {
105
+ return [...this.runs.values()].reverse()
106
+ .filter(entry => entry.run.toolId === toolId && entry.ownerId === ownerId)
107
+ .sort((a, b) => Number(b.run.status === "running") - Number(a.run.status === "running"))
108
+ .slice(0, 16)
109
+ .map(({ run: { id, status, startedAt, finishedAt } }) => ({ id, status, startedAt, finishedAt }));
110
+ }
104
111
  get(id, toolId) { const active = this.runs.get(id); return active?.run.toolId === toolId ? copy(active.run) : undefined; }
105
112
  cancel(id, toolId) {
106
113
  const active = this.runs.get(id);
@@ -81,6 +81,7 @@ export declare class ToolRunner {
81
81
  definition: ToolScript;
82
82
  params: Record<string, unknown>;
83
83
  environment?: ToolEnvironment;
84
+ ownerId?: string;
84
85
  }): ToolRun;
85
86
  private prepare;
86
87
  /**
@@ -92,6 +93,12 @@ export declare class ToolRunner {
92
93
  */
93
94
  private ensureEnvironment;
94
95
  private launch;
96
+ list(toolId: string, ownerId: string): {
97
+ id: string;
98
+ status: "cancelled" | "failed" | "running" | "succeeded" | "timed_out";
99
+ startedAt: string;
100
+ finishedAt: string | undefined;
101
+ }[];
95
102
  get(id: string, toolId: string): ToolRun | undefined;
96
103
  cancel(id: string, toolId: string): ToolRun | undefined;
97
104
  private finish;
@@ -98,7 +98,7 @@ export class ToolRunner {
98
98
  const run = { id, toolId: input.toolId, status: "running", startedAt: new Date().toISOString(), logs: "" };
99
99
  const timer = setTimeout(() => this.finish(id, "timed_out", `准备运行环境超过 ${MAX_ENV_TIMEOUT_MS}ms 时限`), MAX_ENV_TIMEOUT_MS);
100
100
  timer.unref();
101
- const active = { run, stdout: "", cancelled: false, timer };
101
+ const active = { run, ownerId: input.ownerId, stdout: "", cancelled: false, timer };
102
102
  this.runs.set(id, active);
103
103
  void this.prepare(id, active, input);
104
104
  return copy(run);
@@ -195,6 +195,13 @@ export class ToolRunner {
195
195
  });
196
196
  child.stdin.end(JSON.stringify(input.params));
197
197
  }
198
+ list(toolId, ownerId) {
199
+ return [...this.runs.values()].reverse()
200
+ .filter(entry => entry.run.toolId === toolId && entry.ownerId === ownerId)
201
+ .sort((a, b) => Number(b.run.status === "running") - Number(a.run.status === "running"))
202
+ .slice(0, 16)
203
+ .map(({ run: { id, status, startedAt, finishedAt } }) => ({ id, status, startedAt, finishedAt }));
204
+ }
198
205
  get(id, toolId) { const active = this.runs.get(id); return active?.run.toolId === toolId ? copy(active.run) : undefined; }
199
206
  cancel(id, toolId) { const active = this.runs.get(id); if (!active || active.run.toolId !== toolId)
200
207
  return undefined; if (active.run.status === "running") {