@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
@@ -17,7 +17,7 @@ import {
17
17
  toolHeader,
18
18
  } from "./render-common.js";
19
19
 
20
- export type StatefulRenderTool = "spawn" | "send" | "manage" | "mailbox";
20
+ export type StatefulRenderTool = "spawn" | "send" | "await" | "manage" | "mailbox";
21
21
 
22
22
  export function createStatefulToolRenderer(tool: StatefulRenderTool) {
23
23
  return {
@@ -71,6 +71,11 @@ function renderStatefulCall(tool: StatefulRenderTool, args: Record<string, unkno
71
71
  0,
72
72
  );
73
73
  }
74
+ if (tool === "await") {
75
+ const metadata = ["blocking"];
76
+ if (typeof args.timeoutMs === "number") metadata.push(`timeout:${args.timeoutMs}ms`);
77
+ return new Text(toolHeader(theme, "subagent_await", args.agentId, metadata), 0, 0);
78
+ }
74
79
  if (tool === "manage") {
75
80
  const metadata: string[] = [];
76
81
  if (typeof args.agentId === "string") metadata.push(`id:${safeLine(args.agentId, "", 256)}`);
@@ -98,9 +103,12 @@ function renderStatefulResult(
98
103
  const details = recordValue(result.details);
99
104
  const args = recordValue(context.args) ?? {};
100
105
  if (!details) return renderFallbackResult(result, options, theme, context.isError);
101
- if (tool === "spawn" || tool === "send") {
106
+ if (tool === "spawn" || tool === "send" || tool === "await") {
102
107
  const agent = recordValue(details.agent);
103
108
  if (!agent) return renderFallbackResult(result, options, theme, context.isError);
109
+ if (tool === "await" && details.timedOut === true) {
110
+ return new Text(renderAwaitTimeout(agent, result, options.expanded, theme), 0, 0);
111
+ }
104
112
  return new Text(renderAgentResult(agent, result, options.expanded, theme), 0, 0);
105
113
  }
106
114
  if (tool === "manage") {
@@ -173,6 +181,22 @@ function renderAgentResult(
173
181
  return lines.join("\n");
174
182
  }
175
183
 
184
+ function renderAwaitTimeout(
185
+ agent: Record<string, unknown>,
186
+ result: AgentToolResult<unknown>,
187
+ expanded: boolean,
188
+ theme: Theme,
189
+ ): string {
190
+ const lines = [
191
+ `${statusBadge(theme, "running")} · ${theme.fg("accent", safeLine(agent.id, "agent", 256))} · ${theme.fg("warning", "wait timed out")} · ${theme.fg("muted", safeLine(agent.state, "unknown", 128))}`,
192
+ ];
193
+ if (expanded) {
194
+ const content = safeBlock(textResult(result), "", 8 * 1024).trim();
195
+ if (content) lines.push(theme.fg("toolOutput", content));
196
+ } else lines.push(expansionHint());
197
+ return lines.join("\n");
198
+ }
199
+
176
200
  function renderManageResult(
177
201
  args: Record<string, unknown>,
178
202
  details: Record<string, unknown>,
@@ -276,6 +300,7 @@ function lifecycleStatus(state: string): RenderStatus {
276
300
  return "running";
277
301
  case "idle":
278
302
  return "idle";
303
+ case "partial":
279
304
  case "blocked":
280
305
  case "needs-input":
281
306
  case "abstained":
@@ -0,0 +1,43 @@
1
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
+ import type { SchedulingDecision } from "./adaptive-scheduler.js";
3
+ import type { AgentScope } from "./agents/types.js";
4
+ import type { OrchestrationMetrics } from "./orchestration-metrics.js";
5
+ import type { PanelSynthesis } from "./panel-contract.js";
6
+ import type { PanelEvidenceArtifact } from "./panel-evidence.js";
7
+ import type { PanelFailure } from "./panel-failure.js";
8
+ import type { PanelPhaseBudgets, PanelPreset } from "./panel-planning.js";
9
+ import type { SingleResult } from "./runner-types.js";
10
+ import type { WorkItemLedgerSnapshot } from "./work-item-ledger.js";
11
+
12
+ export interface PanelDetails {
13
+ id: string;
14
+ preset: PanelPreset;
15
+ sharedTaskPreview: string;
16
+ state: "running" | "completed" | "degraded" | "insufficient-panel" | "failed" | "cancelled";
17
+ reviewerIds: string[];
18
+ validReviewCount: number;
19
+ failedReviewCount: number;
20
+ blockingObjectionCount: number;
21
+ dissentCount: number;
22
+ budgets: PanelPhaseBudgets;
23
+ evidence: PanelEvidenceArtifact[];
24
+ failures: PanelFailure[];
25
+ synthesis?: PanelSynthesis;
26
+ synthesizerResult?: SingleResult;
27
+ cleanupComplete: boolean;
28
+ }
29
+
30
+ export interface SubagentDetails {
31
+ mode: "single" | "parallel" | "chain" | "workflow" | "panel";
32
+ agentScope: AgentScope;
33
+ projectAgentsDir: string | null;
34
+ results: SingleResult[];
35
+ aggregator?: SingleResult;
36
+ workflow?: WorkItemLedgerSnapshot;
37
+ schedulerDecisions?: SchedulingDecision[];
38
+ metrics?: OrchestrationMetrics;
39
+ panel?: PanelDetails;
40
+ isError?: boolean;
41
+ }
42
+
43
+ export type OnUpdateCallback = (partial: AgentToolResult<SubagentDetails>) => void;
@@ -39,7 +39,10 @@ import {
39
39
  import { MAX_BLOCKING_PARALLEL_CONCURRENCY } from "./limits.js";
40
40
  import { SubagentParams } from "./params.js";
41
41
  import { renderSubagentCall, renderSubagentResult } from "./render.js";
42
- import type { SubagentDetails } from "./runner.js";
42
+ import {
43
+ registerSubagentSessionGuidance,
44
+ type SubagentSessionGuidanceSnapshot,
45
+ } from "./session-guidance-contract.js";
43
46
  import {
44
47
  consumeSubagentSettingsNotice,
45
48
  DEFAULT_CONSULT_RESOURCE_POLICY,
@@ -50,7 +53,14 @@ import {
50
53
  resolveBlockingMaxParallelTasks,
51
54
  } from "./settings-reader.js";
52
55
  import { registerStatefulSubagents } from "./stateful-registration.js";
56
+ import type { SubagentDetails } from "./subagent-details.js";
53
57
  import type { SubagentTransport } from "./transport.js";
58
+ import {
59
+ registerUsageRecording,
60
+ type UsageRecordingDependencies,
61
+ type UsageSurfaceArm,
62
+ } from "./usage-recording.js";
63
+ import { resolveUsageRecordingEnabled } from "./usage-recording-config.js";
54
64
 
55
65
  type BlockingExecutionModule = Pick<typeof import("./execution.js"), "executeSubagent">;
56
66
 
@@ -60,6 +70,7 @@ export interface SubagentsDependencies {
60
70
  config?: ConfigRegistrationDependencies;
61
71
  consult?: ConsultRegistrationDependencies;
62
72
  inspect?: InspectRegistrationDependencies;
73
+ usageRecording?: Partial<UsageRecordingDependencies>;
63
74
  }
64
75
 
65
76
  export default function (pi: ExtensionAPI, dependencies: SubagentsDependencies = {}) {
@@ -68,17 +79,17 @@ export default function (pi: ExtensionAPI, dependencies: SubagentsDependencies =
68
79
  dependencies.loadBlockingExecution ?? (() => import("./execution.js")),
69
80
  );
70
81
  const configOwner = registerSubagentConfigLifecycle(pi);
82
+ const usageRecording = registerUsageRecording(pi, dependencies.usageRecording);
71
83
  const settings = readSubagentSettings();
72
84
  let currentSettings: SubagentSettings | undefined = settings;
73
85
  let currentCatalog = "";
74
86
  const blockingEnabled = settings?.blocking?.enabled !== false;
75
- const refreshBlockingCatalog = blockingEnabled
76
- ? registerBlockingSubagent(pi, () => currentSettings, loadBlockingExecution)
77
- : () => undefined;
78
- let refreshStatefulCatalog: (catalog: string) => void = () => undefined;
79
- let refreshConsultCatalog: (catalog: string) => void = () => undefined;
87
+ const statefulEnabled = settings?.stateful?.enabled !== false;
88
+ if (blockingEnabled) {
89
+ registerBlockingSubagent(pi, () => currentSettings, statefulEnabled, loadBlockingExecution);
90
+ }
80
91
 
81
- pi.on("session_start", (_event, ctx) => {
92
+ pi.on("session_start", async (event, ctx) => {
82
93
  // Preserve a one-shot migration notice from extension load while refreshing
83
94
  // validation against settings that may have changed before this session.
84
95
  const loadNotice = consumeSubagentSettingsNotice();
@@ -93,9 +104,14 @@ export default function (pi: ExtensionAPI, dependencies: SubagentsDependencies =
93
104
  currentCatalog = formatAgentCatalog(
94
105
  discoverAgentCatalog(ctx.cwd, ctx.isProjectTrusted(), refreshedSettings),
95
106
  ).text;
96
- refreshBlockingCatalog(currentCatalog);
97
- refreshStatefulCatalog(currentCatalog);
98
- refreshConsultCatalog(currentCatalog);
107
+ await usageRecording.startSession({
108
+ enabled: resolveUsageRecordingEnabled(currentSettings?.usageRecording),
109
+ surfaceArm: usageSurfaceArm(blockingEnabled, statefulRuntime.getRuntimeStatus().enabled),
110
+ reason: event.reason,
111
+ onWarning: (message) => {
112
+ if (ctx.hasUI) ctx.ui.notify(message, "warning");
113
+ },
114
+ });
99
115
  });
100
116
 
101
117
  const statefulRuntime = registerStatefulSubagents(pi, {
@@ -103,8 +119,8 @@ export default function (pi: ExtensionAPI, dependencies: SubagentsDependencies =
103
119
  settings: settings?.stateful,
104
120
  getSettings: () => currentSettings,
105
121
  loadTransport: dependencies.loadStatefulTransport,
122
+ usageRecording,
106
123
  });
107
- refreshStatefulCatalog = statefulRuntime.setAgentCatalog;
108
124
  const getBlockingEnabled = () => blockingEnabled;
109
125
  const getMaxParallelTasks = () => resolveBlockingMaxParallelTasks(currentSettings);
110
126
  const getConsultResourcePolicy = () =>
@@ -122,80 +138,102 @@ export default function (pi: ExtensionAPI, dependencies: SubagentsDependencies =
122
138
  getConsultResourcePolicy,
123
139
  getConsultationCwdPolicy,
124
140
  getDelegationCwdPolicy,
141
+ getUsageRecordingStatus: () => usageRecording.getStatus(),
125
142
  },
126
143
  dependencies.inspect,
127
144
  );
128
145
  if (blockingEnabled) {
129
- refreshConsultCatalog = registerSubagentConsult(
130
- pi,
131
- { getSettings: () => currentSettings },
132
- dependencies.consult,
133
- );
146
+ registerSubagentConsult(pi, { getSettings: () => currentSettings }, dependencies.consult);
134
147
  }
148
+ const sessionGuidance = registerSubagentSessionGuidance(
149
+ pi,
150
+ (): SubagentSessionGuidanceSnapshot => {
151
+ const runtimeStatus = statefulRuntime.getRuntimeStatus();
152
+ return {
153
+ blockingEnabled,
154
+ statefulEnabled: runtimeStatus.enabled,
155
+ completionDelivery: runtimeStatus.completionDelivery,
156
+ blockingMaxParallelTasks: resolveBlockingMaxParallelTasks(currentSettings),
157
+ statefulLimits: runtimeStatus.limits,
158
+ consultationCwdPolicy: getConsultationCwdPolicy(),
159
+ delegationCwdPolicy: getDelegationCwdPolicy(),
160
+ consultResourcePolicy: getConsultResourcePolicy(),
161
+ agentCatalog: currentCatalog,
162
+ };
163
+ },
164
+ () => statefulRuntime.listAgents(),
165
+ );
135
166
  registerSubagentConfigCommand(
136
167
  pi,
137
168
  {
138
169
  ...statefulRuntime,
170
+ setCompletionDelivery(value) {
171
+ statefulRuntime.setCompletionDelivery(value);
172
+ sessionGuidance.publish();
173
+ },
139
174
  getBlockingEnabled,
140
175
  getMaxParallelTasks,
141
176
  getConsultResourcePolicy,
142
177
  getConsultationCwdPolicy,
143
178
  getDelegationCwdPolicy,
179
+ getUsageRecordingEnabled: () => usageRecording.getStatus().enabled,
180
+ getUsageRecordingStatus: () => usageRecording.getStatus(),
181
+ setUsageRecordingEnabled: async (value: boolean) => {
182
+ await usageRecording.setEnabled(value);
183
+ currentSettings = {
184
+ ...(currentSettings ?? {}),
185
+ usageRecording: { ...(currentSettings?.usageRecording ?? {}), enabled: value },
186
+ };
187
+ },
144
188
  setMaxParallelTasks(value: number) {
145
- const previousSettings = currentSettings;
146
189
  currentSettings = {
147
190
  ...(currentSettings ?? {}),
148
191
  blocking: { ...(currentSettings?.blocking ?? {}), maxParallelTasks: value },
149
192
  };
150
- try {
151
- refreshBlockingCatalog(currentCatalog);
152
- } catch (applyError) {
153
- currentSettings = previousSettings;
154
- try {
155
- refreshBlockingCatalog(currentCatalog);
156
- } catch (rollbackError) {
157
- throw new AggregateError(
158
- [applyError, rollbackError],
159
- "Failed to apply and roll back the parallel-worker limit",
160
- );
161
- }
162
- throw applyError;
163
- }
193
+ sessionGuidance.publish();
164
194
  },
165
195
  setConsultResourcePolicy(value: ConsultResourcePolicy) {
166
196
  currentSettings = {
167
197
  ...(currentSettings ?? {}),
168
198
  consult: { ...(currentSettings?.consult ?? {}), resources: value },
169
199
  };
170
- refreshConsultCatalog(currentCatalog);
200
+ sessionGuidance.publish();
171
201
  },
172
202
  setConsultationCwdPolicy(value: ConsultationCwdPolicy) {
173
203
  currentSettings = {
174
204
  ...(currentSettings ?? {}),
175
205
  cwdPolicy: { ...(currentSettings?.cwdPolicy ?? {}), consultation: value },
176
206
  };
177
- refreshConsultCatalog(currentCatalog);
207
+ sessionGuidance.publish();
178
208
  },
179
209
  setDelegationCwdPolicy(value: DelegationCwdPolicy) {
180
210
  currentSettings = {
181
211
  ...(currentSettings ?? {}),
182
212
  cwdPolicy: { ...(currentSettings?.cwdPolicy ?? {}), delegation: value },
183
213
  };
184
- refreshBlockingCatalog(currentCatalog);
185
- statefulRuntime.refreshSettingsGuidance();
214
+ sessionGuidance.publish();
186
215
  },
187
216
  },
188
217
  configOwner,
189
218
  dependencies.config,
190
219
  );
220
+ pi.on("session_shutdown", (event) => usageRecording.shutdown(event.reason));
221
+ }
222
+
223
+ function usageSurfaceArm(blockingEnabled: boolean, statefulEnabled: boolean): UsageSurfaceArm {
224
+ if (blockingEnabled && statefulEnabled) return "all";
225
+ if (statefulEnabled) return "async-only";
226
+ if (blockingEnabled) return "blocking-only";
227
+ return "disabled";
191
228
  }
192
229
 
193
230
  function registerBlockingSubagent(
194
231
  pi: ExtensionAPI,
195
232
  getSettings: () => SubagentSettings | undefined,
233
+ statefulEnabled: boolean,
196
234
  loadExecution: () => Promise<BlockingExecutionModule>,
197
- ): (catalog: string) => void {
198
- let catalog = "";
235
+ ): void {
236
+ let deprecationWarningShown = false;
199
237
  const activeControllers = new Set<AbortController>();
200
238
  const activeWork = new Set<Promise<unknown>>();
201
239
  const cancelAndWaitForWork = async (reason: string) => {
@@ -204,29 +242,40 @@ function registerBlockingSubagent(
204
242
  }
205
243
  await Promise.allSettled([...activeWork]);
206
244
  };
207
- pi.on("session_start", () => cancelAndWaitForWork("Blocking subagent session replaced"));
245
+ pi.on("session_start", () => {
246
+ deprecationWarningShown = false;
247
+ return cancelAndWaitForWork("Blocking subagent session replaced");
248
+ });
208
249
  pi.on("session_shutdown", () => cancelAndWaitForWork("Blocking subagent session shut down"));
209
- const baseDescription = () =>
210
- [
211
- "Run specialized subagents as a blocking operation with isolated contexts.",
212
- "The call blocks the main agent until every worker and optional aggregator finishes, so queued steering waits.",
213
- "Modes: single (agent + task), parallel (tasks array), chain (sequential with {previous} placeholder), workflow (named dependency tasks with optional capability routing), or panel (independent reviewers plus evidence-preserving synthesis).",
214
- "Parallel mode may include an aggregator fan-in step; workflow mode validates dependencies, authority, artifacts, scope conflicts, retries, and hedging before scheduling. Use subagent_consult instead for one synchronous child that must be executor-constrained to read-only tools.",
215
- 'Default agent scope is "user" (from ~/.pi/agent/agents).',
216
- `To enable project-local agents in ${CONFIG_DIR_NAME}/agents, pass agentScope: "both" (or "project") as a top-level argument for that call.`,
217
- `Maximum parallel worker tasks per call: ${resolveBlockingMaxParallelTasks(getSettings())}. Parallel execution starts at most ${MAX_BLOCKING_PARALLEL_CONCURRENCY} workers at once.`,
218
- `Working-directory target policy: ${getSettings()?.cwdPolicy?.delegation ?? DEFAULT_DELEGATION_CWD_POLICY}. This controls launch targets and protected project resources, not filesystem access or sandboxing.`,
219
- ].join(" ");
220
- const promptGuidelines = () => [
221
- "Use subagent only when delegation fits; the main agent should decide how many subagents to spawn from task shape instead of waiting for the user to specify a count.",
250
+ const deprecationAlternatives = () =>
251
+ statefulEnabled
252
+ ? "Prefer the main agent for tightly coupled work, subagent_spawn for detached work, subagent_await for an intentional retained-agent join, or subagent_consult for bounded synchronous read-only evidence."
253
+ : "Prefer the main agent for tightly coupled work or subagent_consult for bounded synchronous read-only evidence; enable the background workflow before using detached alternatives.";
254
+ const baseDescription = [
255
+ "Deprecated compatibility tool: do not choose subagent for new work.",
256
+ deprecationAlternatives(),
257
+ "Run specialized subagents as a blocking operation with isolated contexts.",
258
+ "The call blocks the main agent until every worker and optional aggregator finishes, so queued steering waits.",
259
+ "Modes: single (agent + task), parallel (tasks array), chain (sequential with {previous} placeholder), workflow (named dependency tasks with optional capability routing), or panel (independent reviewers plus evidence-preserving synthesis).",
260
+ "Parallel mode may include an aggregator fan-in step; workflow mode validates dependencies, authority, artifacts, scope conflicts, retries, and hedging before scheduling. Use subagent_consult instead for one synchronous child that must be executor-constrained to read-only tools.",
261
+ 'Default agent scope is "user" (from ~/.pi/agent/agents).',
262
+ `To enable project-local agents in ${CONFIG_DIR_NAME}/agents, pass agentScope: "both" (or "project") as a top-level argument for that call.`,
263
+ `Configured parallel limits never exceed ${MAX_BLOCKING_PARALLEL_CONCURRENCY} concurrently started workers. The current call limit, working-directory policy, and available agent definitions are published in the pi-subagents session-guidance message.`,
264
+ "Working-directory policy controls launch targets and protected project resources, not filesystem access or sandboxing.",
265
+ ].join(" ");
266
+ const promptGuidelines = [
267
+ statefulEnabled
268
+ ? "The subagent tool is deprecated for new work; prefer the main agent, subagent_spawn with supported completion delivery, subagent_await for an intentional retained-agent join, or subagent_consult for bounded synchronous read-only evidence."
269
+ : "The subagent tool is deprecated for new work; prefer the main agent or subagent_consult for bounded synchronous read-only evidence, and enable the background workflow before using detached alternatives.",
270
+ "Use deprecated subagent 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.",
271
+ "When compatibility requires subagent, decide how many subagents to spawn from task shape instead of waiting for the user to specify a count.",
222
272
  "The main agent retains overall planning, immediate critical-path work, integration, final verification, and the final answer.",
223
273
  "Use no subagent for simple answers, quick targeted edits, latency-sensitive one-step work, tasks requiring frequent user back-and-forth, or critical-path work the main agent can perform directly.",
224
274
  "One ordinary implementation worker should not replace work the main agent can perform directly; use a blocking single only when intentional synchronous isolation or a user-requested specialist justifies waiting.",
225
275
  "Keep ordinary planning in the main agent, or use explicit workflow mode when a genuine dependency graph requires caller-authored orchestration.",
226
276
  "Keep ordinary review in the main agent with a review skill and deterministic checks; reserve panel mode or custom verifier agents for consequential independent verification.",
227
- "Use the blocking subagent tool only when delegated outputs are required before the main agent's next action and waiting is intentional; the main agent cannot process queued steering until the call returns.",
228
- "Use a blocking subagent single, parallel, chain, workflow, panel, or fan-in call only when synchronous context or output isolation is worth making the main agent unavailable while it runs.",
229
- `If a blocking parallel subagent call is genuinely required, keep tasks independent, stay within the configured max ${resolveBlockingMaxParallelTasks(getSettings())}, and avoid write-heavy implementation touching the same files or shared state.`,
277
+ "A compatibility subagent call blocks the main agent from processing queued steering until it returns; use it only when the explicit legacy workflow justifies making Pi unavailable.",
278
+ "If a blocking parallel subagent call is genuinely required, keep tasks independent, stay within the configured maximum from the current pi-subagents session-guidance message, and avoid write-heavy implementation touching the same files or shared state.",
230
279
  "For parallel subagent calls, omit the aggregator key entirely unless a fan-in step is required; do not send null, empty strings, or an empty object for unused optional fields.",
231
280
  "Use workflow mode for explicit dependencies or capability routing; declare read/write or ownership scopes, require structured-v2 artifacts when downstream tasks consume them, and use retry or hedging only with the required side-effect contract.",
232
281
  "Use panel mode only for consequential review or research that benefits from at least two independent reviewers and one bounded synthesis; agreement is not proof, dissent and blocking objections remain visible, and simple or latency-sensitive work should not use a panel.",
@@ -236,11 +285,11 @@ function registerBlockingSubagent(
236
285
  ];
237
286
  const definition: ToolDefinition<typeof SubagentParams, SubagentDetails> = {
238
287
  name: "subagent",
239
- label: "Blocking Subagent",
240
- description: appendAgentCatalog(baseDescription(), catalog),
288
+ label: "Blocking Subagent · Deprecated",
289
+ description: baseDescription,
241
290
  promptSnippet:
242
- "Run blocking isolated subagents only when their outputs are required before the main agent can continue.",
243
- promptGuidelines: promptGuidelines(),
291
+ "Deprecated blocking subagent compatibility tool; prefer detached or read-only alternatives.",
292
+ promptGuidelines,
244
293
  parameters: SubagentParams,
245
294
 
246
295
  async execute(toolCallId, params, signal, onUpdate, ctx) {
@@ -251,6 +300,15 @@ function registerBlockingSubagent(
251
300
  : lifecycleController.signal;
252
301
  const work = (async () => {
253
302
  throwIfAborted(effectiveSignal, "Blocking subagent execution was cancelled");
303
+ if (!deprecationWarningShown && ctx.hasUI) {
304
+ deprecationWarningShown = true;
305
+ ctx.ui.notify(
306
+ statefulEnabled
307
+ ? "subagent is deprecated for new work. Prefer the main agent, subagent_spawn with completion delivery, subagent_await for an intentional join, or subagent_consult for synchronous read-only evidence."
308
+ : "subagent is deprecated for new work. Prefer the main agent or subagent_consult; enable the background workflow before using detached alternatives.",
309
+ "warning",
310
+ );
311
+ }
254
312
  let executionModule: BlockingExecutionModule;
255
313
  try {
256
314
  executionModule = await loadExecution();
@@ -294,14 +352,4 @@ function registerBlockingSubagent(
294
352
  if ((event.details as (SubagentDetails & { isError?: boolean }) | undefined)?.isError)
295
353
  return { isError: true };
296
354
  });
297
- return (nextCatalog: string) => {
298
- catalog = nextCatalog;
299
- definition.description = appendAgentCatalog(baseDescription(), catalog);
300
- definition.promptGuidelines = promptGuidelines();
301
- pi.registerTool<typeof SubagentParams, SubagentDetails>(definition);
302
- };
303
- }
304
-
305
- function appendAgentCatalog(baseDescription: string, catalog: string): string {
306
- return catalog ? `${baseDescription}\n\n${catalog}` : baseDescription;
307
355
  }
package/src/subagents.ts CHANGED
@@ -11,6 +11,7 @@ export {
11
11
  inspectDelegationWorkflowSettings,
12
12
  inspectStatefulLimitSettings,
13
13
  inspectSubagentSettings,
14
+ inspectUsageRecordingSettings,
14
15
  normalizeAgentSettings,
15
16
  normalizeSubagentSettings,
16
17
  readSubagentSettings,
@@ -27,6 +28,7 @@ export {
27
28
  updateCwdPolicySetting,
28
29
  updateDelegationWorkflowSetting,
29
30
  updateStatefulLimitSetting,
31
+ updateUsageRecordingSetting,
30
32
  } from "./settings.js";
31
33
  export { default, type SubagentsDependencies } from "./subagents-extension.js";
32
34
  export { formatTokens, formatUsageStats } from "./usage-format.js";
@@ -8,9 +8,10 @@ import {
8
8
  } from "./peer-transport.js";
9
9
  import { resolvePiPromptResources } from "./prompt-resources.js";
10
10
  import type { ManagedAgent, TurnOutcome } from "./registry.js";
11
- import { getResultFinalOutput, runSingleAgent, type SubagentDetails } from "./runner.js";
11
+ import { getResultFinalOutput, runSingleAgent } from "./runner.js";
12
12
  import { readSubagentSettings, resolveSubagentThinkingLevel } from "./settings.js";
13
13
  import { buildStatefulTurnPrompt, resolveStatefulTurnTimeout } from "./stateful-prompt.js";
14
+ import type { SubagentDetails } from "./subagent-details.js";
14
15
  import type { SubagentTransport } from "./transport.js";
15
16
  import type { TransportProgressCallback, TransportTelemetry } from "./transport-types.js";
16
17
 
@@ -1,4 +1,5 @@
1
- import { isResultError, type SingleResult } from "./runner.js";
1
+ import { isResultError } from "./runner-outcome.js";
2
+ import type { SingleResult } from "./runner-types.js";
2
3
 
3
4
  const HEDGE_LOSER_GRACE_MS = 5_000;
4
5
 
@@ -1,7 +1,7 @@
1
1
  import { redactPrivateText } from "./context.js";
2
2
  import { DEFAULT_MAX_CONTEXT_BYTES, truncateUtf8 } from "./limits.js";
3
3
  import { appendResultInstruction, type SubagentResultFormat } from "./result-contract.js";
4
- import type { RecentActivityItem } from "./runner.js";
4
+ import type { RecentActivityItem } from "./runner-types.js";
5
5
  import {
6
6
  formatTimeoutCheckpoint,
7
7
  type TimeoutCheckpoint,
@@ -0,0 +1,73 @@
1
+ import { type TObject, type TObjectOptions, type TProperties, type TSchema, Type } from "typebox";
2
+
3
+ const LLAMA_CPP_MAX_REPETITION_THRESHOLD = 2_000;
4
+
5
+ /**
6
+ * Remove large nested string repetitions that llama.cpp cannot compile into GBNF.
7
+ *
8
+ * Runtime normalization and validation continue to bound these inputs.
9
+ * See https://github.com/ggml-org/llama.cpp/issues/25746.
10
+ */
11
+ export function grammarSafeToolObject<Properties extends TProperties>(
12
+ properties: Properties,
13
+ options?: TObjectOptions,
14
+ ): TObject<Properties> {
15
+ return makeGrammarSafeToolSchema(Type.Object(properties, options));
16
+ }
17
+
18
+ function makeGrammarSafeToolSchema<Schema extends TSchema>(schema: Schema): Schema {
19
+ return cloneSchema(schema, 0) as Schema;
20
+ }
21
+
22
+ function cloneSchema(schema: unknown, depth: number): unknown {
23
+ if (!isRecord(schema)) return schema;
24
+ const clone = cloneWithDescriptors(schema);
25
+ if (
26
+ depth > 1 &&
27
+ clone.type === "string" &&
28
+ typeof clone.maxLength === "number" &&
29
+ clone.maxLength >= LLAMA_CPP_MAX_REPETITION_THRESHOLD
30
+ ) {
31
+ delete clone.maxLength;
32
+ }
33
+ if (isRecord(clone.properties)) {
34
+ clone.properties = mapSchemas(clone.properties, depth + 1);
35
+ }
36
+ if (clone.items !== undefined) {
37
+ clone.items = Array.isArray(clone.items)
38
+ ? clone.items.map((item) => cloneSchema(item, depth + 1))
39
+ : cloneSchema(clone.items, depth + 1);
40
+ }
41
+ if (Array.isArray(clone.prefixItems)) {
42
+ clone.prefixItems = clone.prefixItems.map((item) => cloneSchema(item, depth + 1));
43
+ }
44
+ for (const keyword of ["allOf", "anyOf", "oneOf"] as const) {
45
+ if (Array.isArray(clone[keyword])) {
46
+ clone[keyword] = clone[keyword].map((item) => cloneSchema(item, depth));
47
+ }
48
+ }
49
+ if (isRecord(clone.patternProperties)) {
50
+ clone.patternProperties = mapSchemas(clone.patternProperties, depth + 1);
51
+ }
52
+ if (isRecord(clone.additionalProperties)) {
53
+ clone.additionalProperties = cloneSchema(clone.additionalProperties, depth + 1);
54
+ }
55
+ return clone;
56
+ }
57
+
58
+ function mapSchemas(schemas: Record<string, unknown>, depth: number): Record<string, unknown> {
59
+ return Object.fromEntries(
60
+ Object.entries(schemas).map(([name, schema]) => [name, cloneSchema(schema, depth)]),
61
+ );
62
+ }
63
+
64
+ function cloneWithDescriptors(value: Record<string, unknown>): Record<string, unknown> {
65
+ return Object.defineProperties(
66
+ Object.create(Object.getPrototypeOf(value)),
67
+ Object.getOwnPropertyDescriptors(value),
68
+ ) as Record<string, unknown>;
69
+ }
70
+
71
+ function isRecord(value: unknown): value is Record<string, unknown> {
72
+ return typeof value === "object" && value !== null && !Array.isArray(value);
73
+ }
@@ -50,6 +50,12 @@ export interface TransportTelemetry {
50
50
  model?: string;
51
51
  thinkingLevel?: SubagentThinkingLevel;
52
52
  usage?: TransportUsage;
53
+ budgetSource?: {
54
+ timeout: "runtime" | "explicit";
55
+ idleTimeout: "runtime" | "explicit";
56
+ turnLimit: "runtime" | "explicit";
57
+ toolCallLimit: "runtime" | "explicit";
58
+ };
53
59
  failurePhase?: TransportProgressPhase;
54
60
  }
55
61