@evandu/super-pi 0.1.240 → 0.1.241

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.
@@ -6,6 +6,7 @@
6
6
  * bash commands without going through the subagent dispatch machinery.
7
7
  */
8
8
  import { createRequire } from "node:module";
9
+ import { BACKGROUND_LOG_LIMIT } from "../shared/background-task.js";
9
10
  let ptyModule;
10
11
  let ptyLoadFailure;
11
12
  function loadPty() {
@@ -27,13 +28,15 @@ function ptyLoadError() {
27
28
  loadPty(); // ensure the failure is populated
28
29
  return ptyLoadFailure;
29
30
  }
30
- const FLUSH_INTERVAL_MS = 16;
31
- const MAX_BACKLOG_BYTES = 4 * 1024 * 1024;
31
+ const CHECKPOINT_INTERVAL_MS = 500;
32
+ const STOP_TIMEOUT_MS = 2000;
32
33
  export class ExecService {
34
+ onCheckpoint;
33
35
  sessions = new Map();
34
36
  broadcast;
35
37
  onComplete;
36
- constructor(broadcast, onComplete) {
38
+ constructor(broadcast, onComplete, onCheckpoint) {
39
+ this.onCheckpoint = onCheckpoint;
37
40
  this.broadcast = broadcast;
38
41
  this.onComplete = onComplete;
39
42
  }
@@ -49,6 +52,8 @@ export class ExecService {
49
52
  throw new Error("node-pty is not available");
50
53
  // Determine shell to run the command.
51
54
  const shell = defaultShell();
55
+ let resolveEnd;
56
+ const ended = new Promise(resolve => { resolveEnd = resolve; });
52
57
  const active = {
53
58
  conversationId,
54
59
  pty: pty.spawn(shell.file, [...shell.args, "-c", cmd], {
@@ -58,28 +63,30 @@ export class ExecService {
58
63
  cwd,
59
64
  env: { ...process.env, TERM: "xterm-256color" },
60
65
  }),
61
- stdout: "",
62
- stderr: "",
63
- killed: false,
66
+ output: "",
67
+ offset: 0,
68
+ checkpoint: undefined,
69
+ ended,
70
+ resolveEnd,
64
71
  };
72
+ this.sessions.set(id, active);
65
73
  active.pty.onData((data) => {
66
- active.stdout += data;
67
- if (active.stdout.length > MAX_BACKLOG_BYTES)
68
- active.stdout = active.stdout.slice(-MAX_BACKLOG_BYTES);
69
- this.broadcast({ type: "exec.output", sessionId: id, conversationId, data });
70
- });
71
- // Flush stderr via a periodic timer rather than a separate channel.
72
- // node-pty on Windows multiplexes both streams; on Unix they are separate.
73
- // We treat all output as stdout for simplicity.
74
- active.timer = setInterval(() => this.flushStderr(id, active), FLUSH_INTERVAL_MS);
75
- active.pty.onExit(({ exitCode }) => {
76
- if (active.timer)
77
- clearInterval(active.timer);
78
- const code = active.killed ? 0 : (exitCode ?? 0);
79
- this.sessions.delete(id);
80
- this.onComplete(id, code, active.stdout, active.stderr);
74
+ if (this.sessions.get(id) !== active)
75
+ return;
76
+ active.offset += data.length;
77
+ active.output = (active.output + data).slice(-BACKGROUND_LOG_LIMIT);
78
+ this.broadcast({ type: "exec.output", sessionId: id, conversationId, data, offset: active.offset, truncated: active.offset > active.output.length });
79
+ if (this.onCheckpoint && !active.checkpoint) {
80
+ active.checkpoint = setTimeout(() => {
81
+ active.checkpoint = undefined;
82
+ void this.onCheckpoint?.(id, active.output, active.offset).catch(error => {
83
+ console.warn("Super Pi: could not checkpoint background output:", error);
84
+ });
85
+ }, CHECKPOINT_INTERVAL_MS);
86
+ active.checkpoint.unref();
87
+ }
81
88
  });
82
- this.sessions.set(id, active);
89
+ active.pty.onExit(({ exitCode, signal }) => this.finish(id, active, exitCode ?? 1, signal));
83
90
  return {
84
91
  id,
85
92
  pid: active.pty.pid,
@@ -93,37 +100,56 @@ export class ExecService {
93
100
  outputSnapshots(state, scope) {
94
101
  const visible = new Set(state.conversations.map(conversation => conversation.id));
95
102
  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))));
103
+ const maxPerTask = Math.min(BACKGROUND_LOG_LIMIT, Math.max(1, Math.floor(512_000 / Math.max(ids.length, 1))));
97
104
  return ids.flatMap(id => {
98
105
  const session = this.sessions.get(id);
99
- return session ? [{ type: "exec.output", sessionId: id, conversationId: session.conversationId, data: session.stdout.slice(-maxPerTask), replace: true }] : [];
106
+ if (!session)
107
+ return [];
108
+ const data = session.output.slice(-maxPerTask);
109
+ return [{ type: "exec.output", sessionId: id, conversationId: session.conversationId, data, replace: true, offset: session.offset, truncated: session.offset > data.length }];
100
110
  });
101
111
  }
102
- kill(id) {
112
+ kill(id, cancellation = "cancelled") {
103
113
  const session = this.sessions.get(id);
104
- if (!session || session.killed)
114
+ if (!session)
105
115
  return;
106
- session.killed = true;
116
+ session.cancellation ??= cancellation;
107
117
  try {
108
118
  session.pty.kill();
109
119
  }
110
120
  catch { /* already gone */ }
111
121
  }
112
- closeAll() {
113
- for (const [id, session] of this.sessions) {
114
- session.killed = true;
115
- if (session.timer)
116
- clearInterval(session.timer);
117
- try {
118
- session.pty.kill();
119
- }
120
- catch { /* already gone */ }
121
- this.sessions.delete(id);
122
+ async stop(id, cancellation = "cancelled") {
123
+ const session = this.sessions.get(id);
124
+ if (!session)
125
+ return false;
126
+ this.kill(id, cancellation);
127
+ let timer;
128
+ await Promise.race([session.ended, new Promise(resolve => { timer = setTimeout(resolve, STOP_TIMEOUT_MS); })]);
129
+ clearTimeout(timer);
130
+ if (this.sessions.get(id) === session)
131
+ throw new Error("后台命令尚未退出,可以重试终止。");
132
+ return true;
133
+ }
134
+ async closeAll() {
135
+ const results = await Promise.allSettled([...this.sessions.keys()].map(id => this.stop(id, "interrupted")));
136
+ for (const result of results) {
137
+ if (result.status === "rejected")
138
+ console.warn("Super Pi: a background command did not exit at shutdown:", result.reason);
122
139
  }
123
140
  }
124
- flushStderr(_id, _session) {
125
- // Currently all output goes to stdout. If we add a separate stderr channel in future,
126
- // this is where it would be broadcast.
141
+ finish(id, session, exitCode, signal) {
142
+ if (this.sessions.get(id) !== session)
143
+ return;
144
+ this.sessions.delete(id);
145
+ clearTimeout(session.checkpoint);
146
+ // A PTY delivers one stream, including error diagnostics.
147
+ try {
148
+ this.onComplete(id, exitCode, session.output, "", { status: session.cancellation ?? "exited", signal, offset: session.offset });
149
+ }
150
+ finally {
151
+ session.resolveEnd();
152
+ }
127
153
  }
128
154
  }
129
155
  function defaultShell() {
@@ -1590,6 +1590,7 @@ export function createHttpServer(options) {
1590
1590
  json(403, { error: result.message });
1591
1591
  return;
1592
1592
  }
1593
+ const foreground = runService.foregroundSignal(conversationId);
1593
1594
  // The `cwd` here is the directory the Pi child was launched in - which is the conversation's
1594
1595
  // workspace, already authenticated by the per-conversation capability check above. Validating it
1595
1596
  // against the workspace list looked cheap, but Windows path normalization (8.3 short names, UNC
@@ -1605,6 +1606,10 @@ export function createHttpServer(options) {
1605
1606
  // inside a turn belongs at that call. Resolved AFTER the capability check above, because a position
1606
1607
  // is worth reading only from a caller already inside the turn.
1607
1608
  const origin = await runService.waitForToolCall(conversationId, toolCallId);
1609
+ if (!runService.canAdmitBackgroundTask(foreground)) {
1610
+ json(409, { error: "原回合已停止,命令未启动。" });
1611
+ return;
1612
+ }
1608
1613
  await store.setBackgroundTask({
1609
1614
  id: sessionId,
1610
1615
  conversationId,
@@ -1620,18 +1625,19 @@ export function createHttpServer(options) {
1620
1625
  broadcaster.broadcast({ type: "message.tools", conversationId, messageId: origin.originMessageId, toolCalls });
1621
1626
  }
1622
1627
  broadcaster.broadcastState();
1628
+ if (!runService.canAdmitBackgroundTask(foreground) || !store.backgroundTask(sessionId)) {
1629
+ await runService.failBackgroundTaskStart(sessionId, "原回合已停止,命令未启动。", true);
1630
+ json(409, { error: "原回合已停止,命令未启动。" });
1631
+ return;
1632
+ }
1623
1633
  try {
1624
1634
  execService.spawn(sessionId, cmd, cwd, conversationId);
1625
1635
  json(202, { sessionId, status: "running" });
1626
1636
  }
1627
1637
  catch (error) {
1628
- if (origin) {
1629
- const toolCalls = await store.updateToolCall(conversationId, origin.originMessageId, origin.originCallRow, { backgroundTask: { id: sessionId, status: "failed", output: error instanceof Error ? error.message : "spawn failed" } });
1630
- broadcaster.broadcast({ type: "message.tools", conversationId, messageId: origin.originMessageId, toolCalls });
1631
- }
1632
- await store.removeBackgroundTask(sessionId);
1633
- broadcaster.broadcastState();
1634
- json(500, { error: error instanceof Error ? error.message : "spawn failed" });
1638
+ const reason = error instanceof Error ? error.message : "后台命令启动失败。";
1639
+ await runService.failBackgroundTaskStart(sessionId, reason);
1640
+ json(500, { error: reason });
1635
1641
  }
1636
1642
  return;
1637
1643
  }
@@ -216,11 +216,12 @@ const subagents = new SubagentRunRecorder(supervisor, {
216
216
  broadcaster.broadcastState();
217
217
  },
218
218
  // The full state broadcast moved from "every delta" to "on settle": a browser that reloads mid-run
219
- // rebuilds the card from the store (written per delta); the settle frame is what puts the FINAL
219
+ // rebuilds the card from the current store snapshot; the settle frame puts the final
220
220
  // record into `state` so a reload after the finish sees it too.
221
221
  onSettled: legacySubagentFlood ? undefined : () => broadcaster.broadcastState(),
222
222
  liveTailCap: legacySubagentFlood ? Number.POSITIVE_INFINITY : undefined,
223
223
  host: (conversationId, runId) => extensionUiService.createHost(conversationId, runId),
224
+ closeHost: (conversationId, runId) => extensionUiService.cancelPendingUi(conversationId, "aborted", { runId }),
224
225
  });
225
226
  /**
226
227
  * The orchestration engine: walks a whole plan the primary agent declared, dispatching each step through
@@ -305,8 +306,8 @@ const terminalService = new TerminalService({
305
306
  * Background command execution, independent from subagents. Uses node-pty to run shell commands
306
307
  * and delivers results via WebSocket + injected conversation message.
307
308
  */
308
- const execService = new ExecService((event) => broadcaster.broadcast(event), (sessionId, exitCode, stdout, stderr) => runService.enqueueExecResult(sessionId, exitCode, stdout, stderr));
309
- runService.setExecService(execService);
309
+ const execService = new ExecService((event) => broadcaster.broadcast(event), (sessionId, exitCode, stdout, stderr, completion) => runService.enqueueExecResult(sessionId, exitCode, stdout, stderr, completion), (sessionId, output, offset) => store.checkpointBackgroundOutput(sessionId, output, offset));
310
+ runService.setExecService(execService, join(dataDir, "background-logs"));
310
311
  replayRuntime = (state, scope) => execService.outputSnapshots(state, scope);
311
312
  projectRuntime = state => {
312
313
  const visible = new Set(state.conversations.map(conversation => conversation.id));
@@ -393,7 +394,7 @@ async function shutdown(reason) {
393
394
  const httpClosed = closeHttpServer();
394
395
  // Kill every shell BEFORE the sockets close, so a PTY is never outlived by the server that owns it.
395
396
  terminalService.closeAll();
396
- execService.closeAll();
397
+ const execClosed = execService.closeAll();
397
398
  runService.abortAll();
398
399
  workflows.abortAll();
399
400
  // The scheduler stops BEFORE the runs are waited for, so no new task starts while the server is
@@ -404,6 +405,7 @@ async function shutdown(reason) {
404
405
  extensionUiService.cancelPendingUi(c.id, "aborted");
405
406
  }
406
407
  await sessionOrchestratorService.watchdog.dispose();
408
+ await execClosed;
407
409
  await Promise.all([runService.waitForIdle(), workflows.waitForIdle()]);
408
410
  // THE LIVE SESSIONS GO NEXT, AND THEY HAVE TO GO EXPLICITLY. `runService.abortAll()` stops the
409
411
  // TURNS, and a stopped turn is not a stopped session: a session with nothing running on it is idle,
@@ -415,8 +417,6 @@ async function shutdown(reason) {
415
417
  // The capabilities die AFTER the sessions that carry them: a session that is still alive could
416
418
  // otherwise use a credential the server has already forgotten about.
417
419
  releaseAllCapabilities();
418
- // Clean up background tasks so the flushed state never freezes running zombies on disk.
419
- await store.clearBackgroundTasks();
420
420
  await store.flush();
421
421
  wsServer.close();
422
422
  httpServer.closeAllConnections();
@@ -3,7 +3,8 @@ import type { AppStateRepository } from "./persistence/app-state-repository.js";
3
3
  import { defaultJsonStatePath } from "./persistence/json-state-repository.js";
4
4
  import type { ScheduledTask } from "./scheduled-tasks.js";
5
5
  import type { WorkflowRun } from "./workflow.js";
6
- import type { AppState, Conversation, Message, MessageDelivery, MessageImage, ModelSelection, Project, SubagentRun, SubagentRunUpdate, TodoItem, ToolCallQuestion, ToolCallArg, ToolCallBlock, ToolResultSummary, Workspace } from "./types.js";
6
+ import type { AppState, BackgroundTaskSummary, Conversation, Message, MessageDelivery, MessageImage, ModelSelection, Project, SubagentRun, SubagentRunUpdate, TodoItem, ToolCallQuestion, ToolCallArg, ToolCallBlock, ToolResultSummary, Workspace } from "./types.js";
7
+ import { type BackgroundCompletion } from "../shared/background-task.js";
7
8
  import type { TurnUsageReadout } from "./conversation-usage.js";
8
9
  /** Mints the id a forked conversation will have, BEFORE its Pi transcript exists.
9
10
  *
@@ -942,6 +943,9 @@ export declare class Store {
942
943
  */
943
944
  setWorkflow(plan: WorkflowRun): Promise<WorkflowRun>;
944
945
  setBackgroundTask(summary: AppState["backgroundTasks"][number]): Promise<void>;
946
+ backgroundTask(id: string): BackgroundTaskSummary | undefined;
947
+ checkpointBackgroundOutput(id: string, output: string, offset: number): Promise<void>;
948
+ finishBackgroundTask(taskId: string, outcome: BackgroundCompletion, content: string, deliver: boolean): Promise<Message | undefined>;
945
949
  removeBackgroundTask(id: string): Promise<void>;
946
950
  clearBackgroundTasks(): Promise<void>;
947
951
  /**
@@ -979,6 +983,8 @@ export declare class Store {
979
983
  * as durable as the conversation it belongs to.
980
984
  */
981
985
  setSubagentRun(runId: string, changes: SubagentRunUpdate): Promise<SubagentRun>;
986
+ updateSubagentProgress(runId: string, changes: SubagentRunUpdate): void;
987
+ checkpointSubagentProgress(runId: string): Promise<void>;
982
988
  /**
983
989
  * Adds ONE settled run's usage to the ledger of the conversation that dispatched it.
984
990
  *
@@ -4,6 +4,7 @@ import { JsonStateRepository, defaultJsonStatePath } from "./persistence/json-st
4
4
  import { normalizeTodos } from "./task-tool.js";
5
5
  import { initializeMemoryTrees, memoryTreeId } from "./session-memory-scope.js";
6
6
  import { TOOL_ARG_CAP } from "./tool-calls.js";
7
+ import { BACKGROUND_LOG_LIMIT, subagentProgress } from "../shared/background-task.js";
7
8
  import { serverTimeZone } from "./time-zone.js";
8
9
  import { pendingUserDecisionsByOwner } from "../shared/archive-decisions.js";
9
10
  function id(prefix) { return `${prefix}_${crypto.randomUUID()}`; }
@@ -601,30 +602,26 @@ function reconcileTodos(state) {
601
602
  const after = JSON.stringify({ todos: state.todos, todosByConversation: state.todosByConversation });
602
603
  return { changed: before !== after };
603
604
  }
604
- /**
605
- * Startup reconciliation: cleans up background tasks left over from previous server process.
606
- *
607
- * `backgroundTasks` is a LIFECYCLE collection: it tracks active in-flight executions (pty child
608
- * processes or detached subagents) and is emptied as each task settles. When a server restarts,
609
- * those processes are dead and cannot report their completion. Leaving them in `backgroundTasks`
610
- * creates permanent "zombies" in the main sidebar that can never be dismissed.
611
- *
612
- * If a task originated from a tool call in a conversation, its tool call block is marked as failed
613
- * so the chat transcript accurately reflects that the task was interrupted by server restart.
614
- *
615
- * WHY ONLY THE LINKED ONES ARE SWEPT, and not every entry in the list.
616
- *
617
- * A task is created by exactly one route: the `/api/exec` endpoint, and that endpoint REQUIRES a
618
- * `conversationId` (it is what the capability check and the tool-call anchor are resolved against).
619
- * So every task this server ever creates is linked to a conversation's tool call, and every one of
620
- * those is swept here - the zombie problem is fully covered.
621
- *
622
- * A task with NO conversation anchor is a shape this server cannot produce. The sweep cannot account
623
- * for it either: there is no tool call to mark failed, so there is nothing to tell the reader that
624
- * the task died. Deleting it would remove a record without replacing it with an explanation, which is
625
- * the one outcome worse than a stale entry. So those are LEFT ALONE, and this function says so in its
626
- * return value rather than silently keeping them.
627
- */
605
+ function backgroundTaskMessage(conversation, task, outcome, content, deliver) {
606
+ const finished = { ...task, ...outcome, finishedAt: now() };
607
+ const origin = conversation.messages.find(message => message.id === task.originMessageId);
608
+ const call = task.originCallRow === undefined ? undefined : origin?.toolCalls?.[task.originCallRow];
609
+ const anchored = task.agentId === "exec" && call?.backgroundTask?.id === task.id;
610
+ if (anchored && call)
611
+ call.backgroundTask = { id: task.id, ...outcome };
612
+ const message = {
613
+ id: id("message"),
614
+ role: "tool",
615
+ content,
616
+ createdAt: finished.finishedAt,
617
+ backgroundTask: anchored ? { ...finished, output: undefined } : finished,
618
+ ...(deliver && !conversation.archivedAt ? { delivery: "waiting" } : {}),
619
+ };
620
+ conversation.messages.push(message);
621
+ conversation.updatedAt = message.createdAt;
622
+ return message;
623
+ }
624
+ // Restore interrupted tasks and their checkpoints to the owning transcript on startup.
628
625
  function reconcileBackgroundTasks(state) {
629
626
  const tasks = Array.isArray(state.backgroundTasks) ? state.backgroundTasks : [];
630
627
  state.backgroundTasks = [];
@@ -635,22 +632,24 @@ function reconcileBackgroundTasks(state) {
635
632
  for (const task of tasks) {
636
633
  if (!task)
637
634
  continue;
638
- // The three fields are destructured rather than tested through a boolean, because a boolean does not
639
- // narrow their types and `toolCalls[undefined]` is not an index.
640
- const { conversationId, originMessageId, originCallRow } = task;
641
- if (!conversationId || originMessageId === undefined || originCallRow === undefined) {
635
+ const conversation = state.conversations?.find(c => c?.id === task.conversationId);
636
+ if (!conversation) {
642
637
  unlinked.push(task);
643
638
  state.backgroundTasks.push(task);
644
639
  continue;
645
640
  }
646
641
  orphaned.push(task);
647
- const conv = state.conversations?.find((c) => c?.id === conversationId);
648
- const msg = conv?.messages?.find((m) => m?.id === originMessageId);
649
- const call = msg?.toolCalls?.[originCallRow];
650
- if (call?.backgroundTask && call.backgroundTask.status === "running") {
651
- call.backgroundTask.status = "failed";
652
- call.backgroundTask.output = "任务随服务重启被终止";
653
- }
642
+ const reason = "任务随服务重启被终止";
643
+ const kind = task.agentId === "exec" ? "exec" : "subagent";
644
+ const content = `<task id="${task.id}" state="error" kind="${kind}">\n<summary>${task.title}</summary>\n<task_error>\n${reason}</task_error>\n</task>`;
645
+ const run = task.agentId === "exec" ? undefined : state.subagentRuns.find(item => item.id === task.id);
646
+ const output = run ? subagentProgress(run) : task.output;
647
+ backgroundTaskMessage(conversation, task, {
648
+ status: "interrupted", reason, output: output?.slice(-BACKGROUND_LOG_LIMIT), outputOffset: task.outputOffset,
649
+ outputTruncated: task.outputTruncated || (output?.length ?? 0) > BACKGROUND_LOG_LIMIT || run?.outputTruncated || run?.toolCalls?.some(call => call.outputTruncated),
650
+ }, content, false);
651
+ if (conversation.status === "awaiting_background")
652
+ conversation.status = "stopped";
654
653
  }
655
654
  return { orphaned, changed: orphaned.length > 0, unlinked };
656
655
  }
@@ -3030,6 +3029,34 @@ export class Store {
3030
3029
  }
3031
3030
  await this.persistCollections("backgroundTasks");
3032
3031
  }
3032
+ backgroundTask(id) {
3033
+ const task = this.state.backgroundTasks.find(item => item.id === id);
3034
+ return task && structuredClone(task);
3035
+ }
3036
+ async checkpointBackgroundOutput(id, output, offset) {
3037
+ const task = this.state.backgroundTasks.find(item => item.id === id && item.status === "running");
3038
+ if (!task || (task.outputOffset ?? 0) >= offset)
3039
+ return;
3040
+ task.output = output.slice(-BACKGROUND_LOG_LIMIT);
3041
+ task.outputOffset = offset;
3042
+ task.outputTruncated = offset > task.output.length;
3043
+ await this.persistCollections("backgroundTasks");
3044
+ }
3045
+ async finishBackgroundTask(taskId, outcome, content, deliver) {
3046
+ const task = this.state.backgroundTasks.find(item => item.id === taskId);
3047
+ if (!task)
3048
+ return;
3049
+ const conversation = this.state.conversations.find(item => item.id === task.conversationId);
3050
+ this.state.backgroundTasks = this.state.backgroundTasks.filter(item => item.id !== taskId);
3051
+ const message = conversation && backgroundTaskMessage(conversation, task, outcome, content, deliver);
3052
+ if (message?.delivery === "waiting" && conversation) {
3053
+ const waiting = this.waitingMessages(conversation);
3054
+ const lastSending = waiting.reduce((last, item, index) => item.delivery === "sending" ? index : last, -1);
3055
+ this.moveWaitingMessage(conversation, waiting, waiting.length - 1, lastSending + 1);
3056
+ }
3057
+ await this.persist();
3058
+ return message && structuredClone(message);
3059
+ }
3033
3060
  async removeBackgroundTask(id) {
3034
3061
  this.state.backgroundTasks = this.state.backgroundTasks.filter((item) => item.id !== id);
3035
3062
  await this.persistCollections("backgroundTasks");
@@ -3105,6 +3132,16 @@ export class Store {
3105
3132
  await this.persistTransaction({ kind: "subagent.replace", run: structuredClone(run) });
3106
3133
  return structuredClone(run);
3107
3134
  }
3135
+ updateSubagentProgress(runId, changes) {
3136
+ const run = this.state.subagentRuns.find(item => item.id === runId && item.status === "running");
3137
+ if (run)
3138
+ Object.assign(run, changes);
3139
+ }
3140
+ async checkpointSubagentProgress(runId) {
3141
+ const run = this.state.subagentRuns.find(item => item.id === runId && item.status === "running");
3142
+ if (run)
3143
+ await this.persistTransaction({ kind: "subagent.replace", run: structuredClone(run) });
3144
+ }
3108
3145
  /**
3109
3146
  * Adds ONE settled run's usage to the ledger of the conversation that dispatched it.
3110
3147
  *
@@ -37,8 +37,8 @@ export declare const PER_TASK_OUTPUT_CAP: number;
37
37
  * accumulated text makes the Nth event N characters long - the traffic is quadratic in the output length
38
38
  * (the flood behind "连接中 / 断连 / 连接中", see docs/SUBAGENT-WS-FLOOD-FIX-2026-10-29.md). So a live
39
39
  * event carries only the TAIL of what the child has said; the run's full output still reaches everyone -
40
- * the STORE record is written unabridged on every delta (a mid-run reload rebuilds from `state`, not from
41
- * events), and the settle event carries the final text in full. A watching human needs the last few
40
+ * the store keeps a larger tail for reconnects, and the settle event carries the saved result.
41
+ * A watching human needs the last few
42
42
  * hundred characters, not the first ones, so the tail is the useful end.
43
43
  *
44
44
  * THIS CHANGES WHAT AN OLD CLIENT SEES: a card whose child has said more than this shows the latest 8 KB
@@ -111,6 +111,7 @@ export type SubagentRunHooks = {
111
111
  * cancelled, never guessed at.
112
112
  */
113
113
  host?: (conversationId: string, runId: string) => ExtensionUiHost;
114
+ closeHost?: (conversationId: string, runId: string) => void;
114
115
  };
115
116
  export declare class SubagentRunRecorder {
116
117
  private readonly supervisor;
@@ -34,8 +34,8 @@ export const PER_TASK_OUTPUT_CAP = 50 * 1024;
34
34
  * accumulated text makes the Nth event N characters long - the traffic is quadratic in the output length
35
35
  * (the flood behind "连接中 / 断连 / 连接中", see docs/SUBAGENT-WS-FLOOD-FIX-2026-10-29.md). So a live
36
36
  * event carries only the TAIL of what the child has said; the run's full output still reaches everyone -
37
- * the STORE record is written unabridged on every delta (a mid-run reload rebuilds from `state`, not from
38
- * events), and the settle event carries the final text in full. A watching human needs the last few
37
+ * the store keeps a larger tail for reconnects, and the settle event carries the saved result.
38
+ * A watching human needs the last few
39
39
  * hundred characters, not the first ones, so the tail is the useful end.
40
40
  *
41
41
  * THIS CHANGES WHAT AN OLD CLIENT SEES: a card whose child has said more than this shows the latest 8 KB
@@ -193,37 +193,27 @@ export class SubagentRunRecorder {
193
193
  // Live events carry only the tail of the accumulated output (see LIVE_OUTPUT_TAIL_CAP) so a
194
194
  // per-delta snapshot stays small no matter how much the child has said.
195
195
  const liveTailCap = this.hooks.liveTailCap ?? LIVE_OUTPUT_TAIL_CAP;
196
+ let checkpoint;
196
197
  const publish = () => {
197
198
  record.output = streamed.length > liveTailCap ? streamed.slice(streamed.length - liveTailCap) : streamed;
198
199
  record.toolCalls = toolCalls;
199
200
  record.activity = activity;
200
- // WRITE BEFORE ANNOUNCE, and this is the whole defect. The order of the two statements below is
201
- // load-bearing; swapping them back reintroduces a card that loses text it already streamed.
202
- //
203
- // Announcing before the store write means any `state` snapshot taken after the announce - from
204
- // whatever command, this run's or an unrelated conversation's - still reads the PRE-delta record.
205
- // The browser REPLACES on `state` (`App.tsx`), so a card that had just been handed the right text
206
- // would have it taken back one frame later. This run's own delta phase no longer triggers a
207
- // `state` broadcast at all (the caller hooks that via `onSettled` at settle time only), but OTHER
208
- // commands broadcast `state` while this child streams, and every one of them reads this record.
209
- //
210
- // The write is still not awaited, and still must not be: `onTextDelta` is synchronous, and a drain loop
211
- // that flushed to disk per token would throttle the child. Reordering buys the correctness anyway,
212
- // because `Store.setSubagentRun` applies its patch BEFORE its first `await` - the same adjacency
213
- // `claimQueuedMessage` relies on to make claiming atomic. `Store.snapshot` clones in-memory state
214
- // rather than the file, so the frame is correct whether or not the flush behind it has landed yet.
215
- const persisted = this.hooks.store.setSubagentRun(id, { output: streamed, toolCalls, activity });
216
- this.hooks.broadcast({ type: "subagent.event", run: structuredClone(record) });
217
- // Written through on every delta, NOT left until the run settles. `state` is broadcast from other
218
- // commands while this run is in flight, and a browser that reloads mid-run reads the record from
219
- // there: a store that only saw the final answer would show an empty card and never fill it in until
220
- // the child finished. Never rejected into the void, because an unhandled rejection would take the
221
- // server down over a write that the next delta is about to make irrelevant.
222
- void persisted.catch((error) => {
223
- console.warn(`Super Pi: recording a delta of sub-agent run ${id} failed: ${error instanceof Error ? error.message : "unknown error"}`);
201
+ // Update the snapshot before streaming so reconnects read at least the progress already sent.
202
+ this.hooks.store.updateSubagentProgress(id, {
203
+ output: streamed.slice(-PER_TASK_OUTPUT_CAP), toolCalls, activity,
204
+ outputTruncated: streamed.length > PER_TASK_OUTPUT_CAP || undefined,
224
205
  });
206
+ this.hooks.broadcast({ type: "subagent.event", run: structuredClone(record) });
207
+ if (!checkpoint)
208
+ checkpoint = setTimeout(() => {
209
+ checkpoint = undefined;
210
+ void this.hooks.store.checkpointSubagentProgress(id).catch(error => {
211
+ console.warn(`Super Pi: could not checkpoint sub-agent run ${id}:`, error);
212
+ });
213
+ }, 500).unref();
225
214
  };
226
215
  const settle = async (changes) => {
216
+ clearTimeout(checkpoint);
227
217
  Object.assign(record, changes);
228
218
  // PERSIST FIRST, ANNOUNCE SECOND. The order is load-bearing and was previously reversed.
229
219
  //
@@ -280,6 +270,32 @@ export class SubagentRunRecorder {
280
270
  activity = { kind: "tool", label: call.name, at: new Date().toISOString() };
281
271
  publish();
282
272
  },
273
+ onToolUpdate: (id, output, final) => {
274
+ const row = toolRowById.get(id);
275
+ if (row === undefined)
276
+ return;
277
+ const current = toolCalls[row];
278
+ if (final && current.output) {
279
+ if (current.output.includes(output))
280
+ return;
281
+ if (!output.includes(current.output))
282
+ output = current.output + "\n\n" + output;
283
+ }
284
+ const tail = output.slice(-8_000);
285
+ const truncated = current.outputTruncated || output.length > tail.length || undefined;
286
+ if (tail === current.output && truncated === current.outputTruncated)
287
+ return;
288
+ toolCalls = toolCalls.map((item, index) => {
289
+ if (index === row)
290
+ return { ...item, output: tail, outputTruncated: truncated };
291
+ return item;
292
+ });
293
+ const loggedRows = toolCalls.flatMap((item, index) => item.output ? [index] : []);
294
+ for (const index of loggedRows.slice(0, -4)) {
295
+ toolCalls[index] = { ...toolCalls[index], output: undefined, outputTruncated: true };
296
+ }
297
+ publish();
298
+ },
283
299
  // The end of a call, matched back to its row by Pi's own id. A `tool_execution_end` with no
284
300
  // matching start is DROPPED rather than appended: it would otherwise become a row for a call the
285
301
  // card never announced, which reads as a tool the child used that it did not.
@@ -344,14 +360,9 @@ export class SubagentRunRecorder {
344
360
  const stopped = error instanceof SubagentCancelled;
345
361
  return await settle({
346
362
  status: stopped ? "stopped" : "failed",
347
- // Cleared rather than left as the partial stream: `output` is defined as the last assistant
348
- // message, and a run that produced none has none. What the child managed to say is not lost - it
349
- // was already broadcast - and `error` says why the run ended without one.
350
363
  output: undefined,
351
- outputTruncated: undefined,
352
- // KEPT, unlike `output`: which tools the child reached for before it stopped is a true fact about
353
- // the run and is usually the whole diagnosis. They are labels and derived targets, never
354
- // arguments or results, so §5's rule about the child's turn not entering `state.json` still holds.
364
+ partialOutput: streamed.slice(-PER_TASK_OUTPUT_CAP) || undefined,
365
+ outputTruncated: streamed.length > PER_TASK_OUTPUT_CAP || undefined,
355
366
  toolCalls,
356
367
  // WHERE, not only WHAT. `error` says what went wrong; this says which phase the child was in when
357
368
  // it did, so a card can answer 「卡在哪」 - and a run stopped by a person is not given one, because
@@ -364,6 +375,7 @@ export class SubagentRunRecorder {
364
375
  });
365
376
  }
366
377
  finally {
378
+ this.hooks.closeHost?.(conversationId, id);
367
379
  input.signal?.removeEventListener("abort", onCallerAbort);
368
380
  this.controllers.delete(id);
369
381
  }
@@ -101,6 +101,7 @@ export type SubagentRunInput = {
101
101
  onTextDelta?: (delta: string) => void;
102
102
  /** Called on `tool_execution_start`, with the name and the derived target label. */
103
103
  onToolCall?: (call: SubagentToolCall) => void;
104
+ onToolUpdate?: (id: string, output: string, final: boolean) => void;
104
105
  /**
105
106
  * Called on `tool_execution_end` for the same `id`, carrying how the call ended.
106
107
  *