@introspection-ai/recipes 0.63.1 → 0.65.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 (147) hide show
  1. package/dist/agent-tool/arguments.d.ts +39 -0
  2. package/dist/agent-tool/arguments.d.ts.map +1 -0
  3. package/dist/agent-tool/arguments.generated.d.ts +4 -0
  4. package/dist/agent-tool/arguments.generated.d.ts.map +1 -0
  5. package/dist/agent-tool/arguments.generated.js +60 -0
  6. package/dist/agent-tool/arguments.generated.js.map +1 -0
  7. package/dist/agent-tool/arguments.js +8 -0
  8. package/dist/agent-tool/arguments.js.map +1 -0
  9. package/dist/agents.d.ts +28 -6
  10. package/dist/agents.d.ts.map +1 -1
  11. package/dist/agents.js +280 -47
  12. package/dist/agents.js.map +1 -1
  13. package/dist/api-bindings.d.ts.map +1 -1
  14. package/dist/api-bindings.js +2 -2
  15. package/dist/api-bindings.js.map +1 -1
  16. package/dist/artifact-review-tui.js +1 -1
  17. package/dist/artifact-review-tui.js.map +1 -1
  18. package/dist/artifact-viewer-tui.js +1 -1
  19. package/dist/artifact-viewer-tui.js.map +1 -1
  20. package/dist/artifact-viewer.d.ts.map +1 -1
  21. package/dist/artifact-viewer.js +3 -3
  22. package/dist/artifact-viewer.js.map +1 -1
  23. package/dist/batch/agent-batches.d.ts +53 -0
  24. package/dist/batch/agent-batches.d.ts.map +1 -0
  25. package/dist/batch/agent-batches.js +168 -0
  26. package/dist/batch/agent-batches.js.map +1 -0
  27. package/dist/batch/index.d.ts +2 -0
  28. package/dist/batch/index.d.ts.map +1 -1
  29. package/dist/batch/index.js +2 -1
  30. package/dist/batch/index.js.map +1 -1
  31. package/dist/batch/lines.d.ts.map +1 -1
  32. package/dist/batch/lines.js +4 -2
  33. package/dist/batch/lines.js.map +1 -1
  34. package/dist/child/agent-completions.d.ts +16 -1
  35. package/dist/child/agent-completions.d.ts.map +1 -1
  36. package/dist/child/agent-completions.js +31 -5
  37. package/dist/child/agent-completions.js.map +1 -1
  38. package/dist/child/agent-store.d.ts +2 -0
  39. package/dist/child/agent-store.d.ts.map +1 -1
  40. package/dist/child/agent-store.js.map +1 -1
  41. package/dist/child/agent.d.ts +9 -0
  42. package/dist/child/agent.d.ts.map +1 -1
  43. package/dist/child/agent.js +7 -0
  44. package/dist/child/agent.js.map +1 -1
  45. package/dist/child/arguments.d.ts +32 -0
  46. package/dist/child/arguments.d.ts.map +1 -0
  47. package/dist/child/arguments.generated.d.ts +4 -0
  48. package/dist/child/arguments.generated.d.ts.map +1 -0
  49. package/dist/child/arguments.generated.js +29 -0
  50. package/dist/child/arguments.generated.js.map +1 -0
  51. package/dist/child/arguments.js +8 -0
  52. package/dist/child/arguments.js.map +1 -0
  53. package/dist/child/inboxes.d.ts +21 -0
  54. package/dist/child/inboxes.d.ts.map +1 -0
  55. package/dist/child/inboxes.js +35 -0
  56. package/dist/child/inboxes.js.map +1 -0
  57. package/dist/child/messages.d.ts +202 -0
  58. package/dist/child/messages.d.ts.map +1 -0
  59. package/dist/child/messages.js +490 -0
  60. package/dist/child/messages.js.map +1 -0
  61. package/dist/child/run-processes.d.ts +14 -0
  62. package/dist/child/run-processes.d.ts.map +1 -0
  63. package/dist/child/run-processes.js +101 -0
  64. package/dist/child/run-processes.js.map +1 -0
  65. package/dist/child/session.d.ts +10 -0
  66. package/dist/child/session.d.ts.map +1 -1
  67. package/dist/child/session.js +34 -3
  68. package/dist/child/session.js.map +1 -1
  69. package/dist/child/streaming-usage.d.ts +40 -0
  70. package/dist/child/streaming-usage.d.ts.map +1 -0
  71. package/dist/child/streaming-usage.js +101 -0
  72. package/dist/child/streaming-usage.js.map +1 -0
  73. package/dist/documents/python.d.ts.map +1 -1
  74. package/dist/documents/python.js +2 -2
  75. package/dist/documents/python.js.map +1 -1
  76. package/dist/judges/cli-main.d.ts.map +1 -1
  77. package/dist/judges/cli-main.js +1 -1
  78. package/dist/judges/cli-main.js.map +1 -1
  79. package/dist/judges/run.d.ts.map +1 -1
  80. package/dist/judges/run.js +6 -2
  81. package/dist/judges/run.js.map +1 -1
  82. package/dist/judges/verdict.d.ts.map +1 -1
  83. package/dist/judges/verdict.js +1 -1
  84. package/dist/judges/verdict.js.map +1 -1
  85. package/dist/mcp/contract.d.ts.map +1 -1
  86. package/dist/mcp/contract.js +1 -3
  87. package/dist/mcp/contract.js.map +1 -1
  88. package/dist/mcp/daemon/client.d.ts.map +1 -1
  89. package/dist/mcp/daemon/client.js +1 -2
  90. package/dist/mcp/daemon/client.js.map +1 -1
  91. package/dist/mcp/pi-mcp-runtime.js +2 -2
  92. package/dist/mcp/pi-mcp-runtime.js.map +1 -1
  93. package/dist/mcp/pi-runtime.d.ts +3 -3
  94. package/dist/mcp/pi-runtime.d.ts.map +1 -1
  95. package/dist/mcp/pi-runtime.js +11 -20
  96. package/dist/mcp/pi-runtime.js.map +1 -1
  97. package/dist/mcp/tools.d.ts.map +1 -1
  98. package/dist/mcp/tools.js +1 -1
  99. package/dist/mcp/tools.js.map +1 -1
  100. package/dist/mcp-chunks/{chunk-OHAXEQ22.js → chunk-N6QLCGHR.js} +2 -2
  101. package/dist/mcp-chunks/{chunk-3UONQ24E.js → chunk-WVHEDCS6.js} +6 -4
  102. package/dist/mcp-chunks/chunk-ZH6FNTNJ.js +34 -0
  103. package/dist/mcp-chunks/{pi-mcp-runtime-V2OMZAIR.js → pi-mcp-runtime-W5OLELOO.js} +34 -27
  104. package/dist/mcp-chunks/{server-6DQUPUFW.js → server-UZ5OMTWP.js} +3 -3
  105. package/dist/mcp-daemon.js +3 -3
  106. package/dist/mcp-run-worker.js +2 -2
  107. package/dist/pi-extension.d.ts +2 -0
  108. package/dist/pi-extension.d.ts.map +1 -1
  109. package/dist/pi-extension.js +241 -43
  110. package/dist/pi-extension.js.map +1 -1
  111. package/dist/recipe/manifest.generated.d.ts +1 -1
  112. package/dist/recipe/manifest.generated.js +1 -1
  113. package/dist/recipe/package.d.ts +2 -0
  114. package/dist/recipe/package.d.ts.map +1 -1
  115. package/dist/recipe/package.js +15 -21
  116. package/dist/recipe/package.js.map +1 -1
  117. package/dist/recipe/python.d.ts.map +1 -1
  118. package/dist/recipe/python.js +8 -5
  119. package/dist/recipe/python.js.map +1 -1
  120. package/dist/run-controller.d.ts +5 -0
  121. package/dist/run-controller.d.ts.map +1 -1
  122. package/dist/run-controller.js +89 -12
  123. package/dist/run-controller.js.map +1 -1
  124. package/dist/session.d.ts +14 -0
  125. package/dist/session.d.ts.map +1 -1
  126. package/dist/session.js +21 -3
  127. package/dist/session.js.map +1 -1
  128. package/dist/shell-quote.d.ts +3 -0
  129. package/dist/shell-quote.d.ts.map +1 -0
  130. package/dist/shell-quote.js +5 -0
  131. package/dist/shell-quote.js.map +1 -0
  132. package/dist/skill-progress.d.ts +12 -1
  133. package/dist/skill-progress.d.ts.map +1 -1
  134. package/dist/skill-progress.js +11 -4
  135. package/dist/skill-progress.js.map +1 -1
  136. package/docs/agent-batch.md +87 -0
  137. package/docs/agent-composition.md +49 -19
  138. package/docs/batch.md +7 -0
  139. package/docs/documents/README.md +1 -1
  140. package/docs/mcp-auth.md +2 -1
  141. package/docs/mcp-configuration.md +2 -3
  142. package/docs/productivity/google.md +27 -15
  143. package/docs/recipe-format.md +4 -4
  144. package/package.json +15 -14
  145. package/python/shared/pyproject.toml +2 -2
  146. package/python/shared/uv.lock +30 -30
  147. package/dist/mcp-chunks/chunk-V65N6VX7.js +0 -33
@@ -2,18 +2,24 @@ import { registerSkillProgress, skillFolders, } from "./skill-progress.js";
2
2
  import { RECIPE_SESSION_ENTRY_TYPE, recipeSessionChanged, } from "./recipe-session-entry.js";
3
3
  import { loadMemoryIndex } from "./memory.js";
4
4
  import { registerMemoryContext } from "./memory-context.js";
5
+ import { DEFAULT_SUBAGENT_CONCURRENCY } from "./run-controller.js";
6
+ import { createAgentBatches, } from "./batch/agent-batches.js";
7
+ import { runBatch } from "./batch/index.js";
5
8
  import { existsSync } from "node:fs";
6
9
  import { rm } from "node:fs/promises";
7
10
  import { basename, resolve } from "node:path";
8
11
  import { createCodemodeExtension, } from "@earendil-works/pi-coding-agent";
9
- import { Text } from "@earendil-works/pi-tui";
12
+ import { createRootInbox, createRunnerInbox } from "./child/inboxes.js";
13
+ import { Text, truncateToWidth } from "@earendil-works/pi-tui";
10
14
  import { createRecipeChildAgentRunner, promptResultText, } from "./child/agent.js";
11
15
  import { registerGenAiSpansFile } from "./genai-spans-file.js";
12
16
  import { loadRecipeExtensionFactory } from "./recipe/extensions.js";
13
17
  import { bindRecipeExtensionFactory, createRecipeExtensionSessionContext, createRecipeExtensionRegistrationRegistry, } from "./extensions.js";
14
18
  import { ChildAgentRunStore, } from "./child/agent-store.js";
15
- import { ChildCompletionQueue, envelopeFromRun, renderCompletionNotice, usageText, } from "./child/agent-completions.js";
16
- import { AGENT_RUN_EVENT_ENTRY_TYPE, compactTokens, notifyAgentRunEvent, persistsAgentRunEvent, runProgress, } from "./agents.js";
19
+ import { ChildCompletionQueue, costText, envelopeFromRun, renderCompletionNotice, tokenText, usageText, } from "./child/agent-completions.js";
20
+ import { AGENT_RUN_MESSAGE_TYPE, AgentMessageBus, renderAgentMessages, ROOT_AGENT, } from "./child/messages.js";
21
+ import { AGENT_RUN_EVENT_ENTRY_TYPE, notifyAgentRunEvent, persistsAgentRunEvent, agentLine, runProgress, toolActivity, } from "./agents.js";
22
+ import { applyStreamingEvent, liveUsage, } from "./child/streaming-usage.js";
17
23
  import { clearMcpSession, clearSessionMcpCli, configureMcpLocalConfigPath, createIsolatedMcpEnvironment, endpointBindings, formatMcpConfigurationDiagnostics, materializeMcpSession, materializeSessionMcpCli, resolveAgentMcpSelections, resolveMcpSessionServers, stopMcpDaemon, } from "./mcp/index.js";
18
24
  import { mcpServersBehindTools } from "./mcp/policy.js";
19
25
  import { clearMcpCatalogPreload, preloadMcpCatalogs } from "./mcp/catalog.js";
@@ -249,6 +255,35 @@ function snapshotOf(run) {
249
255
  error: run.error,
250
256
  toolCalls: run.toolCalls.map((call) => ({ ...call })),
251
257
  ...(run.usage ? { usage: { ...run.usage } } : {}),
258
+ ...(run.pricing ? { pricing: { ...run.pricing } } : {}),
259
+ };
260
+ }
261
+ /** Folds how one assistant message's model is paid for into its run's pricing. */
262
+ function notePricing(run, event, registry) {
263
+ const record = asRecord(event);
264
+ if (record?.type !== "message_start" && record?.type !== "message_end")
265
+ return;
266
+ const message = asRecord(record.message);
267
+ if (message?.role !== "assistant" ||
268
+ typeof message.provider !== "string" ||
269
+ typeof message.model !== "string")
270
+ return;
271
+ const model = registry.find(message.provider, message.model);
272
+ const price = model?.cost;
273
+ const pricing = {
274
+ subscription: model !== undefined && registry.isUsingOAuth(model),
275
+ priced: price !== undefined &&
276
+ [price.input, price.output, price.cacheRead, price.cacheWrite].some((rate) => typeof rate === "number" && rate > 0),
277
+ };
278
+ run.pricing = mergePricing(run.pricing, pricing);
279
+ }
280
+ /** Several runs' pricing: a subscription only if every one is, priced if any one is. */
281
+ function mergePricing(a, b) {
282
+ if (!a || !b)
283
+ return a ?? b;
284
+ return {
285
+ subscription: a.subscription && b.subscription,
286
+ priced: a.priced || b.priced,
252
287
  };
253
288
  }
254
289
  /** Adds an assistant message's usage, from a child's `message_end` event, to its run's. */
@@ -277,16 +312,29 @@ function addMessageUsage(run, event) {
277
312
  };
278
313
  return true;
279
314
  }
315
+ /** Applies a streaming event to the state of the run that streams it. */
316
+ function streamFor(run, streamId, event) {
317
+ let state = run.streaming.get(streamId);
318
+ if (!state) {
319
+ state = {};
320
+ run.streaming.set(streamId, state);
321
+ }
322
+ return applyStreamingEvent(state, event);
323
+ }
280
324
  function controllerSummary(run, status = run.status) {
325
+ const streaming = run.streaming;
281
326
  const startedAt = Date.parse(run.startedAt);
282
327
  const completedAt = run.completedAt ? Date.parse(run.completedAt) : undefined;
283
- const currentTool = [...run.toolCalls]
328
+ const running = [...run.toolCalls]
284
329
  .reverse()
285
- .find((call) => call.status === "running")?.name;
330
+ .find((call) => call.status === "running");
331
+ const currentActivity = running && toolActivity(running.name, running.args);
332
+ const usage = liveUsage(run.usage, streaming?.values() ?? []);
286
333
  return {
287
334
  agent_run_id: run.id,
288
335
  invocation_name: run.agent,
289
336
  agent_name: run.agent,
337
+ ...(run.queued ? { queued: true } : {}),
290
338
  label: run.label ?? run.agent,
291
339
  prompt: run.prompt,
292
340
  status,
@@ -299,7 +347,11 @@ function controllerSummary(run, status = run.status) {
299
347
  : Number.isFinite(startedAt)
300
348
  ? startedAt
301
349
  : Date.now(),
302
- ...(currentTool ? { current_tool: currentTool } : {}),
350
+ ...(running
351
+ ? { current_tool: running.name, current_activity: currentActivity }
352
+ : {}),
353
+ ...(run.statusNote ? { status_text: run.statusNote.text } : {}),
354
+ ...(run.statusNote?.usage ? { reported_usage: run.statusNote.usage } : {}),
303
355
  nested_tools: run.toolCalls.map((call) => ({
304
356
  toolName: call.name,
305
357
  verb: call.name,
@@ -309,14 +361,15 @@ function controllerSummary(run, status = run.status) {
309
361
  output_preview: run.output,
310
362
  output: run.output,
311
363
  error: run.error,
312
- ...(run.usage
364
+ ...(usage
313
365
  ? {
314
366
  usage: {
315
- input_tokens: run.usage.input,
316
- output_tokens: run.usage.output,
317
- cache_read_tokens: run.usage.cacheRead,
318
- cache_write_tokens: run.usage.cacheWrite,
319
- cost_usd: run.usage.cost,
367
+ input_tokens: usage.input,
368
+ output_tokens: usage.output,
369
+ cache_read_tokens: usage.cacheRead,
370
+ cache_write_tokens: usage.cacheWrite,
371
+ cost_usd: usage.cost,
372
+ ...(run.pricing ? { pricing: run.pricing } : {}),
320
373
  },
321
374
  }
322
375
  : {}),
@@ -419,8 +472,55 @@ export function createRecipesExtension(opts = {}) {
419
472
  let lastLaunchErrorKey = null;
420
473
  let childRunIndex = 0;
421
474
  const childRuns = new Map();
475
+ // Labels a batch is about to start a row under: the run started under one is the batch's.
476
+ const quietLabels = new Set();
477
+ let agentBatches;
478
+ const subagentConcurrency = Math.max(1, opts.subagentConcurrency ?? DEFAULT_SUBAGENT_CONCURRENCY);
479
+ let activeChildren = 0;
480
+ const waitingChildren = [];
481
+ /** A slot for `run`, at once or once a running run ends; false when it left the queue without one. */
482
+ const takeChildSlot = (run) => {
483
+ if (activeChildren < subagentConcurrency) {
484
+ activeChildren += 1;
485
+ return Promise.resolve(true);
486
+ }
487
+ run.queued = true;
488
+ return new Promise((resolve) => waitingChildren.push({ run, resolve }));
489
+ };
490
+ const freeChildSlot = () => {
491
+ const next = waitingChildren.shift();
492
+ if (!next) {
493
+ activeChildren -= 1;
494
+ return;
495
+ }
496
+ next.run.queued = false;
497
+ next.resolve(true);
498
+ };
499
+ const leaveChildQueue = (run) => {
500
+ const index = waitingChildren.findIndex((waiting) => waiting.run === run);
501
+ if (index < 0)
502
+ return;
503
+ const [waiting] = waitingChildren.splice(index, 1);
504
+ run.queued = false;
505
+ waiting.resolve(false);
506
+ };
507
+ // The session's agents by name, for `send_message`. Root takes a message in
508
+ // its current wait, or as a steer or follow-up, starting a turn when idle.
509
+ const messages = new AgentMessageBus();
510
+ let deliverToRoot;
511
+ const root = createRootInbox({
512
+ api: () => extensionApi ?? undefined,
513
+ session: () => sessionCtx,
514
+ onHeld: () => deliverToRoot?.(),
515
+ });
516
+ const rootInbox = root.inbox;
517
+ messages.register({
518
+ id: ROOT_AGENT,
519
+ name: ROOT_AGENT,
520
+ inbox: rootInbox,
521
+ accepting: () => true,
522
+ });
422
523
  // Usage of runs already closed: closing a run removes it from childRuns, not its cost.
423
- const closedUsage = { output: 0, cost: 0 };
424
524
  let releaseApiBindings;
425
525
  // Runs restored from a previous Pi process via rehydrateChildRuns(). They
426
526
  // have no live runner: readable (status/wait) but not controllable.
@@ -436,7 +536,7 @@ export function createRecipesExtension(opts = {}) {
436
536
  let agentsWidgetTimer;
437
537
  // Re-reports the step when the running count moves; set once the footer is registered.
438
538
  let refreshAgentStep;
439
- const runningAgents = () => [...childRuns.values()].filter((run) => run.status === "running").length;
539
+ const runningAgents = () => [...childRuns.values()].filter((run) => run.status === "running" && !run.queued).length;
440
540
  const renderAgentsWidget = () => {
441
541
  refreshAgentStep?.();
442
542
  const ctx = localAgentContext;
@@ -449,27 +549,28 @@ export function createRecipesExtension(opts = {}) {
449
549
  return;
450
550
  ctx.ui.setWidget(AGENTS_WIDGET_KEY, running.length === 0
451
551
  ? undefined
452
- : running.map((run) => {
453
- const summary = controllerSummary(run);
454
- const label = summary.label && summary.label !== summary.agent_name
455
- ? ` (${summary.label})`
456
- : "";
457
- return `▸ ${summary.agent_name}${label} · ${runProgress(summary)}`;
552
+ : () => ({
553
+ render: (width) => running.map((run) => truncateToWidth(agentLine(controllerSummary(run)), width)),
554
+ invalidate: () => { },
458
555
  }), { placement: "belowEditor" });
459
556
  };
460
- /** `4 agents · ↓ 4.1k · $0.45`: how many run now, and every run's usage this session. */
557
+ /** `2 agents · ↓ 4.1k · $0.450 (sub)`: the runs in progress and their usage so far; nothing once none runs. */
461
558
  const agentsSummary = () => {
462
- const runs = [...childRuns.values()];
463
- const running = runningAgents();
464
- const output = runs.reduce((sum, run) => sum + (run.usage?.output ?? 0), closedUsage.output);
465
- const cost = runs.reduce((sum, run) => sum + (run.usage?.cost ?? 0), closedUsage.cost);
466
- const parts = [
467
- ...(running > 0 ? [`${running} agent${running === 1 ? "" : "s"}`] : []),
559
+ const runs = [...childRuns.values()].filter((run) => run.status === "running");
560
+ if (runs.length === 0)
561
+ return undefined;
562
+ const usages = runs.map((run) => liveUsage(run.usage, run.streaming.values()));
563
+ const input = usages.reduce((sum, usage) => sum + (usage?.input ?? 0), 0);
564
+ const output = usages.reduce((sum, usage) => sum + (usage?.output ?? 0), 0);
565
+ const cost = usages.reduce((sum, usage) => sum + (usage?.cost ?? 0), 0);
566
+ const pricing = runs.reduce((merged, run) => mergePricing(merged, run.pricing), undefined);
567
+ const costPart = costText(cost, pricing);
568
+ return [
569
+ `${runs.length} agent${runs.length === 1 ? "" : "s"}`,
468
570
  ...(output > 0
469
- ? [`↓ ${compactTokens(output)}`, `$${cost.toFixed(2)}`]
571
+ ? [tokenText(input, output), ...(costPart ? [costPart] : [])]
470
572
  : []),
471
- ];
472
- return parts.length > 0 ? parts.join(" · ") : undefined;
573
+ ].join(" · ");
473
574
  };
474
575
  const watchAgents = () => {
475
576
  if (agentsWidgetTimer)
@@ -566,14 +667,23 @@ export function createRecipesExtension(opts = {}) {
566
667
  if (!run)
567
668
  throw new Error(`Unknown agent run: ${id}`);
568
669
  if (run.status === "running") {
569
- await run.runner.steer(message);
670
+ // Its inbox keeps this behind older messages; a queued run gets it with its first prompt.
671
+ await run.inbox.deliver({
672
+ from: ROOT_AGENT,
673
+ fromId: ROOT_AGENT,
674
+ text: message,
675
+ deliver: "steer",
676
+ });
570
677
  return controllerSummary(run);
571
678
  }
679
+ // Claimed, and its new turn published, before anything yields: a second caller's
680
+ // message goes to its inbox, and a wait waits for that turn.
572
681
  run.status = "running";
573
682
  run.completedAt = undefined;
574
683
  run.error = undefined;
575
684
  run.output = undefined;
576
- run.promise = executeChildPrompt(run, message, state?.cwd ?? process.cwd());
685
+ const resumed = run.inbox.resume();
686
+ run.promise = resumed.then(() => executeChildPrompt(run, message, state?.cwd ?? process.cwd()));
577
687
  void persistRun(state?.cwd ?? process.cwd(), run);
578
688
  return controllerSummary(run);
579
689
  },
@@ -585,9 +695,13 @@ export function createRecipesExtension(opts = {}) {
585
695
  if (!run)
586
696
  throw new Error(`Unknown agent run: ${id}`);
587
697
  if (run.status === "running") {
698
+ const queued = run.queued;
588
699
  run.status = "interrupted";
589
700
  run.completedAt = run.completedAt ?? new Date().toISOString();
590
- await run.runner.cancel();
701
+ if (queued)
702
+ leaveChildQueue(run);
703
+ else
704
+ await run.runner.cancel();
591
705
  if (state)
592
706
  void persistRun(state.cwd, run);
593
707
  }
@@ -601,13 +715,17 @@ export function createRecipesExtension(opts = {}) {
601
715
  if (!run)
602
716
  throw new Error(`Unknown agent run: ${id}`);
603
717
  if (run.status === "running") {
718
+ const queued = run.queued;
604
719
  run.status = "interrupted";
605
- await run.runner.cancel();
720
+ if (queued)
721
+ leaveChildQueue(run);
722
+ else
723
+ await run.runner.cancel();
606
724
  await run.promise;
607
725
  }
726
+ await run.inbox.close();
608
727
  await run.runner.shutdown();
609
- closedUsage.output += run.usage?.output ?? 0;
610
- closedUsage.cost += run.usage?.cost ?? 0;
728
+ run.unregisterMessages();
611
729
  childRuns.delete(id);
612
730
  return controllerSummary(run, "closed");
613
731
  },
@@ -616,7 +734,10 @@ export function createRecipesExtension(opts = {}) {
616
734
  },
617
735
  };
618
736
  async function closeAllChildRuns() {
737
+ // Batches stop starting rows first, or a row closed here would make room for the next.
738
+ const stopping = agentBatches?.stopAll();
619
739
  await Promise.all([...childRuns.keys()].map((id) => localRunController.close(id)));
740
+ await stopping;
620
741
  }
621
742
  async function closeRootMcpRuntime() {
622
743
  const privateEnv = state?.mcpPrivateEnv;
@@ -1203,7 +1324,11 @@ export function createRecipesExtension(opts = {}) {
1203
1324
  }
1204
1325
  }
1205
1326
  async function runChildAgent(launchState, agentName, prompt, label, ctx, onUpdate) {
1327
+ if (label !== undefined && messages.hasName(label)) {
1328
+ throw new Error(`An agent named "${label}" is already running in this session; pick another label.`);
1329
+ }
1206
1330
  const id = nextChildRunId();
1331
+ const inbox = createRunnerInbox(() => run.runner);
1207
1332
  // `notifyUpdate` reads it and can run before the run record exists.
1208
1333
  // eslint-disable-next-line prefer-const
1209
1334
  let run;
@@ -1237,6 +1362,7 @@ export function createRecipesExtension(opts = {}) {
1237
1362
  }
1238
1363
  };
1239
1364
  const runner = createChildAgentRunner({
1365
+ messages: { bus: messages, id, inbox },
1240
1366
  recipe: launchState.resolvedRecipe,
1241
1367
  workspaceDir: launchState.cwd,
1242
1368
  env,
@@ -1245,14 +1371,20 @@ export function createRecipesExtension(opts = {}) {
1245
1371
  agentRunId: id,
1246
1372
  // Runs the child starts in turn arrive already attributed to it, and their usage counts as its own.
1247
1373
  onAgentRunEvent(envelope) {
1248
- if (run && addMessageUsage(run, envelope.event))
1249
- notifyUpdate();
1374
+ if (run) {
1375
+ notePricing(run, envelope.event, ctx.modelRegistry);
1376
+ const started = streamFor(run, envelope.agent_run_id, envelope.event);
1377
+ if (addMessageUsage(run, envelope.event) || started)
1378
+ notifyUpdate();
1379
+ }
1250
1380
  recordRunEvent(envelope);
1251
1381
  },
1252
1382
  onEvent(event) {
1253
1383
  if (!run)
1254
1384
  return;
1255
- if (addMessageUsage(run, event))
1385
+ notePricing(run, event, ctx.modelRegistry);
1386
+ const started = streamFor(run, run.id, event);
1387
+ if (addMessageUsage(run, event) || started)
1256
1388
  notifyUpdate();
1257
1389
  recordRunEvent({
1258
1390
  type: "agent_run_event",
@@ -1290,9 +1422,28 @@ export function createRecipesExtension(opts = {}) {
1290
1422
  status: "running",
1291
1423
  startedAt: new Date().toISOString(),
1292
1424
  toolCalls: [],
1425
+ streaming: new Map(),
1293
1426
  runner,
1294
1427
  promise: Promise.resolve(undefined),
1295
1428
  notifyUpdate,
1429
+ inbox,
1430
+ // The batch marked this label for the run it is about to start; no later run inherits it.
1431
+ ...(label !== undefined && quietLabels.delete(label)
1432
+ ? { batchRow: true }
1433
+ : {}),
1434
+ unregisterMessages: messages.register({
1435
+ id,
1436
+ ...(label !== undefined ? { name: label } : {}),
1437
+ inbox,
1438
+ accepting: () => run.status === "running",
1439
+ setStatus(note) {
1440
+ const current = run;
1441
+ // A note without usage keeps the last reported total.
1442
+ const usage = note.usage ?? current.statusNote?.usage;
1443
+ current.statusNote = { text: note.text, ...(usage ? { usage } : {}) };
1444
+ current.notifyUpdate();
1445
+ },
1446
+ }),
1296
1447
  };
1297
1448
  // Registered before the first update, so the widget sees it running and keeps its timer.
1298
1449
  childRuns.set(id, run);
@@ -1303,9 +1454,23 @@ export function createRecipesExtension(opts = {}) {
1303
1454
  }
1304
1455
  function executeChildPrompt(run, prompt, cwd) {
1305
1456
  return (async () => {
1457
+ let held = false;
1306
1458
  try {
1459
+ held = await takeChildSlot(run);
1460
+ // Closed or interrupted while it waited for a slot.
1461
+ if (!held || run.status !== "running")
1462
+ return run;
1463
+ run.notifyUpdate();
1307
1464
  await run.runner.start();
1308
- const result = await run.runner.prompt(prompt);
1465
+ // Messages sent before the session was up come with its first prompt.
1466
+ const early = await run.inbox.started();
1467
+ if (run.status !== "running") {
1468
+ await run.inbox.turnEnded(early);
1469
+ return run;
1470
+ }
1471
+ const result = await run.runner.prompt(early.length > 0
1472
+ ? `${prompt}\n\n${renderAgentMessages(early)}`
1473
+ : prompt);
1309
1474
  const finalOutput = promptResultText(result);
1310
1475
  // The streamed buffer spans every turn the child took (a nested
1311
1476
  // child also takes a turn per batch of its own results), so the
@@ -1321,7 +1486,11 @@ export function createRecipesExtension(opts = {}) {
1321
1486
  }
1322
1487
  }
1323
1488
  finally {
1489
+ if (held)
1490
+ freeChildSlot();
1324
1491
  run.completedAt = new Date().toISOString();
1492
+ // A message cut off before its end has no real total to replace its estimate.
1493
+ run.streaming.clear();
1325
1494
  // Queue the parent wake-up BEFORE persisting. The deliverer reads the
1326
1495
  // in-memory queue (not disk), so enqueuing first makes a persisted
1327
1496
  // status.json imply the completion is already queued — closing a race
@@ -1330,7 +1499,8 @@ export function createRecipesExtension(opts = {}) {
1330
1499
  // still notifies if the disk write fails. Wait and terminal status
1331
1500
  // reads acknowledge it back out.
1332
1501
  const envelope = envelopeFromRun(run);
1333
- if (envelope)
1502
+ // A batch row is reported in its batch's results, not on its own.
1503
+ if (envelope && !run.batchRow)
1334
1504
  completions.enqueue(envelope);
1335
1505
  run.notifyUpdate();
1336
1506
  await persistRun(cwd, run);
@@ -1370,7 +1540,7 @@ export function createRecipesExtension(opts = {}) {
1370
1540
  clearTimeout(deliveryRetryTimer);
1371
1541
  deliveryRetryTimer = null;
1372
1542
  }
1373
- if (!completions.hasPending())
1543
+ if (!completions.hasPending() && !rootInbox.needsTurn())
1374
1544
  return;
1375
1545
  // The retry timer can outlive this extension instance across a reload,
1376
1546
  // where pi API calls throw as stale. Never crash the timer callback;
@@ -1381,6 +1551,8 @@ export function createRecipesExtension(opts = {}) {
1381
1551
  deliveryRetryTimer.unref?.();
1382
1552
  return;
1383
1553
  }
1554
+ // Follow-ups held while root was busy, in send order, go the same idle-gated way.
1555
+ root.flush().catch(() => { });
1384
1556
  const batch = completions.consumeBatch();
1385
1557
  if (batch.length === 0)
1386
1558
  return;
@@ -1399,9 +1571,18 @@ export function createRecipesExtension(opts = {}) {
1399
1571
  }
1400
1572
  };
1401
1573
  completions.setDeliverer(deliverCompletions);
1574
+ deliverToRoot = deliverCompletions;
1575
+ pi.on("message_end", (event) => {
1576
+ const message = event.message;
1577
+ if (message.customType === AGENT_RUN_MESSAGE_TYPE)
1578
+ rootInbox.read(message.details);
1579
+ });
1402
1580
  pi.on("agent_end", (_event, ctx) => {
1403
1581
  sessionCtx = ctx;
1404
- completions.poke();
1582
+ if (rootInbox.needsTurn())
1583
+ deliverCompletions();
1584
+ else
1585
+ completions.poke();
1405
1586
  });
1406
1587
  // Rendered from the session's entries for now; these should become
1407
1588
  // `instrumentSession` spans: https://github.com/introspection-org/recipes/issues/340
@@ -1413,6 +1594,12 @@ export function createRecipesExtension(opts = {}) {
1413
1594
  return undefined;
1414
1595
  return applyRecipeAgentPayloadPolicy(event.payload, ctx.model, state.resolved.modelConfig);
1415
1596
  });
1597
+ pi.registerMessageRenderer(AGENT_RUN_MESSAGE_TYPE, (message, _options, theme) => {
1598
+ const sent = message.details;
1599
+ if (!sent)
1600
+ return undefined;
1601
+ return new Text(`${theme.fg("accent", `message from ${sent.from}`)} ${theme.fg("muted", sent.fromId)}\n${sent.text}`, 0, 0);
1602
+ });
1416
1603
  pi.registerMessageRenderer(AGENT_COMPLETIONS_TYPE, (message, options, theme) => {
1417
1604
  const batch = message.details
1418
1605
  ?.completions;
@@ -1491,8 +1678,19 @@ export function createRecipesExtension(opts = {}) {
1491
1678
  ctx.ui.notify(recipeSummary(launchState, pi.getActiveTools()), "info");
1492
1679
  },
1493
1680
  });
1681
+ agentBatches = createAgentBatches({
1682
+ controller: localRunController,
1683
+ runBatch,
1684
+ cwd: () => state?.cwd ?? process.cwd(),
1685
+ quiet: (label) => {
1686
+ quietLabels.add(label);
1687
+ return () => quietLabels.delete(label);
1688
+ },
1689
+ });
1494
1690
  const agentTool = createAgentTool(localRunController, visibleAgentDefinitions, {
1495
1691
  acknowledgeCompletions: (ids) => completions.acknowledge(ids),
1692
+ inbox: rootInbox,
1693
+ batches: agentBatches,
1496
1694
  });
1497
1695
  agentTool.label = "Agent";
1498
1696
  agentTool.renderCall = (params, theme, context) => {