@evandu/super-pi 0.1.239 → 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.
Files changed (33) hide show
  1. package/dist/client/.super-pi-client-sources.json +8 -8
  2. package/dist/client/assets/{CodeMirrorEditor-CtzPSOsS.js → CodeMirrorEditor-CiOKD-_q.js} +1 -1
  3. package/dist/client/assets/{GitDiffEditor-iNVZVVMb.js → GitDiffEditor-D5VMi7K-.js} +1 -1
  4. package/dist/client/assets/index-CwH7sttH.css +1 -0
  5. package/dist/client/assets/index-oUDSLOqG.js +347 -0
  6. package/dist/client/index.html +2 -2
  7. package/dist/server/application/extension-ui-service.d.ts +3 -1
  8. package/dist/server/application/extension-ui-service.js +20 -7
  9. package/dist/server/application/run-service.d.ts +19 -61
  10. package/dist/server/application/run-service.js +221 -372
  11. package/dist/server/application/workspace-service.js +1 -1
  12. package/dist/server/content-search.d.ts +13 -39
  13. package/dist/server/content-search.js +202 -219
  14. package/dist/server/exec-service.d.ts +14 -7
  15. package/dist/server/exec-service.js +66 -40
  16. package/dist/server/http-server.js +69 -31
  17. package/dist/server/index.js +6 -6
  18. package/dist/server/store.d.ts +11 -24
  19. package/dist/server/store.js +88 -62
  20. package/dist/server/subagent-runs.d.ts +3 -2
  21. package/dist/server/subagent-runs.js +45 -33
  22. package/dist/server/subagents.d.ts +1 -0
  23. package/dist/server/subagents.js +30 -12
  24. package/dist/server/types.d.ts +13 -11
  25. package/dist/server/ws-server.d.ts +3 -0
  26. package/dist/server/ws-server.js +40 -6
  27. package/dist/shared/background-task.d.ts +22 -0
  28. package/dist/shared/background-task.js +5 -0
  29. package/dist/shared/content-search.d.ts +22 -0
  30. package/dist/shared/content-search.js +1 -0
  31. package/package.json +1 -1
  32. package/dist/client/assets/index-C5kxyPTT.js +0 -340
  33. package/dist/client/assets/index-DN0oBG6l.css +0 -1
@@ -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
  }
@@ -2054,6 +2053,11 @@ export class Store {
2054
2053
  ...(options?.delivery ? { delivery: options.delivery } : {}),
2055
2054
  };
2056
2055
  conversation.messages.push(message);
2056
+ if (options?.prioritizeWaiting && message.delivery === "waiting") {
2057
+ const waiting = this.waitingMessages(conversation);
2058
+ const lastSending = waiting.reduce((last, item, index) => item.delivery === "sending" ? index : last, -1);
2059
+ this.moveWaitingMessage(conversation, waiting, waiting.length - 1, lastSending + 1);
2060
+ }
2057
2061
  conversation.updatedAt = message.createdAt;
2058
2062
  await this.persist();
2059
2063
  return structuredClone(message);
@@ -2815,6 +2819,13 @@ export class Store {
2815
2819
  }
2816
2820
  if (target === from)
2817
2821
  return structuredClone(message);
2822
+ this.moveWaitingMessage(conversation, waiting, from, target);
2823
+ await this.persistMessages(conversation);
2824
+ return structuredClone(message);
2825
+ }
2826
+ moveWaitingMessage(conversation, waiting, from, target) {
2827
+ if (from === target)
2828
+ return;
2818
2829
  // Permute THE WAITING SLOTS rather than splicing a message to an index. The waiting messages are
2819
2830
  // usually a suffix of the array, but they are not guaranteed to be one - an assistant message sits
2820
2831
  // between two of them once a steer has been delivered mid-turn - and an offset derived from "where in
@@ -2822,36 +2833,13 @@ export class Store {
2822
2833
  // place is total: it cannot land a message outside the group, and it moves nothing that is not waiting.
2823
2834
  const slots = waiting.map((item) => conversation.messages.indexOf(item));
2824
2835
  const reordered = [...waiting];
2825
- reordered.splice(from, 1);
2836
+ const [message] = reordered.splice(from, 1);
2826
2837
  reordered.splice(target, 0, message);
2827
2838
  slots.forEach((slot, order) => { conversation.messages[slot] = reordered[order]; });
2828
- await this.persistMessages(conversation);
2829
- return structuredClone(message);
2830
2839
  }
2831
2840
  /**
2832
- * Pi has just delivered one steered message: unmark it and open the answer to it, in ONE write.
2833
- *
2834
- * Oldest rather than matched on text, and that is forced on us by Pi rather than chosen: Pi identifies
2835
- * its own queued entry by `indexOf` on the message text (`agent-session.ts:1123`), so two identical
2836
- * steered messages are ONE entry to it and no host-side matching could do better. Position is sufficient
2837
- * anyway because Pi's steering queue is FIFO and Super Pi only ever steers from the front of the waiting
2838
- * group.
2839
- *
2840
- * ONE WRITE, because the reader must never see the intermediate: a message that has stopped waiting but
2841
- * has no answer under it yet is the exact broken state this refactor exists to remove, and a browser
2842
- * that broadcast between the two halves would put it right back on screen.
2843
- *
2844
- * WHAT IS DIFFERENT FROM BEFORE, and is the whole point: the message used to be DELETED here. It is now
2845
- * merely unmarked, with an assistant message spliced in after it. It was on screen the whole time - it
2846
- * was written into the transcript when the user pressed send, long before Pi ever saw it - and it stays
2847
- * exactly where it was, now with the agent answering it. Deleting it is what made a steered reply appear
2848
- * with no question above it.
2849
- *
2850
- * `messageId` says WHICH message Pi picked up, for the case where position cannot answer it. A message
2851
- * handed to Pi's follow-up queue was never CLAIMED here - it is still `waiting`, because Super Pi keeps
2852
- * it in its own list so the user can still withdraw it - and a conversation can hold a `waiting` message
2853
- * and a `sending` one at the same time. The caller resolves the delivery by the text Pi announced,
2854
- * which is the same text Pi itself matched on.
2841
+ * Open the reply to a Pi steer and clear its delivery state in one write.
2842
+ * The text match and the FIFO fallback both require a claimed `sending` row.
2855
2843
  */
2856
2844
  async deliverWaitingMessage(conversationId, agentIdentity, messageId) {
2857
2845
  const conversation = this.requireConversation(conversationId);
@@ -2865,7 +2853,7 @@ export class Store {
2865
2853
  if (index < 0)
2866
2854
  return undefined;
2867
2855
  const user = conversation.messages[index];
2868
- if (user.role !== "user" && user.role !== "tool")
2856
+ if ((user.role !== "user" && user.role !== "tool") || user.delivery !== "sending")
2869
2857
  return undefined;
2870
2858
  delete user.delivery;
2871
2859
  const assistant = { id: id("message"), role: "assistant", content: "", createdAt: now(), ...(agentIdentity ? { agentIdentity: structuredClone(agentIdentity) } : {}) };
@@ -3041,6 +3029,34 @@ export class Store {
3041
3029
  }
3042
3030
  await this.persistCollections("backgroundTasks");
3043
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
+ }
3044
3060
  async removeBackgroundTask(id) {
3045
3061
  this.state.backgroundTasks = this.state.backgroundTasks.filter((item) => item.id !== id);
3046
3062
  await this.persistCollections("backgroundTasks");
@@ -3116,6 +3132,16 @@ export class Store {
3116
3132
  await this.persistTransaction({ kind: "subagent.replace", run: structuredClone(run) });
3117
3133
  return structuredClone(run);
3118
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
+ }
3119
3145
  /**
3120
3146
  * Adds ONE settled run's usage to the ledger of the conversation that dispatched it.
3121
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
  *
@@ -7,7 +7,7 @@ import { resolvePiCommand, shellQuote } from "./pi-command.js";
7
7
  import { buildExtensionUiResponse, describeExtensionUiRequest, killTree, } from "./runtime.js";
8
8
  import { RpcChannel } from "./rpc-channel.js";
9
9
  import { InlineThinkingSplitter, stripInlineThinking } from "./inline-thinking.js";
10
- import { describeToolCall, TOOL_DETAIL_CAP } from "./tool-calls.js";
10
+ import { describeToolCall, extractPartialResultText, TOOL_DETAIL_CAP } from "./tool-calls.js";
11
11
  /**
12
12
  * The tool-call derivation now lives in `tool-calls.js`, because the primary agent's runtime needs the
13
13
  * identical mapping and `subagents.ts` already imports `runtime.ts` - so the shared definition has to sit
@@ -224,7 +224,7 @@ export class SubagentSupervisor {
224
224
  * this costs nothing and removes the whole class of bug.
225
225
  */
226
226
  async run(input) {
227
- const { conversationId, agentId, task, cwd, model, host, signal, onTextDelta, onToolCall, onToolEnd, onThinking, onStage } = input;
227
+ const { conversationId, agentId, task, cwd, model, host, signal, onTextDelta, onToolCall, onToolUpdate, onToolEnd, onThinking, onStage } = input;
228
228
  // Refused here, with the reason, rather than handed to the spawn: an ENOENT from `spawn` reads as
229
229
  // "the app is broken" and hides the one fact that matters, which is where it looked for Pi.
230
230
  if (!this.pi.found)
@@ -304,6 +304,14 @@ export class SubagentSupervisor {
304
304
  const usage = { ...NO_USAGE };
305
305
  /** Set rather than thrown so a child's own failure is reported AFTER its output has been drained. */
306
306
  let failed;
307
+ const noteOutcome = (message, reason) => {
308
+ const status = message?.stopReason ?? reason;
309
+ if (!status)
310
+ return;
311
+ failed = status === "error" || status === "aborted"
312
+ ? `sub-agent ${agentId} (${id}) stopped with reason ${status}: ${message?.errorMessage?.trim() || stripInlineThinking(assistantText(message)) || "no detail from Pi"}`
313
+ : undefined;
314
+ };
307
315
  /**
308
316
  * Which phase the child is in, for a caller that has to say where a run died.
309
317
  *
@@ -471,12 +479,10 @@ export class SubagentSupervisor {
471
479
  finalText = current;
472
480
  addUsage(usage, record.usage);
473
481
  enter("turn");
474
- const reason = event.message?.stopReason ?? event.reason;
475
- if (reason === "error" || reason === "aborted")
476
- failed ??= `sub-agent ${agentId} (${id}) stopped with reason ${reason}: ${stripInlineThinking(assistantText(event.message)) || "no output"}`;
482
+ noteOutcome(event.message, event.reason);
477
483
  }
478
484
  else if (event?.type === "error") {
479
- failed ??= `sub-agent ${agentId} (${id}) reported ${event.reason ?? "an error"}: ${stripInlineThinking(assistantText(event.message)) || "no detail from Pi"}`;
485
+ noteOutcome(event.message, "error");
480
486
  }
481
487
  else if (event?.type === "thinking_delta") {
482
488
  // CONSUMED, not discarded. A reasoning model spends the first seconds of every turn here,
@@ -504,17 +510,21 @@ export class SubagentSupervisor {
504
510
  onToolCall?.({ id: record.toolCallId ?? "", name: record.toolName ?? "unknown", detail: describeToolCall(record.toolName ?? "unknown", record.args) });
505
511
  continue;
506
512
  }
507
- if (record.type === "tool_execution_end") {
513
+ if (record.type === "tool_execution_update" || record.type === "tool_execution_end") {
514
+ const final = record.type === "tool_execution_end";
515
+ if (onToolUpdate && record.toolCallId && /^(bash|powershell|shell|command)$/i.test(record.toolName ?? "")) {
516
+ const output = extractPartialResultText(final ? record.result : record.partialResult);
517
+ if (output)
518
+ onToolUpdate(record.toolCallId, output, final);
519
+ }
520
+ if (!final)
521
+ continue;
508
522
  // THE OTHER HALF OF THE SAME CALL, and the half that makes a row mean something. Until Pi
509
523
  // started sending this, a `read` row could only ever say that a `read` happened: not whether
510
524
  // it found the file, not how long a slow call had been running, and - for a card whose child
511
525
  // is still working - not whether the row was even finished yet.
512
526
  //
513
- // ONLY `isError` AND `durationMs` CROSS OVER. `result` is deliberately not read: for a `read`
514
- // it is the file's contents, and a card row is persisted in a file that is serialized on
515
- // every single broadcast. `durationMs` is Pi's own number off a monotonic clock, so it is
516
- // the one outcome fact available for EVERY tool rather than only for result shapes this code
517
- // would have to guess at.
527
+ // Every tool reports timing and success. Only shell tools expose captured output.
518
528
  enter("turn");
519
529
  onToolEnd?.({
520
530
  id: record.toolCallId ?? "",
@@ -528,6 +538,14 @@ export class SubagentSupervisor {
528
538
  await handleExtensionUi(record);
529
539
  continue;
530
540
  }
541
+ if (record.type === "agent_end") {
542
+ if (!record.willRetry) {
543
+ const message = record.messages && [...record.messages].reverse().find(item => item.role === "assistant");
544
+ if (message)
545
+ noteOutcome(message);
546
+ }
547
+ continue;
548
+ }
531
549
  // Pi caught this inside its own extension host, so it never becomes a thrown failure there. Every
532
550
  // run is a fresh process, so any extension_error seen while draining belongs to the task in
533
551
  // flight - and a sub-agent whose extension failed has not really done the job.
@@ -5,6 +5,7 @@ export type ModelFilterRule = {
5
5
  label?: string;
6
6
  };
7
7
  import type { WorkflowRun } from "./workflow.js";
8
+ import type { BackgroundTaskDetails } from "../shared/background-task.js";
8
9
  import type { ScheduledTask } from "./scheduled-tasks.js";
9
10
  import type { ThinkingLevelMap } from "../shared/thinking-levels.js";
10
11
  import type { TerminalCommand, TerminalEvent } from "../shared/terminal-protocol.js";
@@ -111,6 +112,7 @@ export type ToolCallQuestion = {
111
112
  answers?: QuestionAnswer[];
112
113
  };
113
114
  export type Message = {
115
+ backgroundTask?: BackgroundTaskSummary;
114
116
  id: string;
115
117
  role: MessageRole;
116
118
  source?: "session-reminder";
@@ -272,12 +274,7 @@ export type ToolCallBlock = {
272
274
  * null means outside reasoning; absence is an older record with offsets only. */
273
275
  thinkingBlock?: number | null;
274
276
  /** A background command keeps its dispatch position and settled output after the active task is removed. */
275
- backgroundTask?: {
276
- id: string;
277
- status: "running" | "completed" | "failed";
278
- output?: string;
279
- exitCode?: number;
280
- };
277
+ backgroundTask?: BackgroundTaskDetails;
281
278
  question?: ToolCallQuestion;
282
279
  };
283
280
  /**
@@ -793,6 +790,8 @@ export type ConversationContextUsage = {
793
790
  */
794
791
  export type SubagentToolCall = {
795
792
  label: string;
793
+ output?: string;
794
+ outputTruncated?: boolean;
796
795
  status?: "ok" | "error";
797
796
  detail?: string;
798
797
  durationMs?: number;
@@ -898,6 +897,7 @@ export type SubagentRun = {
898
897
  finishedAt?: string;
899
898
  /** The last assistant message. Absent while running is only for a run that has produced none yet. */
900
899
  output?: string;
900
+ partialOutput?: string;
901
901
  /**
902
902
  * Every tool the child started, oldest first, appended as the run streams. Same rule as `output`:
903
903
  * short labels go here and to the card, the child's full turn stays in Pi's session directory.
@@ -955,14 +955,13 @@ export type SubagentRun = {
955
955
  * `sessionId` is the one identity field allowed to move, and only because a run's id and Pi's session id
956
956
  * happen to coincide today rather than by definition.
957
957
  */
958
- export type SubagentRunUpdate = Partial<Pick<SubagentRun, "status" | "output" | "outputTruncated" | "toolCalls" | "usage" | "error" | "finishedAt" | "sessionId" | "durationMs" | "activity" | "failure">>;
959
- export type BackgroundTaskSummary = {
960
- id: string;
958
+ export type SubagentRunUpdate = Partial<Pick<SubagentRun, "status" | "output" | "partialOutput" | "outputTruncated" | "toolCalls" | "usage" | "error" | "finishedAt" | "sessionId" | "durationMs" | "activity" | "failure">>;
959
+ export type BackgroundTaskSummary = BackgroundTaskDetails & {
961
960
  conversationId: string;
962
961
  title: string;
963
962
  agentId: string;
964
- status: "running" | "completed" | "failed";
965
963
  startedAt: string;
964
+ finishedAt?: string;
966
965
  resultBlockId: string;
967
966
  /** The same call-position anchor a `SubagentRun` carries, and for the same reason: a background command
968
967
  * asked for inside a turn belongs at that call, not wherever its output happened to land. Absent when
@@ -2270,6 +2269,8 @@ export type ServerEvent = {
2270
2269
  conversationId?: string;
2271
2270
  data: string;
2272
2271
  replace?: boolean;
2272
+ offset?: number;
2273
+ truncated?: boolean;
2273
2274
  }
2274
2275
  /**
2275
2276
  * A background exec session ended. `stdout` and `stderr` are the collected output; the exec service
@@ -2278,7 +2279,8 @@ export type ServerEvent = {
2278
2279
  | {
2279
2280
  type: "exec.exit";
2280
2281
  sessionId: string;
2281
- exitCode: number;
2282
+ conversationId?: string;
2283
+ exitCode?: number;
2282
2284
  stdout: string;
2283
2285
  stderr: string;
2284
2286
  }
@@ -50,6 +50,7 @@ export declare class WsBroadcaster implements EventBroadcaster {
50
50
  private readonly fileIndexScopes;
51
51
  private readonly coalescedSockets;
52
52
  private readonly pendingStreams;
53
+ private readonly pendingRuntimeReplays;
53
54
  /**
54
55
  * DIAGNOSTIC ONLY - sends every requested state frame immediately instead of merging them.
55
56
  *
@@ -74,6 +75,8 @@ export declare class WsBroadcaster implements EventBroadcaster {
74
75
  unregister(socket: WebSocket): void;
75
76
  subscribe(socket: WebSocket, conversationId?: string): void;
76
77
  sendState(socket: WebSocket): void;
78
+ private scheduleRuntimeReplay;
79
+ private clearRuntimeReplay;
77
80
  subscribeFileIndex(socket: WebSocket, workspaceId?: string, cwd?: string): void;
78
81
  private receives;
79
82
  configureStreaming(socket: WebSocket, coalesce: boolean): void;