oira666_pi-subagent 0.5.13 → 0.6.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.
Files changed (57) hide show
  1. package/README.md +31 -11
  2. package/docs/async-performance.md +79 -0
  3. package/docs/configuration.md +21 -8
  4. package/docs/performance-audit.md +59 -0
  5. package/docs/sessions.md +28 -14
  6. package/docs/usage.md +22 -26
  7. package/extension/activity-widget.ts +95 -0
  8. package/extension/activity.ts +80 -0
  9. package/extension/async-jobs.ts +139 -0
  10. package/extension/broadcast-history.ts +194 -0
  11. package/extension/broadcast.ts +68 -105
  12. package/extension/completion.ts +55 -0
  13. package/extension/events.ts +13 -20
  14. package/extension/execution.ts +33 -2
  15. package/extension/expand-command.ts +118 -49
  16. package/extension/launch-result.ts +27 -0
  17. package/extension/launch-tool.ts +48 -47
  18. package/extension/lead-message-tool.ts +43 -0
  19. package/extension/message-command.ts +63 -0
  20. package/extension/message-tool.ts +246 -0
  21. package/extension/policy.ts +2 -2
  22. package/extension/progress-details.ts +159 -0
  23. package/extension/progress-preview.ts +92 -0
  24. package/extension/progress.ts +39 -47
  25. package/extension/prompt-hook.ts +8 -14
  26. package/extension/prompts.ts +1 -1
  27. package/extension/schemas.ts +14 -0
  28. package/extension/session-start.ts +10 -4
  29. package/extension/state.ts +12 -1
  30. package/extension/tool-registration.ts +28 -2
  31. package/extension/usage.ts +199 -52
  32. package/index.ts +4 -0
  33. package/package.json +1 -1
  34. package/resume.ts +43 -8
  35. package/runner/attempt-state.ts +7 -0
  36. package/runner/attempt.ts +60 -58
  37. package/runner/events.ts +3 -23
  38. package/runner/jsonl-framer.ts +48 -0
  39. package/runner/lead-message.ts +37 -0
  40. package/runner/message-index.ts +66 -0
  41. package/runner/options.ts +8 -1
  42. package/runner/parallel.ts +132 -26
  43. package/runner/progress-coalescer.ts +45 -0
  44. package/runner/protocol.ts +145 -9
  45. package/types/contracts.ts +7 -2
  46. package/types/messages.ts +138 -12
  47. package/ui/detail-async.ts +108 -0
  48. package/ui/detail-lines.ts +113 -3
  49. package/ui/detail-model.ts +1 -0
  50. package/ui/detail-selectors.ts +13 -3
  51. package/ui/detail-transcript.ts +32 -30
  52. package/ui/expand-view.ts +29 -2
  53. package/ui/pager-view.ts +18 -29
  54. package/ui/pager.ts +11 -19
  55. package/ui/picker.ts +35 -5
  56. package/ui/tree-live.ts +4 -0
  57. package/extension/resume-tool.ts +0 -298
@@ -0,0 +1,80 @@
1
+ import type { ExtensionState } from "./state.js";
2
+
3
+ export interface ActivityEntry {
4
+ name: string;
5
+ path: string[];
6
+ depth: number;
7
+ startedAt: number;
8
+ status: "running" | "idle";
9
+ topLevelId: number;
10
+ }
11
+
12
+ interface ActivityCache {
13
+ generation: number;
14
+ targets: unknown;
15
+ activeCount: number;
16
+ at: number;
17
+ firstSeen: Map<string, number>;
18
+ entries: ActivityEntry[];
19
+ }
20
+ const caches = new WeakMap<ExtensionState, ActivityCache>();
21
+
22
+ /** Only live handles and their latest snapshots. Never read session files on a UI tick. */
23
+ export function getActivitySnapshot(state: ExtensionState, now = Date.now()): ActivityEntry[] {
24
+ const previous = caches.get(state);
25
+ const targets = state.latestBroadcastTargets.all;
26
+ if (
27
+ previous?.generation === state.lifecycleGeneration &&
28
+ previous.targets === targets &&
29
+ previous.activeCount === state.activeSubagents.size &&
30
+ now - previous.at < 250
31
+ )
32
+ return previous.entries;
33
+ const firstSeen = new Map<string, number>();
34
+ const entries = new Map<string, ActivityEntry>();
35
+ const add = (path: string[], topLevelId: number, startedAt?: number, idle = false) => {
36
+ const name = path.at(-1) || "worker";
37
+ const key = `${topLevelId}:${name}`;
38
+ const start =
39
+ startedAt ??
40
+ (previous?.generation === state.lifecycleGeneration ? previous.firstSeen.get(key) : undefined) ??
41
+ now;
42
+ firstSeen.set(key, start);
43
+ entries.set(key, {
44
+ name,
45
+ path,
46
+ depth: path.length - 1,
47
+ topLevelId,
48
+ startedAt: start,
49
+ status: idle ? "idle" : "running",
50
+ });
51
+ };
52
+ const roots = new Map(
53
+ targets.filter((target) => target.restPath.length === 0).map((target) => [target.topLevelId, target]),
54
+ );
55
+ for (const target of targets) {
56
+ if (!state.activeSubagents.has(target.topLevelId) || target.restPath.length === 0) continue;
57
+ add(target.display.split(" > "), target.topLevelId, target.startedAt, target.idle);
58
+ }
59
+ for (const [id, active] of state.activeSubagents) {
60
+ const target = roots.get(id);
61
+ add(
62
+ [active.name || active.agent || "worker"],
63
+ id,
64
+ active.startedAt ?? target?.startedAt,
65
+ active.handle.isIdle?.() ?? target?.idle ?? false,
66
+ );
67
+ }
68
+ const sorted = [...entries.values()].sort(
69
+ (a, b) => a.depth - b.depth || a.topLevelId - b.topLevelId || a.name.localeCompare(b.name),
70
+ );
71
+ caches.set(state, {
72
+ generation: state.lifecycleGeneration,
73
+ targets,
74
+ activeCount: state.activeSubagents.size,
75
+ at: now,
76
+ firstSeen,
77
+ entries: sorted,
78
+ });
79
+ return sorted;
80
+ }
@@ -0,0 +1,139 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { SUBAGENT_COMPLETION_TYPE, SUBAGENT_MESSAGE_TYPE } from "../types.js";
3
+ import type { ProgressUpdate } from "./contracts.js";
4
+ import type { ExtensionState } from "./state.js";
5
+ import { updateCombinedUsageStatus } from "./runtime.js";
6
+
7
+ export interface BackgroundJob {
8
+ names: string[];
9
+ controller: AbortController;
10
+ promise: Promise<void>;
11
+ }
12
+
13
+ // Session teardown may clear the map directly. Size/generation changes invalidate
14
+ // this count; normal reservations and acknowledgments update it in constant time.
15
+ const deliveryCounts = new WeakMap<object, { generation: number; size: number; count: number }>();
16
+ function pendingCount(state: ExtensionState): number {
17
+ const map = (state.pendingCompletionDeliveries ??= new Map());
18
+ const cached = deliveryCounts.get(map);
19
+ if (cached?.generation === state.lifecycleGeneration && cached.size === map.size) return cached.count;
20
+ let count = 0;
21
+ for (const generation of map.values()) if (generation === state.lifecycleGeneration) count++;
22
+ deliveryCounts.set(map, { generation: state.lifecycleGeneration, size: map.size, count });
23
+ return count;
24
+ }
25
+ function recordCount(state: ExtensionState, count: number): void {
26
+ deliveryCounts.set(state.pendingCompletionDeliveries, {
27
+ generation: state.lifecycleGeneration,
28
+ size: state.pendingCompletionDeliveries.size,
29
+ count,
30
+ });
31
+ }
32
+
33
+ /** Pending delivery is work too: a queued message has not started its continuation yet. */
34
+ function emitBackgroundCount(state: ExtensionState): void {
35
+ if (state.currentDepth > 0) {
36
+ const running = state.backgroundJobs.size + pendingCount(state);
37
+ if (state.latestSessionCtx?.mode === "rpc") {
38
+ // RPC redirects ordinary stdout to stderr. Public status events share
39
+ // the ordered RPC output queue with agent_settled, without persistence.
40
+ state.latestSessionCtx.ui.setStatus("pi-subagent-background", String(running));
41
+ return;
42
+ }
43
+ process.stdout.write(`${JSON.stringify({ type: "subagent_background", running })}\n`);
44
+ }
45
+ }
46
+
47
+ /** Reserve before scheduling, so job settlement cannot expose a false idle window. */
48
+ export function retainCompletionDelivery(state: ExtensionState, generation: number): string {
49
+ const token = randomUUID();
50
+ const count = pendingCount(state);
51
+ state.pendingCompletionDeliveries.set(token, generation);
52
+ recordCount(state, count + Number(generation === state.lifecycleGeneration));
53
+ emitBackgroundCount(state);
54
+ return token;
55
+ }
56
+
57
+ export function releaseCompletionDelivery(state: ExtensionState, token: string, generation: number): void {
58
+ if (generation !== state.lifecycleGeneration || state.pendingCompletionDeliveries?.get(token) !== generation) return;
59
+ const count = pendingCount(state);
60
+ state.pendingCompletionDeliveries.delete(token);
61
+ recordCount(state, count - 1);
62
+ emitBackgroundCount(state);
63
+ }
64
+
65
+ /** Register once from registerSessionEvents. Starting an unrelated run must not drain this counter. */
66
+ export function registerAsyncDeliveryEvents(state: ExtensionState): void {
67
+ state.pi.on("message_start", (event) => {
68
+ const message = event.message;
69
+ if (!state.sessionActive || message.role !== "custom" || message.customType !== SUBAGENT_COMPLETION_TYPE) return;
70
+ const details: unknown = message.details;
71
+ if (!details || typeof details !== "object" || !("asyncDeliveryId" in details)) return;
72
+ if (typeof details.asyncDeliveryId !== "string") return;
73
+ // Pi emits message_start on consumption, after turn_start, for both an idle
74
+ // prompt and a steering message drained within an already-running agent.
75
+ releaseCompletionDelivery(state, details.asyncDeliveryId, state.lifecycleGeneration);
76
+ });
77
+ }
78
+
79
+ export function notifyLead(state: ExtensionState, content: string, generation = state.lifecycleGeneration): void {
80
+ if (!state.sessionActive || state.lifecycleGeneration !== generation) return;
81
+ // Custom messages use Pi\'s distinct customMessageBg instead of userMessageBg.
82
+ state.pi.sendMessage(
83
+ { customType: SUBAGENT_MESSAGE_TYPE, content, display: true, details: undefined },
84
+ {
85
+ deliverAs: "steer",
86
+ triggerTurn: true,
87
+ },
88
+ );
89
+ }
90
+
91
+ export function startBackground(
92
+ state: ExtensionState,
93
+ key: string,
94
+ names: string[],
95
+ run: (signal: AbortSignal) => Promise<ProgressUpdate>,
96
+ cleanup?: () => Promise<void>,
97
+ ): void {
98
+ const generation = state.lifecycleGeneration;
99
+ const controller = new AbortController();
100
+ const job: BackgroundJob = { names, controller, promise: Promise.resolve() };
101
+ state.backgroundJobs.set(key, job);
102
+ emitBackgroundCount(state);
103
+ // Defer execution one microtask so the job is visible before its first handle.
104
+ job.promise = Promise.resolve()
105
+ .then(() => run(controller.signal))
106
+ .then(() => undefined)
107
+ .catch((error) => {
108
+ notifyLead(
109
+ state,
110
+ `Subagent job ${names.join(", ") || key} failed: ${error instanceof Error ? error.message : String(error)}`,
111
+ generation,
112
+ );
113
+ })
114
+ .finally(async () => {
115
+ try {
116
+ await cleanup?.();
117
+ } catch (error) {
118
+ console.error("[pi-subagent] Background cleanup failed:", error);
119
+ }
120
+ if (state.backgroundJobs.get(key) !== job) return;
121
+ state.backgroundJobs.delete(key);
122
+ if (generation !== state.lifecycleGeneration) return;
123
+ state.activeSubagentUsageSummaries.delete(key);
124
+ emitBackgroundCount(state);
125
+ updateCombinedUsageStatus(state);
126
+ });
127
+ }
128
+
129
+ export async function stopBackgroundJobs(state: ExtensionState): Promise<void> {
130
+ const generation = state.lifecycleGeneration;
131
+ const jobs = Array.from(state.backgroundJobs.entries());
132
+ for (const [, job] of jobs) job.controller.abort();
133
+ await Promise.allSettled(jobs.map(([, job]) => job.promise));
134
+ // A replacement with the same key belongs to its new caller, not this drain.
135
+ for (const [key, job] of jobs) {
136
+ if (state.backgroundJobs.get(key) === job) state.backgroundJobs.delete(key);
137
+ }
138
+ if (generation === state.lifecycleGeneration) emitBackgroundCount(state);
139
+ }
@@ -0,0 +1,194 @@
1
+ import { getNestedSubagentResults, isSubagentToolName, type SingleResult, type SubagentDetails } from "../types.js";
2
+ import type { TranscriptMessage } from "../types/transcript.js";
3
+ import type { BroadcastTarget } from "./broadcast.js";
4
+ import type { ExtensionState } from "./state.js";
5
+
6
+ const histories = new WeakMap<
7
+ TranscriptMessage[],
8
+ {
9
+ length: number;
10
+ last: unknown;
11
+ relevant: TranscriptMessage[];
12
+ nested: ReturnType<typeof getNestedSubagentResults>;
13
+ }
14
+ >();
15
+
16
+ /** Ignore assistant/token history when updating live descendant routing. */
17
+ export function nestedBroadcastHistory(messages: TranscriptMessage[] | undefined) {
18
+ // Compact refs and serialized progress deliberately omit transcripts.
19
+ if (!Array.isArray(messages)) return [];
20
+ let cache = histories.get(messages);
21
+ if (!cache || cache.length > messages.length || (cache.length && cache.last !== messages[cache.length - 1])) {
22
+ cache = { length: 0, last: undefined, relevant: [], nested: [] };
23
+ histories.set(messages, cache);
24
+ }
25
+ const before = cache.relevant.length;
26
+ for (let i = cache.length; i < messages.length; i++) {
27
+ const message = messages[i];
28
+ if (!message || typeof message !== "object") continue;
29
+ if (
30
+ (message.role === "toolResult" && isSubagentToolName(message.toolName)) ||
31
+ (message.role === "custom" && Reflect.get(message, "customType") === "subagent_completion")
32
+ )
33
+ cache.relevant.push(message);
34
+ }
35
+ cache.length = messages.length;
36
+ cache.last = messages[messages.length - 1];
37
+ if (before !== cache.relevant.length) cache.nested = getNestedSubagentResults(cache.relevant);
38
+ return cache.nested;
39
+ }
40
+
41
+ type Targets = ExtensionState["latestBroadcastTargets"];
42
+ type Active = ExtensionState["activeSubagents"] extends Map<number, infer T> ? T : never;
43
+ interface RootTargets extends Targets {
44
+ id: number;
45
+ handle: Active["handle"];
46
+ name: string;
47
+ fallback?: boolean;
48
+ }
49
+ interface TargetCache {
50
+ generation: number;
51
+ source: Targets;
52
+ // Removed handles release unread snapshots too, including in headless sessions.
53
+ roots: WeakMap<Active, RootTargets>;
54
+ observed: Map<number, RootTargets>;
55
+ flat?: Targets;
56
+ }
57
+ const targetCaches = new WeakMap<ExtensionState, TargetCache>();
58
+
59
+ function resetGeneration(state: ExtensionState, cache: TargetCache): void {
60
+ if (cache.generation === state.lifecycleGeneration) return;
61
+ cache.generation = state.lifecycleGeneration;
62
+ cache.roots = new WeakMap();
63
+ cache.observed.clear();
64
+ cache.flat = undefined;
65
+ }
66
+
67
+ function rootTargets(owner: Active, id: number, targets: Targets, fallback = false): RootTargets {
68
+ return { id, handle: owner.handle, name: owner.name || owner.agent, ...targets, fallback };
69
+ }
70
+
71
+ function importTargets(
72
+ state: ExtensionState,
73
+ cache: TargetCache,
74
+ key: keyof Targets,
75
+ targets: BroadcastTarget[],
76
+ ): void {
77
+ for (const target of targets) {
78
+ const owner = state.activeSubagents.get(target.topLevelId);
79
+ if (!owner) continue;
80
+ let root = cache.roots.get(owner);
81
+ if (
82
+ !root ||
83
+ root.id !== target.topLevelId ||
84
+ root.handle !== owner.handle ||
85
+ root.name !== (owner.name || owner.agent)
86
+ ) {
87
+ root = rootTargets(owner, target.topLevelId, { all: [], youngest: [] });
88
+ cache.roots.set(owner, root);
89
+ }
90
+ root[key].push(target);
91
+ }
92
+ }
93
+
94
+ /** Assignments replace one public list without reviving older per-root snapshots. */
95
+ function replaceTargets(
96
+ state: ExtensionState,
97
+ cache: TargetCache,
98
+ key: keyof Targets,
99
+ targets: BroadcastTarget[],
100
+ ): void {
101
+ resetGeneration(state, cache);
102
+ for (const owner of state.activeSubagents.values()) {
103
+ const root = cache.roots.get(owner);
104
+ if (!root) continue;
105
+ root[key] = [];
106
+ root.fallback = false;
107
+ }
108
+ importTargets(state, cache, key, targets);
109
+ cache.flat = undefined;
110
+ }
111
+
112
+ function getTargetCache(state: ExtensionState): TargetCache {
113
+ let cache = targetCaches.get(state);
114
+ if (!cache || cache.source !== state.latestBroadcastTargets) {
115
+ const source = state.latestBroadcastTargets;
116
+ const { all, youngest } = source;
117
+ cache = { generation: state.lifecycleGeneration, source, roots: new WeakMap(), observed: new Map() };
118
+ targetCaches.set(state, cache);
119
+ importTargets(state, cache, "all", all);
120
+ importTargets(state, cache, "youngest", youngest);
121
+ const current = cache;
122
+ for (const key of ["all", "youngest"] as const) {
123
+ Object.defineProperty(source, key, {
124
+ enumerable: true,
125
+ configurable: true,
126
+ get: () => readTargets(state, current)[key],
127
+ set: (targets: BroadcastTarget[]) => replaceTargets(state, current, key, targets),
128
+ });
129
+ }
130
+ }
131
+ resetGeneration(state, cache);
132
+ return cache;
133
+ }
134
+
135
+ /** Reconcile on reads, not on every job's progress. Map size alone misses replacements. */
136
+ function readTargets(state: ExtensionState, cache: TargetCache): Targets {
137
+ resetGeneration(state, cache);
138
+ const observed = new Map<number, RootTargets>();
139
+ for (const [id, owner] of state.activeSubagents) {
140
+ let root = cache.roots.get(owner);
141
+ if (root && (root.id !== id || root.handle !== owner.handle || root.name !== (owner.name || owner.agent)))
142
+ root = undefined;
143
+ if (!root || root.fallback) {
144
+ const old = root?.all[0];
145
+ const idle = owner.handle.isIdle?.() === true;
146
+ if (!old || old.startedAt !== owner.startedAt || Boolean(old.idle) !== idle) {
147
+ const target: BroadcastTarget = {
148
+ display: owner.name || owner.agent,
149
+ topLevelId: id,
150
+ restPath: [],
151
+ ...(owner.startedAt !== undefined ? { startedAt: owner.startedAt } : {}),
152
+ ...(idle ? { idle: true } : {}),
153
+ };
154
+ root = rootTargets(owner, id, { all: [target], youngest: [target] }, true);
155
+ cache.roots.set(owner, root);
156
+ }
157
+ }
158
+ observed.set(id, root!);
159
+ if (cache.observed.get(id) !== root) cache.flat = undefined;
160
+ }
161
+ if (cache.observed.size !== observed.size) cache.flat = undefined;
162
+ cache.observed = observed;
163
+ if (!cache.flat) {
164
+ const all = new Map<string, BroadcastTarget>();
165
+ const youngest = new Map<string, BroadcastTarget>();
166
+ for (const root of observed.values()) {
167
+ for (const target of root.all) all.set(target.display, target);
168
+ for (const target of root.youngest) youngest.set(target.display, target);
169
+ }
170
+ const sorted = (targets: Map<string, BroadcastTarget>) =>
171
+ [...targets.values()].sort((a, b) => a.display.localeCompare(b.display));
172
+ cache.flat = { all: sorted(all), youngest: sorted(youngest) };
173
+ }
174
+ return cache.flat;
175
+ }
176
+
177
+ /** A progress update visits only its own roots. Flattening and fallback discovery are lazy. */
178
+ export function updateBroadcastTargetCache(
179
+ state: ExtensionState,
180
+ details: SubagentDetails | undefined,
181
+ topLevelBaseId: number,
182
+ collect: (result: SingleResult, path: string[], id: number, targets: Targets) => boolean,
183
+ ): void {
184
+ const cache = getTargetCache(state);
185
+ details?.results.forEach((result, index) => {
186
+ const id = topLevelBaseId + index;
187
+ const owner = state.activeSubagents.get(id);
188
+ if (!owner) return;
189
+ const targets: Targets = { all: [], youngest: [] };
190
+ collect(result, [result.name || result.agent], id, targets);
191
+ cache.roots.set(owner, rootTargets(owner, id, targets));
192
+ });
193
+ cache.flat = undefined;
194
+ }
@@ -1,4 +1,5 @@
1
- import { type SingleResult, type SubagentDetails, getNestedSubagentResults, isSubagentDetails } from "../types.js";
1
+ import { type SingleResult, type SubagentDetails, isSubagentDetails } from "../types.js";
2
+ import { nestedBroadcastHistory, updateBroadcastTargetCache } from "./broadcast-history.js";
2
3
  import type { SessionContext } from "./contracts.js";
3
4
  import type { ExtensionState } from "./state.js";
4
5
 
@@ -9,6 +10,8 @@ export interface BroadcastTarget {
9
10
  display: string;
10
11
  topLevelId: number;
11
12
  restPath: string[];
13
+ startedAt?: number;
14
+ idle?: boolean;
12
15
  }
13
16
 
14
17
  export interface ParsedBroadcastSelection {
@@ -70,10 +73,14 @@ export function collectRunningBroadcastTargetsFromResult(
70
73
  let hasRunningDescendant = false;
71
74
  const completedIds = new Set<string>();
72
75
  const nestedDetails: SubagentDetails[] = [];
73
- for (const nested of getNestedSubagentResults(result.messages)) {
76
+ for (const nested of nestedBroadcastHistory(result.messages)) {
74
77
  if (!isSubagentDetails(nested.details)) continue;
78
+ const live = result.liveNestedSubagents?.[nested.toolCallId];
75
79
  if (nested.toolCallId) completedIds.add(nested.toolCallId);
76
- nestedDetails.push(nested.details);
80
+ // Async launch receipts are not completed runs. Their live snapshot carries
81
+ // current descendants, including children launched after the receipt.
82
+ const hasRunningPlaceholder = nested.details.results.some((child) => child.exitCode === -1);
83
+ nestedDetails.push(hasRunningPlaceholder && isSubagentDetails(live) ? live : nested.details);
77
84
  }
78
85
  for (const [toolCallId, live] of Object.entries(result.liveNestedSubagents ?? {})) {
79
86
  if (!completedIds.has(toolCallId) && isSubagentDetails(live)) nestedDetails.push(live);
@@ -89,7 +96,13 @@ export function collectRunningBroadcastTargetsFromResult(
89
96
 
90
97
  if (result.exitCode !== -1) return hasRunningDescendant;
91
98
  const restPath = namePath.slice(1);
92
- const self = { display: namePath.join(" > "), topLevelId, restPath };
99
+ const self: BroadcastTarget = {
100
+ display: namePath.join(" > "),
101
+ topLevelId,
102
+ restPath,
103
+ ...(result.startedAt !== undefined ? { startedAt: result.startedAt } : {}),
104
+ ...(result.idle ? { idle: true } : {}),
105
+ };
93
106
  targets.all.push(self);
94
107
  if (!hasRunningDescendant) targets.youngest.push(self);
95
108
  return true;
@@ -100,132 +113,82 @@ export function updateLatestBroadcastTargets(
100
113
  details: SubagentDetails | undefined,
101
114
  topLevelBaseId = 1,
102
115
  ): void {
103
- state.latestBroadcastTargets.all = [];
104
- state.latestBroadcastTargets.youngest = [];
105
- if (!details) {
106
- for (const [id, active] of state.activeSubagents) {
107
- const display = active.name || active.agent;
108
- const target = { display, topLevelId: id, restPath: [] };
109
- state.latestBroadcastTargets.all.push(target);
110
- state.latestBroadcastTargets.youngest.push(target);
111
- }
112
- return;
113
- }
114
- details.results.forEach((result, index) => {
115
- collectRunningBroadcastTargetsFromResult(
116
- result,
117
- [result.name || result.agent],
118
- topLevelBaseId + index,
119
- state.latestBroadcastTargets,
120
- );
121
- });
122
- const dedupe = (targets: BroadcastTarget[]) =>
123
- Array.from(new Map(targets.map((target) => [target.display, target])).values())
124
- .filter((target) => state.activeSubagents.has(target.topLevelId))
125
- .sort((a, b) => a.display.localeCompare(b.display));
126
- state.latestBroadcastTargets.all = dedupe(state.latestBroadcastTargets.all);
127
- state.latestBroadcastTargets.youngest = dedupe(state.latestBroadcastTargets.youngest);
116
+ updateBroadcastTargetCache(state, details, topLevelBaseId, collectRunningBroadcastTargetsFromResult);
117
+ state.onActivityChanged?.();
128
118
  }
129
119
 
130
120
  export function getFallbackTopLevelTargets(state: ExtensionState): BroadcastTarget[] {
131
121
  return Array.from(state.activeSubagents.entries())
132
122
  .sort(([a], [b]) => a - b)
133
- .map(([id, active]) => ({ display: active.name || active.agent, topLevelId: id, restPath: [] }));
123
+ .map(([id, active]) => ({
124
+ display: active.name || active.agent,
125
+ topLevelId: id,
126
+ restPath: [],
127
+ ...(active.startedAt !== undefined ? { startedAt: active.startedAt } : {}),
128
+ ...(active.handle.isIdle?.() ? { idle: true } : {}),
129
+ }));
134
130
  }
135
131
 
136
- export function sendBroadcastToTargets(
132
+ export async function sendBroadcastToTargets(
137
133
  state: ExtensionState,
138
134
  message: string,
139
135
  targets: BroadcastTarget[],
140
136
  ctx: SessionContext,
141
- ): void {
137
+ ): Promise<void> {
138
+ const generation = state.lifecycleGeneration;
142
139
  const delivered: string[] = [];
143
140
  const missed: string[] = [];
144
- for (const target of targets) {
145
- const item = state.activeSubagents.get(target.topLevelId);
146
- if (!item) {
147
- missed.push(target.display);
148
- continue;
149
- }
150
- item.handle.steer(target.restPath.length > 0 ? encodeNestedBroadcast(message, target.restPath) : message);
151
- delivered.push(target.display);
152
- }
141
+ const failed: string[] = [];
142
+ await Promise.all(
143
+ targets.map(async (target) => {
144
+ const item = state.activeSubagents.get(target.topLevelId);
145
+ if (!item) {
146
+ missed.push(target.display);
147
+ return;
148
+ }
149
+ try {
150
+ const accepted = await item.handle.steer(
151
+ target.restPath.length > 0 ? encodeNestedBroadcast(message, target.restPath) : message,
152
+ );
153
+ if (accepted === false) failed.push(target.display);
154
+ else delivered.push(target.display);
155
+ } catch {
156
+ failed.push(target.display);
157
+ }
158
+ }),
159
+ );
160
+ if (generation !== state.lifecycleGeneration) return;
153
161
  if (delivered.length > 0) {
154
- ctx.ui.notify(`Broadcasted steering message to subagent(s): ${delivered.join(", ")}`, "info");
162
+ ctx.ui.notify(`Sent steering message to subagent(s): ${delivered.join(", ")}`, "info");
155
163
  }
156
164
  if (missed.length > 0) {
157
165
  ctx.ui.notify(`Some selected subagents are no longer running: ${missed.join(", ")}`, "warning");
158
166
  }
167
+ if (failed.length > 0) {
168
+ ctx.ui.notify(`Some selected subagents could not accept steering: ${failed.join(", ")}`, "warning");
169
+ }
159
170
  }
160
171
 
161
- export async function askBroadcastForSteering(
172
+ /** Forward only machine-addressed messages. Ordinary input never selects recipients. */
173
+ export async function forwardNestedBroadcast(
162
174
  state: ExtensionState,
163
- message: string,
175
+ text: string,
164
176
  ctx: SessionContext,
165
- ): Promise<"continue" | "handled"> {
166
- const nested = decodeNestedBroadcast(message);
167
- if (nested) {
168
- if (state.activeSubagents.size === 0) return "handled";
169
- const [rawTarget, ...restPath] = nested.path;
170
- let resolvedId: number | undefined;
171
- for (const [id, item] of state.activeSubagents) {
172
- if ((item.name || item.agent).toLowerCase() === rawTarget.toLowerCase()) {
173
- resolvedId = id;
174
- break;
175
- }
176
- }
177
- if (resolvedId === undefined) return "handled";
178
- sendBroadcastToTargets(
177
+ ): Promise<boolean> {
178
+ const nested = decodeNestedBroadcast(text);
179
+ if (!nested) return false;
180
+ const [rawTarget, ...restPath] = nested.path;
181
+ // Missing targets are dropped rather than becoming prompts for this agent.
182
+ if (!rawTarget) return true;
183
+ for (const [id, item] of state.activeSubagents) {
184
+ if ((item.name || item.agent).toLowerCase() !== rawTarget.toLowerCase()) continue;
185
+ await sendBroadcastToTargets(
179
186
  state,
180
187
  nested.message,
181
- [{ display: nested.path.join(" > "), topLevelId: resolvedId, restPath }],
188
+ [{ display: nested.path.join(" > "), topLevelId: id, restPath }],
182
189
  ctx,
183
190
  );
184
- return "handled";
185
- }
186
-
187
- if (!ctx.hasUI || state.activeSubagents.size === 0) return "continue";
188
-
189
- const choice = await ctx.ui.select("Broadcast this steering message to subagents?", [
190
- "No",
191
- "All (+nested)",
192
- "Youngest",
193
- "Names (e.g. John, Maria)",
194
- ]);
195
- if (choice === "All (+nested)" || choice === "Youngest") {
196
- const fallback = getFallbackTopLevelTargets(state);
197
- const selected =
198
- choice === "Youngest"
199
- ? state.latestBroadcastTargets.youngest.length > 0
200
- ? state.latestBroadcastTargets.youngest
201
- : fallback
202
- : state.latestBroadcastTargets.all.length > 0
203
- ? state.latestBroadcastTargets.all
204
- : fallback;
205
- const current = selected.filter((target) => state.activeSubagents.has(target.topLevelId));
206
- if (current.length === 0) {
207
- ctx.ui.notify("No selected subagents are still running. Continuing with normal steering.", "warning");
208
- return "continue";
209
- }
210
- sendBroadcastToTargets(state, message, current, ctx);
211
- return "handled";
212
- }
213
- if (choice !== "Names (e.g. John, Maria)") return "continue";
214
-
215
- const answer = await ctx.ui.input("Subagent names to broadcast to (comma-separated)", "");
216
- if (!answer) return "continue";
217
- const current =
218
- state.latestBroadcastTargets.all.length > 0 ? state.latestBroadcastTargets.all : getFallbackTopLevelTargets(state);
219
- const parsed = parseBroadcastSelection(answer, current);
220
- const validatedTargets = parsed.targets;
221
- const errors = parsed.errors;
222
- if (errors.length > 0) {
223
- ctx.ui.notify(errors.slice(0, 4).join("\n"), "warning");
191
+ break;
224
192
  }
225
- if (validatedTargets.length === 0) {
226
- ctx.ui.notify("No valid running subagents selected. Continuing with normal steering.", "warning");
227
- return "continue";
228
- }
229
- sendBroadcastToTargets(state, message, validatedTargets, ctx);
230
- return "handled";
193
+ return true;
231
194
  }