@narumitw/pi-subagents 2.0.6 → 2.1.1

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 (180) hide show
  1. package/README.md +171 -60
  2. package/dist/chunks/{auto-transport-SY2VHUFH.ts → auto-transport-FUUKFDIG.ts} +6 -6
  3. package/dist/chunks/{capability-grant-CGEWOEKE.ts → capability-grant-PR72SWWS.ts} +4 -4
  4. package/dist/chunks/{chunk-CBP76ARQ.ts → chunk-2LMJU25E.ts} +172 -74
  5. package/dist/chunks/chunk-2LMJU25E.ts.map +7 -0
  6. package/dist/chunks/{chunk-DPPVEQAM.ts → chunk-4AQSF7AS.ts} +1 -1
  7. package/dist/chunks/chunk-4AQSF7AS.ts.map +7 -0
  8. package/dist/chunks/chunk-6H6TBBED.ts +108 -0
  9. package/dist/chunks/chunk-6H6TBBED.ts.map +7 -0
  10. package/dist/chunks/{chunk-YBUWBRF7.ts → chunk-6NSJVPXX.ts} +6 -16
  11. package/dist/chunks/{chunk-YBUWBRF7.ts.map → chunk-6NSJVPXX.ts.map} +2 -2
  12. package/dist/chunks/{chunk-DSOOH73Y.ts → chunk-7AAJEUSL.ts} +3 -3
  13. package/dist/chunks/{chunk-DSOOH73Y.ts.map → chunk-7AAJEUSL.ts.map} +2 -2
  14. package/dist/chunks/{chunk-7QPPBBXZ.ts → chunk-D4CR7T73.ts} +21 -3
  15. package/dist/chunks/chunk-D4CR7T73.ts.map +7 -0
  16. package/dist/chunks/{chunk-NIF42QMF.ts → chunk-FEVPWRMU.ts} +7 -4
  17. package/dist/chunks/chunk-FEVPWRMU.ts.map +7 -0
  18. package/dist/chunks/{chunk-S2IWVK3J.ts → chunk-ILEQ27AL.ts} +3 -2
  19. package/dist/chunks/chunk-ILEQ27AL.ts.map +7 -0
  20. package/dist/chunks/{chunk-DQMN4OYM.ts → chunk-ITVWPNU4.ts} +12 -106
  21. package/dist/chunks/chunk-ITVWPNU4.ts.map +7 -0
  22. package/dist/chunks/{chunk-QDVGH2X7.ts → chunk-IWC32VPY.ts} +2 -1
  23. package/dist/chunks/{chunk-QDVGH2X7.ts.map → chunk-IWC32VPY.ts.map} +2 -2
  24. package/dist/chunks/{chunk-I2FAK44T.ts → chunk-JSZIP73U.ts} +48 -10
  25. package/dist/chunks/chunk-JSZIP73U.ts.map +7 -0
  26. package/dist/chunks/{chunk-ZHTNCZIA.ts → chunk-JU6LUNLP.ts} +2 -2
  27. package/dist/chunks/{chunk-PSK43Y6A.ts → chunk-LASD73CM.ts} +2 -2
  28. package/dist/chunks/{chunk-C4L6P266.ts → chunk-LEOYDZI3.ts} +1 -1
  29. package/dist/chunks/{chunk-C4L6P266.ts.map → chunk-LEOYDZI3.ts.map} +2 -2
  30. package/dist/chunks/{chunk-H3BFJ7HJ.ts → chunk-LL4LP2T7.ts} +5 -5
  31. package/dist/chunks/chunk-N2T5IN4X.ts +18 -0
  32. package/dist/chunks/chunk-N2T5IN4X.ts.map +7 -0
  33. package/dist/chunks/chunk-NLT67IZS.ts +322 -0
  34. package/dist/chunks/chunk-NLT67IZS.ts.map +7 -0
  35. package/dist/chunks/{chunk-G3RSMSXJ.ts → chunk-NTRPLF46.ts} +1 -1
  36. package/dist/chunks/chunk-NTRPLF46.ts.map +7 -0
  37. package/dist/chunks/{chunk-EFBPISNT.ts → chunk-PBZMBTNJ.ts} +104 -103
  38. package/dist/chunks/chunk-PBZMBTNJ.ts.map +7 -0
  39. package/dist/chunks/{chunk-SCZ33MYW.ts → chunk-PGLSFLYW.ts} +2 -2
  40. package/dist/chunks/{chunk-O4VO6JUJ.ts → chunk-TM2R67J3.ts} +3 -3
  41. package/dist/chunks/{chunk-QBORTI4W.ts → chunk-TMZRHIIK.ts} +32 -3
  42. package/dist/chunks/chunk-TMZRHIIK.ts.map +7 -0
  43. package/dist/chunks/chunk-TZ34IQ3M.ts +59 -0
  44. package/dist/chunks/chunk-TZ34IQ3M.ts.map +7 -0
  45. package/dist/chunks/{chunk-7OBINKFM.ts → chunk-VDG7LTYE.ts} +11 -11
  46. package/dist/chunks/chunk-VDG7LTYE.ts.map +7 -0
  47. package/dist/chunks/{chunk-AEUYS7JC.ts → chunk-X4NMONPE.ts} +1 -1
  48. package/dist/chunks/chunk-X4NMONPE.ts.map +7 -0
  49. package/dist/chunks/{chunk-HKC4ES4B.ts → chunk-YPJEN6NU.ts} +2 -2
  50. package/dist/chunks/{chunk-434NII74.ts → chunk-YU53SHA7.ts} +54 -8
  51. package/dist/chunks/chunk-YU53SHA7.ts.map +7 -0
  52. package/dist/chunks/{completion-delivery-YPOWSSV3.ts → completion-delivery-RSJU6BXL.ts} +5 -4
  53. package/dist/chunks/{config-status-J4GPWP46.ts → config-status-FKGDECZ3.ts} +7 -6
  54. package/dist/chunks/{config-ui-2YUCUEBM.ts → config-ui-ABHYNGQ7.ts} +297 -231
  55. package/dist/chunks/config-ui-ABHYNGQ7.ts.map +7 -0
  56. package/dist/chunks/{consult-IV7UBNQQ.ts → consult-LJU3IQY5.ts} +14 -13
  57. package/dist/chunks/consult-LJU3IQY5.ts.map +7 -0
  58. package/dist/chunks/{create-stateful-transport-ZP3IXNV3.ts → create-stateful-transport-JWC2EFYL.ts} +6 -6
  59. package/dist/chunks/{delegation-contract-WJPT4FVS.ts → delegation-contract-LA56I5DT.ts} +2 -2
  60. package/dist/chunks/{discovery-K25T3SH4.ts → discovery-MIFB2U4Y.ts} +3 -3
  61. package/dist/chunks/{execution-LA7HN5YF.ts → execution-Q2JZLKJA.ts} +19 -16
  62. package/dist/chunks/execution-Q2JZLKJA.ts.map +7 -0
  63. package/dist/chunks/{in-process-transport-4RF3J6XK.ts → in-process-transport-HJ6TZXC3.ts} +9 -9
  64. package/dist/chunks/{inspect-XV2QALMR.ts → inspect-UH2TKH6E.ts} +25 -10
  65. package/dist/chunks/inspect-UH2TKH6E.ts.map +7 -0
  66. package/dist/chunks/{persistence-VSGXAW4P.ts → persistence-UY3PY6E5.ts} +11 -7
  67. package/dist/chunks/persistence-UY3PY6E5.ts.map +7 -0
  68. package/dist/chunks/{registry-E6XPJB7L.ts → registry-BT54L6CY.ts} +136 -15
  69. package/dist/chunks/registry-BT54L6CY.ts.map +7 -0
  70. package/dist/chunks/{retained-semantic-state-7WXSGRJU.ts → retained-semantic-state-GM75FZGE.ts} +3 -3
  71. package/dist/chunks/{rpc-transport-NEHBHWX4.ts → rpc-transport-7R7DVCEB.ts} +12 -16
  72. package/dist/chunks/rpc-transport-7R7DVCEB.ts.map +7 -0
  73. package/dist/chunks/{spawn-idempotency-QGHO2WKC.ts → spawn-idempotency-BNHOSMZW.ts} +2 -2
  74. package/dist/chunks/{subprocess-transport-NSHOGDC4.ts → subprocess-transport-VHZJRBTW.ts} +15 -14
  75. package/dist/chunks/subprocess-transport-VHZJRBTW.ts.map +7 -0
  76. package/dist/chunks/usage-recording-store-CW3EH2SZ.ts +164 -0
  77. package/dist/chunks/usage-recording-store-CW3EH2SZ.ts.map +7 -0
  78. package/dist/index.ts +682 -82
  79. package/dist/index.ts.map +3 -3
  80. package/docs/async-runtime-protocol.md +83 -0
  81. package/docs/implementation-notes/pi-subagents-capability-matrix.md +62 -0
  82. package/docs/implementation-notes/pi-subagents-current-direction.md +99 -0
  83. package/docs/implementation-notes/pi-subagents-rpc-v1.md +153 -0
  84. package/docs/pi-subagents-diagrams.md +183 -0
  85. package/package.json +9 -8
  86. package/src/agents/types.ts +2 -0
  87. package/src/async-subagent-benchmark.ts +532 -0
  88. package/src/completion-delivery.ts +71 -4
  89. package/src/completion-render.ts +1 -0
  90. package/src/completion-requirement.ts +479 -0
  91. package/src/config-registration.ts +5 -5
  92. package/src/config-status.ts +66 -70
  93. package/src/config-ui.ts +244 -150
  94. package/src/consult-registration.ts +4 -12
  95. package/src/consult-resources.ts +1 -1
  96. package/src/consult.ts +3 -8
  97. package/src/delegation-contract.ts +55 -9
  98. package/src/execution-plan.ts +1 -1
  99. package/src/execution-ui.ts +40 -29
  100. package/src/execution.ts +2 -3
  101. package/src/inspect.ts +24 -1
  102. package/src/orchestration-metrics.ts +1 -1
  103. package/src/panel-execution.ts +2 -3
  104. package/src/panel-failure.ts +1 -1
  105. package/src/panel-render.ts +1 -1
  106. package/src/parallel-limit-ui.ts +6 -5
  107. package/src/params.ts +2 -1
  108. package/src/persistence.ts +9 -0
  109. package/src/process-control.ts +43 -0
  110. package/src/registry-types.ts +5 -0
  111. package/src/registry.ts +162 -18
  112. package/src/render.ts +2 -1
  113. package/src/rpc-transport.ts +1 -1
  114. package/src/runner-outcome.ts +1 -1
  115. package/src/runner-result.ts +1 -1
  116. package/src/runner-types.ts +102 -0
  117. package/src/runner.ts +11 -192
  118. package/src/session-guidance-contract.ts +309 -0
  119. package/src/settings/inspection.ts +27 -0
  120. package/src/settings/schema.ts +9 -0
  121. package/src/settings-reader.ts +7 -0
  122. package/src/settings.ts +20 -0
  123. package/src/spawn-idempotency.ts +5 -0
  124. package/src/stateful-agent-view.ts +15 -19
  125. package/src/stateful-guidance.ts +11 -18
  126. package/src/stateful-limit-ui.ts +23 -20
  127. package/src/stateful-limits.ts +10 -10
  128. package/src/stateful-registration.ts +126 -36
  129. package/src/stateful-render.ts +27 -2
  130. package/src/subagent-details.ts +43 -0
  131. package/src/subagents-extension.ts +116 -68
  132. package/src/subagents.ts +2 -0
  133. package/src/subprocess-transport.ts +2 -1
  134. package/src/supervision.ts +2 -1
  135. package/src/timeout-finalization.ts +1 -1
  136. package/src/tool-schema-compatibility.ts +73 -0
  137. package/src/transport-types.ts +6 -0
  138. package/src/transport-ui.ts +18 -46
  139. package/src/usage-recording-config.ts +13 -0
  140. package/src/usage-recording-store.ts +183 -0
  141. package/src/usage-recording.ts +478 -0
  142. package/src/verification-harness.ts +1 -1
  143. package/src/workflow-ui.ts +17 -9
  144. package/dist/chunks/chunk-434NII74.ts.map +0 -7
  145. package/dist/chunks/chunk-7OBINKFM.ts.map +0 -7
  146. package/dist/chunks/chunk-7QPPBBXZ.ts.map +0 -7
  147. package/dist/chunks/chunk-AEUYS7JC.ts.map +0 -7
  148. package/dist/chunks/chunk-CBP76ARQ.ts.map +0 -7
  149. package/dist/chunks/chunk-DPPVEQAM.ts.map +0 -7
  150. package/dist/chunks/chunk-DQMN4OYM.ts.map +0 -7
  151. package/dist/chunks/chunk-EFBPISNT.ts.map +0 -7
  152. package/dist/chunks/chunk-G3RSMSXJ.ts.map +0 -7
  153. package/dist/chunks/chunk-I2FAK44T.ts.map +0 -7
  154. package/dist/chunks/chunk-NIF42QMF.ts.map +0 -7
  155. package/dist/chunks/chunk-QBORTI4W.ts.map +0 -7
  156. package/dist/chunks/chunk-S2IWVK3J.ts.map +0 -7
  157. package/dist/chunks/config-ui-2YUCUEBM.ts.map +0 -7
  158. package/dist/chunks/consult-IV7UBNQQ.ts.map +0 -7
  159. package/dist/chunks/execution-LA7HN5YF.ts.map +0 -7
  160. package/dist/chunks/inspect-XV2QALMR.ts.map +0 -7
  161. package/dist/chunks/persistence-VSGXAW4P.ts.map +0 -7
  162. package/dist/chunks/registry-E6XPJB7L.ts.map +0 -7
  163. package/dist/chunks/rpc-transport-NEHBHWX4.ts.map +0 -7
  164. package/dist/chunks/subprocess-transport-NSHOGDC4.ts.map +0 -7
  165. /package/dist/chunks/{auto-transport-SY2VHUFH.ts.map → auto-transport-FUUKFDIG.ts.map} +0 -0
  166. /package/dist/chunks/{capability-grant-CGEWOEKE.ts.map → capability-grant-PR72SWWS.ts.map} +0 -0
  167. /package/dist/chunks/{chunk-ZHTNCZIA.ts.map → chunk-JU6LUNLP.ts.map} +0 -0
  168. /package/dist/chunks/{chunk-PSK43Y6A.ts.map → chunk-LASD73CM.ts.map} +0 -0
  169. /package/dist/chunks/{chunk-H3BFJ7HJ.ts.map → chunk-LL4LP2T7.ts.map} +0 -0
  170. /package/dist/chunks/{chunk-SCZ33MYW.ts.map → chunk-PGLSFLYW.ts.map} +0 -0
  171. /package/dist/chunks/{chunk-O4VO6JUJ.ts.map → chunk-TM2R67J3.ts.map} +0 -0
  172. /package/dist/chunks/{chunk-HKC4ES4B.ts.map → chunk-YPJEN6NU.ts.map} +0 -0
  173. /package/dist/chunks/{completion-delivery-YPOWSSV3.ts.map → completion-delivery-RSJU6BXL.ts.map} +0 -0
  174. /package/dist/chunks/{config-status-J4GPWP46.ts.map → config-status-FKGDECZ3.ts.map} +0 -0
  175. /package/dist/chunks/{create-stateful-transport-ZP3IXNV3.ts.map → create-stateful-transport-JWC2EFYL.ts.map} +0 -0
  176. /package/dist/chunks/{delegation-contract-WJPT4FVS.ts.map → delegation-contract-LA56I5DT.ts.map} +0 -0
  177. /package/dist/chunks/{discovery-K25T3SH4.ts.map → discovery-MIFB2U4Y.ts.map} +0 -0
  178. /package/dist/chunks/{in-process-transport-4RF3J6XK.ts.map → in-process-transport-HJ6TZXC3.ts.map} +0 -0
  179. /package/dist/chunks/{retained-semantic-state-7WXSGRJU.ts.map → retained-semantic-state-GM75FZGE.ts.map} +0 -0
  180. /package/dist/chunks/{spawn-idempotency-QGHO2WKC.ts.map → spawn-idempotency-BNHOSMZW.ts.map} +0 -0
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import type { AgentScope, SubagentThinkingLevel } from "./agents/types.js";
3
+ import type { CompletionRequirementMode } from "./completion-requirement.js";
3
4
  import type { DelegationContract } from "./delegation-contract.js";
4
5
  import type { SubagentResultFormat } from "./result-contract.js";
5
6
 
@@ -23,6 +24,7 @@ export interface CanonicalSpawnRequest {
23
24
  allowConcurrentWrites: boolean;
24
25
  contract?: DelegationContract;
25
26
  resultFormat: SubagentResultFormat;
27
+ completionRequirement?: CompletionRequirementMode;
26
28
  }
27
29
 
28
30
  export function hashSpawnRequest(request: CanonicalSpawnRequest): string {
@@ -48,6 +50,9 @@ export function hashSpawnRequest(request: CanonicalSpawnRequest): string {
48
50
  allowConcurrentWrites: request.allowConcurrentWrites,
49
51
  ...(request.contract === undefined ? {} : { contract: request.contract }),
50
52
  resultFormat: request.resultFormat,
53
+ ...(request.completionRequirement === "required"
54
+ ? { completionRequirement: "required" }
55
+ : {}),
51
56
  }),
52
57
  )
53
58
  .digest("hex");
@@ -3,28 +3,10 @@ import type { ManagedAgent } from "./registry.js";
3
3
 
4
4
  export function formatStatefulAgentLine(agent: ManagedAgent, now = Date.now()): string {
5
5
  const elapsedSeconds = Math.max(0, Math.floor((now - agent.updatedAt) / 1000));
6
- const actions =
7
- agent.state === "running" || agent.state === "starting"
8
- ? "interrupt, close"
9
- : agent.state === "closed"
10
- ? "inspect"
11
- : "send, close";
12
6
  const task = agent.currentTask ? ` — ${sanitizeStatusLine(agent.currentTask, 80)}` : "";
13
7
  const unread = agent.mailbox.filter((message) => !message.readAt).length;
14
8
  const indent = " ".repeat(agent.depth);
15
- const thinking = agent.thinkingLevel ? ` thinking:${agent.thinkingLevel}` : "";
16
- const timeout = agent.currentTimeoutMs ?? agent.timeoutMs;
17
- const timeoutText = timeout ? ` timeout:${timeout}ms` : "";
18
- const idleTimeout = agent.currentIdleTimeoutMs ?? agent.idleTimeoutMs;
19
- const idleText = idleTimeout ? ` idle:${idleTimeout}ms` : "";
20
- const maxTurns = agent.currentMaxTurns ?? agent.maxTurns;
21
- const turnsText = maxTurns ? ` turns:${maxTurns}` : "";
22
- const maxToolCalls = agent.currentMaxToolCalls ?? agent.maxToolCalls;
23
- const toolsText = maxToolCalls ? ` tools:${maxToolCalls}` : "";
24
- const transport = agent.telemetry?.transport ? ` transport:${agent.telemetry.transport}` : "";
25
- const phase = agent.telemetry?.phase ? ` phase:${agent.telemetry.phase}` : "";
26
- const queued = agent.telemetry?.queuePosition ? ` queue:${agent.telemetry.queuePosition}` : "";
27
- return `${indent}${sanitizeStatusLine(agent.taskPath ?? agent.id, 256)} (${sanitizeStatusLine(agent.id, 128)}) ${sanitizeStatusLine(agent.agent, 128)} ${agent.state} ${elapsedSeconds}s${thinking}${timeoutText}${idleText}${turnsText}${toolsText}${transport}${phase}${queued} unread:${unread} [${actions}]${task}`;
9
+ return `${indent}${sanitizeStatusLine(agent.taskPath ?? agent.id, 256)} · ${sanitizeStatusLine(agent.agent, 128)} · ${agentStateLabel(agent.state)} · updated ${elapsedSeconds}s ago · ${unread} unread${task}`;
28
10
  }
29
11
 
30
12
  export function summarizeStatefulAgent(agent: ManagedAgent) {
@@ -63,6 +45,9 @@ export function summarizeStatefulAgent(agent: ManagedAgent) {
63
45
  truncated: agent.contextTruncated === true,
64
46
  },
65
47
  resultFormat: agent.resultFormat ?? "text",
48
+ completionRequirements: (agent.completionRequirements ?? []).map((record) => ({
49
+ ...record,
50
+ })),
66
51
  structuredResult: agent.structuredResult,
67
52
  termination: agent.termination,
68
53
  outcome: agent.outcome,
@@ -77,6 +62,17 @@ export function summarizeStatefulAgent(agent: ManagedAgent) {
77
62
  };
78
63
  }
79
64
 
65
+ function agentStateLabel(state: ManagedAgent["state"]): string {
66
+ switch (state) {
67
+ case "running":
68
+ return "working";
69
+ case "completed":
70
+ return "finished";
71
+ default:
72
+ return state;
73
+ }
74
+ }
75
+
80
76
  function sanitizeStatusLine(value: string, maxLength: number): string {
81
77
  return (
82
78
  value
@@ -1,35 +1,28 @@
1
- import type { CompletionDelivery } from "./agents/types.js";
2
-
3
- export function createSpawnPromptGuidelines(
4
- completionDelivery: CompletionDelivery,
5
- blockingEnabled = true,
6
- ): string[] {
7
- const deliveryGuidance =
8
- completionDelivery === "auto-resume"
9
- ? blockingEnabled
10
- ? "With subagent_spawn completion delivery set to auto-resume, prefer one subagent_spawn for broad asynchronous research or consequential independent review that covers related branches even when the final answer depends on its result; do not choose blocking parallel fan-out merely to keep delegation in the same turn."
11
- : "With subagent_spawn completion delivery set to auto-resume, prefer one subagent_spawn for broad asynchronous research or consequential independent review that covers related branches even when the final answer depends on its result."
12
- : blockingEnabled
13
- ? "With subagent_spawn completion delivery set to next-turn (the default), prefer one subagent_spawn for broad asynchronous research or consequential independent review only when the current response does not depend on its result; use the blocking subagent when the final answer depends on the detached result."
14
- : "With subagent_spawn completion delivery set to next-turn (the default), use subagent_spawn only when the current response does not depend on its result; complete final-answer-dependent work directly because an idle root is not awakened.";
1
+ export function createSpawnPromptGuidelines(blockingEnabled = true): string[] {
15
2
  return [
16
3
  "Do not use subagent_spawn for simple or critical-path work that the main agent can perform directly. The main agent retains overall planning, immediate critical-path work, integration, final verification, and the final answer.",
17
4
  "Before one ordinary subagent_spawn, identify concrete useful non-overlapping main-agent work you can start immediately and a supported completion integration path. If none exists, perform the task directly instead of calling subagent_spawn.",
18
5
  "Give subagent_spawn a concise unique taskName using lowercase letters, digits, and underscores so the retained agent has a stable canonical task path.",
19
6
  "Set subagent_spawn thinkingLevel to the lowest sufficient thinking level for the delegated task: use off or minimal for extraction, formatting, or mechanical work; low for straightforward bounded work; medium for ordinary multi-step research or implementation; high for complex debugging, design, review, or cross-file analysis; xhigh for highly ambiguous, cross-system, or high-risk analysis; and max only for the hardest tasks when quality clearly outweighs latency and cost. Omit subagent_spawn thinkingLevel only to preserve the agent or child default.",
20
- "Set subagent_spawn timeoutMs to the shortest realistic work deadline for the task difficulty; use idleTimeoutMs for stalled work and maxTurns or maxToolCalls to stop repeated work without progress. Split oversized tasks instead of extending budgets merely to compensate for broad scope. Omit these fields only to preserve the retained agent or configured defaults.",
21
- deliveryGuidance,
7
+ "Set subagent_spawn timeoutMs to the shortest realistic work deadline for the task difficulty; use idleTimeoutMs for stalled work and maxTurns or maxToolCalls to stop repeated work without progress. Scope the task to the smallest named files or questions. When setting subagent_spawn maxTurns or maxToolCalls, leave sufficient headroom for discovery, evidence reads, and final synthesis; otherwise omit them instead of guessing speculative tight values. Split oversized tasks instead of extending budgets merely to compensate for broad scope.",
8
+ "For an ordinary subagent_spawn, omit contract; use a delegation contract only when explicit acceptance, authority, evidence, or admission semantics are required.",
9
+ "Do not set subagent_spawn contract enforcement to enforce with requestedAuthority readPaths, writePaths, network, or secrets; those guarantees are unsupported and reject before child launch, while capabilities and tools remain enforceable.",
10
+ "If subagent_spawn rejects an unsupported guarantee, retry once with those fields removed or enforcement set to audit only when they were advisory; when any field is a required security boundary, stop instead of weakening it.",
11
+ "Read the current pi-subagents session-guidance message before choosing detached completion behavior. With next-turn delivery, use subagent_spawn only when the current response does not depend on its result unless useful overlap ends with an intentional subagent_await. With auto-resume delivery, final-answer-dependent detached work may continue asynchronously.",
12
+ 'Track every final-answer-dependent subagent_spawn by setting completionRequirement to "required" and retaining its returned agentId or taskPath; treat interim output as progress, and synthesize only after every corresponding completion message is visible or terminal.',
22
13
  "Keep ordinary review in the main agent with a review skill and deterministic checks; use subagent_spawn for detached review only when consequential independent verification has concrete parallel value.",
23
14
  "Use a single subagent_spawn for a bounded implementation slice with clear ownership only when it can run beside the identified main-agent work.",
24
15
  "Use a single subagent_spawn without concurrent main-agent work only for an explicit user-requested specialist model, tool profile, or isolation boundary.",
25
16
  ...(blockingEnabled
26
17
  ? [
27
- "Use the blocking subagent instead of subagent_spawn when synchronous output is required before the main agent can continue and waiting is intentional; queued steering cannot be processed until that blocking call returns.",
28
- "When subagent_spawn fits the completion-delivery policy, do not choose a blocking parallel subagent merely to keep delegation in the same turn.",
18
+ "The subagent tool is deprecated; do not select it merely because synchronous output is required. Prefer subagent_spawn with supported completion delivery, and use subagent_await only after useful overlapping main-agent work is complete and an intentional join is required.",
19
+ "Use deprecated subagent instead of subagent_spawn only for an existing caller or an explicit user request whose blocking chain, fan-in, panel, or workflow semantics do not yet have a detached replacement; queued steering cannot be processed until it returns.",
29
20
  ]
30
21
  : []),
31
22
  "Add another subagent_spawn only for truly independent work with safe workspace concurrency and disjoint write ownership; shared workspaces permit concurrent writes by default, so use workspaceMode worktree when repository isolation is required. The main agent still owns integration.",
32
23
  "After subagent_spawn returns, immediately continue the identified local task; do not merely announce the spawn, wait, poll, or end the response while useful local work remains.",
24
+ "When completionRequirement required subagent_spawn work remains active after local work is exhausted, emit at most one brief progress sentence and end the turn; do not repeat waiting updates or use the requested final format, verdict, or conclusion until every required completion is visible or terminal. Current Pi versions do not enforce a hard pre-display barrier.",
25
+ "Do not duplicate assigned work from subagent_spawn while its retained agent is running; use a bounded parent fallback only after its completion reports failure or insufficient evidence.",
33
26
  'Consume and synthesize available subagent_spawn completion messages; use subagent_manage with action "interrupt" or "close" for agents that are no longer needed.',
34
27
  'Completion from subagent_spawn is delivered automatically. Do not poll with subagent_inspect or subagent_mailbox action "read", repeatedly check progress, or duplicate the delegated work.',
35
28
  ];
@@ -28,10 +28,10 @@ export function statefulLimitListScreen(runtime: StatefulLimitRuntime) {
28
28
  const current = runtime.getRuntimeStatus().limits;
29
29
  return {
30
30
  kind: "actions" as const,
31
- title: "Detached Agent Limits",
31
+ title: "Background Agent Limits",
32
32
  lines: [
33
- "These limits apply after /reload or the next Pi session.",
34
- "Reloading can interrupt retained detached work.",
33
+ "These advanced limits apply after /reload or the next Pi session.",
34
+ "Reloading can interrupt subagents saved for follow-up.",
35
35
  ...(inspected.error
36
36
  ? [
37
37
  `Settings cannot be edited: ${safeTerminalText(inspected.error)}`,
@@ -46,7 +46,7 @@ export function statefulLimitListScreen(runtime: StatefulLimitRuntime) {
46
46
  return {
47
47
  id: definition.field,
48
48
  label: definition.label,
49
- description: `Current ${current[definition.field]} · configured ${configured?.value ?? "unavailable"} (${configured?.source ?? "unknown"})`,
49
+ description: `Current: ${current[definition.field]} · after reload: ${configured?.value ?? "unavailable"} (${configured?.source ?? "unknown"})`,
50
50
  action: "pick-stateful-limit" as const,
51
51
  };
52
52
  })
@@ -67,7 +67,7 @@ export function statefulLimitInputScreen(field: StatefulLimitField, runtime: Sta
67
67
  lines: [
68
68
  definition.description,
69
69
  `Current session: ${runtime.getRuntimeStatus().limits[field]}`,
70
- `Configured after reload: ${configured?.value ?? "unavailable"} (${configured?.source ?? "unknown"})`,
70
+ `After reload: ${configured?.value ?? "unavailable"} (${configured?.source ?? "unknown"})`,
71
71
  `Allowed: whole numbers ${definition.minimum === 0 ? "0 or greater" : "1 or greater"}`,
72
72
  `Read from: ${safeTerminalText(inspected.path)}`,
73
73
  ...(inspected.writePath !== inspected.path
@@ -114,9 +114,9 @@ export async function applyStatefulLimitSetting(
114
114
  const confirmed = await ctx.ui.confirm(
115
115
  `Lower ${statefulLimitDefinition(field).label}?`,
116
116
  [
117
- `This configured value would omit ${affectedBefore.length} currently retained agent record${affectedBefore.length === 1 ? "" : "s"} from projected recovery after reload.`,
118
- "No agent is closed now, and this menu will not reload Pi.",
119
- "A later state rewrite can make omitted records unavailable for recovery.",
117
+ `After reload, this value could exclude ${affectedBefore.length} saved subagent record${affectedBefore.length === 1 ? "" : "s"} from recovery.`,
118
+ "No subagent is removed now, and this menu will not reload Pi.",
119
+ "A later state save can make excluded records unavailable for recovery.",
120
120
  ].join("\n\n"),
121
121
  { signal: options.signal },
122
122
  );
@@ -127,7 +127,10 @@ export async function applyStatefulLimitSetting(
127
127
  [field]: next,
128
128
  });
129
129
  if (!sameIds(affectedBefore, affectedAfter)) {
130
- ctx.ui.notify("Detached agents changed while confirming; review the limit again.", "warning");
130
+ ctx.ui.notify(
131
+ "Current subagents changed while confirming; review the limit again.",
132
+ "warning",
133
+ );
131
134
  return { kind: "rejected" as const };
132
135
  }
133
136
  }
@@ -138,7 +141,7 @@ export async function applyStatefulLimitSetting(
138
141
  } catch (error) {
139
142
  if (options.isCurrent() && !options.signal.aborted) {
140
143
  ctx.ui.notify(
141
- `Detached limit was not saved; the previous setting is unchanged: ${formatError(error)}`,
144
+ `Background-agent limit was not saved; the previous setting is unchanged: ${formatError(error)}`,
142
145
  "error",
143
146
  );
144
147
  }
@@ -146,7 +149,7 @@ export async function applyStatefulLimitSetting(
146
149
  }
147
150
  if (options.signal.aborted || !options.isCurrent()) return { kind: "close" as const };
148
151
  ctx.ui.notify(
149
- `Saved ${statefulLimitDefinition(field).label.toLowerCase()}: ${next}. Applies after /reload; clear retained agents before reloading if their work must not be interrupted.`,
152
+ `Saved ${statefulLimitDefinition(field).label.toLowerCase()}: ${next}. Applies after /reload; clear current subagents first if their work must not be interrupted.`,
150
153
  "info",
151
154
  );
152
155
  return { kind: "back" as const };
@@ -154,11 +157,11 @@ export async function applyStatefulLimitSetting(
154
157
 
155
158
  export function formatDetachedLimitSummary(status: StatefulSubagentRuntimeStatus): string {
156
159
  return [
157
- `${status.limits.maxAgents} retained`,
158
- `${status.limits.maxActiveTurns} active turns`,
159
- `${status.limits.maxChildrenPerAgent} children`,
160
- `depth ${status.limits.maxDepth}`,
161
- `${status.limits.maxStoredAgents} stored`,
160
+ `${status.limits.maxAgents} saved`,
161
+ `${status.limits.maxActiveTurns} working at once`,
162
+ `${status.limits.maxChildrenPerAgent} children each`,
163
+ `${status.limits.maxDepth} nested levels`,
164
+ `${status.limits.maxStoredAgents} stored records`,
162
165
  ].join(" · ");
163
166
  }
164
167
 
@@ -172,7 +175,7 @@ export function formatConfiguredDetachedLimitDivergence(
172
175
  ? []
173
176
  : [`${definition.label.toLowerCase()} ${configured}`];
174
177
  });
175
- return changed.length > 0 ? `Configured after reload: ${changed.join(" · ")}` : undefined;
178
+ return changed.length > 0 ? `After /reload: ${changed.join(" · ")}` : undefined;
176
179
  }
177
180
 
178
181
  export function formatConfiguredDetachedLimits(
@@ -185,9 +188,9 @@ export function formatConfiguredDetachedLimits(
185
188
  }
186
189
 
187
190
  export function formatEmptyStatefulRuntime(status: StatefulSubagentRuntimeStatus): string {
188
- if (!status.enabled) return "Stateful subagents are disabled in user settings.";
189
- if (!status.initialized) return "Stateful subagents are not initialized for this session.";
190
- return "No current-session subagents.";
191
+ if (!status.enabled) return "Background subagents are disabled in How subagents run.";
192
+ if (!status.initialized) return "Background subagents have not started in this session.";
193
+ return "No subagents are working or saved for follow-up in this session.";
191
194
  }
192
195
 
193
196
  function parseStatefulLimit(
@@ -29,36 +29,36 @@ export interface StatefulLimitDefinition {
29
29
  export const STATEFUL_LIMIT_DEFINITIONS: readonly StatefulLimitDefinition[] = [
30
30
  {
31
31
  field: "maxAgents",
32
- label: "Retained agents",
33
- description: "Running, queued, and reusable idle detached agents",
32
+ label: "Subagents saved for follow-up",
33
+ description: "Working, queued, and reusable background subagents kept in one session",
34
34
  defaultValue: 16,
35
35
  minimum: 1,
36
36
  },
37
37
  {
38
38
  field: "maxActiveTurns",
39
- label: "Active turns",
40
- description: "Detached agent turns that may run at the same time",
39
+ label: "Subagents working at once",
40
+ description: "Background subagent turns that may run at the same time",
41
41
  defaultValue: 4,
42
42
  minimum: 1,
43
43
  },
44
44
  {
45
45
  field: "maxChildrenPerAgent",
46
- label: "Children per agent",
47
- description: "Direct child agents retained beneath one parent",
46
+ label: "Direct children per subagent",
47
+ description: "Subagents that one parent subagent may keep for follow-up",
48
48
  defaultValue: 8,
49
49
  minimum: 1,
50
50
  },
51
51
  {
52
52
  field: "maxDepth",
53
- label: "Agent tree depth",
54
- description: "Nested child levels below a root agent",
53
+ label: "Nested subagent levels",
54
+ description: "Child levels allowed below a top-level subagent",
55
55
  defaultValue: 3,
56
56
  minimum: 0,
57
57
  },
58
58
  {
59
59
  field: "maxStoredAgents",
60
- label: "Stored agents",
61
- description: "Detached agent records kept per session on disk",
60
+ label: "Stored subagent records",
61
+ description: "Background subagent records kept on disk for each session",
62
62
  defaultValue: 50,
63
63
  minimum: 1,
64
64
  },
@@ -17,6 +17,10 @@ import {
17
17
  THINKING_LEVELS,
18
18
  } from "./agents/types.js";
19
19
  import type { CompletionDeliveryBroker } from "./completion-delivery.js";
20
+ import {
21
+ CompletionRequirementModeSchema,
22
+ completionRequirementsFromBranch,
23
+ } from "./completion-requirement.js";
20
24
  import type { ContextMode } from "./context.js";
21
25
  import type { CreateStatefulTransportOptions } from "./create-stateful-transport.js";
22
26
  import { DelegationContractSchema } from "./delegation-contract.js";
@@ -55,7 +59,9 @@ import {
55
59
  validateManageParams,
56
60
  } from "./stateful-tool-params.js";
57
61
  import { MAX_TASK_NAME_LENGTH } from "./task-path.js";
62
+ import { grammarSafeToolObject } from "./tool-schema-compatibility.js";
58
63
  import { MAX_SUBAGENT_TOOL_CALLS, MAX_SUBAGENT_TURNS } from "./turn-budget.js";
64
+ import type { UsageRecordingController } from "./usage-recording.js";
59
65
  import type { WorkspaceManager } from "./workspace.js";
60
66
 
61
67
  type CwdPolicyModule = typeof import("./cwd-policy.js");
@@ -196,6 +202,21 @@ const StatefulTimeoutSchema = Type.Integer({
196
202
  description:
197
203
  "Work deadline in milliseconds selected for the task difficulty. On expiry, Pi aborts the work and makes one separately bounded summary attempt. Retained as the agent default.",
198
204
  });
205
+ const DEFAULT_SUBAGENT_AWAIT_TIMEOUT_MS = 30_000;
206
+ const SubagentAwaitParams = Type.Object({
207
+ agentId: Type.String({
208
+ minLength: 1,
209
+ description: "Retained agent ID or canonical task path.",
210
+ }),
211
+ timeoutMs: Type.Optional(
212
+ Type.Integer({
213
+ minimum: 1,
214
+ maximum: MAX_SUBAGENT_TIMEOUT_MS,
215
+ description:
216
+ "Maximum time to wait in milliseconds. A wait timeout stops only this tool call and does not interrupt or close the subagent. Defaults to 30000.",
217
+ }),
218
+ ),
219
+ });
199
220
  const StatefulTurnLimitFields = {
200
221
  idleTimeoutMs: Type.Optional(
201
222
  Type.Integer({
@@ -209,14 +230,16 @@ const StatefulTurnLimitFields = {
209
230
  Type.Integer({
210
231
  minimum: 1,
211
232
  maximum: MAX_SUBAGENT_TURNS,
212
- description: "Maximum unfinished assistant turns; retained as the agent default.",
233
+ description:
234
+ "Maximum unfinished assistant turns; retained as the agent default. Omit rather than guessing a tight bound.",
213
235
  }),
214
236
  ),
215
237
  maxToolCalls: Type.Optional(
216
238
  Type.Integer({
217
239
  minimum: 1,
218
240
  maximum: MAX_SUBAGENT_TOOL_CALLS,
219
- description: "Maximum tool calls; retained as the agent default.",
241
+ description:
242
+ "Maximum tool calls; retained as the agent default. Omit rather than guessing a tight bound.",
220
243
  }),
221
244
  ),
222
245
  };
@@ -227,6 +250,7 @@ export interface StatefulSubagentDependencies {
227
250
  settings?: SubagentRuntimeSettings;
228
251
  getSettings?: () => SubagentSettings | undefined;
229
252
  loadTransport?: CreateStatefulTransportOptions["loadTransport"];
253
+ usageRecording?: UsageRecordingController;
230
254
  }
231
255
 
232
256
  export interface StatefulSubagentRuntimeStatus {
@@ -242,8 +266,6 @@ export interface StatefulSubagentRuntimeStatus {
242
266
  export interface StatefulSubagentController {
243
267
  getCompletionDelivery(): CompletionDelivery;
244
268
  setCompletionDelivery(value: CompletionDelivery): void;
245
- setAgentCatalog(value: string): void;
246
- refreshSettingsGuidance(): void;
247
269
  getRuntimeStatus(): StatefulSubagentRuntimeStatus;
248
270
  listAgents(includeClosed?: boolean): ManagedAgent[];
249
271
  listRunInspection(includeClosed?: boolean): AgentRunInspectionSummary[];
@@ -268,10 +290,8 @@ export function registerStatefulSubagents(
268
290
  const transportKind = resolveStatefulTransportKind(settings.transport);
269
291
  let completionDelivery = resolveCompletionDelivery(settings.completionDelivery);
270
292
  let runtimeLimits = resolveStatefulLimits(settings);
271
- let agentCatalog = "";
272
293
  let completionBroker: CompletionDeliveryBroker | undefined;
273
294
  let peerBroker: import("./peer-communication.js").PeerCommunicationBroker | undefined;
274
- let refreshSpawnToolRegistration: (() => void) | undefined;
275
295
  let registry: AgentRegistry | undefined;
276
296
  let persistence: AgentPersistence | undefined;
277
297
  let sweepTimer: NodeJS.Timeout | undefined;
@@ -325,14 +345,6 @@ export function registerStatefulSubagents(
325
345
  setCompletionDelivery(value) {
326
346
  completionDelivery = value;
327
347
  completionBroker?.setDelivery(value);
328
- refreshSpawnToolRegistration?.();
329
- },
330
- setAgentCatalog(value) {
331
- agentCatalog = value;
332
- refreshSpawnToolRegistration?.();
333
- },
334
- refreshSettingsGuidance() {
335
- refreshSpawnToolRegistration?.();
336
348
  },
337
349
  getRuntimeStatus() {
338
350
  const counts = registry?.inspectionCounts() ?? { activeAgents: 0, retainedAgents: 0 };
@@ -362,7 +374,7 @@ export function registerStatefulSubagents(
362
374
  if (!registry) throw new Error("Stateful subagents are not initialized for this session");
363
375
  return registry;
364
376
  };
365
- pi.on("session_start", async (_event, ctx) => {
377
+ pi.on("session_start", async (event, ctx) => {
366
378
  const generation = ++runtimeGeneration;
367
379
  completionBroker?.close();
368
380
  completionBroker = undefined;
@@ -415,9 +427,16 @@ export function registerStatefulSubagents(
415
427
  const reason = error instanceof Error ? error.message : String(error);
416
428
  ctx.ui.notify(`Subagent completion delivery failed: ${reason}`, "warning");
417
429
  },
430
+ onDeliveryAttempt: (completions, input) => {
431
+ if (generation !== runtimeGeneration) return;
432
+ for (const completion of completions) {
433
+ dependencies.usageRecording?.recordCompletionDeliveryAttempt(completion, input);
434
+ }
435
+ },
418
436
  onAcknowledged: (completions, deliveredAt) => {
419
437
  if (generation !== runtimeGeneration) return;
420
438
  for (const completion of completions) {
439
+ dependencies.usageRecording?.recordCompletionVisible(completion);
421
440
  void nextRegistry
422
441
  .markCompletionDelivered(completion.completionId, deliveredAt)
423
442
  .catch((error: unknown) => {
@@ -479,6 +498,7 @@ export function registerStatefulSubagents(
479
498
  if (generation !== runtimeGeneration) return;
480
499
  await sessionPersistence.save(agents);
481
500
  if (generation !== runtimeGeneration) return;
501
+ dependencies.usageRecording?.observeAgents(agents);
482
502
  for (const agent of agents) {
483
503
  for (const message of agent.mailbox) {
484
504
  if (seenMessageIds.has(message.id)) continue;
@@ -506,9 +526,9 @@ export function registerStatefulSubagents(
506
526
  }
507
527
  },
508
528
  onTurnComplete: (completion) => {
509
- if (generation === runtimeGeneration && completion.recipientId === "root") {
510
- sessionBroker.enqueue(completion);
511
- }
529
+ if (generation !== runtimeGeneration) return;
530
+ dependencies.usageRecording?.recordChildCompletion(completion);
531
+ if (completion.recipientId === "root") sessionBroker.enqueue(completion);
512
532
  },
513
533
  });
514
534
  const persisted = sessionPersistence.load();
@@ -550,6 +570,26 @@ export function registerStatefulSubagents(
550
570
  for (const message of agent.mailbox) seenMessageIds.add(message.id);
551
571
  }
552
572
  nextRegistry.restore(restored);
573
+ const branchRequirements = completionRequirementsFromBranch(ctx.sessionManager.getBranch());
574
+ const branchOwnsRequirementState =
575
+ branchRequirements.observedState || event.reason === "fork" || event.reason === "new";
576
+ nextRegistry.reconcileCompletionRequirements(
577
+ branchRequirements.records,
578
+ branchOwnsRequirementState,
579
+ );
580
+ if (branchOwnsRequirementState) {
581
+ try {
582
+ await sessionPersistence.save(nextRegistry.list(true));
583
+ } catch (error) {
584
+ if (generation === runtimeGeneration && ctx.hasUI) {
585
+ const reason = error instanceof Error ? error.message : String(error);
586
+ ctx.ui.notify(
587
+ `Subagent requirement reconciliation could not be persisted yet: ${reason}`,
588
+ "warning",
589
+ );
590
+ }
591
+ }
592
+ }
553
593
  if (generation !== runtimeGeneration) {
554
594
  sessionBroker.close();
555
595
  await sessionPeerBroker.close();
@@ -564,7 +604,6 @@ export function registerStatefulSubagents(
564
604
  if (completion.recipientId === "root") sessionBroker.enqueue(completion);
565
605
  }
566
606
  runtimeLimits = nextLimits;
567
- refreshSpawnToolRegistration?.();
568
607
  const sweepEveryMs = Math.max(
569
608
  1_000,
570
609
  Math.min(sessionSettings.idleTtlMs ?? 60 * 60 * 1000, 60_000),
@@ -631,15 +670,14 @@ export function registerStatefulSubagents(
631
670
  await transition;
632
671
  });
633
672
 
634
- const baseSpawnDescription = () =>
635
- `Start an addressable background subagent with an opaque agentId and canonical taskPath, plus an optional thinking level and execution budgets chosen for the task difficulty, return immediately with an agentId, and receive its completion asynchronously. Detached capacity: ${runtimeLimits.maxAgents} retained agents, ${runtimeLimits.maxActiveTurns} active turns, ${runtimeLimits.maxChildrenPerAgent} direct children per agent, and depth ${runtimeLimits.maxDepth}. Working-directory target policy: ${dependencies.getSettings?.()?.cwdPolicy?.delegation ?? DEFAULT_DELEGATION_CWD_POLICY}. This controls launch targets and protected project resources, not filesystem access or sandboxing.`;
636
673
  const spawnTool = defineTool({
637
674
  name: "subagent_spawn",
638
675
  label: "Spawn Subagent",
639
- description: appendAgentCatalog(baseSpawnDescription(), agentCatalog),
676
+ description:
677
+ "Start an addressable background subagent with an opaque agentId and canonical taskPath, an optional thinking level and execution budgets chosen for the task difficulty, and asynchronous completion delivery. The current bounded capacity, completion policy, working-directory policy, and available agent definitions are published in the pi-subagents session-guidance message. Working-directory policy controls launch targets and protected project resources, not filesystem access or sandboxing.",
640
678
  promptSnippet: "Start a reusable detached subagent; completion is delivered asynchronously",
641
- promptGuidelines: createSpawnPromptGuidelines(completionDelivery, blockingEnabled),
642
- parameters: Type.Object({
679
+ promptGuidelines: createSpawnPromptGuidelines(blockingEnabled),
680
+ parameters: grammarSafeToolObject({
643
681
  agent: Type.String({ minLength: 1 }),
644
682
  taskName: Type.Optional(
645
683
  Type.String({
@@ -689,6 +727,7 @@ export function registerStatefulSubagents(
689
727
  "Use text (default), structured-v1, or the evidence-preserving structured-v2 completion contract.",
690
728
  }),
691
729
  ),
730
+ completionRequirement: Type.Optional(CompletionRequirementModeSchema),
692
731
  }),
693
732
  ...createStatefulToolRenderer("spawn"),
694
733
  async execute(_id, params, signal, _update, ctx) {
@@ -780,6 +819,7 @@ export function registerStatefulSubagents(
780
819
  allowConcurrentWrites: params.allowConcurrentWrites ?? false,
781
820
  contract,
782
821
  resultFormat,
822
+ completionRequirement: params.completionRequirement ?? "background",
783
823
  });
784
824
  if (!capturedRegistry) {
785
825
  throw new Error("Stateful subagents are not initialized for this session");
@@ -873,6 +913,7 @@ export function registerStatefulSubagents(
873
913
  spawnRequestHash: params.idempotencyKey ? requestHash : undefined,
874
914
  contract,
875
915
  resultFormat: resultFormat === "text" ? undefined : resultFormat,
916
+ completionRequirement: params.completionRequirement ?? "background",
876
917
  executionPlan,
877
918
  capabilityGrant,
878
919
  semanticSnapshot,
@@ -892,11 +933,15 @@ export function registerStatefulSubagents(
892
933
  resolvePending?.(agent);
893
934
  const deliveryNote =
894
935
  completionDelivery === "auto-resume"
895
- ? "Auto-resume will request synthesis after completion."
936
+ ? "Auto-resume steers completions into active parent work or requests synthesis when idle. Treat this response as progress, not final synthesis, until every final-answer-required completion message is visible. If local work is exhausted while required children remain active, emit at most one brief progress sentence and end the turn; do not repeat waiting updates or use the requested final format, verdict, or conclusion. Do not redo a running child's assigned work."
896
937
  : "The current response must not depend on the result because next-turn delivery will not wake an idle root.";
938
+ const requirementNote =
939
+ params.completionRequirement === "required"
940
+ ? "This exact run is runtime-tracked as required until its completion becomes visible or reaches an explicit terminal state. Current Pi versions still cannot prevent already-streamed premature output."
941
+ : "This run is background work and does not block the parent final answer.";
897
942
  return result(
898
943
  agent,
899
- `Spawned ${agent.agent} as ${agent.taskPath ?? agent.id} (${agent.id}). Continue the identified non-overlapping local work immediately; do not merely announce the spawn or end while useful local work remains. Only an explicit user-requested specialist model, tool-profile, or isolation exception may lack concurrent local work. ${deliveryNote} Do not poll for progress.`,
944
+ `Spawned ${agent.agent} as ${agent.taskPath ?? agent.id} (${agent.id}). ${requirementNote} Continue the identified non-overlapping local work immediately; do not merely announce the spawn or end while useful local work remains. Only an explicit user-requested specialist model, tool-profile, or isolation exception may lack concurrent local work. ${deliveryNote} Do not poll for progress.`,
900
945
  );
901
946
  } catch (error) {
902
947
  rejectPending?.(error);
@@ -912,12 +957,7 @@ export function registerStatefulSubagents(
912
957
  }
913
958
  },
914
959
  });
915
- refreshSpawnToolRegistration = () => {
916
- spawnTool.description = appendAgentCatalog(baseSpawnDescription(), agentCatalog);
917
- spawnTool.promptGuidelines = createSpawnPromptGuidelines(completionDelivery, blockingEnabled);
918
- pi.registerTool(spawnTool);
919
- };
920
- refreshSpawnToolRegistration();
960
+ pi.registerTool(spawnTool);
921
961
 
922
962
  pi.registerTool({
923
963
  name: "subagent_send",
@@ -937,6 +977,7 @@ export function registerStatefulSubagents(
937
977
  }),
938
978
  ),
939
979
  ...StatefulTurnLimitFields,
980
+ completionRequirement: Type.Optional(CompletionRequirementModeSchema),
940
981
  revalidate: Type.Optional(
941
982
  Type.Boolean({
942
983
  description:
@@ -1055,12 +1096,37 @@ export function registerStatefulSubagents(
1055
1096
  idleTimeoutMs: params.idleTimeoutMs,
1056
1097
  maxTurns: params.maxTurns,
1057
1098
  maxToolCalls: params.maxToolCalls,
1099
+ completionRequirement: params.completionRequirement ?? "background",
1058
1100
  });
1059
1101
  assertCurrentSpawn(signal, generation, runtimeGeneration);
1060
1102
  return result(agent, `Started follow-up for ${agent.id}.`);
1061
1103
  },
1062
1104
  });
1063
1105
 
1106
+ if (blockingEnabled) {
1107
+ pi.registerTool({
1108
+ name: "subagent_await",
1109
+ label: "Await Subagent",
1110
+ description:
1111
+ "Wait for one retained subagent's current turn to settle and return its latest bounded output. This blocks Pi from processing queued steering until the wait finishes. A wait timeout or caller cancellation stops only the wait and never interrupts or closes the subagent; use subagent_manage for lifecycle changes. Automatic completion delivery remains active and may later repeat the same at-least-once completion.",
1112
+ promptSnippet:
1113
+ "Intentionally block until one retained subagent settles or the wait times out",
1114
+ promptGuidelines: [
1115
+ "Use subagent_await only when the retained result is required before the next action, useful overlapping main-agent work is complete, and blocking Pi is intentional.",
1116
+ "Do not repeatedly call subagent_await after a timeout; the subagent keeps running and completion delivery remains active. Use subagent_manage only when the user wants to interrupt or close it.",
1117
+ ],
1118
+ parameters: SubagentAwaitParams,
1119
+ ...createStatefulToolRenderer("await"),
1120
+ async execute(_id, params, signal): Promise<StatefulActionToolResult> {
1121
+ const generation = runtimeGeneration;
1122
+ const timeoutMs = params.timeoutMs ?? DEFAULT_SUBAGENT_AWAIT_TIMEOUT_MS;
1123
+ const waited = await requireRegistry().wait(params.agentId, timeoutMs, signal);
1124
+ assertCurrentSpawn(signal, generation, runtimeGeneration);
1125
+ return awaitResult(waited.agent, waited.timedOut, timeoutMs);
1126
+ },
1127
+ });
1128
+ }
1129
+
1064
1130
  pi.registerTool({
1065
1131
  name: "subagent_manage",
1066
1132
  label: "Manage Subagents",
@@ -1214,10 +1280,6 @@ async function cleanupClosedWorkspaces(
1214
1280
  }
1215
1281
  }
1216
1282
 
1217
- function appendAgentCatalog(baseDescription: string, catalog: string): string {
1218
- return catalog ? `${baseDescription}\n\n${catalog}` : baseDescription;
1219
- }
1220
-
1221
1283
  function result(agent: ManagedAgent, text: string) {
1222
1284
  return {
1223
1285
  content: [{ type: "text" as const, text }],
@@ -1225,6 +1287,34 @@ function result(agent: ManagedAgent, text: string) {
1225
1287
  };
1226
1288
  }
1227
1289
 
1290
+ function awaitResult(agent: ManagedAgent, timedOut: boolean, timeoutMs: number) {
1291
+ const latestTurn = agent.history.at(-1);
1292
+ const output = timedOut
1293
+ ? ""
1294
+ : truncateUtf8(latestTurn?.output ?? "", DEFAULT_MAX_CONTEXT_BYTES).text;
1295
+ const error = timedOut ? "" : truncateUtf8(agent.error ?? "", MAX_TOOL_MESSAGE_BYTES).text;
1296
+ const text = timedOut
1297
+ ? `Stopped waiting for ${agent.taskPath ?? agent.id} after ${timeoutMs}ms; it remains ${agent.state}. The wait did not interrupt or close the subagent.`
1298
+ : [`Subagent ${agent.taskPath ?? agent.id} settled as ${agent.state}.`, output || error]
1299
+ .filter(Boolean)
1300
+ .join("\n\n");
1301
+ return {
1302
+ content: [
1303
+ {
1304
+ type: "text" as const,
1305
+ text: truncateUtf8(text, DEFAULT_MAX_CONTEXT_BYTES).text,
1306
+ },
1307
+ ],
1308
+ details: {
1309
+ agent: summarizeStatefulAgent(agent),
1310
+ timedOut,
1311
+ timeoutMs,
1312
+ ...(output ? { output } : {}),
1313
+ ...(error ? { error } : {}),
1314
+ },
1315
+ };
1316
+ }
1317
+
1228
1318
  function normalizeRuntimeThinkingLevel(value: string): ParentRuntimeSnapshot["thinkingLevel"] {
1229
1319
  return isThinkingLevel(value) ? value : "off";
1230
1320
  }