@ian-pascoe/pi-minimal-subagents 0.12.0 → 0.13.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
@@ -31,6 +31,20 @@ filter in `~/.pi/agent/settings.json` using the repository-relative path:
31
31
  From this package checkout, load the source directly with
32
32
  `pi -e ./src/index.ts`. Requires Node `>=22.19.0` and Pi `>=0.99.0`.
33
33
 
34
+ ## Typical workflow
35
+
36
+ 1. `subagent` launches a Child Agent from a self-contained task: by default the
37
+ child starts without the parent's conversation. It returns at once with its `agent_id`,
38
+ `turn_id`, and resolved model, thinking level, tools, delegation, and any
39
+ tool-resolution `warnings`. Spawns run sequentially, so a `subagent_wait` or
40
+ `agent_message` in the same tool batch can target the new child.
41
+ 2. `subagent_wait` claims the turn's result, or leave it unclaimed and the final
42
+ response arrives automatically as a steer message.
43
+ 3. `agent_message` continues an idle child: the result reports
44
+ `disposition: "started-turn"` with the new `turn_id` to wait on.
45
+ 4. `subagent_status` inspects children; `subagent_cancel` stops work but keeps
46
+ the session; `subagent_delete` removes it. Deleted IDs cannot be reused.
47
+
34
48
  ## Configuration
35
49
 
36
50
  Configure the extension in Pi's standard settings files:
@@ -240,7 +254,32 @@ and `subagent_status`.
240
254
  Targeted `subagent_status` includes `recent_activity`, a bounded tail of message
241
255
  text, reasoning, tool calls, and tool results. It includes the current streaming
242
256
  assistant message but omits image data. Timeout Wait Events include the same
243
- detailed status snapshot.
257
+ detailed status snapshot. Children target only direct children; the Root Agent
258
+ may inspect any descendant. Model-facing status reports a `child_count` but no
259
+ nested `children` summaries. Reported `usage` always includes `cacheWrite1h`
260
+ and `reasoning`, as `0` when the provider reports none. `subagent_cancel`
261
+ lists in `affected_agent_ids` only agents whose active turns it cancelled.
262
+
263
+ `session_context` defaults to `omit`: the child starts with only its system
264
+ prompt and task, so the task should be a self-contained brief covering the goal,
265
+ target files and non-goals, the change or question, and acceptance criteria.
266
+ Opt in to `inherit` to copy the parent's conversation, or `compact` to summarize
267
+ it first, only when the child needs that discussion. Inheriting is costly: the
268
+ child's system prompt differs from its parent's, so the copied conversation
269
+ cannot reuse the parent's prompt cache, and `compact` adds a summarization call.
270
+ With either opt-in, the parent's conversation is quoted rather than replayed as
271
+ the child's own turns: each parent message becomes one
272
+ `minimal-subagents.parent-context` custom message, sent to the model as
273
+ user-role text wrapped in `<parent_message from="…" role="…">`. Tool calls and
274
+ results become text, a custom message's label names its `customType`, and an
275
+ errored, aborted, or length-limited parent turn is marked as incomplete. Images
276
+ are kept; parent reasoning and the parent's system prompt and tool declarations
277
+ are omitted, since the child declares its own. Each quoted message stays a
278
+ separate session entry, so `compact` can still summarize older entries. The task
279
+ is then framed as a handoff: the quoted conversation is background, its requests
280
+ belonged to the parent, and the child's own assignment follows. Quoting keeps
281
+ the parent's turns distinct from the child's own; it does not guarantee that a
282
+ child, particularly a small model, ignores the quoted requests. Existing Child Agents keep the mode recorded in their Launch Contracts.
244
283
 
245
284
  The `subagent` `tools` argument distinguishes configurable Tool Presets from
246
285
  exact lists; every selection also receives the permitted Base Toolset described
@@ -260,15 +299,18 @@ tools while the Launch Contract continues to record the originally granted
260
299
  capability names.
261
300
 
262
301
  `agent_message` reports whether a message was delivered through an active
263
- parent wait, queued for the recipient, or failed. A failed delivery and a
302
+ parent wait (`delivered-via-wait`), queued into the recipient's active turn
303
+ (`queued`), started a new turn on an idle child (`started-turn`, with its
304
+ `turn_id`), or failed. A failed delivery and a
264
305
  partially failed `subagent_delete` return an error result (`isError: true`) that
265
306
  still carries the declared structured output, so the model sees an error while
266
307
  codemode scripts receive the `failures` or `error` data instead of a data-less
267
308
  rejection. `subagent_wait` can return an
268
309
  intermediate Wait Event containing a Coordination Message before the child turn
269
310
  settles. That event claims only its message, so later unconsumed messages and the
270
- terminal result retain automatic fallback. If the turn has already settled, one
271
- wait returns its terminal result with queued messages in `messages`. Pass
311
+ terminal result retain automatic fallback. If the turn has already settled, a
312
+ wait returns its terminal result with queued messages in `messages`; waiting
313
+ again for the same settled turn returns the same result. Pass
272
314
  optional `turn_id` to address an older retained turn exactly. Without it, waits
273
315
  select the oldest observable claimed or pending turn before the active/latest
274
316
  turn. A caller may have only one outstanding wait for the same source turn; a
@@ -333,6 +375,18 @@ The coordinator tools declare MCP-style `annotations`, which Pi reports through
333
375
 
334
376
  ## Status and TUI
335
377
 
378
+ Coordinator tool calls and results stay readable without expanding. A
379
+ `subagent` call shows the launch settings the caller chose and its task; an
380
+ `agent_message` call shows its message. While `subagent_wait` blocks, it shows
381
+ the child's tool-call count and, on a tree rail, the latest work of the turn
382
+ being waited on, rendered with Pi's own message and tool components as in the
383
+ `/subagents` viewer and refreshed each second; collapsed, the rail keeps the
384
+ newest items within 20 lines. A settled wait shows the child's output as
385
+ Markdown, or its error, with duration, tokens, and cost. Long text previews its
386
+ first 10 lines, like Pi's `read`. Every collapsed result ends its first line
387
+ with Pi's tool-expansion hint (normally Ctrl+O), which reveals the rest and the
388
+ full detail. Automatic agent results and messages preview the same way.
389
+
336
390
  In TUI mode, `/subagents` or `/subagents status` opens a large, centered,
337
391
  framed overlay. Up/Down selects a Child Agent; Enter opens its Child Session
338
392
  Transcript. Escape returns to the tree, then Escape closes the overlay. The
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ian-pascoe/pi-minimal-subagents",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "private": false,
5
5
  "description": "Persistent nested subagents with bounded delegation for Pi",
6
6
  "keywords": [
@@ -75,7 +75,9 @@ export function resolveOrdinaryToolSelection(
75
75
  const ceiling = new Set(context.capabilityCeiling);
76
76
  const exceeded = uniqueRequested.filter((name) => !ceiling.has(name));
77
77
  if (exceeded.length > 0) {
78
- throw new Error(`Minimal subagents capability ceiling exceeded: ${exceeded.join(", ")}`);
78
+ throw new Error(
79
+ `Minimal subagents tool selection: ${exceeded.join(", ")} ${exceeded.length === 1 ? "is" : "are"} unknown or outside the caller's capability ceiling. ${describePermittedTools(excludeCoordinatorTools(context.capabilityCeiling))}`,
80
+ );
79
81
  }
80
82
 
81
83
  const toolsets = context.toolsets ?? DEFAULT_TOOLSETS;
@@ -103,6 +105,15 @@ export function resolveOrdinaryToolSelection(
103
105
  };
104
106
  }
105
107
 
108
+ const PERMITTED_TOOL_LISTING_LIMIT = 40;
109
+
110
+ function describePermittedTools(permitted: readonly string[]): string {
111
+ if (permitted.length === 0) return "No ordinary tools are permitted.";
112
+ const listed = permitted.slice(0, PERMITTED_TOOL_LISTING_LIMIT).join(", ");
113
+ const remaining = permitted.length - PERMITTED_TOOL_LISTING_LIMIT;
114
+ return `Permitted ordinary tools: ${listed}${remaining > 0 ? `, and ${remaining} more` : ""}.`;
115
+ }
116
+
106
117
  /** Return an agent's hierarchy depth where the interactive root is depth zero. */
107
118
  export function getSubagentDepth(agentId: string): number {
108
119
  if (agentId === "root") return 0;
@@ -1,7 +1,13 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
- import { contentText, type ImageContent, type TextContent } from "@earendil-works/pi-ai";
2
+ import {
3
+ contentText,
4
+ type AssistantMessage,
5
+ type ImageContent,
6
+ type TextContent,
7
+ } from "@earendil-works/pi-ai";
3
8
  import { truncateTail } from "@earendil-works/pi-coding-agent";
4
9
  import type {
10
+ ActiveTurnProgress,
5
11
  ChildAgentTranscriptSnapshot,
6
12
  RecentAgentActivity,
7
13
  SessionContextMode,
@@ -141,19 +147,189 @@ export function buildRecentAgentActivity(messages: readonly AgentMessage[]): Rec
141
147
  return activity.slice(-RECENT_AGENT_ACTIVITY_LIMIT);
142
148
  }
143
149
 
150
+ /** A message the child produced during the turn, as opposed to the turn's prompt or coordination input. */
151
+ function isTurnWork(message: AgentMessage, turnStartedAtMs: number): boolean {
152
+ return (
153
+ message.timestamp >= turnStartedAtMs &&
154
+ (message.role === "assistant" || message.role === "toolResult")
155
+ );
156
+ }
157
+
158
+ /** Count the tool calls a running turn has made so far. */
159
+ export function buildActiveTurnProgress(
160
+ messages: readonly AgentMessage[],
161
+ turnStartedAtMs: number,
162
+ ): Omit<ActiveTurnProgress, "turn_id"> {
163
+ let toolCalls = 0;
164
+ for (const message of messages) {
165
+ if (message.role !== "assistant" || !isTurnWork(message, turnStartedAtMs)) continue;
166
+ toolCalls += message.content.filter((content) => content.type === "toolCall").length;
167
+ }
168
+ return { tool_calls: toolCalls };
169
+ }
170
+
171
+ /**
172
+ * Keep the running turn's last `assistantMessageCount` assistant messages and the tool results after
173
+ * them, so a live view renders recent work without the turn's earlier history.
174
+ */
175
+ export function selectActiveTurnTranscript(
176
+ snapshot: ChildAgentTranscriptSnapshot,
177
+ turnStartedAtMs: number,
178
+ assistantMessageCount: number,
179
+ ): ChildAgentTranscriptSnapshot {
180
+ const work = snapshot.messages.flatMap((message, index) =>
181
+ isTurnWork(message, turnStartedAtMs) ? [{ message, index }] : [],
182
+ );
183
+ const assistantPositions = work.flatMap((entry, position) =>
184
+ entry.message.role === "assistant" ? [position] : [],
185
+ );
186
+ const tail = work.slice(assistantPositions.at(-assistantMessageCount) ?? 0);
187
+ const streamingPosition = tail.findIndex(
188
+ (entry) => entry.index === snapshot.streamingAssistantIndex,
189
+ );
190
+ return {
191
+ messages: tail.map((entry) => entry.message),
192
+ streamingAssistantIndex: streamingPosition >= 0 ? streamingPosition : undefined,
193
+ toolDefinitions: snapshot.toolDefinitions,
194
+ };
195
+ }
196
+
144
197
  /** Carries the selected caller messages and whether child preparation should compact them. */
145
198
  export interface ImportedSubagentContext {
146
199
  messages: AgentMessage[];
147
200
  compact: boolean;
148
201
  }
149
202
 
150
- /** Select the imported message snapshot and defer expensive compact preparation to the child turn. */
203
+ /** Custom message type carrying one quoted message from a parent's conversation. */
204
+ export const PARENT_CONTEXT_MESSAGE_TYPE = "minimal-subagents.parent-context";
205
+
206
+ type QuotedContent = TextContent | ImageContent;
207
+
208
+ function quotedParts(content: string | QuotedContent[]): QuotedContent[] {
209
+ if (Array.isArray(content)) return content.map((part) => structuredClone(part));
210
+ return content ? [{ type: "text", text: content }] : [];
211
+ }
212
+
213
+ function parentMessageBody(
214
+ message: AgentMessage,
215
+ ): { label: string; parts: QuotedContent[] } | undefined {
216
+ switch (message.role) {
217
+ case "user":
218
+ return { label: "user", parts: quotedParts(message.content) };
219
+ case "assistant": {
220
+ // Reasoning is omitted: it is model-private and often signature-bound to the parent's model.
221
+ const parts = message.content.flatMap((content): QuotedContent[] => {
222
+ if (content.type === "text")
223
+ return content.text ? [{ type: "text", text: content.text }] : [];
224
+ if (content.type === "toolCall") {
225
+ return [
226
+ {
227
+ type: "text",
228
+ text: `[tool call ${content.name}] ${JSON.stringify(content.arguments)}`,
229
+ },
230
+ ];
231
+ }
232
+ return [];
233
+ });
234
+ const stopNote = incompleteAssistantNote(message.stopReason, message.errorMessage);
235
+ if (stopNote) parts.push({ type: "text", text: stopNote });
236
+ return { label: "assistant", parts };
237
+ }
238
+ case "toolResult":
239
+ return {
240
+ label: `tool result ${message.toolName}${message.isError ? " (error)" : ""}`,
241
+ parts: quotedParts(message.content),
242
+ };
243
+ case "custom":
244
+ return {
245
+ label: `context message: ${message.customType}`,
246
+ parts: quotedParts(message.content),
247
+ };
248
+ case "bashExecution":
249
+ if (message.excludeFromContext) return undefined;
250
+ return {
251
+ label: "shell command",
252
+ parts: [{ type: "text", text: `$ ${message.command}\n${message.output || "(no output)"}` }],
253
+ };
254
+ case "branchSummary":
255
+ case "compactionSummary":
256
+ return {
257
+ label: message.role === "branchSummary" ? "branch summary" : "compaction summary",
258
+ parts: quotedParts(message.summary),
259
+ };
260
+ case "system":
261
+ // The parent's prompt sections and tool declarations describe the parent, not the child,
262
+ // which declares its own prompt and tools on its first request.
263
+ return undefined;
264
+ default: {
265
+ // Fails typecheck when Pi adds a message role, so new roles are quoted deliberately.
266
+ const unhandled: never = message;
267
+ return unhandled;
268
+ }
269
+ }
270
+ }
271
+
272
+ /** Mark a parent turn that ended early, so quoted partial output does not read as complete. */
273
+ function incompleteAssistantNote(
274
+ stopReason: AssistantMessage["stopReason"],
275
+ errorMessage: string | undefined,
276
+ ): string | undefined {
277
+ if (stopReason === "error") return `[turn failed: ${errorMessage ?? "unknown error"}]`;
278
+ if (stopReason === "aborted") return "[turn aborted before completion]";
279
+ if (stopReason === "length") return "[turn stopped at the output length limit]";
280
+ return undefined;
281
+ }
282
+
283
+ /**
284
+ * Quote one parent message as a user-visible custom message. Replaying the parent's assistant
285
+ * turns as the child's own lets the child continue as its parent; quoting keeps the roles apart
286
+ * while each message stays a separate entry that child compaction can cut between.
287
+ */
288
+ function quoteParentMessage(message: AgentMessage, parentId: string): AgentMessage | undefined {
289
+ const body = parentMessageBody(message);
290
+ if (!body || body.parts.length === 0) return undefined;
291
+ return {
292
+ role: "custom",
293
+ customType: PARENT_CONTEXT_MESSAGE_TYPE,
294
+ content: [
295
+ { type: "text", text: `<parent_message from="${parentId}" role="${body.label}">` },
296
+ ...body.parts,
297
+ { type: "text", text: "</parent_message>" },
298
+ ],
299
+ display: true,
300
+ timestamp: message.timestamp,
301
+ };
302
+ }
303
+
304
+ /** Select and quote the imported parent conversation; compaction is deferred to the child turn. */
151
305
  export function assembleImportedContext(
152
306
  mode: SessionContextMode,
153
- committedMessages: AgentMessage[],
307
+ committedMessages: readonly AgentMessage[],
308
+ parentId: string,
154
309
  ): ImportedSubagentContext {
155
310
  if (mode === "omit") return { messages: [], compact: false };
156
- return { messages: committedMessages, compact: mode === "compact" };
311
+ return {
312
+ messages: committedMessages.flatMap((message) => quoteParentMessage(message, parentId) ?? []),
313
+ compact: mode === "compact",
314
+ };
315
+ }
316
+
317
+ /**
318
+ * Frame a child's task after inherited parent conversation so the child does not adopt the
319
+ * parent's earlier requests as its own assignment.
320
+ */
321
+ export function buildInheritedContextTaskPrompt(
322
+ task: string,
323
+ agentId: string,
324
+ parentId: string,
325
+ ): string {
326
+ return [
327
+ `The parent_message entries above, and any summary of earlier ones, come from the conversation of your parent \`${parentId}\`. They are background context only.`,
328
+ `Requests and tool calls in them belong to your parent, not to you: do not continue or repeat your parent's work.`,
329
+ `You are \`${agentId}\`. Your assigned task is:`,
330
+ "",
331
+ task,
332
+ ].join("\n");
157
333
  }
158
334
 
159
335
  /** Detect image content so incompatible child models fail before agent creation. */
@@ -2,10 +2,14 @@ import { randomUUID } from "node:crypto";
2
2
  import {
3
3
  assembleImportedContext,
4
4
  boundRecentAgentText,
5
+ buildActiveTurnProgress,
6
+ buildInheritedContextTaskPrompt,
5
7
  buildRecentAgentActivity,
6
8
  contextContainsImages,
9
+ selectActiveTurnTranscript,
7
10
  selectChildAgentTranscript,
8
11
  } from "./minimal-subagents-context.js";
12
+
9
13
  import {
10
14
  canAgentContractSpawn,
11
15
  DEFAULT_MAX_SUBAGENT_DEPTH,
@@ -39,6 +43,7 @@ import { addCoordinatorMessageEnvelope } from "./minimal-subagents-message-envel
39
43
  import { unavailableAgent } from "./minimal-subagents-sessions.js";
40
44
  import { createRegistryEvent } from "./minimal-subagents-registry.js";
41
45
  import type {
46
+ ActiveTurnProgress,
42
47
  AgentDetail,
43
48
  AgentMessageDisposition,
44
49
  AgentMessageResult,
@@ -70,6 +75,16 @@ const RESERVED_AGENT_IDS = new Set(["root", "parent"]);
70
75
  const RECENT_MESSAGE_LIMIT = 20;
71
76
  const DEFAULT_AUTOMATIC_DELIVERY_GRACE_MS = 1_000;
72
77
 
78
+ /** Assistant messages a waiting parent's live view renders from the child's running turn. */
79
+ const ACTIVE_TURN_TRANSCRIPT_ASSISTANT_MESSAGES = 3;
80
+
81
+ /** A direct child's running turn as its waiting parent may observe it. */
82
+ interface ObservedActiveTurn {
83
+ turnId: string;
84
+ startedAtMs: number;
85
+ runtime: ChildAgentRuntime;
86
+ }
87
+
73
88
  interface MessageParameters {
74
89
  agent_id?: string;
75
90
  message: string;
@@ -197,13 +212,15 @@ export class MinimalSubagentsCoordinator {
197
212
  this.validateFriendlyId(friendlyId);
198
213
  const agentId = this.buildChildAgentId(callerId, friendlyId);
199
214
  if (this.tombstones.has(agentId)) {
200
- throw new Error(`Minimal subagents agent ID is tombstoned: ${agentId}`);
215
+ throw new Error(
216
+ `Minimal subagents agent ID ${agentId} belonged to a deleted agent and cannot be reused; choose a different agent_id`,
217
+ );
201
218
  }
202
219
  if (this.agents.has(agentId) || this.pendingAgentIds.has(agentId)) {
203
220
  throw new Error(`Minimal subagents duplicate agent ID: ${agentId}`);
204
221
  }
205
222
 
206
- const sessionContext = parameters.session_context ?? "inherit";
223
+ const sessionContext = parameters.session_context ?? "omit";
207
224
  const projectContext = parameters.project_context ?? "inherit";
208
225
  const model = parameters.model ?? caller.model;
209
226
  const requestedThinking = parameters.thinking_level ?? caller.thinkingLevel;
@@ -218,7 +235,7 @@ export class MinimalSubagentsCoordinator {
218
235
  toolsets: this.dependencies.toolsets,
219
236
  });
220
237
  const committedMessages = structuredClone(caller.messages);
221
- const imported = assembleImportedContext(sessionContext, committedMessages);
238
+ const imported = assembleImportedContext(sessionContext, committedMessages, callerId);
222
239
  if (
223
240
  contextContainsImages(imported.messages) &&
224
241
  !this.dependencies.sessions.modelSupportsImages(model)
@@ -296,11 +313,12 @@ export class MinimalSubagentsCoordinator {
296
313
  createRegistryEvent(this.dependencies.registry.rootSessionId, "agent-created", { agent }),
297
314
  );
298
315
  const turnId = this.beginTurn(agent);
299
- if (toolWarnings.length > 0) {
316
+ const warnings = [...new Set(toolWarnings)];
317
+ if (warnings.length > 0) {
300
318
  this.dependencies.notify?.({
301
319
  type: "tool-warning",
302
320
  agentId,
303
- message: `Minimal subagents tool warnings for ${agentId}:\n- ${[...new Set(toolWarnings)].join("\n- ")}`,
321
+ message: `Minimal subagents tool warnings for ${agentId}:\n- ${warnings.join("\n- ")}`,
304
322
  });
305
323
  }
306
324
  this.dependencies.notify?.({
@@ -313,13 +331,25 @@ export class MinimalSubagentsCoordinator {
313
331
  this.initializeAndRunPrompt(
314
332
  agentId,
315
333
  turnId,
316
- parameters.task,
334
+ imported.messages.length > 0
335
+ ? buildInheritedContextTaskPrompt(parameters.task, agentId, callerId)
336
+ : parameters.task,
317
337
  imported.compact,
318
338
  caller.model,
319
339
  caller.thinkingLevel,
320
340
  ),
321
341
  );
322
- return { agent_id: agentId, turn_id: turnId, status: "running" };
342
+ const result: SpawnResult = {
343
+ agent_id: agentId,
344
+ turn_id: turnId,
345
+ status: "running",
346
+ model: agent.launch_contract.model,
347
+ thinking_level: agent.launch_contract.thinking_level,
348
+ tools: [...agent.launch_contract.ordinary_tools],
349
+ delegation: agent.launch_contract.delegation ?? "none",
350
+ };
351
+ if (warnings.length > 0) result.warnings = warnings;
352
+ return result;
323
353
  }
324
354
 
325
355
  /** Capture immutable launch defaults for a nested caller from its active child runtime. */
@@ -365,10 +395,12 @@ export class MinimalSubagentsCoordinator {
365
395
  this.queuePendingParentMessage(targetId, message, delivery);
366
396
  return { agent_id: targetId, message_id: messageId, disposition: "queued" };
367
397
  }
368
- const disposition = await this.enqueueRecipientDelivery(targetId, async () =>
398
+ const { disposition, turnId } = await this.enqueueRecipientDelivery(targetId, async () =>
369
399
  this.deliverExplicitMessage(message, targetId, delivery),
370
400
  );
371
- return { agent_id: targetId, message_id: messageId, disposition };
401
+ const result: AgentMessageResult = { agent_id: targetId, message_id: messageId, disposition };
402
+ if (turnId) result.turn_id = turnId;
403
+ return result;
372
404
  } catch (error) {
373
405
  const deliveryError = error instanceof Error ? error.message : String(error);
374
406
  if (this.isCoordinationDeliveryCurrent(delivery)) {
@@ -423,7 +455,9 @@ export class MinimalSubagentsCoordinator {
423
455
  if (pendingMessage) return Promise.resolve(pendingMessage);
424
456
  if (agent.active_turn_id !== turnId) {
425
457
  return Promise.reject(
426
- new Error(`Minimal subagents wait: turn ${turnId} is no longer retained for ${agentId}`),
458
+ new Error(
459
+ `Minimal subagents wait: turn ${turnId} is unknown or no longer retained for ${agentId}; omit turn_id to wait for its oldest observable turn`,
460
+ ),
427
461
  );
428
462
  }
429
463
 
@@ -460,11 +494,11 @@ export class MinimalSubagentsCoordinator {
460
494
  });
461
495
  }
462
496
 
463
- /** Return direct-child status authorized for one root or child caller. */
497
+ /** Return direct-child status for a child caller; the root may inspect any descendant. */
464
498
  status(callerId: string, agentId?: string): StatusResult {
465
499
  this.assertCallerExists(callerId);
466
500
  if (agentId !== undefined) {
467
- this.assertCallerTargetsDirectChild(callerId, agentId, "status");
501
+ if (callerId !== "root") this.assertCallerTargetsDirectChild(callerId, agentId, "status");
468
502
  return { agent: this.buildAgentDetail(this.requireAgent(agentId), false) };
469
503
  }
470
504
  return {
@@ -482,6 +516,56 @@ export class MinimalSubagentsCoordinator {
482
516
  };
483
517
  }
484
518
 
519
+ /**
520
+ * Find a direct child's running turn for its parent's live wait view. Only the direct parent
521
+ * observes it, and a requested `turnId` must be the active turn.
522
+ */
523
+ private observeActiveTurn(
524
+ callerId: string,
525
+ agentId: string,
526
+ turnId: string | undefined,
527
+ ): ObservedActiveTurn | undefined {
528
+ const agent = this.agents.get(agentId);
529
+ if (!agent || agent.parent_id !== callerId) return undefined;
530
+ const activeTurnId = agent.active_turn_id;
531
+ const startedAt = agent.active_turn_started_at;
532
+ if (!activeTurnId || !startedAt || (turnId !== undefined && turnId !== activeTurnId)) {
533
+ return undefined;
534
+ }
535
+ const runtime = this.runtimes.get(agentId);
536
+ if (!runtime) return undefined;
537
+ return { turnId: activeTurnId, startedAtMs: Date.parse(startedAt), runtime };
538
+ }
539
+
540
+ /** Count a direct child's running-turn tool calls for its waiting parent. */
541
+ previewActiveTurn(
542
+ callerId: string,
543
+ agentId: string,
544
+ turnId?: string,
545
+ ): ActiveTurnProgress | undefined {
546
+ const turn = this.observeActiveTurn(callerId, agentId, turnId);
547
+ if (!turn) return undefined;
548
+ return {
549
+ turn_id: turn.turnId,
550
+ ...buildActiveTurnProgress(turn.runtime.snapshotActivityMessages(), turn.startedAtMs),
551
+ };
552
+ }
553
+
554
+ /** Return a direct child's Active Turn Tail, with its tool definitions, for its waiting parent. */
555
+ inspectActiveTurnTranscript(
556
+ callerId: string,
557
+ agentId: string,
558
+ turnId?: string,
559
+ ): ChildAgentTranscriptSnapshot | undefined {
560
+ const turn = this.observeActiveTurn(callerId, agentId, turnId);
561
+ if (!turn) return undefined;
562
+ return selectActiveTurnTranscript(
563
+ this.inspectTranscript(agentId),
564
+ turn.startedAtMs,
565
+ ACTIVE_TURN_TRANSCRIPT_ASSISTANT_MESSAGES,
566
+ );
567
+ }
568
+
485
569
  /** Lazily inspect one Child Session Transcript without restoring a missing runtime. */
486
570
  inspectTranscript(agentId: string): ChildAgentTranscriptSnapshot {
487
571
  const agent = this.requireAgent(agentId);
@@ -528,15 +612,18 @@ export class MinimalSubagentsCoordinator {
528
612
  this.assertCallerCanManageAgent(callerId, agentId, "cancel");
529
613
  const target = this.requireUsableAgent(agentId, "cancel");
530
614
  const affected = recursive ? [target, ...this.descendantsOf(agentId)] : [target];
615
+ const affectedAgentIds: string[] = [];
531
616
  const cancelledTurnIds: string[] = [];
532
617
  for (const agent of affected) {
533
618
  const cancelledTurnId = await this.cancelActiveTurn(agent);
534
- if (cancelledTurnId) cancelledTurnIds.push(cancelledTurnId);
619
+ if (!cancelledTurnId) continue;
620
+ affectedAgentIds.push(agent.agent_id);
621
+ cancelledTurnIds.push(cancelledTurnId);
535
622
  }
536
623
  return {
537
624
  agent_id: agentId,
538
625
  recursive,
539
- affected_agent_ids: affected.map((agent) => agent.agent_id),
626
+ affected_agent_ids: affectedAgentIds,
540
627
  cancelled_turn_ids: cancelledTurnIds,
541
628
  };
542
629
  }
@@ -1315,24 +1402,27 @@ export class MinimalSubagentsCoordinator {
1315
1402
  message: CoordinatorMessage,
1316
1403
  targetId: string,
1317
1404
  delivery: PersistedCoordinationDelivery,
1318
- ): Promise<AgentMessageDisposition> {
1405
+ ): Promise<{ disposition: AgentMessageDisposition; turnId?: string }> {
1319
1406
  this.waitHandedDeliveryIds.add(delivery.delivery_id);
1320
1407
  try {
1321
- await this.deliverToRecipient(targetId, message, () =>
1408
+ const startedTurnId = await this.deliverToRecipient(targetId, message, () =>
1322
1409
  this.isCoordinationDeliveryCurrent(delivery),
1323
1410
  );
1324
- return "queued";
1411
+ return startedTurnId
1412
+ ? { disposition: "started-turn", turnId: startedTurnId }
1413
+ : { disposition: "queued" };
1325
1414
  } catch (error) {
1326
1415
  this.waitHandedDeliveryIds.delete(delivery.delivery_id);
1327
1416
  throw error;
1328
1417
  }
1329
1418
  }
1330
1419
 
1420
+ /** Deliver one message, returning the turn ID when it starts a new turn on an idle child. */
1331
1421
  private async deliverToRecipient(
1332
1422
  targetId: string,
1333
1423
  message: CoordinatorMessage,
1334
1424
  isCurrentDelivery: () => boolean = () => true,
1335
- ): Promise<void> {
1425
+ ): Promise<string | undefined> {
1336
1426
  if (!isCurrentDelivery()) {
1337
1427
  throw new Error("Minimal subagents delivery abandoned after session branch change");
1338
1428
  }
@@ -1352,7 +1442,7 @@ export class MinimalSubagentsCoordinator {
1352
1442
  const visibleMessage = addCoordinatorMessageEnvelope(message);
1353
1443
  if (target.active_turn_id || runtime.isRunning) {
1354
1444
  await runtime.queueCoordinatorMessage(visibleMessage);
1355
- return;
1445
+ return undefined;
1356
1446
  }
1357
1447
  const turnId = this.beginTurn(target);
1358
1448
  const runMessage = runtime
@@ -1374,6 +1464,7 @@ export class MinimalSubagentsCoordinator {
1374
1464
  }
1375
1465
  });
1376
1466
  this.trackBackgroundOperation(runMessage);
1467
+ return turnId;
1377
1468
  }
1378
1469
 
1379
1470
  private trackBackgroundOperation(operation: Promise<void>): void {
@@ -1527,9 +1618,6 @@ export class MinimalSubagentsCoordinator {
1527
1618
 
1528
1619
  private buildAgentSummary(agent: PersistedAgent, includeDescendants = true): AgentSummary {
1529
1620
  const directChildren = this.childrenOf(agent.agent_id);
1530
- const children = includeDescendants
1531
- ? directChildren.map((child) => this.buildAgentSummary(child))
1532
- : [];
1533
1621
  const elapsed = agent.active_turn_started_at
1534
1622
  ? Math.max(0, this.now().getTime() - new Date(agent.active_turn_started_at).getTime())
1535
1623
  : undefined;
@@ -1538,7 +1626,7 @@ export class MinimalSubagentsCoordinator {
1538
1626
  model: agent.launch_contract.model,
1539
1627
  thinking_level: agent.launch_contract.thinking_level,
1540
1628
  };
1541
- return {
1629
+ const summary: AgentSummary = {
1542
1630
  agent_id: agent.agent_id,
1543
1631
  parent_id: agent.parent_id,
1544
1632
  state: agent.active_turn_id ? "running" : "idle",
@@ -1553,8 +1641,11 @@ export class MinimalSubagentsCoordinator {
1553
1641
  latest_activity_at: agent.latest_activity_at ?? agent.created_at,
1554
1642
  task: agent.task,
1555
1643
  child_count: directChildren.length,
1556
- children,
1557
1644
  };
1645
+ if (includeDescendants) {
1646
+ summary.children = directChildren.map((child) => this.buildAgentSummary(child));
1647
+ }
1648
+ return summary;
1558
1649
  }
1559
1650
 
1560
1651
  private buildAgentDetail(agent: PersistedAgent, includeDescendants = true): AgentDetail {
@@ -505,6 +505,9 @@ export class MinimalSubagentsLifecycleController {
505
505
  private readonly coordinatorOperations: CoordinatorToolOperations = {
506
506
  spawn: (...args) => this.requireCoordinator().spawn(...args),
507
507
  inspectStatus: (...args) => this.requireCoordinator().inspectStatus(...args),
508
+ previewActiveTurn: (...args) => this.requireCoordinator().previewActiveTurn(...args),
509
+ inspectActiveTurnTranscript: (...args) =>
510
+ this.requireCoordinator().inspectActiveTurnTranscript(...args),
508
511
  sendAgentMessage: (...args) => this.requireCoordinator().sendAgentMessage(...args),
509
512
  wait: (...args) => this.requireCoordinator().wait(...args),
510
513
  status: (...args) => this.requireCoordinator().status(...args),
@@ -1,6 +1,7 @@
1
1
  import type { JsonValue } from "@earendil-works/pi-ai";
2
2
  import { Value } from "typebox/value";
3
3
  import { COORDINATOR_TOOL_NAMES } from "./minimal-subagents-capabilities.js";
4
+ import { normalizeMinimalSubagentsUsage } from "./minimal-subagents-usage.js";
4
5
  import {
5
6
  createDeliveryLedger,
6
7
  deliveryLedgerSnapshot,
@@ -280,7 +281,8 @@ function cloneRegistryTurnResult(value: RegistryTurnResultWire): TurnResult {
280
281
  output: value.output,
281
282
  };
282
283
  if (value.error !== undefined) result.error = value.error;
283
- if (value.usage !== undefined) result.usage = structuredClone(value.usage);
284
+ // Records from older versions may lack optional usage counters.
285
+ if (value.usage !== undefined) result.usage = normalizeMinimalSubagentsUsage(value.usage);
284
286
  if (value.elapsed_ms !== undefined) result.elapsed_ms = value.elapsed_ms;
285
287
  return result;
286
288
  }