@introspection-ai/recipes 0.63.0 → 0.64.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 (76) 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 +30 -6
  10. package/dist/agents.d.ts.map +1 -1
  11. package/dist/agents.js +283 -46
  12. package/dist/agents.js.map +1 -1
  13. package/dist/batch/agent-batches.d.ts +53 -0
  14. package/dist/batch/agent-batches.d.ts.map +1 -0
  15. package/dist/batch/agent-batches.js +168 -0
  16. package/dist/batch/agent-batches.js.map +1 -0
  17. package/dist/batch/index.d.ts +2 -0
  18. package/dist/batch/index.d.ts.map +1 -1
  19. package/dist/batch/index.js +2 -1
  20. package/dist/batch/index.js.map +1 -1
  21. package/dist/child/agent-completions.d.ts +16 -1
  22. package/dist/child/agent-completions.d.ts.map +1 -1
  23. package/dist/child/agent-completions.js +31 -5
  24. package/dist/child/agent-completions.js.map +1 -1
  25. package/dist/child/agent-store.d.ts +2 -0
  26. package/dist/child/agent-store.d.ts.map +1 -1
  27. package/dist/child/agent-store.js.map +1 -1
  28. package/dist/child/agent.d.ts +9 -0
  29. package/dist/child/agent.d.ts.map +1 -1
  30. package/dist/child/agent.js +7 -0
  31. package/dist/child/agent.js.map +1 -1
  32. package/dist/child/arguments.d.ts +32 -0
  33. package/dist/child/arguments.d.ts.map +1 -0
  34. package/dist/child/arguments.generated.d.ts +4 -0
  35. package/dist/child/arguments.generated.d.ts.map +1 -0
  36. package/dist/child/arguments.generated.js +29 -0
  37. package/dist/child/arguments.generated.js.map +1 -0
  38. package/dist/child/arguments.js +8 -0
  39. package/dist/child/arguments.js.map +1 -0
  40. package/dist/child/messages.d.ts +128 -0
  41. package/dist/child/messages.d.ts.map +1 -0
  42. package/dist/child/messages.js +265 -0
  43. package/dist/child/messages.js.map +1 -0
  44. package/dist/child/session.d.ts +10 -0
  45. package/dist/child/session.d.ts.map +1 -1
  46. package/dist/child/session.js +22 -3
  47. package/dist/child/session.js.map +1 -1
  48. package/dist/child/streaming-usage.d.ts +40 -0
  49. package/dist/child/streaming-usage.d.ts.map +1 -0
  50. package/dist/child/streaming-usage.js +101 -0
  51. package/dist/child/streaming-usage.js.map +1 -0
  52. package/dist/pi-extension.d.ts +2 -0
  53. package/dist/pi-extension.d.ts.map +1 -1
  54. package/dist/pi-extension.js +263 -52
  55. package/dist/pi-extension.js.map +1 -1
  56. package/dist/recipe/manifest.generated.d.ts +1 -1
  57. package/dist/recipe/manifest.generated.js +1 -1
  58. package/dist/run-controller.d.ts +5 -0
  59. package/dist/run-controller.d.ts.map +1 -1
  60. package/dist/run-controller.js +70 -8
  61. package/dist/run-controller.js.map +1 -1
  62. package/dist/session.d.ts +11 -0
  63. package/dist/session.d.ts.map +1 -1
  64. package/dist/session.js +15 -1
  65. package/dist/session.js.map +1 -1
  66. package/dist/skill-progress.d.ts +12 -1
  67. package/dist/skill-progress.d.ts.map +1 -1
  68. package/dist/skill-progress.js +11 -4
  69. package/dist/skill-progress.js.map +1 -1
  70. package/docs/agent-batch.md +87 -0
  71. package/docs/agent-composition.md +49 -19
  72. package/docs/batch.md +7 -0
  73. package/docs/host-api.md +4 -3
  74. package/docs/pi-extension.md +4 -1
  75. package/docs/productivity/google.md +27 -15
  76. package/package.json +6 -6
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Usage of a child's assistant message while it streams. A provider reports
3
+ * input and cache tokens when the message starts and output only when it ends,
4
+ * so output is estimated from the characters streamed so far, at four to a
5
+ * token, and priced at the run's last completed rate. `message_end` replaces
6
+ * the estimate with the real total.
7
+ */
8
+ const STREAMED_DELTAS = new Set([
9
+ "text_delta",
10
+ "thinking_delta",
11
+ "toolcall_delta",
12
+ ]);
13
+ const asRecord = (value) => value && typeof value === "object" && !Array.isArray(value)
14
+ ? value
15
+ : undefined;
16
+ const number = (value) => typeof value === "number" && Number.isFinite(value) ? value : 0;
17
+ const reportedCost = (usage) => {
18
+ const cost = asRecord(usage?.cost);
19
+ const outputCost = number(cost?.output);
20
+ return { cost: number(cost?.total) - outputCost, outputCost };
21
+ };
22
+ /**
23
+ * Applies one child session event to the run's streaming state. True when a
24
+ * message started, the one moment worth an update of its own; deltas are read
25
+ * by the next redraw.
26
+ */
27
+ export function applyStreamingEvent(state, event) {
28
+ const record = asRecord(event);
29
+ const message = asRecord(record?.message);
30
+ if (message?.role !== "assistant")
31
+ return false;
32
+ if (record?.type === "message_start") {
33
+ const usage = asRecord(message.usage);
34
+ state.streaming = {
35
+ input: number(usage?.input),
36
+ output: number(usage?.output),
37
+ cacheRead: number(usage?.cacheRead),
38
+ cacheWrite: number(usage?.cacheWrite),
39
+ ...reportedCost(usage),
40
+ chars: 0,
41
+ };
42
+ return true;
43
+ }
44
+ if (record?.type === "message_update") {
45
+ // Some providers report input and cache usage only after the message starts.
46
+ const usage = asRecord(message.usage);
47
+ if (state.streaming && usage) {
48
+ state.streaming.input = number(usage.input);
49
+ state.streaming.output = number(usage.output);
50
+ state.streaming.cacheRead = number(usage.cacheRead);
51
+ state.streaming.cacheWrite = number(usage.cacheWrite);
52
+ Object.assign(state.streaming, reportedCost(usage));
53
+ }
54
+ const delta = asRecord(record.assistantMessageEvent);
55
+ if (state.streaming &&
56
+ typeof delta?.type === "string" &&
57
+ STREAMED_DELTAS.has(delta.type) &&
58
+ typeof delta.delta === "string")
59
+ state.streaming.chars += delta.delta.length;
60
+ return false;
61
+ }
62
+ if (record?.type === "message_end") {
63
+ const usage = asRecord(message.usage);
64
+ const output = number(usage?.output);
65
+ const outputCost = number(asRecord(usage?.cost)?.output);
66
+ if (output > 0 && outputCost > 0)
67
+ state.outputRate = outputCost / output;
68
+ state.streaming = undefined;
69
+ }
70
+ return false;
71
+ }
72
+ /** The run's completed usage plus each streaming message's estimate. */
73
+ export function liveUsage(completed, states) {
74
+ let total = completed;
75
+ for (const state of states) {
76
+ const streaming = state.streaming;
77
+ if (!streaming)
78
+ continue;
79
+ const output = Math.max(streaming.output, Math.ceil(streaming.chars / 4));
80
+ const covered = streaming.outputCost > 0 ? streaming.output : 0;
81
+ const base = total ?? {
82
+ input: 0,
83
+ output: 0,
84
+ cacheRead: 0,
85
+ cacheWrite: 0,
86
+ cost: 0,
87
+ };
88
+ total = {
89
+ input: base.input + streaming.input,
90
+ output: base.output + output,
91
+ cacheRead: base.cacheRead + streaming.cacheRead,
92
+ cacheWrite: base.cacheWrite + streaming.cacheWrite,
93
+ cost: base.cost +
94
+ streaming.cost +
95
+ streaming.outputCost +
96
+ (output - covered) * (state.outputRate ?? 0),
97
+ };
98
+ }
99
+ return total;
100
+ }
101
+ //# sourceMappingURL=streaming-usage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streaming-usage.js","sourceRoot":"","sources":["../../src/child/streaming-usage.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AA4BH,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC;IAC9B,YAAY;IACZ,gBAAgB;IAChB,gBAAgB;CACjB,CAAC,CAAC;AAEH,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAuC,EAAE,CACvE,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;IACzD,CAAC,CAAE,KAAiC;IACpC,CAAC,CAAC,SAAS,CAAC;AAEhB,MAAM,MAAM,GAAG,CAAC,KAAc,EAAU,EAAE,CACxC,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,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tensionOptions {
9
9
  onAgentRunEvent?: AgentRunEventObserver;
10
10
  /** The clock behind the date in the prompt and the `today` tool. Default: the host's. */
11
11
  clock?: RecipeClockOptions;
12
+ /** Subagent runs at once; later starts queue until a run ends. Default 4. */
13
+ subagentConcurrency?: number;
12
14
  }
13
15
  export declare function createRecipesExtension(opts?: RecipesExtensionOptions): ExtensionFactory;
14
16
  declare const _default: ExtensionFactory;
@@ -1 +1 @@
1
- {"version":3,"file":"pi-extension.d.ts","sourceRoot":"","sources":["../src/pi-extension.ts"],"names":[],"mappings":"AAeA,OAAO,EAIL,KAAK,gBAAgB,EAEtB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAGL,KAAK,4BAA4B,EAGlC,MAAM,kBAAkB,CAAC;AAqB1B,OAAO,EAGL,KAAK,qBAAqB,EAI3B,MAAM,aAAa,CAAC;AA4ErB,OAAO,EAKL,KAAK,kBAAkB,EACxB,MAAM,YAAY,CAAC;AAiBpB,MAAM,WAAW,uBAAuB;IACtC,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,sBAAsB,CAAC,EAAE,4BAA4B,CAAC;IACtD,wDAAwD;IACxD,eAAe,CAAC,EAAE,qBAAqB,CAAC;IACxC,yFAAyF;IACzF,KAAK,CAAC,EAAE,kBAAkB,CAAC;CAC5B;AAqgBD,wBAAgB,sBAAsB,CACpC,IAAI,GAAE,uBAA4B,GACjC,gBAAgB,CAmiDlB"}
1
+ {"version":3,"file":"pi-extension.d.ts","sourceRoot":"","sources":["../src/pi-extension.ts"],"names":[],"mappings":"AAqBA,OAAO,EAIL,KAAK,gBAAgB,EAEtB,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAGL,KAAK,4BAA4B,EAGlC,MAAM,kBAAkB,CAAC;AAkC1B,OAAO,EAGL,KAAK,qBAAqB,EAM3B,MAAM,aAAa,CAAC;AAiFrB,OAAO,EAKL,KAAK,kBAAkB,EACxB,MAAM,YAAY,CAAC;AAiBpB,MAAM,WAAW,uBAAuB;IACtC,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,sBAAsB,CAAC,EAAE,4BAA4B,CAAC;IACtD,wDAAwD;IACxD,eAAe,CAAC,EAAE,qBAAqB,CAAC;IACxC,yFAAyF;IACzF,KAAK,CAAC,EAAE,kBAAkB,CAAC;IAC3B,6EAA6E;IAC7E,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAklBD,wBAAgB,sBAAsB,CACpC,IAAI,GAAE,uBAA4B,GACjC,gBAAgB,CA8sDlB"}
@@ -2,18 +2,23 @@ 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 { Text, truncateToWidth } from "@earendil-works/pi-tui";
10
13
  import { createRecipeChildAgentRunner, promptResultText, } from "./child/agent.js";
11
14
  import { registerGenAiSpansFile } from "./genai-spans-file.js";
12
15
  import { loadRecipeExtensionFactory } from "./recipe/extensions.js";
13
16
  import { bindRecipeExtensionFactory, createRecipeExtensionSessionContext, createRecipeExtensionRegistrationRegistry, } from "./extensions.js";
14
17
  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, runProgress, } from "./agents.js";
18
+ import { ChildCompletionQueue, costText, envelopeFromRun, renderCompletionNotice, tokenText, usageText, } from "./child/agent-completions.js";
19
+ import { AGENT_RUN_MESSAGE_TYPE, AgentInbox, AgentMessageBus, renderAgentMessage, renderAgentMessages, ROOT_AGENT, } from "./child/messages.js";
20
+ import { AGENT_RUN_EVENT_ENTRY_TYPE, notifyAgentRunEvent, persistsAgentRunEvent, agentLine, runProgress, toolActivity, } from "./agents.js";
21
+ import { applyStreamingEvent, liveUsage, } from "./child/streaming-usage.js";
17
22
  import { clearMcpSession, clearSessionMcpCli, configureMcpLocalConfigPath, createIsolatedMcpEnvironment, endpointBindings, formatMcpConfigurationDiagnostics, materializeMcpSession, materializeSessionMcpCli, resolveAgentMcpSelections, resolveMcpSessionServers, stopMcpDaemon, } from "./mcp/index.js";
18
23
  import { mcpServersBehindTools } from "./mcp/policy.js";
19
24
  import { clearMcpCatalogPreload, preloadMcpCatalogs } from "./mcp/catalog.js";
@@ -249,6 +254,35 @@ function snapshotOf(run) {
249
254
  error: run.error,
250
255
  toolCalls: run.toolCalls.map((call) => ({ ...call })),
251
256
  ...(run.usage ? { usage: { ...run.usage } } : {}),
257
+ ...(run.pricing ? { pricing: { ...run.pricing } } : {}),
258
+ };
259
+ }
260
+ /** Folds how one assistant message's model is paid for into its run's pricing. */
261
+ function notePricing(run, event, registry) {
262
+ const record = asRecord(event);
263
+ if (record?.type !== "message_start" && record?.type !== "message_end")
264
+ return;
265
+ const message = asRecord(record.message);
266
+ if (message?.role !== "assistant" ||
267
+ typeof message.provider !== "string" ||
268
+ typeof message.model !== "string")
269
+ return;
270
+ const model = registry.find(message.provider, message.model);
271
+ const price = model?.cost;
272
+ const pricing = {
273
+ subscription: model !== undefined && registry.isUsingOAuth(model),
274
+ priced: price !== undefined &&
275
+ [price.input, price.output, price.cacheRead, price.cacheWrite].some((rate) => typeof rate === "number" && rate > 0),
276
+ };
277
+ run.pricing = mergePricing(run.pricing, pricing);
278
+ }
279
+ /** Several runs' pricing: a subscription only if every one is, priced if any one is. */
280
+ function mergePricing(a, b) {
281
+ if (!a || !b)
282
+ return a ?? b;
283
+ return {
284
+ subscription: a.subscription && b.subscription,
285
+ priced: a.priced || b.priced,
252
286
  };
253
287
  }
254
288
  /** Adds an assistant message's usage, from a child's `message_end` event, to its run's. */
@@ -277,16 +311,29 @@ function addMessageUsage(run, event) {
277
311
  };
278
312
  return true;
279
313
  }
314
+ /** Applies a streaming event to the state of the run that streams it. */
315
+ function streamFor(run, streamId, event) {
316
+ let state = run.streaming.get(streamId);
317
+ if (!state) {
318
+ state = {};
319
+ run.streaming.set(streamId, state);
320
+ }
321
+ return applyStreamingEvent(state, event);
322
+ }
280
323
  function controllerSummary(run, status = run.status) {
324
+ const streaming = run.streaming;
281
325
  const startedAt = Date.parse(run.startedAt);
282
326
  const completedAt = run.completedAt ? Date.parse(run.completedAt) : undefined;
283
- const currentTool = [...run.toolCalls]
327
+ const running = [...run.toolCalls]
284
328
  .reverse()
285
- .find((call) => call.status === "running")?.name;
329
+ .find((call) => call.status === "running");
330
+ const currentActivity = running && toolActivity(running.name, running.args);
331
+ const usage = liveUsage(run.usage, streaming?.values() ?? []);
286
332
  return {
287
333
  agent_run_id: run.id,
288
334
  invocation_name: run.agent,
289
335
  agent_name: run.agent,
336
+ ...(run.queued ? { queued: true } : {}),
290
337
  label: run.label ?? run.agent,
291
338
  prompt: run.prompt,
292
339
  status,
@@ -299,7 +346,11 @@ function controllerSummary(run, status = run.status) {
299
346
  : Number.isFinite(startedAt)
300
347
  ? startedAt
301
348
  : Date.now(),
302
- ...(currentTool ? { current_tool: currentTool } : {}),
349
+ ...(running
350
+ ? { current_tool: running.name, current_activity: currentActivity }
351
+ : {}),
352
+ ...(run.statusNote ? { status_text: run.statusNote.text } : {}),
353
+ ...(run.statusNote?.usage ? { reported_usage: run.statusNote.usage } : {}),
303
354
  nested_tools: run.toolCalls.map((call) => ({
304
355
  toolName: call.name,
305
356
  verb: call.name,
@@ -309,14 +360,15 @@ function controllerSummary(run, status = run.status) {
309
360
  output_preview: run.output,
310
361
  output: run.output,
311
362
  error: run.error,
312
- ...(run.usage
363
+ ...(usage
313
364
  ? {
314
365
  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,
366
+ input_tokens: usage.input,
367
+ output_tokens: usage.output,
368
+ cache_read_tokens: usage.cacheRead,
369
+ cache_write_tokens: usage.cacheWrite,
370
+ cost_usd: usage.cost,
371
+ ...(run.pricing ? { pricing: run.pricing } : {}),
320
372
  },
321
373
  }
322
374
  : {}),
@@ -419,8 +471,59 @@ export function createRecipesExtension(opts = {}) {
419
471
  let lastLaunchErrorKey = null;
420
472
  let childRunIndex = 0;
421
473
  const childRuns = new Map();
474
+ // Labels a batch is about to start a row under: the run started under one is the batch's.
475
+ const quietLabels = new Set();
476
+ let agentBatches;
477
+ const subagentConcurrency = Math.max(1, opts.subagentConcurrency ?? DEFAULT_SUBAGENT_CONCURRENCY);
478
+ let activeChildren = 0;
479
+ const waitingChildren = [];
480
+ /** A slot for `run`, at once or once a running run ends; false when it left the queue without one. */
481
+ const takeChildSlot = (run) => {
482
+ if (activeChildren < subagentConcurrency) {
483
+ activeChildren += 1;
484
+ return Promise.resolve(true);
485
+ }
486
+ run.queued = true;
487
+ return new Promise((resolve) => waitingChildren.push({ run, resolve }));
488
+ };
489
+ const freeChildSlot = () => {
490
+ const next = waitingChildren.shift();
491
+ if (!next) {
492
+ activeChildren -= 1;
493
+ return;
494
+ }
495
+ next.run.queued = false;
496
+ next.resolve(true);
497
+ };
498
+ const leaveChildQueue = (run) => {
499
+ const index = waitingChildren.findIndex((waiting) => waiting.run === run);
500
+ if (index < 0)
501
+ return;
502
+ const [waiting] = waitingChildren.splice(index, 1);
503
+ run.queued = false;
504
+ waiting.resolve(false);
505
+ };
506
+ // The session's agents by name, for `send_message`. Root takes a message in
507
+ // its current wait, or as a steer or follow-up, starting a turn when idle.
508
+ const messages = new AgentMessageBus();
509
+ const rootInbox = new AgentInbox(async (message) => {
510
+ extensionApi?.sendMessage({
511
+ customType: AGENT_RUN_MESSAGE_TYPE,
512
+ content: renderAgentMessage(message),
513
+ display: true,
514
+ details: message,
515
+ },
516
+ // An idle root only stores a message without triggerTurn; streaming, it
517
+ // takes the message as `deliver` says.
518
+ { triggerTurn: true, deliverAs: message.deliver });
519
+ }, () => !(sessionCtx?.isIdle?.() ?? true));
520
+ messages.register({
521
+ id: ROOT_AGENT,
522
+ name: ROOT_AGENT,
523
+ inbox: rootInbox,
524
+ accepting: () => true,
525
+ });
422
526
  // Usage of runs already closed: closing a run removes it from childRuns, not its cost.
423
- const closedUsage = { output: 0, cost: 0 };
424
527
  let releaseApiBindings;
425
528
  // Runs restored from a previous Pi process via rehydrateChildRuns(). They
426
529
  // have no live runner: readable (status/wait) but not controllable.
@@ -436,7 +539,7 @@ export function createRecipesExtension(opts = {}) {
436
539
  let agentsWidgetTimer;
437
540
  // Re-reports the step when the running count moves; set once the footer is registered.
438
541
  let refreshAgentStep;
439
- const runningAgents = () => [...childRuns.values()].filter((run) => run.status === "running").length;
542
+ const runningAgents = () => [...childRuns.values()].filter((run) => run.status === "running" && !run.queued).length;
440
543
  const renderAgentsWidget = () => {
441
544
  refreshAgentStep?.();
442
545
  const ctx = localAgentContext;
@@ -449,27 +552,28 @@ export function createRecipesExtension(opts = {}) {
449
552
  return;
450
553
  ctx.ui.setWidget(AGENTS_WIDGET_KEY, running.length === 0
451
554
  ? 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)}`;
555
+ : () => ({
556
+ render: (width) => running.map((run) => truncateToWidth(agentLine(controllerSummary(run)), width)),
557
+ invalidate: () => { },
458
558
  }), { placement: "belowEditor" });
459
559
  };
460
- /** `4 agents · ↓ 4.1k · $0.45`: how many run now, and every run's usage this session. */
560
+ /** `2 agents · ↓ 4.1k · $0.450 (sub)`: the runs in progress and their usage so far; nothing once none runs. */
461
561
  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"}`] : []),
562
+ const runs = [...childRuns.values()].filter((run) => run.status === "running");
563
+ if (runs.length === 0)
564
+ return undefined;
565
+ const usages = runs.map((run) => liveUsage(run.usage, run.streaming.values()));
566
+ const input = usages.reduce((sum, usage) => sum + (usage?.input ?? 0), 0);
567
+ const output = usages.reduce((sum, usage) => sum + (usage?.output ?? 0), 0);
568
+ const cost = usages.reduce((sum, usage) => sum + (usage?.cost ?? 0), 0);
569
+ const pricing = runs.reduce((merged, run) => mergePricing(merged, run.pricing), undefined);
570
+ const costPart = costText(cost, pricing);
571
+ return [
572
+ `${runs.length} agent${runs.length === 1 ? "" : "s"}`,
468
573
  ...(output > 0
469
- ? [`↓ ${compactTokens(output)}`, `$${cost.toFixed(2)}`]
574
+ ? [tokenText(input, output), ...(costPart ? [costPart] : [])]
470
575
  : []),
471
- ];
472
- return parts.length > 0 ? parts.join(" · ") : undefined;
576
+ ].join(" · ");
473
577
  };
474
578
  const watchAgents = () => {
475
579
  if (agentsWidgetTimer)
@@ -566,7 +670,13 @@ export function createRecipesExtension(opts = {}) {
566
670
  if (!run)
567
671
  throw new Error(`Unknown agent run: ${id}`);
568
672
  if (run.status === "running") {
569
- await run.runner.steer(message);
673
+ // Its inbox keeps this behind older messages; a queued run gets it with its first prompt.
674
+ await run.inbox.deliver({
675
+ from: ROOT_AGENT,
676
+ fromId: ROOT_AGENT,
677
+ text: message,
678
+ deliver: "steer",
679
+ });
570
680
  return controllerSummary(run);
571
681
  }
572
682
  run.status = "running";
@@ -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,16 @@ 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
  }
608
726
  await run.runner.shutdown();
609
- closedUsage.output += run.usage?.output ?? 0;
610
- closedUsage.cost += run.usage?.cost ?? 0;
727
+ run.unregisterMessages();
611
728
  childRuns.delete(id);
612
729
  return controllerSummary(run, "closed");
613
730
  },
@@ -616,7 +733,10 @@ export function createRecipesExtension(opts = {}) {
616
733
  },
617
734
  };
618
735
  async function closeAllChildRuns() {
736
+ // Batches stop starting rows first, or a row closed here would make room for the next.
737
+ const stopping = agentBatches?.stopAll();
619
738
  await Promise.all([...childRuns.keys()].map((id) => localRunController.close(id)));
739
+ await stopping;
620
740
  }
621
741
  async function closeRootMcpRuntime() {
622
742
  const privateEnv = state?.mcpPrivateEnv;
@@ -944,17 +1064,30 @@ export function createRecipesExtension(opts = {}) {
944
1064
  catch {
945
1065
  // A session that can't record its Recipe still runs; continuing it just needs --recipe again.
946
1066
  }
947
- const { provider, model } = modelParts(launchState.resolved.modelSpec);
948
- const lookupProvider = provider === "gemini" ? "google" : provider;
949
- const registeredModel = ctx.modelRegistry.find(lookupProvider, model);
950
- if (!registeredModel) {
951
- throw new Error(`Recipe model is not available: ${launchState.resolved.modelSpec}`);
1067
+ // The session starts on the first of `ai.model` and `ai.fallbacks` this host can serve.
1068
+ const fallbacks = launchState.resolved.modelConfig?.fallbacks ?? [];
1069
+ let failure;
1070
+ let started = false;
1071
+ for (const spec of [launchState.resolved.modelSpec, ...fallbacks]) {
1072
+ const { provider, model } = modelParts(spec);
1073
+ const lookupProvider = provider === "gemini" ? "google" : provider;
1074
+ const registeredModel = ctx.modelRegistry.find(lookupProvider, model);
1075
+ if (!registeredModel) {
1076
+ failure ??= `Recipe model is not available: ${spec}`;
1077
+ continue;
1078
+ }
1079
+ const resolvedModel = cloneModelForRecipe(registeredModel);
1080
+ applyRecipeAgentModelConfigToModel(resolvedModel, launchState.resolved.modelConfig);
1081
+ if (await pi.setModel(resolvedModel)) {
1082
+ started = true;
1083
+ break;
1084
+ }
1085
+ failure ??= `Recipe model has no configured API key: ${spec}`;
952
1086
  }
953
- const resolvedModel = cloneModelForRecipe(registeredModel);
954
- applyRecipeAgentModelConfigToModel(resolvedModel, launchState.resolved.modelConfig);
955
- const ok = await pi.setModel(resolvedModel);
956
- if (!ok) {
957
- throw new Error(`Recipe model has no configured API key: ${launchState.resolved.modelSpec}`);
1087
+ if (!started) {
1088
+ throw new Error(fallbacks.length > 0
1089
+ ? `${failure}; none of its fallbacks can start either: ${fallbacks.join(", ")}`
1090
+ : failure);
958
1091
  }
959
1092
  if (launchState.resolved.thinkingLevel) {
960
1093
  pi.setThinkingLevel(launchState.resolved.thinkingLevel);
@@ -1190,7 +1323,18 @@ export function createRecipesExtension(opts = {}) {
1190
1323
  }
1191
1324
  }
1192
1325
  async function runChildAgent(launchState, agentName, prompt, label, ctx, onUpdate) {
1326
+ if (label !== undefined && messages.hasName(label)) {
1327
+ throw new Error(`An agent named "${label}" is already running in this session; pick another label.`);
1328
+ }
1193
1329
  const id = nextChildRunId();
1330
+ const inbox = new AgentInbox(async (message) => {
1331
+ const text = renderAgentMessage(message);
1332
+ if (message.deliver === "followUp")
1333
+ await run.runner.followUp(text);
1334
+ else
1335
+ await run.runner.steer(text);
1336
+ });
1337
+ inbox.holdUntilStarted();
1194
1338
  // `notifyUpdate` reads it and can run before the run record exists.
1195
1339
  // eslint-disable-next-line prefer-const
1196
1340
  let run;
@@ -1208,6 +1352,10 @@ export function createRecipesExtension(opts = {}) {
1208
1352
  };
1209
1353
  const recordRunEvent = (envelope) => {
1210
1354
  notifyAgentRunEvent(opts.onAgentRunEvent, envelope);
1355
+ // Streaming updates reach the observer above but are not appended: the
1356
+ // end events carry their final content.
1357
+ if (!persistsAgentRunEvent(envelope))
1358
+ return;
1211
1359
  // Custom entries join Pi's canonical session event stream without
1212
1360
  // entering model context. JSON mode serializes the resulting single
1213
1361
  // `entry_appended` event through Pi's guarded output writer.
@@ -1220,6 +1368,7 @@ export function createRecipesExtension(opts = {}) {
1220
1368
  }
1221
1369
  };
1222
1370
  const runner = createChildAgentRunner({
1371
+ messages: { bus: messages, id, inbox },
1223
1372
  recipe: launchState.resolvedRecipe,
1224
1373
  workspaceDir: launchState.cwd,
1225
1374
  env,
@@ -1228,14 +1377,20 @@ export function createRecipesExtension(opts = {}) {
1228
1377
  agentRunId: id,
1229
1378
  // Runs the child starts in turn arrive already attributed to it, and their usage counts as its own.
1230
1379
  onAgentRunEvent(envelope) {
1231
- if (run && addMessageUsage(run, envelope.event))
1232
- notifyUpdate();
1380
+ if (run) {
1381
+ notePricing(run, envelope.event, ctx.modelRegistry);
1382
+ const started = streamFor(run, envelope.agent_run_id, envelope.event);
1383
+ if (addMessageUsage(run, envelope.event) || started)
1384
+ notifyUpdate();
1385
+ }
1233
1386
  recordRunEvent(envelope);
1234
1387
  },
1235
1388
  onEvent(event) {
1236
1389
  if (!run)
1237
1390
  return;
1238
- if (addMessageUsage(run, event))
1391
+ notePricing(run, event, ctx.modelRegistry);
1392
+ const started = streamFor(run, run.id, event);
1393
+ if (addMessageUsage(run, event) || started)
1239
1394
  notifyUpdate();
1240
1395
  recordRunEvent({
1241
1396
  type: "agent_run_event",
@@ -1273,9 +1428,28 @@ export function createRecipesExtension(opts = {}) {
1273
1428
  status: "running",
1274
1429
  startedAt: new Date().toISOString(),
1275
1430
  toolCalls: [],
1431
+ streaming: new Map(),
1276
1432
  runner,
1277
1433
  promise: Promise.resolve(undefined),
1278
1434
  notifyUpdate,
1435
+ inbox,
1436
+ // The batch marked this label for the run it is about to start; no later run inherits it.
1437
+ ...(label !== undefined && quietLabels.delete(label)
1438
+ ? { batchRow: true }
1439
+ : {}),
1440
+ unregisterMessages: messages.register({
1441
+ id,
1442
+ ...(label !== undefined ? { name: label } : {}),
1443
+ inbox,
1444
+ accepting: () => run.status === "running",
1445
+ setStatus(note) {
1446
+ const current = run;
1447
+ // A note without usage keeps the last reported total.
1448
+ const usage = note.usage ?? current.statusNote?.usage;
1449
+ current.statusNote = { text: note.text, ...(usage ? { usage } : {}) };
1450
+ current.notifyUpdate();
1451
+ },
1452
+ }),
1279
1453
  };
1280
1454
  // Registered before the first update, so the widget sees it running and keeps its timer.
1281
1455
  childRuns.set(id, run);
@@ -1286,9 +1460,19 @@ export function createRecipesExtension(opts = {}) {
1286
1460
  }
1287
1461
  function executeChildPrompt(run, prompt, cwd) {
1288
1462
  return (async () => {
1463
+ let held = false;
1289
1464
  try {
1465
+ held = await takeChildSlot(run);
1466
+ // Closed or interrupted while it waited for a slot.
1467
+ if (!held || run.status !== "running")
1468
+ return run;
1469
+ run.notifyUpdate();
1290
1470
  await run.runner.start();
1291
- const result = await run.runner.prompt(prompt);
1471
+ // Messages sent before the session was up come with its first prompt.
1472
+ const early = run.inbox.started();
1473
+ const result = await run.runner.prompt(early.length > 0
1474
+ ? `${prompt}\n\n${renderAgentMessages(early)}`
1475
+ : prompt);
1292
1476
  const finalOutput = promptResultText(result);
1293
1477
  // The streamed buffer spans every turn the child took (a nested
1294
1478
  // child also takes a turn per batch of its own results), so the
@@ -1304,7 +1488,11 @@ export function createRecipesExtension(opts = {}) {
1304
1488
  }
1305
1489
  }
1306
1490
  finally {
1491
+ if (held)
1492
+ freeChildSlot();
1307
1493
  run.completedAt = new Date().toISOString();
1494
+ // A message cut off before its end has no real total to replace its estimate.
1495
+ run.streaming.clear();
1308
1496
  // Queue the parent wake-up BEFORE persisting. The deliverer reads the
1309
1497
  // in-memory queue (not disk), so enqueuing first makes a persisted
1310
1498
  // status.json imply the completion is already queued — closing a race
@@ -1313,7 +1501,8 @@ export function createRecipesExtension(opts = {}) {
1313
1501
  // still notifies if the disk write fails. Wait and terminal status
1314
1502
  // reads acknowledge it back out.
1315
1503
  const envelope = envelopeFromRun(run);
1316
- if (envelope)
1504
+ // A batch row is reported in its batch's results, not on its own.
1505
+ if (envelope && !run.batchRow)
1317
1506
  completions.enqueue(envelope);
1318
1507
  run.notifyUpdate();
1319
1508
  await persistRun(cwd, run);
@@ -1353,7 +1542,7 @@ export function createRecipesExtension(opts = {}) {
1353
1542
  clearTimeout(deliveryRetryTimer);
1354
1543
  deliveryRetryTimer = null;
1355
1544
  }
1356
- if (!completions.hasPending())
1545
+ if (!completions.hasPending() && !rootInbox.hasHeld())
1357
1546
  return;
1358
1547
  // The retry timer can outlive this extension instance across a reload,
1359
1548
  // where pi API calls throw as stale. Never crash the timer callback;
@@ -1364,6 +1553,8 @@ export function createRecipesExtension(opts = {}) {
1364
1553
  deliveryRetryTimer.unref?.();
1365
1554
  return;
1366
1555
  }
1556
+ // Follow-ups held while root was busy, in send order, go the same idle-gated way.
1557
+ rootInbox.flush().catch(() => { });
1367
1558
  const batch = completions.consumeBatch();
1368
1559
  if (batch.length === 0)
1369
1560
  return;
@@ -1384,7 +1575,10 @@ export function createRecipesExtension(opts = {}) {
1384
1575
  completions.setDeliverer(deliverCompletions);
1385
1576
  pi.on("agent_end", (_event, ctx) => {
1386
1577
  sessionCtx = ctx;
1387
- completions.poke();
1578
+ if (rootInbox.hasHeld())
1579
+ deliverCompletions();
1580
+ else
1581
+ completions.poke();
1388
1582
  });
1389
1583
  // Rendered from the session's entries for now; these should become
1390
1584
  // `instrumentSession` spans: https://github.com/introspection-org/recipes/issues/340
@@ -1396,6 +1590,12 @@ export function createRecipesExtension(opts = {}) {
1396
1590
  return undefined;
1397
1591
  return applyRecipeAgentPayloadPolicy(event.payload, ctx.model, state.resolved.modelConfig);
1398
1592
  });
1593
+ pi.registerMessageRenderer(AGENT_RUN_MESSAGE_TYPE, (message, _options, theme) => {
1594
+ const sent = message.details;
1595
+ if (!sent)
1596
+ return undefined;
1597
+ return new Text(`${theme.fg("accent", `message from ${sent.from}`)} ${theme.fg("muted", sent.fromId)}\n${sent.text}`, 0, 0);
1598
+ });
1399
1599
  pi.registerMessageRenderer(AGENT_COMPLETIONS_TYPE, (message, options, theme) => {
1400
1600
  const batch = message.details
1401
1601
  ?.completions;
@@ -1474,8 +1674,19 @@ export function createRecipesExtension(opts = {}) {
1474
1674
  ctx.ui.notify(recipeSummary(launchState, pi.getActiveTools()), "info");
1475
1675
  },
1476
1676
  });
1677
+ agentBatches = createAgentBatches({
1678
+ controller: localRunController,
1679
+ runBatch,
1680
+ cwd: () => state?.cwd ?? process.cwd(),
1681
+ quiet: (label) => {
1682
+ quietLabels.add(label);
1683
+ return () => quietLabels.delete(label);
1684
+ },
1685
+ });
1477
1686
  const agentTool = createAgentTool(localRunController, visibleAgentDefinitions, {
1478
1687
  acknowledgeCompletions: (ids) => completions.acknowledge(ids),
1688
+ inbox: rootInbox,
1689
+ batches: agentBatches,
1479
1690
  });
1480
1691
  agentTool.label = "Agent";
1481
1692
  agentTool.renderCall = (params, theme, context) => {