@luxass/pi-subagents 0.1.0 → 0.2.0

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.
package/README.md CHANGED
@@ -14,7 +14,7 @@ To try it from this repository, run `pi -e ./packages/pi-subagents`.
14
14
 
15
15
  Ask Pi to delegate a task, or start a prompt with an agent type, such as `@explorer review authentication`. The main model starts the agent and gives it a unique task name, such as `auth-review`. Agents run in the background by default. Their results appear in the chat when they finish.
16
16
 
17
- In Rex, the extension reports how many subagents are running, even after Pi's main turn ends. It clears the report when the last subagent stops. Queued subagents do not count as running.
17
+ The extension reports each running subagent to Rex by task name, even after Pi's main turn ends. Each status clears when that subagent finishes or stops. Queued subagents do not appear. Rex controls which statuses appear on hover and when the tab spinner runs.
18
18
 
19
19
  Two agent types are built in. `general-purpose` has Pi's default tools: `read`, `bash`, `edit`, and `write`. `explorer` is told not to change files and has `read`, `grep`, `find`, `ls`, and `bash`. Its instructions are not a sandbox, because `bash` can still change files.
20
20
 
@@ -87,7 +87,9 @@ Set these under `subagents` in Pi's `settings.json`. Project settings apply only
87
87
  | `widget` | `"background"` | Agents counted in the line above the editor: `"background"`, `"all"`, or `"off"`. |
88
88
  | `delivery.mode` | `"grouped"` | `"grouped"` reports agents of one request together, after at most 60 seconds. `"immediate"` reports each result when it is ready. |
89
89
 
90
- Agent conversations are saved under `~/.pi/agent/subagents/<session id>/`. After `/reload` or a resumed session, finished agents can still be read and continued. Agents that were running or queued show as interrupted and can also be continued. An agent that never started begins with the new prompt only. A result that finished but was not yet delivered arrives after the reload.
90
+ Agent conversations are saved under `~/.pi/agent/subagents/<session id>/`. After `/reload` or a resumed session, finished agents can still be read and continued. Agents that were running or queued show as interrupted and can also be continued. An agent that never started begins with the new prompt only. A result that finished but was not yet delivered can arrive after the reload.
91
+
92
+ If you switch branches with `/tree`, a background result arrives only on a branch that started the run and has not received it. Returning to a branch that already has the result does not repeat it. Running agents stay active and `/agents` still shows agents from the whole session.
91
93
 
92
94
  ## Costs
93
95
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luxass/pi-subagents",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Delegate tasks to named Pi agents and follow their conversations.",
5
5
  "keywords": [
6
6
  "pi",
@@ -23,16 +23,17 @@
23
23
  "publishConfig": {
24
24
  "access": "public"
25
25
  },
26
+ "dependencies": {
27
+ "@earendil-works/pi-schema": "1.6.0"
28
+ },
26
29
  "devDependencies": {
27
30
  "@earendil-works/pi-ai": "1.6.0",
28
31
  "@earendil-works/pi-coding-agent": "1.6.0",
29
- "@earendil-works/pi-schema": "1.6.0",
30
32
  "@earendil-works/pi-tui": "1.6.0"
31
33
  },
32
34
  "peerDependencies": {
33
35
  "@earendil-works/pi-ai": "*",
34
36
  "@earendil-works/pi-coding-agent": "*",
35
- "@earendil-works/pi-schema": "*",
36
37
  "@earendil-works/pi-tui": "*",
37
38
  "typebox": "*"
38
39
  },
package/src/index.ts CHANGED
@@ -72,7 +72,7 @@ export default function piSubagents(pi: ExtensionAPI): void {
72
72
  stopRexStatus = reportSubagentsToRex(current);
73
73
  }
74
74
  // Last, so the tools exist when a restored result starts a main-model turn.
75
- delivery.deliverRestored();
75
+ delivery.branchChanged();
76
76
  });
77
77
 
78
78
  // A leading type mention asks the main model to start that type. The instruction stays hidden.
@@ -94,6 +94,7 @@ export default function piSubagents(pi: ExtensionAPI): void {
94
94
  pi.on("turn_end", (event) => delivery?.turnEnded(event));
95
95
 
96
96
  pi.on("agent_settled", () => delivery?.agentSettled());
97
+ pi.on("session_tree", () => delivery?.branchChanged());
97
98
 
98
99
  pi.on("session_shutdown", async (_event, ctx) => {
99
100
  // Delivery stops first, so aborted runs never deliver.
package/src/manager.ts CHANGED
@@ -57,7 +57,10 @@ export interface SubagentTokens {
57
57
  /** Custom entry type that stores agent records in the main session. */
58
58
  export const SUBAGENT_RECORD_ENTRY = "subagents-record";
59
59
 
60
- /** Whether the main model may still receive this run's result automatically. */
60
+ /** Custom entry type that marks a result as read on one conversation branch. */
61
+ export const SUBAGENT_READ_ENTRY = "subagents-read";
62
+
63
+ /** Saved delivery state. For background runs, receipts only apply on the branch that recorded them. */
61
64
  export type SubagentReceipt = "pending" | "unread" | "consumed" | "delivered" | "suppressed";
62
65
 
63
66
  /** One named agent and its latest run. Saved in the main session with `pi.appendEntry`. */
@@ -165,8 +168,8 @@ export class SubagentManager {
165
168
  private readonly live = new Map<string, LiveRun>();
166
169
  private readonly queue: string[] = [];
167
170
  private readonly listeners = new Set<() => void>();
168
- /** How each earlier run of a continued agent ended, by `<id>:<run>`, for its `Agent` card. */
169
- private readonly earlierRuns = new Map<string, SubagentRecord>();
171
+ /** Finished runs by `<id>:<run>`, for `Agent` cards and branch-aware delivery. */
172
+ private readonly finishedRuns = new Map<string, SubagentRecord>();
170
173
  /** Cost of the runs whose usage entry is saved in this session. */
171
174
  private savedCost = 0;
172
175
  /** Number of saved usage entries in this session. */
@@ -212,7 +215,18 @@ export class SubagentManager {
212
215
  runOutcome(id: string, run: number | undefined): SubagentRecord | undefined {
213
216
  const record = this.records.get(id);
214
217
  if (run === undefined || record?.run === run) return record;
215
- return this.earlierRuns.get(`${id}:${run}`) ?? record;
218
+ return this.finishedRuns.get(`${id}:${run}`);
219
+ }
220
+
221
+ /** Background results that can be delivered on a branch that has not seen them. */
222
+ finishedBackgroundRuns(): SubagentRecord[] {
223
+ return [...this.finishedRuns.values()].filter(
224
+ (record) =>
225
+ record.background &&
226
+ record.receipt !== "suppressed" &&
227
+ record.stoppedBy !== "model" &&
228
+ record.status !== "interrupted",
229
+ );
216
230
  }
217
231
 
218
232
  /** Subscribes UI to record changes. Returns the unsubscribe function. */
@@ -222,8 +236,8 @@ export class SubagentManager {
222
236
  }
223
237
 
224
238
  /**
225
- * Restores this session's saved agents. Unfinished runs become interrupted and never deliver.
226
- * A finished result that was still waiting stays unread, so it is delivered now.
239
+ * Restores all runs, including ones no longer on the active branch.
240
+ * Unfinished runs become interrupted and never deliver.
227
241
  */
228
242
  restore(): void {
229
243
  for (const entry of this.ctx.sessionManager.getEntries()) {
@@ -237,7 +251,7 @@ export class SubagentManager {
237
251
  this.records.set(record.id, { ...record });
238
252
  // Entries are in time order, so the last finished entry of a run is how that run ended.
239
253
  if (isSubagentFinished(record.status)) {
240
- this.earlierRuns.set(`${record.id}:${record.run}`, { ...record });
254
+ this.finishedRuns.set(`${record.id}:${record.run}`, { ...record });
241
255
  }
242
256
  }
243
257
  for (const record of this.records.values()) {
@@ -341,8 +355,8 @@ export class SubagentManager {
341
355
  pi: this.pi,
342
356
  settings: this.settings,
343
357
  });
344
- // The card of the run that just ended keeps showing that run, not the new one.
345
- this.earlierRuns.set(`${record.id}:${record.run}`, { ...record });
358
+ // Keep an interrupted run's outcome for its card even when it never finished.
359
+ this.finishedRuns.set(`${record.id}:${record.run}`, { ...record });
346
360
  Object.assign(record, {
347
361
  status: "queued",
348
362
  requestId: this.requestId,
@@ -502,6 +516,7 @@ export class SubagentManager {
502
516
  else if (record.receipt === "pending") record.receipt = "unread";
503
517
  live.release?.("finished");
504
518
  this.saveRunUsage(record, live);
519
+ this.finishedRuns.set(`${record.id}:${record.run}`, { ...record });
505
520
  this.persist(record);
506
521
  if (!foreground) this.onRunSettled(record);
507
522
  this.pump();
@@ -653,10 +668,9 @@ export class SubagentManager {
653
668
  return cost;
654
669
  }
655
670
 
656
- /** Marks a result as returned to the model, so it is never delivered again. */
657
- markReceipt(record: SubagentRecord, receipt: SubagentReceipt): void {
658
- record.receipt = receipt;
659
- this.persist(record);
671
+ /** Records that the active branch explicitly read this result. */
672
+ consumeResult(record: SubagentRecord): void {
673
+ this.pi.appendEntry(SUBAGENT_READ_ENTRY, { id: record.id, run: record.run });
660
674
  }
661
675
 
662
676
  /** Transcript for `/agents`: the live session, or the saved session file. */
package/src/results.ts CHANGED
@@ -6,7 +6,13 @@ import type {
6
6
  TurnEndEvent,
7
7
  } from "@earendil-works/pi-coding-agent";
8
8
 
9
- import { isSubagentFinished, type SubagentManager, type SubagentRecord } from "./manager.ts";
9
+ import {
10
+ isSubagentFinished,
11
+ SUBAGENT_READ_ENTRY,
12
+ SUBAGENT_RECORD_ENTRY,
13
+ type SubagentManager,
14
+ type SubagentRecord,
15
+ } from "./manager.ts";
10
16
 
11
17
  /** Custom message type of automatically delivered results. */
12
18
  export const SUBAGENT_RESULT_MESSAGE = "subagents-result";
@@ -25,36 +31,87 @@ export interface SubagentResultDetails {
25
31
  records: SubagentRecord[];
26
32
  }
27
33
 
34
+ function subagentRunKey({ id, run }: Pick<SubagentRecord, "id" | "run">): string {
35
+ return `${id}:${run}`;
36
+ }
37
+
38
+ function savedSubagentRunKey(data: unknown): string | undefined {
39
+ if (
40
+ typeof data !== "object" ||
41
+ data === null ||
42
+ !("id" in data) ||
43
+ typeof data.id !== "string" ||
44
+ !("run" in data) ||
45
+ typeof data.run !== "number"
46
+ )
47
+ return undefined;
48
+ return subagentRunKey({ id: data.id, run: data.run });
49
+ }
50
+
51
+ function readSubagentBranch(ctx: ExtensionContext, sessionId: string) {
52
+ const started = new Set<string>();
53
+ const received = new Set<string>();
54
+ for (const entry of ctx.sessionManager.getBranch()) {
55
+ if (entry.type === "custom" && entry.customType === SUBAGENT_RECORD_ENTRY) {
56
+ const record = entry.data as Partial<SubagentRecord> | undefined;
57
+ if (record?.sessionId !== sessionId) continue;
58
+ const key = savedSubagentRunKey(record);
59
+ if (!key) continue;
60
+ // Only the launch snapshot is queued. A running or finished snapshot can be saved
61
+ // on a different branch if the user navigated while the subagent was working.
62
+ if (record.status === "queued") started.add(key);
63
+ // Older versions recorded explicit reads as full snapshots.
64
+ if (record.receipt === "consumed") received.add(key);
65
+ } else if (entry.type === "custom" && entry.customType === SUBAGENT_READ_ENTRY) {
66
+ const key = savedSubagentRunKey(entry.data);
67
+ if (key) received.add(key);
68
+ } else if (entry.type === "custom_message" && entry.customType === SUBAGENT_RESULT_MESSAGE) {
69
+ const details = entry.details as Partial<SubagentResultDetails> | undefined;
70
+ if (!Array.isArray(details?.records)) continue;
71
+ for (const record of details.records) {
72
+ const key = savedSubagentRunKey(record);
73
+ if (key) received.add(key);
74
+ }
75
+ }
76
+ }
77
+ return { started, received };
78
+ }
79
+
28
80
  /** Cuts automatically delivered text at the limit and points to the full result. */
29
- function cutSubagentResult(text: string, name: string): string {
81
+ function cutSubagentResult(text: string, record: SubagentRecord): string {
30
82
  if (text.length <= SUBAGENT_RESULT_LIMIT) return text;
31
83
  return (
32
84
  text.slice(0, SUBAGENT_RESULT_LIMIT) +
33
- `\n\n[Result cut at ${SUBAGENT_RESULT_LIMIT} characters. Call get_subagent_result with name "${name}" for the full text.]`
85
+ `\n\n[Result cut at ${SUBAGENT_RESULT_LIMIT} characters. Call get_subagent_result with name "${record.name}" and run ${record.run} for the full text.]`
34
86
  );
35
87
  }
36
88
 
37
89
  function resultText(record: SubagentRecord): string {
38
90
  const partial = record.partial ? " (partial: turn limit reached)" : "";
39
- const header = `Agent ${record.name} (${record.agentType}) ${record.status}${partial}.`;
91
+ const header = `Agent ${record.name} (${record.agentType}, run ${record.run}) ${record.status}${partial}.`;
40
92
  if (record.stoppedBy === "user") {
41
- const result = cutSubagentResult(record.result, record.name);
93
+ const result = cutSubagentResult(record.result, record);
42
94
  return `${header} The user stopped it.${result ? `\n\n${result}` : ""}`;
43
95
  }
44
96
  let body = record.result || record.error || "(no answer)";
45
97
  if (record.error && record.result) body += `\nError: ${record.error}`;
46
- return `${header}\n\n${cutSubagentResult(body, record.name)}`;
98
+ return `${header}\n\n${cutSubagentResult(body, record)}`;
47
99
  }
48
100
 
49
- /** Decides when and how finished background results reach the main model. */
101
+ function resultMessage(batch: SubagentRecord[]): CustomMessageEntryDraft {
102
+ return {
103
+ type: "custom_message",
104
+ customType: SUBAGENT_RESULT_MESSAGE,
105
+ content: batch.map(resultText).join("\n\n---\n\n"),
106
+ display: true,
107
+ details: { records: batch } satisfies SubagentResultDetails,
108
+ };
109
+ }
110
+
111
+ /** Delivers finished background runs only to branches that started them and still need the result. */
50
112
  export class SubagentDelivery {
51
113
  private busy = false;
52
114
  private disposed = false;
53
- /** Ready results the model has not read yet, in completion order. */
54
- private ready: SubagentRecord[] = [];
55
- /** When each request's first unread result became ready, for the grouped deadline. */
56
- private readyAt = new Map<number, number>();
57
- private timers = new Map<number, ReturnType<typeof setTimeout>>();
58
115
  private idleCheck: ReturnType<typeof setTimeout> | undefined;
59
116
 
60
117
  constructor(
@@ -62,40 +119,18 @@ export class SubagentDelivery {
62
119
  private readonly ctx: ExtensionContext,
63
120
  private readonly manager: SubagentManager,
64
121
  ) {
65
- manager.onRunSettled = (record) => this.settled(record);
122
+ manager.onRunSettled = () => this.scheduleIdleCheck(0);
66
123
  }
67
124
 
68
- private settled(record: SubagentRecord): void {
69
- if (this.disposed) return;
70
- if (record.receipt === "unread") {
71
- // A continued agent can still wait here with its earlier result. Its newest result replaces
72
- // that one, so the agent is reported once.
73
- this.ready = this.ready.filter((waiting) => waiting !== record);
74
- this.ready.push(record);
75
- if (!this.readyAt.has(record.requestId)) this.readyAt.set(record.requestId, Date.now());
76
- }
77
- // A suppressed sibling can also complete a waiting group.
78
- this.flushWhenIdle();
79
- }
80
-
81
- /**
82
- * After a reload or a resumed session: delivers results that had finished before it but were
83
- * still waiting, for example for a sibling in grouped mode.
84
- */
85
- deliverRestored(): void {
86
- for (const record of this.manager.list()) {
87
- if (record.receipt !== "unread") continue;
88
- this.ready.push(record);
89
- if (!this.readyAt.has(record.requestId)) this.readyAt.set(record.requestId, Date.now());
90
- }
91
- this.flushWhenIdle();
125
+ /** Recheck saved results after opening a session or navigating its tree. */
126
+ branchChanged(): void {
127
+ // Let Pi finish installing the new branch and updating its UI before starting a turn.
128
+ this.scheduleIdleCheck(0);
92
129
  }
93
130
 
94
131
  /** The main session started a run, so ready results wait for a boundary instead. */
95
132
  agentStarted(): void {
96
133
  this.busy = true;
97
- for (const timer of this.timers.values()) clearTimeout(timer);
98
- this.timers.clear();
99
134
  clearTimeout(this.idleCheck);
100
135
  this.idleCheck = undefined;
101
136
  }
@@ -103,135 +138,90 @@ export class SubagentDelivery {
103
138
  /** At a turn boundary that continues, add ready results to the next request without an extra one. */
104
139
  turnEnded(event: TurnEndEvent): BoundaryResult | undefined {
105
140
  if (this.disposed || event.toolResults.length === 0) return undefined;
106
- const batch = this.take(this.ready);
107
- if (!batch.length) return undefined;
108
- const draft: CustomMessageEntryDraft = {
109
- type: "custom_message",
110
- customType: SUBAGENT_RESULT_MESSAGE,
111
- content: batch.map(resultText).join("\n\n---\n\n"),
112
- display: true,
113
- details: { records: batch.map((record) => ({ ...record })) } satisfies SubagentResultDetails,
114
- };
115
- for (const record of batch) this.manager.markReceipt(record, "delivered");
116
- return { entries: [...event.entries, draft] };
141
+ const { ready } = this.branchResults();
142
+ if (!ready.length) return undefined;
143
+ return { entries: [...event.entries, resultMessage(ready)] };
117
144
  }
118
145
 
119
146
  /** The main session stopped. Results it did not read are now idle deliveries. */
120
147
  agentSettled(): void {
121
148
  this.busy = false;
122
- this.flushIdle();
149
+ // In the TUI, check the branch after Pi finishes the event. Pi defers sends made inside
150
+ // agent_settled, so the branch could change before a send made here actually runs.
151
+ if (this.ctx.mode === "tui") this.scheduleIdleCheck(0);
152
+ else this.flushIdle();
123
153
  }
124
154
 
125
- /**
126
- * Delivers ready results when no main-model run is active. Pi is also not idle while it compacts
127
- * or summarizes a branch on the user's command, and no main-model run ends that. So delivery
128
- * checks again until Pi is idle.
129
- */
130
- private flushWhenIdle(): void {
131
- if (this.busy || this.disposed) return;
132
- if (this.ctx.isIdle()) {
133
- this.flushIdle();
134
- return;
135
- }
136
- this.idleCheck ??= setTimeout(() => {
137
- this.idleCheck = undefined;
138
- this.flushWhenIdle();
139
- }, IDLE_CHECK_MS);
155
+ private branchResults() {
156
+ const finished = this.manager.finishedBackgroundRuns();
157
+ if (!finished.length) return { ready: [], started: new Set<string>() };
158
+ const { started, received } = readSubagentBranch(this.ctx, this.manager.sessionId);
159
+ const ready = finished.filter((record) => {
160
+ const key = subagentRunKey(record);
161
+ return started.has(key) && !received.has(key);
162
+ });
163
+ return { ready, started };
164
+ }
165
+
166
+ private scheduleIdleCheck(delay: number): void {
167
+ if (this.disposed || this.busy) return;
168
+ clearTimeout(this.idleCheck);
169
+ this.idleCheck = setTimeout(() => this.flushIdle(), delay);
140
170
  }
141
171
 
142
172
  private flushIdle(): void {
143
- if (this.disposed) return;
144
- this.forgetDelivered();
145
- if (this.manager.settings.delivery.mode === "immediate") {
146
- this.send(this.take(this.ready));
173
+ clearTimeout(this.idleCheck);
174
+ this.idleCheck = undefined;
175
+ if (this.disposed || this.busy) return;
176
+ const { ready, started } = this.branchResults();
177
+ if (!ready.length) return;
178
+ if (!this.ctx.isIdle()) {
179
+ // Compaction and branch summaries can keep Pi busy without an agent_settled event.
180
+ this.scheduleIdleCheck(IDLE_CHECK_MS);
147
181
  return;
148
182
  }
149
- const requests = new Set(this.ready.map((record) => record.requestId));
150
- for (const requestId of requests) {
151
- const group = this.ready.filter((record) => record.requestId === requestId);
152
- const outstanding = this.manager
153
- .list()
154
- .some(
155
- (record) =>
156
- record.requestId === requestId &&
157
- record.background &&
158
- record.receipt === "pending" &&
159
- !isSubagentFinished(record.status),
160
- );
161
- if (!outstanding) {
162
- this.sendGroup(group);
163
- continue;
164
- }
165
- if (this.timers.has(requestId)) continue;
166
- const deadline = (this.readyAt.get(requestId) ?? Date.now()) + GROUP_WAIT_MS;
167
- const timer = setTimeout(
168
- () => {
169
- this.timers.delete(requestId);
170
- if (this.busy || this.disposed) return;
171
- if (!this.ctx.isIdle()) {
172
- // Pi is compacting. The idle check sets this timer again, and it then fires at once.
173
- this.flushWhenIdle();
174
- return;
175
- }
176
- // Report what finished. Stragglers form the next batch.
177
- this.sendGroup(this.ready.filter((record) => record.requestId === requestId));
178
- },
179
- Math.max(0, deadline - Date.now()),
180
- );
181
- this.timers.set(requestId, timer);
182
- }
183
- }
184
183
 
185
- private sendGroup(group: SubagentRecord[]): void {
186
- this.send(this.take(group));
187
- }
188
-
189
- /** Removes the given records from the ready list and keeps only those still unread. */
190
- private take(records: SubagentRecord[]): SubagentRecord[] {
191
- const taken = new Set(records);
192
- this.ready = this.ready.filter((record) => !taken.has(record));
193
- this.forgetDelivered();
194
- return records.filter((record) => record.receipt === "unread");
195
- }
184
+ if (this.manager.settings.delivery.mode === "immediate") {
185
+ this.send(ready);
186
+ return;
187
+ }
196
188
 
197
- /**
198
- * Drops results that no longer wait, such as one the model read with get_subagent_result. A
199
- * request with no waiting result loses its 60-second clock, so its next result starts a new wait.
200
- */
201
- private forgetDelivered(): void {
202
- this.ready = this.ready.filter((record) => record.receipt === "unread");
203
- for (const requestId of this.readyAt.keys()) {
204
- if (!this.ready.some((record) => record.requestId === requestId)) {
205
- this.readyAt.delete(requestId);
189
+ const outstanding = new Set<number>();
190
+ for (const record of this.manager.list()) {
191
+ if (
192
+ record.background &&
193
+ !isSubagentFinished(record.status) &&
194
+ started.has(subagentRunKey(record))
195
+ ) {
196
+ outstanding.add(record.requestId);
206
197
  }
207
198
  }
199
+ const deadlines = new Map<number, number>();
200
+ const now = Date.now();
201
+ for (const record of ready) {
202
+ if (!outstanding.has(record.requestId)) continue;
203
+ const deadline = (record.endedAt ?? now) + GROUP_WAIT_MS;
204
+ deadlines.set(
205
+ record.requestId,
206
+ Math.min(deadlines.get(record.requestId) ?? deadline, deadline),
207
+ );
208
+ }
209
+ const batch = ready.filter((record) => (deadlines.get(record.requestId) ?? now) <= now);
210
+ const nextDeadline = Math.min(...[...deadlines.values()].filter((deadline) => deadline > now));
211
+ if (Number.isFinite(nextDeadline)) this.scheduleIdleCheck(nextDeadline - now);
212
+ if (batch.length) this.send(batch);
208
213
  }
209
214
 
210
215
  private send(batch: SubagentRecord[]): void {
211
- if (!batch.length) return;
212
216
  // Agents the user stopped report without starting a main-model turn.
213
217
  const triggerTurn = batch.some((record) => record.stoppedBy !== "user");
214
- for (const record of batch) this.manager.markReceipt(record, "delivered");
215
- this.pi.sendMessage(
216
- {
217
- customType: SUBAGENT_RESULT_MESSAGE,
218
- content: batch.map(resultText).join("\n\n---\n\n"),
219
- display: true,
220
- details: {
221
- records: batch.map((record) => ({ ...record })),
222
- } satisfies SubagentResultDetails,
223
- },
224
- { triggerTurn },
225
- );
218
+ this.pi.sendMessage(resultMessage(batch), { triggerTurn });
226
219
  }
227
220
 
228
221
  /** Stops delivery before shutdown aborts any agent, so nothing arrives late. */
229
222
  dispose(): void {
230
223
  this.disposed = true;
231
- for (const timer of this.timers.values()) clearTimeout(timer);
232
- this.timers.clear();
233
224
  clearTimeout(this.idleCheck);
234
225
  this.idleCheck = undefined;
235
- this.ready = [];
236
226
  }
237
227
  }
@@ -1,9 +1,13 @@
1
1
  import type { SubagentManager } from "./manager.ts";
2
2
 
3
- // Pi's terminal API writes only the root OSC 7501 record. Use a child record so
3
+ // Pi's terminal API writes only the root OSC 7501 record. Use child records so
4
4
  // Pi can report that its own turn finished or is blocked without hiding subagent work.
5
- const SUBAGENT_STATUS_ID = "pi-subagents";
6
- const CLEAR_SUBAGENTS = `\x1b]7501;state=clear:id=${SUBAGENT_STATUS_ID}\x1b\\`;
5
+ const SUBAGENT_STATUS_NAMESPACE = "pi-subagents";
6
+ const OSC_TITLE_MAX_BYTES = 192;
7
+
8
+ function clearRexStatus(id: string): string {
9
+ return `\x1b]7501;state=clear:id=${id}\x1b\\`;
10
+ }
7
11
 
8
12
  /** Reports running subagents to Rex independently of Pi's main turn. */
9
13
  export function reportSubagentsToRex(manager: SubagentManager): (() => void) | undefined {
@@ -16,7 +20,7 @@ export function reportSubagentsToRex(manager: SubagentManager): (() => void) | u
16
20
  return undefined;
17
21
  }
18
22
 
19
- let reportedCount = 0;
23
+ let reported = new Map<string, "running" | "stopping">();
20
24
  let pending = false;
21
25
  let disposed = false;
22
26
  let resend = false;
@@ -28,24 +32,34 @@ export function reportSubagentsToRex(manager: SubagentManager): (() => void) | u
28
32
  queueMicrotask(() => {
29
33
  pending = false;
30
34
  if (disposed) return;
31
- const count = manager
32
- .list()
33
- .filter(({ status }) => status === "running" || status === "stopping").length;
34
- if (!resend && count === reportedCount) return;
35
- resend = false;
36
- reportedCount = count;
37
- if (count === 0) {
38
- process.stdout.write(CLEAR_SUBAGENTS);
39
- return;
35
+
36
+ const active = new Map<string, "running" | "stopping">();
37
+ let updates = "";
38
+ for (const { id, name, status } of manager.list()) {
39
+ if (status !== "running" && status !== "stopping") continue;
40
+ // A UUID without hyphens fits the OSC limit of 32 bytes per ID segment.
41
+ const statusId = `${SUBAGENT_STATUS_NAMESPACE}/${id.replaceAll("-", "")}`;
42
+ active.set(statusId, status);
43
+ if (!resend && reported.get(statusId) === status) continue;
44
+ // Task names are ASCII and have no length limit. Shorten only the title sent to Rex.
45
+ const title = Buffer.from(name.slice(0, OSC_TITLE_MAX_BYTES)).toString("base64");
46
+ const message = Buffer.from(status === "running" ? "Running" : "Stopping").toString(
47
+ "base64",
48
+ );
49
+ updates += `\x1b]7501;state=working:id=${statusId}:title=${title}:msg=${message}\x1b\\`;
40
50
  }
41
- const message = `${count} ${count === 1 ? "subagent" : "subagents"} running`;
42
- const encoded = Buffer.from(message).toString("base64");
43
- process.stdout.write(`\x1b]7501;state=working:id=${SUBAGENT_STATUS_ID}:msg=${encoded}\x1b\\`);
51
+
52
+ let clears = "";
53
+ for (const id of reported.keys()) {
54
+ if (!active.has(id)) clears += clearRexStatus(id);
55
+ }
56
+ reported = active;
57
+ resend = false;
58
+ if (clears || updates) process.stdout.write(clears + updates);
44
59
  });
45
60
  };
46
61
  const onResume = () => {
47
- // Pi clears all records when it suspends, even if the count stays the same.
48
- if (reportedCount === 0) return;
62
+ // Pi clears all records when it suspends. Resend even if no status changed.
49
63
  resend = true;
50
64
  scheduleReport();
51
65
  };
@@ -54,9 +68,10 @@ export function reportSubagentsToRex(manager: SubagentManager): (() => void) | u
54
68
  scheduleReport();
55
69
 
56
70
  return () => {
71
+ if (disposed) return;
57
72
  disposed = true;
58
73
  unsubscribe();
59
74
  process.off("SIGCONT", onResume);
60
- if (reportedCount > 0) process.stdout.write(CLEAR_SUBAGENTS);
75
+ process.stdout.write(clearRexStatus(SUBAGENT_STATUS_NAMESPACE));
61
76
  };
62
77
  }
package/src/tools.ts CHANGED
@@ -163,12 +163,20 @@ export function registerSubagentTools(pi: ExtensionAPI, getManager: SubagentMana
163
163
  name: "get_subagent_result",
164
164
  label: "Agent result",
165
165
  description:
166
- "Read the full result of a finished agent by task name. For a running or queued agent, report its status without waiting.",
167
- parameters: nameParameter,
166
+ "Read a finished agent's full result by task name and optional run number. For a running or queued run, report its status without waiting.",
167
+ parameters: Type.Object({
168
+ ...nameParameter.properties,
169
+ run: Type.Optional(
170
+ Type.Integer({ minimum: 1, description: "Run number. Omit for the latest run." }),
171
+ ),
172
+ }),
168
173
  async execute(_toolCallId, params) {
169
174
  const manager = requireManager(getManager);
170
- const record = manager.find(params.name);
171
- if (!record) throw new Error(`No agent named "${params.name}" exists in this session.`);
175
+ const agent = manager.find(params.name);
176
+ if (!agent) throw new Error(`No agent named "${params.name}" exists in this session.`);
177
+ const record = manager.runOutcome(agent.id, params.run);
178
+ if (!record)
179
+ throw new Error(`Agent "${params.name}" has no saved result for run ${params.run}.`);
172
180
  if (!isSubagentFinished(record.status)) {
173
181
  return subagentToolResult(
174
182
  `${subagentStatusLine(record)} Current activity: ${record.activity}.`,
@@ -177,8 +185,8 @@ export function registerSubagentTools(pi: ExtensionAPI, getManager: SubagentMana
177
185
  },
178
186
  );
179
187
  }
180
- manager.markReceipt(record, "consumed");
181
- return subagentToolResult(subagentFinishedText(record), { id: record.id });
188
+ manager.consumeResult(record);
189
+ return subagentToolResult(subagentFinishedText(record), { id: record.id, run: record.run });
182
190
  },
183
191
  });
184
192