@narumitw/pi-subagents 2.0.6 → 2.1.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 (178) hide show
  1. package/README.md +152 -50
  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-DPPVEQAM.ts → chunk-4AQSF7AS.ts} +1 -1
  5. package/dist/chunks/chunk-4AQSF7AS.ts.map +7 -0
  6. package/dist/chunks/chunk-6H6TBBED.ts +108 -0
  7. package/dist/chunks/chunk-6H6TBBED.ts.map +7 -0
  8. package/dist/chunks/{chunk-DSOOH73Y.ts → chunk-7AAJEUSL.ts} +3 -3
  9. package/dist/chunks/{chunk-DSOOH73Y.ts.map → chunk-7AAJEUSL.ts.map} +2 -2
  10. package/dist/chunks/{chunk-7QPPBBXZ.ts → chunk-D4CR7T73.ts} +21 -3
  11. package/dist/chunks/chunk-D4CR7T73.ts.map +7 -0
  12. package/dist/chunks/{chunk-434NII74.ts → chunk-DIHBUR2E.ts} +54 -8
  13. package/dist/chunks/chunk-DIHBUR2E.ts.map +7 -0
  14. package/dist/chunks/{chunk-NIF42QMF.ts → chunk-FEVPWRMU.ts} +7 -4
  15. package/dist/chunks/chunk-FEVPWRMU.ts.map +7 -0
  16. package/dist/chunks/{chunk-YBUWBRF7.ts → chunk-FXI45N3J.ts} +5 -5
  17. package/dist/chunks/{chunk-S2IWVK3J.ts → chunk-ILEQ27AL.ts} +3 -2
  18. package/dist/chunks/chunk-ILEQ27AL.ts.map +7 -0
  19. package/dist/chunks/{chunk-DQMN4OYM.ts → chunk-ITVWPNU4.ts} +12 -106
  20. package/dist/chunks/chunk-ITVWPNU4.ts.map +7 -0
  21. package/dist/chunks/{chunk-QDVGH2X7.ts → chunk-IWC32VPY.ts} +2 -1
  22. package/dist/chunks/{chunk-QDVGH2X7.ts.map → chunk-IWC32VPY.ts.map} +2 -2
  23. package/dist/chunks/{chunk-I2FAK44T.ts → chunk-JSZIP73U.ts} +48 -10
  24. package/dist/chunks/chunk-JSZIP73U.ts.map +7 -0
  25. package/dist/chunks/{chunk-ZHTNCZIA.ts → chunk-JU6LUNLP.ts} +2 -2
  26. package/dist/chunks/{chunk-PSK43Y6A.ts → chunk-LASD73CM.ts} +2 -2
  27. package/dist/chunks/{chunk-C4L6P266.ts → chunk-LEOYDZI3.ts} +1 -1
  28. package/dist/chunks/{chunk-C4L6P266.ts.map → chunk-LEOYDZI3.ts.map} +2 -2
  29. package/dist/chunks/{chunk-H3BFJ7HJ.ts → chunk-LL4LP2T7.ts} +5 -5
  30. package/dist/chunks/chunk-N2T5IN4X.ts +18 -0
  31. package/dist/chunks/chunk-N2T5IN4X.ts.map +7 -0
  32. package/dist/chunks/{chunk-G3RSMSXJ.ts → chunk-NTRPLF46.ts} +1 -1
  33. package/dist/chunks/chunk-NTRPLF46.ts.map +7 -0
  34. package/dist/chunks/{chunk-CBP76ARQ.ts → chunk-PABJJYP6.ts} +174 -47
  35. package/dist/chunks/chunk-PABJJYP6.ts.map +7 -0
  36. package/dist/chunks/{chunk-EFBPISNT.ts → chunk-PBZMBTNJ.ts} +104 -103
  37. package/dist/chunks/chunk-PBZMBTNJ.ts.map +7 -0
  38. package/dist/chunks/{chunk-SCZ33MYW.ts → chunk-PGLSFLYW.ts} +2 -2
  39. package/dist/chunks/{chunk-O4VO6JUJ.ts → chunk-TM2R67J3.ts} +3 -3
  40. package/dist/chunks/{chunk-QBORTI4W.ts → chunk-TMZRHIIK.ts} +32 -3
  41. package/dist/chunks/chunk-TMZRHIIK.ts.map +7 -0
  42. package/dist/chunks/chunk-TZ34IQ3M.ts +59 -0
  43. package/dist/chunks/chunk-TZ34IQ3M.ts.map +7 -0
  44. package/dist/chunks/chunk-VBDGNNLM.ts +214 -0
  45. package/dist/chunks/chunk-VBDGNNLM.ts.map +7 -0
  46. package/dist/chunks/{chunk-7OBINKFM.ts → chunk-VDG7LTYE.ts} +11 -11
  47. package/dist/chunks/chunk-VDG7LTYE.ts.map +7 -0
  48. package/dist/chunks/{chunk-AEUYS7JC.ts → chunk-X4NMONPE.ts} +1 -1
  49. package/dist/chunks/chunk-X4NMONPE.ts.map +7 -0
  50. package/dist/chunks/{chunk-HKC4ES4B.ts → chunk-YPJEN6NU.ts} +2 -2
  51. package/dist/chunks/{completion-delivery-YPOWSSV3.ts → completion-delivery-JVLNQRWX.ts} +5 -4
  52. package/dist/chunks/{config-status-J4GPWP46.ts → config-status-FKGDECZ3.ts} +7 -6
  53. package/dist/chunks/{config-ui-2YUCUEBM.ts → config-ui-DDKERQHI.ts} +297 -231
  54. package/dist/chunks/config-ui-DDKERQHI.ts.map +7 -0
  55. package/dist/chunks/{consult-IV7UBNQQ.ts → consult-PQ6PRAKC.ts} +14 -13
  56. package/dist/chunks/consult-PQ6PRAKC.ts.map +7 -0
  57. package/dist/chunks/{create-stateful-transport-ZP3IXNV3.ts → create-stateful-transport-JWC2EFYL.ts} +6 -6
  58. package/dist/chunks/{delegation-contract-WJPT4FVS.ts → delegation-contract-LA56I5DT.ts} +2 -2
  59. package/dist/chunks/{discovery-K25T3SH4.ts → discovery-MIFB2U4Y.ts} +3 -3
  60. package/dist/chunks/{execution-LA7HN5YF.ts → execution-Q2JZLKJA.ts} +19 -16
  61. package/dist/chunks/execution-Q2JZLKJA.ts.map +7 -0
  62. package/dist/chunks/{in-process-transport-4RF3J6XK.ts → in-process-transport-HJ6TZXC3.ts} +9 -9
  63. package/dist/chunks/{inspect-XV2QALMR.ts → inspect-UH2TKH6E.ts} +25 -10
  64. package/dist/chunks/inspect-UH2TKH6E.ts.map +7 -0
  65. package/dist/chunks/{persistence-VSGXAW4P.ts → persistence-XHPJBZL7.ts} +11 -7
  66. package/dist/chunks/persistence-XHPJBZL7.ts.map +7 -0
  67. package/dist/chunks/{registry-E6XPJB7L.ts → registry-XDXPECWF.ts} +136 -15
  68. package/dist/chunks/registry-XDXPECWF.ts.map +7 -0
  69. package/dist/chunks/{retained-semantic-state-7WXSGRJU.ts → retained-semantic-state-GM75FZGE.ts} +3 -3
  70. package/dist/chunks/{rpc-transport-NEHBHWX4.ts → rpc-transport-7R7DVCEB.ts} +12 -16
  71. package/dist/chunks/rpc-transport-7R7DVCEB.ts.map +7 -0
  72. package/dist/chunks/{spawn-idempotency-QGHO2WKC.ts → spawn-idempotency-BNHOSMZW.ts} +2 -2
  73. package/dist/chunks/{subprocess-transport-NSHOGDC4.ts → subprocess-transport-VHZJRBTW.ts} +15 -14
  74. package/dist/chunks/subprocess-transport-VHZJRBTW.ts.map +7 -0
  75. package/dist/chunks/usage-recording-store-CW3EH2SZ.ts +164 -0
  76. package/dist/chunks/usage-recording-store-CW3EH2SZ.ts.map +7 -0
  77. package/dist/index.ts +427 -30
  78. package/dist/index.ts.map +3 -3
  79. package/docs/async-runtime-protocol.md +69 -0
  80. package/docs/implementation-notes/pi-subagents-capability-matrix.md +62 -0
  81. package/docs/implementation-notes/pi-subagents-current-direction.md +99 -0
  82. package/docs/implementation-notes/pi-subagents-rpc-v1.md +153 -0
  83. package/docs/pi-subagents-diagrams.md +183 -0
  84. package/package.json +9 -8
  85. package/src/agents/types.ts +2 -0
  86. package/src/async-subagent-benchmark.ts +532 -0
  87. package/src/completion-delivery.ts +71 -4
  88. package/src/completion-render.ts +1 -0
  89. package/src/completion-requirement.ts +308 -0
  90. package/src/config-registration.ts +5 -5
  91. package/src/config-status.ts +66 -70
  92. package/src/config-ui.ts +244 -150
  93. package/src/consult-resources.ts +1 -1
  94. package/src/consult.ts +3 -8
  95. package/src/delegation-contract.ts +55 -9
  96. package/src/execution-plan.ts +1 -1
  97. package/src/execution-ui.ts +40 -29
  98. package/src/execution.ts +2 -3
  99. package/src/inspect.ts +24 -1
  100. package/src/orchestration-metrics.ts +1 -1
  101. package/src/panel-execution.ts +2 -3
  102. package/src/panel-failure.ts +1 -1
  103. package/src/panel-render.ts +1 -1
  104. package/src/parallel-limit-ui.ts +6 -5
  105. package/src/params.ts +2 -1
  106. package/src/persistence.ts +9 -0
  107. package/src/process-control.ts +43 -0
  108. package/src/registry-types.ts +5 -0
  109. package/src/registry.ts +162 -18
  110. package/src/render.ts +2 -1
  111. package/src/rpc-transport.ts +1 -1
  112. package/src/runner-outcome.ts +1 -1
  113. package/src/runner-result.ts +1 -1
  114. package/src/runner-types.ts +102 -0
  115. package/src/runner.ts +11 -192
  116. package/src/settings/inspection.ts +27 -0
  117. package/src/settings/schema.ts +9 -0
  118. package/src/settings-reader.ts +7 -0
  119. package/src/settings.ts +20 -0
  120. package/src/spawn-idempotency.ts +5 -0
  121. package/src/stateful-agent-view.ts +15 -19
  122. package/src/stateful-guidance.ts +14 -4
  123. package/src/stateful-limit-ui.ts +23 -20
  124. package/src/stateful-limits.ts +10 -10
  125. package/src/stateful-registration.ts +126 -9
  126. package/src/stateful-render.ts +27 -2
  127. package/src/subagent-details.ts +43 -0
  128. package/src/subagents-extension.ts +66 -8
  129. package/src/subagents.ts +2 -0
  130. package/src/subprocess-transport.ts +2 -1
  131. package/src/supervision.ts +2 -1
  132. package/src/timeout-finalization.ts +1 -1
  133. package/src/tool-schema-compatibility.ts +73 -0
  134. package/src/transport-types.ts +6 -0
  135. package/src/transport-ui.ts +18 -46
  136. package/src/usage-recording-config.ts +13 -0
  137. package/src/usage-recording-store.ts +183 -0
  138. package/src/usage-recording.ts +478 -0
  139. package/src/verification-harness.ts +1 -1
  140. package/src/workflow-ui.ts +17 -9
  141. package/dist/chunks/chunk-434NII74.ts.map +0 -7
  142. package/dist/chunks/chunk-7OBINKFM.ts.map +0 -7
  143. package/dist/chunks/chunk-7QPPBBXZ.ts.map +0 -7
  144. package/dist/chunks/chunk-AEUYS7JC.ts.map +0 -7
  145. package/dist/chunks/chunk-CBP76ARQ.ts.map +0 -7
  146. package/dist/chunks/chunk-DPPVEQAM.ts.map +0 -7
  147. package/dist/chunks/chunk-DQMN4OYM.ts.map +0 -7
  148. package/dist/chunks/chunk-EFBPISNT.ts.map +0 -7
  149. package/dist/chunks/chunk-G3RSMSXJ.ts.map +0 -7
  150. package/dist/chunks/chunk-I2FAK44T.ts.map +0 -7
  151. package/dist/chunks/chunk-NIF42QMF.ts.map +0 -7
  152. package/dist/chunks/chunk-QBORTI4W.ts.map +0 -7
  153. package/dist/chunks/chunk-S2IWVK3J.ts.map +0 -7
  154. package/dist/chunks/config-ui-2YUCUEBM.ts.map +0 -7
  155. package/dist/chunks/consult-IV7UBNQQ.ts.map +0 -7
  156. package/dist/chunks/execution-LA7HN5YF.ts.map +0 -7
  157. package/dist/chunks/inspect-XV2QALMR.ts.map +0 -7
  158. package/dist/chunks/persistence-VSGXAW4P.ts.map +0 -7
  159. package/dist/chunks/registry-E6XPJB7L.ts.map +0 -7
  160. package/dist/chunks/rpc-transport-NEHBHWX4.ts.map +0 -7
  161. package/dist/chunks/subprocess-transport-NSHOGDC4.ts.map +0 -7
  162. /package/dist/chunks/{auto-transport-SY2VHUFH.ts.map → auto-transport-FUUKFDIG.ts.map} +0 -0
  163. /package/dist/chunks/{capability-grant-CGEWOEKE.ts.map → capability-grant-PR72SWWS.ts.map} +0 -0
  164. /package/dist/chunks/{chunk-YBUWBRF7.ts.map → chunk-FXI45N3J.ts.map} +0 -0
  165. /package/dist/chunks/{chunk-ZHTNCZIA.ts.map → chunk-JU6LUNLP.ts.map} +0 -0
  166. /package/dist/chunks/{chunk-PSK43Y6A.ts.map → chunk-LASD73CM.ts.map} +0 -0
  167. /package/dist/chunks/{chunk-H3BFJ7HJ.ts.map → chunk-LL4LP2T7.ts.map} +0 -0
  168. /package/dist/chunks/{chunk-SCZ33MYW.ts.map → chunk-PGLSFLYW.ts.map} +0 -0
  169. /package/dist/chunks/{chunk-O4VO6JUJ.ts.map → chunk-TM2R67J3.ts.map} +0 -0
  170. /package/dist/chunks/{chunk-HKC4ES4B.ts.map → chunk-YPJEN6NU.ts.map} +0 -0
  171. /package/dist/chunks/{completion-delivery-YPOWSSV3.ts.map → completion-delivery-JVLNQRWX.ts.map} +0 -0
  172. /package/dist/chunks/{config-status-J4GPWP46.ts.map → config-status-FKGDECZ3.ts.map} +0 -0
  173. /package/dist/chunks/{create-stateful-transport-ZP3IXNV3.ts.map → create-stateful-transport-JWC2EFYL.ts.map} +0 -0
  174. /package/dist/chunks/{delegation-contract-WJPT4FVS.ts.map → delegation-contract-LA56I5DT.ts.map} +0 -0
  175. /package/dist/chunks/{discovery-K25T3SH4.ts.map → discovery-MIFB2U4Y.ts.map} +0 -0
  176. /package/dist/chunks/{in-process-transport-4RF3J6XK.ts.map → in-process-transport-HJ6TZXC3.ts.map} +0 -0
  177. /package/dist/chunks/{retained-semantic-state-7WXSGRJU.ts.map → retained-semantic-state-GM75FZGE.ts.map} +0 -0
  178. /package/dist/chunks/{spawn-idempotency-QGHO2WKC.ts.map → spawn-idempotency-BNHOSMZW.ts.map} +0 -0
package/dist/index.ts CHANGED
@@ -5,33 +5,40 @@ import {
5
5
  formatAgentCatalog,
6
6
  formatUsageStats,
7
7
  registerSubagentConsult
8
- } from "./chunks/chunk-YBUWBRF7.ts";
8
+ } from "./chunks/chunk-FXI45N3J.ts";
9
9
  import {
10
10
  registerSubagentInspect
11
- } from "./chunks/chunk-ZHTNCZIA.ts";
11
+ } from "./chunks/chunk-JU6LUNLP.ts";
12
12
  import {
13
13
  SubagentParams,
14
14
  hasUsableAggregator
15
- } from "./chunks/chunk-NIF42QMF.ts";
15
+ } from "./chunks/chunk-FEVPWRMU.ts";
16
16
  import {
17
17
  cachedModuleLoader,
18
18
  throwIfAborted
19
19
  } from "./chunks/chunk-HOP5FXDT.ts";
20
20
  import {
21
21
  registerStatefulSubagents
22
- } from "./chunks/chunk-CBP76ARQ.ts";
23
- import "./chunks/chunk-S2IWVK3J.ts";
22
+ } from "./chunks/chunk-PABJJYP6.ts";
23
+ import "./chunks/chunk-TZ34IQ3M.ts";
24
+ import "./chunks/chunk-ILEQ27AL.ts";
24
25
  import "./chunks/chunk-P7OH4XMF.ts";
25
26
  import "./chunks/chunk-N7BLVXKK.ts";
26
27
  import {
27
28
  getResultFinalOutput,
28
29
  isResultError
29
- } from "./chunks/chunk-AEUYS7JC.ts";
30
+ } from "./chunks/chunk-X4NMONPE.ts";
30
31
  import "./chunks/chunk-RTCVYIZA.ts";
31
32
  import "./chunks/chunk-ONDTY4EL.ts";
32
- import "./chunks/chunk-O4VO6JUJ.ts";
33
- import "./chunks/chunk-PSK43Y6A.ts";
33
+ import "./chunks/chunk-TM2R67J3.ts";
34
+ import "./chunks/chunk-LASD73CM.ts";
34
35
  import "./chunks/chunk-RSUXZD6S.ts";
36
+ import {
37
+ USAGE_RECORDING_DIRECTORY,
38
+ USAGE_RECORDING_RETENTION_DAYS,
39
+ USAGE_RECORDING_STUDY_ID,
40
+ resolveUsageRecordingEnabled
41
+ } from "./chunks/chunk-N2T5IN4X.ts";
35
42
  import {
36
43
  DEFAULT_CONSULTATION_CWD_POLICY,
37
44
  DEFAULT_CONSULT_RESOURCE_POLICY,
@@ -40,21 +47,22 @@ import {
40
47
  inspectSubagentSettings,
41
48
  readSubagentSettings,
42
49
  resolveBlockingMaxParallelTasks
43
- } from "./chunks/chunk-QBORTI4W.ts";
44
- import "./chunks/chunk-7OBINKFM.ts";
45
- import "./chunks/chunk-DPPVEQAM.ts";
50
+ } from "./chunks/chunk-TMZRHIIK.ts";
51
+ import "./chunks/chunk-VDG7LTYE.ts";
52
+ import "./chunks/chunk-4AQSF7AS.ts";
46
53
  import {
47
54
  SUBAGENT_COMPLETION_MESSAGE_TYPE,
48
55
  renderCompletionMessage
49
- } from "./chunks/chunk-QDVGH2X7.ts";
56
+ } from "./chunks/chunk-IWC32VPY.ts";
50
57
  import {
51
58
  expansionHint,
52
59
  formatToolActivity,
53
60
  safeBlock,
54
61
  safeLine
55
62
  } from "./chunks/chunk-BFK2Z4ZF.ts";
63
+ import "./chunks/chunk-VBDGNNLM.ts";
56
64
  import "./chunks/chunk-SWGQLFSD.ts";
57
- import "./chunks/chunk-I2FAK44T.ts";
65
+ import "./chunks/chunk-JSZIP73U.ts";
58
66
  import {
59
67
  MAX_BLOCKING_PARALLEL_CONCURRENCY
60
68
  } from "./chunks/chunk-H3FP6DLR.ts";
@@ -66,9 +74,9 @@ import {
66
74
 
67
75
  // src/config-registration.ts
68
76
  var SUBCOMMANDS = [
69
- { value: "settings", label: "settings", description: "Configure subagent user settings" },
70
- { value: "status", label: "status", description: "Show effective subagent settings" },
71
- { value: "help", label: "help", description: "Show subagent settings help" }
77
+ { value: "settings", label: "settings", description: "Open grouped subagent settings" },
78
+ { value: "status", label: "status", description: "Show detailed subagent diagnostics" },
79
+ { value: "help", label: "help", description: "Show subagent first steps and safety help" }
72
80
  ];
73
81
  function registerSubagentConfigLifecycle(pi) {
74
82
  const owner = { generation: 0, controller: new AbortController() };
@@ -85,13 +93,13 @@ function registerSubagentConfigLifecycle(pi) {
85
93
  }
86
94
  function registerSubagentConfigCommand(pi, runtime, owner = registerSubagentConfigLifecycle(pi), dependencies = {}) {
87
95
  const loadConfigUi = cachedModuleLoader(
88
- dependencies.loadConfigUi ?? (() => import("./chunks/config-ui-2YUCUEBM.ts"))
96
+ dependencies.loadConfigUi ?? (() => import("./chunks/config-ui-DDKERQHI.ts"))
89
97
  );
90
98
  const loadConfigStatus = cachedModuleLoader(
91
- dependencies.loadConfigStatus ?? (() => import("./chunks/config-status-J4GPWP46.ts"))
99
+ dependencies.loadConfigStatus ?? (() => import("./chunks/config-status-FKGDECZ3.ts"))
92
100
  );
93
101
  pi.registerCommand("subagents", {
94
- description: "Manage current-session subagents and user settings",
102
+ description: "Manage subagents, settings, diagnostics, and help",
95
103
  getArgumentCompletions(prefix) {
96
104
  const normalized = prefix.trim().toLowerCase();
97
105
  const matches = SUBCOMMANDS.filter((item) => item.value.startsWith(normalized));
@@ -138,7 +146,7 @@ function registerSubagentConfigCommand(pi, runtime, owner = registerSubagentConf
138
146
  }
139
147
  if (!isCurrent()) return;
140
148
  if (!subcommand) await configUi.showSubagentManager(pi, ctx, runtime, owner);
141
- else await configUi.showSubagentSettings(ctx, runtime, owner);
149
+ else await configUi.showSubagentSettings(pi, ctx, runtime, owner);
142
150
  return;
143
151
  }
144
152
  if (ctx.mode === "tui" || ctx.hasUI) {
@@ -828,13 +836,360 @@ ${expansionHint()}`;
828
836
  );
829
837
  }
830
838
 
839
+ // src/usage-recording.ts
840
+ import { randomUUID } from "node:crypto";
841
+ import path from "node:path";
842
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
843
+ var SHUTDOWN_FLUSH_MS = 2500;
844
+ var SUBAGENT_TOOLS = /* @__PURE__ */ new Set([
845
+ "subagent",
846
+ "subagent_spawn",
847
+ "subagent_send",
848
+ "subagent_manage",
849
+ "subagent_mailbox",
850
+ "subagent_inspect",
851
+ "subagent_consult",
852
+ "subagent_await"
853
+ ]);
854
+ function registerUsageRecording(pi, dependencies = {}) {
855
+ const deps = {
856
+ createId: dependencies.createId ?? randomUUID,
857
+ monotonicNow: dependencies.monotonicNow ?? performance.now.bind(performance),
858
+ getAgentDir: dependencies.getAgentDir ?? getAgentDir,
859
+ loadStore: dependencies.loadStore ?? (() => import("./chunks/usage-recording-store-CW3EH2SZ.ts"))
860
+ };
861
+ const pathValue = path.join(deps.getAgentDir(), USAGE_RECORDING_DIRECTORY);
862
+ const runtimeInstance = deps.createId();
863
+ let logicalSession = deps.createId();
864
+ let branchEpoch = 0;
865
+ let surfaceArm = "disabled";
866
+ let sessionStartedAt = deps.monotonicNow();
867
+ let enabled = false;
868
+ let eventSequence = 0;
869
+ let recordedEvents = 0;
870
+ let writeFailure = false;
871
+ let warningActive = false;
872
+ let onWarning;
873
+ let storePromise;
874
+ let writeGeneration = 0;
875
+ let writeTail = Promise.resolve();
876
+ let transitionTail = Promise.resolve();
877
+ let currentTurnId;
878
+ let turnOrdinal = 0;
879
+ let operationOrdinal = 0;
880
+ let childOrdinal = 0;
881
+ let runOrdinal = 0;
882
+ let completionOrdinal = 0;
883
+ const operations = /* @__PURE__ */ new Map();
884
+ const children = /* @__PURE__ */ new Map();
885
+ const runs = /* @__PURE__ */ new Map();
886
+ const completions = /* @__PURE__ */ new Map();
887
+ const agentStates = /* @__PURE__ */ new Map();
888
+ const activeRuns = /* @__PURE__ */ new Map();
889
+ pi.on("agent_start", () => record("lifecycle", { phase: "parent_agent_start" }));
890
+ pi.on("agent_settled", () => record("lifecycle", { phase: "parent_agent_settled" }));
891
+ pi.on("turn_start", () => {
892
+ currentTurnId = `turn-${++turnOrdinal}`;
893
+ record("parent_turn_start", { turnOrdinal }, currentTurnId);
894
+ });
895
+ pi.on("turn_end", (event) => {
896
+ record(
897
+ "parent_turn_end",
898
+ {
899
+ turnOrdinal,
900
+ ...usageNumbers(event.message.role === "assistant" ? event.message.usage : void 0)
901
+ },
902
+ currentTurnId
903
+ );
904
+ currentTurnId = void 0;
905
+ });
906
+ pi.on("tool_execution_start", (event) => {
907
+ if (!SUBAGENT_TOOLS.has(event.toolName)) return;
908
+ const operationId = `tool-${++operationOrdinal}`;
909
+ operations.set(event.toolCallId, { id: operationId, startedAt: offset() });
910
+ record("tool_start", { operationId, tool: event.toolName }, currentTurnId);
911
+ });
912
+ pi.on("tool_execution_end", (event) => {
913
+ if (!SUBAGENT_TOOLS.has(event.toolName)) return;
914
+ const operation = operations.get(event.toolCallId);
915
+ operations.delete(event.toolCallId);
916
+ record(
917
+ "tool_end",
918
+ {
919
+ operationId: operation?.id ?? `tool-${++operationOrdinal}`,
920
+ tool: event.toolName,
921
+ isError: event.isError,
922
+ ...operation ? { durationMs: Math.max(0, offset() - operation.startedAt) } : {},
923
+ ...usageNumbers(event.result?.usage)
924
+ },
925
+ currentTurnId
926
+ );
927
+ });
928
+ const controller = {
929
+ startSession(input) {
930
+ return serializeTransition(async () => {
931
+ enabled = false;
932
+ await closeStore();
933
+ logicalSession = deps.createId();
934
+ branchEpoch += 1;
935
+ surfaceArm = input.surfaceArm;
936
+ sessionStartedAt = deps.monotonicNow();
937
+ eventSequence = 0;
938
+ recordedEvents = 0;
939
+ writeFailure = false;
940
+ warningActive = false;
941
+ onWarning = input.onWarning;
942
+ currentTurnId = void 0;
943
+ turnOrdinal = 0;
944
+ operationOrdinal = 0;
945
+ childOrdinal = 0;
946
+ runOrdinal = 0;
947
+ completionOrdinal = 0;
948
+ operations.clear();
949
+ children.clear();
950
+ runs.clear();
951
+ completions.clear();
952
+ agentStates.clear();
953
+ activeRuns.clear();
954
+ enabled = input.enabled;
955
+ if (!enabled) return;
956
+ record("study_exposure", { reason: input.reason });
957
+ record("lifecycle", { phase: "session_start", reason: input.reason });
958
+ enqueue(async (store) => store.prune(USAGE_RECORDING_RETENTION_DAYS));
959
+ await writeTail;
960
+ });
961
+ },
962
+ shutdown(reason) {
963
+ return serializeTransition(async () => {
964
+ if (enabled) record("lifecycle", { phase: "session_shutdown", reason });
965
+ enabled = false;
966
+ await flushWithin(SHUTDOWN_FLUSH_MS);
967
+ await closeStore();
968
+ });
969
+ },
970
+ setEnabled(value) {
971
+ return serializeTransition(async () => {
972
+ if (value === enabled) return;
973
+ if (value) {
974
+ enabled = true;
975
+ record("study_exposure", { reason: "enabled_in_settings" });
976
+ record("lifecycle", { phase: "recording_enabled" });
977
+ enqueue(async (store) => store.prune(USAGE_RECORDING_RETENTION_DAYS));
978
+ await writeTail;
979
+ return;
980
+ }
981
+ record("lifecycle", { phase: "recording_disabled" });
982
+ enabled = false;
983
+ await flushWithin(SHUTDOWN_FLUSH_MS);
984
+ await closeStore();
985
+ });
986
+ },
987
+ getStatus() {
988
+ return {
989
+ enabled,
990
+ initialized: storePromise !== void 0,
991
+ retentionDays: USAGE_RECORDING_RETENTION_DAYS,
992
+ path: pathValue,
993
+ recordedEvents,
994
+ writeFailure
995
+ };
996
+ },
997
+ observeAgents(agents) {
998
+ if (!enabled) return;
999
+ for (const agent of agents) {
1000
+ const childId = localChildId(agent.id);
1001
+ if (agentStates.get(agent.id) !== agent.state) {
1002
+ agentStates.set(agent.id, agent.state);
1003
+ record("lifecycle", { phase: "child_state", childId, state: agent.state });
1004
+ }
1005
+ if (agent.currentRunId && activeRuns.get(agent.id) !== agent.currentRunId) {
1006
+ activeRuns.set(agent.id, agent.currentRunId);
1007
+ record("child_run_start", {
1008
+ childId,
1009
+ runId: localRunId(agent.currentRunId),
1010
+ generation: agent.currentTurnGeneration ?? agent.turnGeneration ?? 0
1011
+ });
1012
+ }
1013
+ }
1014
+ },
1015
+ recordChildCompletion(completion) {
1016
+ if (!enabled) return;
1017
+ const childId = localChildId(completion.agent.id);
1018
+ const runId = localRunId(completion.runId);
1019
+ const timing = completion.agent.telemetry?.timing;
1020
+ record("child_run_end", {
1021
+ childId,
1022
+ runId,
1023
+ generation: completion.generation,
1024
+ state: completion.agent.state,
1025
+ ...completion.agent.outcome?.status ? { outcomeStatus: completion.agent.outcome.status } : {},
1026
+ ...completion.agent.termination?.reason ? { terminationReason: completion.agent.termination.reason } : {},
1027
+ ...completion.agent.telemetry?.budgetSource ? {
1028
+ timeoutBudgetSource: completion.agent.telemetry.budgetSource.timeout,
1029
+ idleTimeoutBudgetSource: completion.agent.telemetry.budgetSource.idleTimeout,
1030
+ turnLimitBudgetSource: completion.agent.telemetry.budgetSource.turnLimit,
1031
+ toolCallLimitBudgetSource: completion.agent.telemetry.budgetSource.toolCallLimit
1032
+ } : {},
1033
+ ...timing?.startedAt !== void 0 && timing.settledAt !== void 0 ? { durationMs: Math.max(0, timing.settledAt - timing.startedAt) } : {},
1034
+ ...transportUsageNumbers(completion.agent.telemetry?.usage)
1035
+ });
1036
+ recordCompletion(completion, "persisted");
1037
+ },
1038
+ recordCompletionDeliveryAttempt(completion, input) {
1039
+ recordCompletion(completion, "delivery_attempt", {
1040
+ delivery: input.delivery,
1041
+ triggerTurn: input.triggerTurn,
1042
+ outcome: input.outcome
1043
+ });
1044
+ },
1045
+ recordCompletionVisible(completion) {
1046
+ recordCompletion(completion, "visible");
1047
+ }
1048
+ };
1049
+ return controller;
1050
+ function record(eventType, data, turnId = currentTurnId) {
1051
+ if (!enabled) return;
1052
+ const event = {
1053
+ schemaVersion: 1,
1054
+ studyId: USAGE_RECORDING_STUDY_ID,
1055
+ surfaceArm,
1056
+ logicalSession,
1057
+ runtimeInstance,
1058
+ branchEpoch,
1059
+ ...turnId ? { turnId } : {},
1060
+ eventSequence: ++eventSequence,
1061
+ monotonicOffsetMs: offset(),
1062
+ eventType,
1063
+ data
1064
+ };
1065
+ enqueue(async (store) => store.append(event), true);
1066
+ }
1067
+ function recordCompletion(completion, transition, extra = {}) {
1068
+ if (!enabled) return;
1069
+ record("completion_transition", {
1070
+ completionId: localCompletionId(completion.completionId),
1071
+ childId: localChildId(completion.agent.id),
1072
+ runId: localRunId(completion.runId),
1073
+ generation: completion.generation,
1074
+ transition,
1075
+ ...extra
1076
+ });
1077
+ }
1078
+ function enqueue(operation, countsAsEvent = false) {
1079
+ const generation = writeGeneration;
1080
+ const task = writeTail.then(async () => {
1081
+ if (generation !== writeGeneration) return false;
1082
+ await operation(await ensureStore());
1083
+ return true;
1084
+ });
1085
+ writeTail = task.then(
1086
+ (completed) => {
1087
+ if (completed && countsAsEvent) recordedEvents += 1;
1088
+ writeFailure = false;
1089
+ warningActive = false;
1090
+ },
1091
+ () => {
1092
+ writeFailure = true;
1093
+ if (!warningActive) {
1094
+ warningActive = true;
1095
+ safeWarn("Local subagent usage recording could not save an event; recording will retry.");
1096
+ }
1097
+ }
1098
+ );
1099
+ }
1100
+ async function ensureStore() {
1101
+ storePromise ??= deps.loadStore().then(({ UsageEventStore }) => new UsageEventStore(pathValue)).catch((error) => {
1102
+ storePromise = void 0;
1103
+ throw error;
1104
+ });
1105
+ return storePromise;
1106
+ }
1107
+ function serializeTransition(operation) {
1108
+ const result = transitionTail.then(operation, operation);
1109
+ transitionTail = result.catch(() => void 0);
1110
+ return result;
1111
+ }
1112
+ async function flushWithin(timeoutMs) {
1113
+ let timer;
1114
+ try {
1115
+ await Promise.race([
1116
+ writeTail,
1117
+ new Promise((resolve) => {
1118
+ timer = setTimeout(resolve, timeoutMs);
1119
+ })
1120
+ ]);
1121
+ } finally {
1122
+ if (timer) clearTimeout(timer);
1123
+ }
1124
+ }
1125
+ async function closeStore() {
1126
+ writeGeneration += 1;
1127
+ const active = storePromise;
1128
+ storePromise = void 0;
1129
+ if (active) await active.then((store) => store.close()).catch(() => void 0);
1130
+ await writeTail;
1131
+ writeTail = Promise.resolve();
1132
+ }
1133
+ function localChildId(value) {
1134
+ return localId(children, value, "child", () => ++childOrdinal);
1135
+ }
1136
+ function localRunId(value) {
1137
+ return localId(runs, value, "run", () => ++runOrdinal);
1138
+ }
1139
+ function localCompletionId(value) {
1140
+ return localId(completions, value, "completion", () => ++completionOrdinal);
1141
+ }
1142
+ function offset() {
1143
+ return Math.max(0, Math.round(deps.monotonicNow() - sessionStartedAt));
1144
+ }
1145
+ function safeWarn(message) {
1146
+ try {
1147
+ onWarning?.(message);
1148
+ } catch {
1149
+ }
1150
+ }
1151
+ }
1152
+ function localId(values, raw, prefix, next) {
1153
+ const existing = values.get(raw);
1154
+ if (existing) return existing;
1155
+ const created = `${prefix}-${next()}`;
1156
+ values.set(raw, created);
1157
+ return created;
1158
+ }
1159
+ function usageNumbers(value) {
1160
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
1161
+ const record = value;
1162
+ return numericFields(record, ["input", "output", "cacheRead", "cacheWrite"]);
1163
+ }
1164
+ function transportUsageNumbers(value) {
1165
+ if (!value) return {};
1166
+ return numericFields(value, [
1167
+ "input",
1168
+ "output",
1169
+ "cacheRead",
1170
+ "cacheWrite",
1171
+ "totalTokens",
1172
+ "cost",
1173
+ "turns"
1174
+ ]);
1175
+ }
1176
+ function numericFields(record, fields) {
1177
+ return Object.fromEntries(
1178
+ fields.flatMap((field) => {
1179
+ const value = record[field];
1180
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? [[field, value]] : [];
1181
+ })
1182
+ );
1183
+ }
1184
+
831
1185
  // src/subagents-extension.ts
832
1186
  function subagents_extension_default(pi, dependencies = {}) {
833
1187
  pi.registerMessageRenderer(SUBAGENT_COMPLETION_MESSAGE_TYPE, renderCompletionMessage);
834
1188
  const loadBlockingExecution = cachedModuleLoader(
835
- dependencies.loadBlockingExecution ?? (() => import("./chunks/execution-LA7HN5YF.ts"))
1189
+ dependencies.loadBlockingExecution ?? (() => import("./chunks/execution-Q2JZLKJA.ts"))
836
1190
  );
837
1191
  const configOwner = registerSubagentConfigLifecycle(pi);
1192
+ const usageRecording = registerUsageRecording(pi, dependencies.usageRecording);
838
1193
  const settings = readSubagentSettings();
839
1194
  let currentSettings = settings;
840
1195
  let currentCatalog = "";
@@ -842,7 +1197,7 @@ function subagents_extension_default(pi, dependencies = {}) {
842
1197
  const refreshBlockingCatalog = blockingEnabled ? registerBlockingSubagent(pi, () => currentSettings, loadBlockingExecution) : () => void 0;
843
1198
  let refreshStatefulCatalog = () => void 0;
844
1199
  let refreshConsultCatalog = () => void 0;
845
- pi.on("session_start", (_event, ctx) => {
1200
+ pi.on("session_start", async (event, ctx) => {
846
1201
  const loadNotice = consumeSubagentSettingsNotice();
847
1202
  const refreshedSettings = readSubagentSettings();
848
1203
  const refreshedNotice = consumeSubagentSettingsNotice();
@@ -857,12 +1212,21 @@ function subagents_extension_default(pi, dependencies = {}) {
857
1212
  refreshBlockingCatalog(currentCatalog);
858
1213
  refreshStatefulCatalog(currentCatalog);
859
1214
  refreshConsultCatalog(currentCatalog);
1215
+ await usageRecording.startSession({
1216
+ enabled: resolveUsageRecordingEnabled(currentSettings?.usageRecording),
1217
+ surfaceArm: usageSurfaceArm(blockingEnabled, statefulRuntime.getRuntimeStatus().enabled),
1218
+ reason: event.reason,
1219
+ onWarning: (message) => {
1220
+ if (ctx.hasUI) ctx.ui.notify(message, "warning");
1221
+ }
1222
+ });
860
1223
  });
861
1224
  const statefulRuntime = registerStatefulSubagents(pi, {
862
1225
  blockingEnabled,
863
1226
  settings: settings?.stateful,
864
1227
  getSettings: () => currentSettings,
865
- loadTransport: dependencies.loadStatefulTransport
1228
+ loadTransport: dependencies.loadStatefulTransport,
1229
+ usageRecording
866
1230
  });
867
1231
  refreshStatefulCatalog = statefulRuntime.setAgentCatalog;
868
1232
  const getBlockingEnabled = () => blockingEnabled;
@@ -878,7 +1242,8 @@ function subagents_extension_default(pi, dependencies = {}) {
878
1242
  getMaxParallelTasks,
879
1243
  getConsultResourcePolicy,
880
1244
  getConsultationCwdPolicy,
881
- getDelegationCwdPolicy
1245
+ getDelegationCwdPolicy,
1246
+ getUsageRecordingStatus: () => usageRecording.getStatus()
882
1247
  },
883
1248
  dependencies.inspect
884
1249
  );
@@ -898,6 +1263,15 @@ function subagents_extension_default(pi, dependencies = {}) {
898
1263
  getConsultResourcePolicy,
899
1264
  getConsultationCwdPolicy,
900
1265
  getDelegationCwdPolicy,
1266
+ getUsageRecordingEnabled: () => usageRecording.getStatus().enabled,
1267
+ getUsageRecordingStatus: () => usageRecording.getStatus(),
1268
+ setUsageRecordingEnabled: async (value) => {
1269
+ await usageRecording.setEnabled(value);
1270
+ currentSettings = {
1271
+ ...currentSettings ?? {},
1272
+ usageRecording: { ...currentSettings?.usageRecording ?? {}, enabled: value }
1273
+ };
1274
+ },
901
1275
  setMaxParallelTasks(value) {
902
1276
  const previousSettings = currentSettings;
903
1277
  currentSettings = {
@@ -945,9 +1319,17 @@ function subagents_extension_default(pi, dependencies = {}) {
945
1319
  configOwner,
946
1320
  dependencies.config
947
1321
  );
1322
+ pi.on("session_shutdown", (event) => usageRecording.shutdown(event.reason));
1323
+ }
1324
+ function usageSurfaceArm(blockingEnabled, statefulEnabled) {
1325
+ if (blockingEnabled && statefulEnabled) return "all";
1326
+ if (statefulEnabled) return "async-only";
1327
+ if (blockingEnabled) return "blocking-only";
1328
+ return "disabled";
948
1329
  }
949
1330
  function registerBlockingSubagent(pi, getSettings, loadExecution) {
950
1331
  let catalog = "";
1332
+ let deprecationWarningShown = false;
951
1333
  const activeControllers = /* @__PURE__ */ new Set();
952
1334
  const activeWork = /* @__PURE__ */ new Set();
953
1335
  const cancelAndWaitForWork = async (reason) => {
@@ -956,9 +1338,16 @@ function registerBlockingSubagent(pi, getSettings, loadExecution) {
956
1338
  }
957
1339
  await Promise.allSettled([...activeWork]);
958
1340
  };
959
- pi.on("session_start", () => cancelAndWaitForWork("Blocking subagent session replaced"));
1341
+ pi.on("session_start", () => {
1342
+ deprecationWarningShown = false;
1343
+ return cancelAndWaitForWork("Blocking subagent session replaced");
1344
+ });
960
1345
  pi.on("session_shutdown", () => cancelAndWaitForWork("Blocking subagent session shut down"));
1346
+ const statefulEnabled = () => getSettings()?.stateful?.enabled !== false;
1347
+ const deprecationAlternatives = () => statefulEnabled() ? "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." : "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.";
961
1348
  const baseDescription = () => [
1349
+ "Deprecated compatibility tool: do not choose subagent for new work.",
1350
+ deprecationAlternatives(),
962
1351
  "Run specialized subagents as a blocking operation with isolated contexts.",
963
1352
  "The call blocks the main agent until every worker and optional aggregator finishes, so queued steering waits.",
964
1353
  "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).",
@@ -969,14 +1358,15 @@ function registerBlockingSubagent(pi, getSettings, loadExecution) {
969
1358
  `Working-directory target policy: ${getSettings()?.cwdPolicy?.delegation ?? DEFAULT_DELEGATION_CWD_POLICY}. This controls launch targets and protected project resources, not filesystem access or sandboxing.`
970
1359
  ].join(" ");
971
1360
  const promptGuidelines = () => [
972
- "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.",
1361
+ statefulEnabled() ? "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." : "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.",
1362
+ "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.",
1363
+ "When compatibility requires subagent, decide how many subagents to spawn from task shape instead of waiting for the user to specify a count.",
973
1364
  "The main agent retains overall planning, immediate critical-path work, integration, final verification, and the final answer.",
974
1365
  "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.",
975
1366
  "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.",
976
1367
  "Keep ordinary planning in the main agent, or use explicit workflow mode when a genuine dependency graph requires caller-authored orchestration.",
977
1368
  "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.",
978
- "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.",
979
- "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.",
1369
+ "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.",
980
1370
  `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.`,
981
1371
  "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.",
982
1372
  "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.",
@@ -987,9 +1377,9 @@ function registerBlockingSubagent(pi, getSettings, loadExecution) {
987
1377
  ];
988
1378
  const definition = {
989
1379
  name: "subagent",
990
- label: "Blocking Subagent",
1380
+ label: "Blocking Subagent \xB7 Deprecated",
991
1381
  description: appendAgentCatalog(baseDescription(), catalog),
992
- promptSnippet: "Run blocking isolated subagents only when their outputs are required before the main agent can continue.",
1382
+ promptSnippet: "Deprecated blocking subagent compatibility tool; prefer detached or read-only alternatives.",
993
1383
  promptGuidelines: promptGuidelines(),
994
1384
  parameters: SubagentParams,
995
1385
  async execute(toolCallId, params, signal, onUpdate, ctx) {
@@ -998,6 +1388,13 @@ function registerBlockingSubagent(pi, getSettings, loadExecution) {
998
1388
  const effectiveSignal = signal ? AbortSignal.any([signal, lifecycleController.signal]) : lifecycleController.signal;
999
1389
  const work = (async () => {
1000
1390
  throwIfAborted(effectiveSignal, "Blocking subagent execution was cancelled");
1391
+ if (!deprecationWarningShown && ctx.hasUI) {
1392
+ deprecationWarningShown = true;
1393
+ ctx.ui.notify(
1394
+ statefulEnabled() ? "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." : "subagent is deprecated for new work. Prefer the main agent or subagent_consult; enable the background workflow before using detached alternatives.",
1395
+ "warning"
1396
+ );
1397
+ }
1001
1398
  let executionModule;
1002
1399
  try {
1003
1400
  executionModule = await loadExecution();