@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
@@ -139,6 +139,7 @@ function renderStatus(state: string): RenderStatus {
139
139
  return "interrupted";
140
140
  case "closed":
141
141
  return "closed";
142
+ case "partial":
142
143
  case "blocked":
143
144
  case "needs-input":
144
145
  case "abstained":
@@ -0,0 +1,308 @@
1
+ import { StringEnum } from "@earendil-works/pi-ai";
2
+ import type { ContextEvent } from "@earendil-works/pi-coding-agent";
3
+ import { DEFAULT_MAX_CONTEXT_BYTES, truncateUtf8 } from "./limits.js";
4
+ import type { AgentLifecycleState, ManagedAgent } from "./registry-types.js";
5
+
6
+ export const COMPLETION_REQUIREMENT_MODES = ["background", "required"] as const;
7
+ export type CompletionRequirementMode = (typeof COMPLETION_REQUIREMENT_MODES)[number];
8
+
9
+ export const CompletionRequirementModeSchema = StringEnum(COMPLETION_REQUIREMENT_MODES, {
10
+ description:
11
+ "Mark this exact turn as background (default) or required for the parent final answer. Required results are tracked until their exact completion becomes visible, but current Pi versions do not provide a hard pre-display final-answer barrier.",
12
+ default: "background",
13
+ });
14
+
15
+ export const COMPLETION_REQUIREMENT_VERSION = "pi-subagents:completion-requirement:v1" as const;
16
+ export const COMPLETION_REQUIREMENT_CONTEXT_TYPE = "pi-subagent-required-completions";
17
+ const MAX_REQUIREMENTS_PER_AGENT = 20;
18
+ export const MAX_UNRESOLVED_REQUIRED_COMPLETIONS = 64;
19
+
20
+ export type CompletionRequirementState = "pending" | "available" | "visible" | "cancelled";
21
+
22
+ export interface CompletionRequirementRecord {
23
+ version: typeof COMPLETION_REQUIREMENT_VERSION;
24
+ runId: string;
25
+ generation: number;
26
+ state: CompletionRequirementState;
27
+ createdAt: number;
28
+ updatedAt: number;
29
+ completionId?: string;
30
+ terminalState?: AgentLifecycleState;
31
+ }
32
+
33
+ export function beginCompletionRequirement(
34
+ records: readonly CompletionRequirementRecord[] | undefined,
35
+ input: { runId: string; generation: number; createdAt: number },
36
+ ): CompletionRequirementRecord[] {
37
+ const retained = (records ?? []).filter(
38
+ (record) => record.runId !== input.runId || record.generation !== input.generation,
39
+ );
40
+ retained.push({
41
+ version: COMPLETION_REQUIREMENT_VERSION,
42
+ runId: input.runId,
43
+ generation: input.generation,
44
+ state: "pending",
45
+ createdAt: input.createdAt,
46
+ updatedAt: input.createdAt,
47
+ });
48
+ return retained.slice(-MAX_REQUIREMENTS_PER_AGENT);
49
+ }
50
+
51
+ export function makeCompletionAvailable(
52
+ records: readonly CompletionRequirementRecord[] | undefined,
53
+ input: {
54
+ runId: string;
55
+ generation: number;
56
+ completionId: string;
57
+ terminalState: AgentLifecycleState;
58
+ updatedAt: number;
59
+ },
60
+ ): CompletionRequirementRecord[] | undefined {
61
+ return updateExact(records, input.runId, input.generation, (record) => ({
62
+ ...record,
63
+ state: "available",
64
+ completionId: input.completionId,
65
+ terminalState: input.terminalState,
66
+ updatedAt: input.updatedAt,
67
+ }));
68
+ }
69
+
70
+ export function makeCompletionVisible(
71
+ records: readonly CompletionRequirementRecord[] | undefined,
72
+ completionId: string,
73
+ updatedAt: number,
74
+ ): CompletionRequirementRecord[] | undefined {
75
+ if (!records?.some((record) => record.completionId === completionId)) {
76
+ return records?.map((record) => ({ ...record }));
77
+ }
78
+ return records.map((record) =>
79
+ record.completionId === completionId
80
+ ? { ...record, state: "visible" as const, updatedAt }
81
+ : { ...record },
82
+ );
83
+ }
84
+
85
+ export function cancelPendingCompletionRequirements(
86
+ records: readonly CompletionRequirementRecord[] | undefined,
87
+ terminalState: AgentLifecycleState,
88
+ updatedAt: number,
89
+ ): CompletionRequirementRecord[] | undefined {
90
+ if (!records?.some((record) => record.state === "pending")) {
91
+ return records?.map((record) => ({ ...record }));
92
+ }
93
+ return records.map((record) =>
94
+ record.state === "pending"
95
+ ? {
96
+ ...record,
97
+ state: "cancelled" as const,
98
+ terminalState,
99
+ updatedAt,
100
+ }
101
+ : { ...record },
102
+ );
103
+ }
104
+
105
+ export function requirementForCompletion(
106
+ agent: Pick<ManagedAgent, "completionRequirements">,
107
+ completionId: string,
108
+ ): CompletionRequirementRecord | undefined {
109
+ return agent.completionRequirements?.find((record) => record.completionId === completionId);
110
+ }
111
+
112
+ export interface BranchCompletionRequirementState {
113
+ observedState: boolean;
114
+ records: Map<string, CompletionRequirementRecord>;
115
+ keys: Set<string>;
116
+ }
117
+
118
+ export function completionRequirementKey(
119
+ record: Pick<CompletionRequirementRecord, "runId" | "generation">,
120
+ ): string {
121
+ return `${record.runId}\u0000${record.generation}`;
122
+ }
123
+
124
+ export function completionRequirementsFromBranch(
125
+ entries: readonly unknown[],
126
+ ): BranchCompletionRequirementState {
127
+ const records = new Map<string, CompletionRequirementRecord>();
128
+ let observedState = false;
129
+ for (const entry of entries) {
130
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
131
+ const candidate = entry as Record<string, unknown>;
132
+ const message =
133
+ candidate.type === "message" && candidate.message && typeof candidate.message === "object"
134
+ ? (candidate.message as Record<string, unknown>)
135
+ : candidate;
136
+ if (
137
+ message.role === "toolResult" &&
138
+ ["subagent_spawn", "subagent_send", "subagent_await", "subagent_manage"].includes(
139
+ String(message.toolName),
140
+ )
141
+ ) {
142
+ observedState = true;
143
+ const details = message.details;
144
+ if (!details || typeof details !== "object" || Array.isArray(details)) continue;
145
+ const detailsRecord = details as Record<string, unknown>;
146
+ const agents = [
147
+ detailsRecord.agent,
148
+ ...(Array.isArray(detailsRecord.agents) ? detailsRecord.agents : []),
149
+ ];
150
+ for (const agent of agents) {
151
+ if (!agent || typeof agent !== "object" || Array.isArray(agent)) continue;
152
+ const requirements = (agent as Record<string, unknown>).completionRequirements;
153
+ if (!Array.isArray(requirements)) continue;
154
+ for (const requirement of requirements) {
155
+ if (isCompletionRequirementRecord(requirement)) {
156
+ records.set(completionRequirementKey(requirement), { ...requirement });
157
+ }
158
+ }
159
+ }
160
+ continue;
161
+ }
162
+ if (message.role !== "custom" || message.customType !== "pi-subagent-completion") continue;
163
+ const details = message.details;
164
+ if (!details || typeof details !== "object" || Array.isArray(details)) continue;
165
+ const detailRecord = details as Record<string, unknown>;
166
+ const completionRecords = Array.isArray(detailRecord.completions)
167
+ ? detailRecord.completions
168
+ : [detailRecord];
169
+ for (const completion of completionRecords) {
170
+ if (!completion || typeof completion !== "object" || Array.isArray(completion)) continue;
171
+ const requirement = (completion as Record<string, unknown>).completionRequirement;
172
+ if (!isCompletionRequirementRecord(requirement)) continue;
173
+ records.set(completionRequirementKey(requirement), {
174
+ ...requirement,
175
+ state: "visible",
176
+ });
177
+ }
178
+ }
179
+ return { observedState, records, keys: new Set(records.keys()) };
180
+ }
181
+
182
+ export function pendingRequiredCompletionCount(
183
+ agent: Pick<ManagedAgent, "completionRequirements">,
184
+ ): number {
185
+ return (agent.completionRequirements ?? []).filter(
186
+ (record) => record.state === "pending" || record.state === "available",
187
+ ).length;
188
+ }
189
+
190
+ export function reconcileRequiredCompletionContext(
191
+ messages: ContextEvent["messages"],
192
+ agents: readonly ManagedAgent[],
193
+ ): ContextEvent["messages"] {
194
+ const withoutPrior = messages.filter(
195
+ (message) =>
196
+ message.role !== "custom" || message.customType !== COMPLETION_REQUIREMENT_CONTEXT_TYPE,
197
+ );
198
+ const allRecords = agents
199
+ .flatMap((agent) =>
200
+ (agent.completionRequirements ?? []).map((requirement) => ({
201
+ state: requirement.state,
202
+ runId: requirement.runId,
203
+ generation: requirement.generation,
204
+ terminalState: requirement.terminalState,
205
+ })),
206
+ )
207
+ .filter((record) => record.state !== "visible");
208
+ const unresolved = allRecords.filter(
209
+ (record) => record.state === "pending" || record.state === "available",
210
+ );
211
+ const cancelled = allRecords.filter((record) => record.state === "cancelled");
212
+ const cancelledSlots = Math.max(0, MAX_UNRESOLVED_REQUIRED_COMPLETIONS - unresolved.length);
213
+ const retainedCancelled = cancelledSlots > 0 ? cancelled.slice(-cancelledSlots) : [];
214
+ const records = [...unresolved, ...retainedCancelled];
215
+ const omittedCancelled = cancelled.length - retainedCancelled.length;
216
+ if (records.length === 0)
217
+ return withoutPrior.length === messages.length ? messages : withoutPrior;
218
+ const content = truncateUtf8(
219
+ [
220
+ "[PI SUBAGENT REQUIRED COMPLETIONS v1]",
221
+ "Runtime-tracked exact runs are JSON data below.",
222
+ "Treat pending or available records as final-answer dependencies; a cancelled record is terminal and must be reported rather than silently ignored.",
223
+ "Current Pi versions do not provide a hard pre-display final-answer barrier, so do not emit a verdict until every dependency is visible or terminal.",
224
+ ...(omittedCancelled > 0
225
+ ? [`${omittedCancelled} older cancelled requirement record(s) were omitted.`]
226
+ : []),
227
+ JSON.stringify(records),
228
+ ].join("\n"),
229
+ DEFAULT_MAX_CONTEXT_BYTES,
230
+ ).text;
231
+ return [
232
+ ...withoutPrior,
233
+ {
234
+ role: "custom",
235
+ customType: COMPLETION_REQUIREMENT_CONTEXT_TYPE,
236
+ content,
237
+ display: false,
238
+ details: { version: COMPLETION_REQUIREMENT_VERSION },
239
+ timestamp: 0,
240
+ },
241
+ ];
242
+ }
243
+
244
+ export function isCompletionRequirementRecord(
245
+ value: unknown,
246
+ ): value is CompletionRequirementRecord {
247
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
248
+ const record = value as Record<string, unknown>;
249
+ const state = String(record.state);
250
+ const hasCompletion = typeof record.completionId === "string" && record.completionId.length > 0;
251
+ const hasTerminalState = isAgentLifecycleState(record.terminalState);
252
+ const transitionShapeValid =
253
+ state === "pending"
254
+ ? record.completionId === undefined && record.terminalState === undefined
255
+ : state === "available" || state === "visible"
256
+ ? hasCompletion && hasTerminalState
257
+ : state === "cancelled" && record.completionId === undefined && hasTerminalState;
258
+ return (
259
+ transitionShapeValid &&
260
+ record.version === COMPLETION_REQUIREMENT_VERSION &&
261
+ typeof record.runId === "string" &&
262
+ record.runId.length > 0 &&
263
+ record.runId.length <= 256 &&
264
+ typeof record.generation === "number" &&
265
+ Number.isSafeInteger(record.generation) &&
266
+ record.generation >= 1 &&
267
+ ["pending", "available", "visible", "cancelled"].includes(state) &&
268
+ typeof record.createdAt === "number" &&
269
+ Number.isFinite(record.createdAt) &&
270
+ typeof record.updatedAt === "number" &&
271
+ Number.isFinite(record.updatedAt) &&
272
+ record.updatedAt >= record.createdAt &&
273
+ (record.completionId === undefined ||
274
+ (typeof record.completionId === "string" && record.completionId.length <= 256)) &&
275
+ (record.terminalState === undefined || isAgentLifecycleState(record.terminalState))
276
+ );
277
+ }
278
+
279
+ function updateExact(
280
+ records: readonly CompletionRequirementRecord[] | undefined,
281
+ runId: string,
282
+ generation: number,
283
+ update: (record: CompletionRequirementRecord) => CompletionRequirementRecord,
284
+ ): CompletionRequirementRecord[] | undefined {
285
+ if (!records?.some((record) => record.runId === runId && record.generation === generation)) {
286
+ return records?.map((record) => ({ ...record }));
287
+ }
288
+ return records.map((record) =>
289
+ record.runId === runId && record.generation === generation ? update(record) : { ...record },
290
+ );
291
+ }
292
+
293
+ function isAgentLifecycleState(value: unknown): value is AgentLifecycleState {
294
+ return [
295
+ "starting",
296
+ "running",
297
+ "idle",
298
+ "completed",
299
+ "partial",
300
+ "blocked",
301
+ "needs-input",
302
+ "abstained",
303
+ "stale",
304
+ "interrupted",
305
+ "failed",
306
+ "closed",
307
+ ].includes(String(value));
308
+ }
@@ -3,9 +3,9 @@ import { cachedModuleLoader } from "./cached-module-loader.js";
3
3
  import type { SubagentMenuOwner, SubagentSettingsRuntime } from "./config-ui.js";
4
4
 
5
5
  const SUBCOMMANDS = [
6
- { value: "settings", label: "settings", description: "Configure subagent user settings" },
7
- { value: "status", label: "status", description: "Show effective subagent settings" },
8
- { value: "help", label: "help", description: "Show subagent settings help" },
6
+ { value: "settings", label: "settings", description: "Open grouped subagent settings" },
7
+ { value: "status", label: "status", description: "Show detailed subagent diagnostics" },
8
+ { value: "help", label: "help", description: "Show subagent first steps and safety help" },
9
9
  ];
10
10
 
11
11
  type ConfigUiModule = Pick<
@@ -50,7 +50,7 @@ export function registerSubagentConfigCommand(
50
50
  dependencies.loadConfigStatus ?? (() => import("./config-status.js")),
51
51
  );
52
52
  pi.registerCommand("subagents", {
53
- description: "Manage current-session subagents and user settings",
53
+ description: "Manage subagents, settings, diagnostics, and help",
54
54
  getArgumentCompletions(prefix: string) {
55
55
  const normalized = prefix.trim().toLowerCase();
56
56
  const matches = SUBCOMMANDS.filter((item) => item.value.startsWith(normalized));
@@ -103,7 +103,7 @@ export function registerSubagentConfigCommand(
103
103
  }
104
104
  if (!isCurrent()) return;
105
105
  if (!subcommand) await configUi.showSubagentManager(pi, ctx, runtime, owner);
106
- else await configUi.showSubagentSettings(ctx, runtime, owner);
106
+ else await configUi.showSubagentSettings(pi, ctx, runtime, owner);
107
107
  return;
108
108
  }
109
109
  if (ctx.mode === "tui" || ctx.hasUI) {
@@ -16,14 +16,15 @@ import {
16
16
  inspectDelegationWorkflowSettings,
17
17
  inspectStatefulLimitSettings,
18
18
  inspectStatefulTransportSettings,
19
+ inspectUsageRecordingSettings,
19
20
  } from "./settings.js";
20
21
  import type { StatefulSubagentRuntimeStatus } from "./stateful.js";
21
22
  import {
22
23
  formatConfiguredDetachedLimitDivergence,
23
- formatConfiguredDetachedLimits,
24
24
  formatDetachedLimitSummary,
25
25
  } from "./stateful-limit-ui.js";
26
26
  import { STATEFUL_LIMIT_DEFINITIONS } from "./stateful-limits.js";
27
+ import { USAGE_RECORDING_RETENTION_DAYS } from "./usage-recording-config.js";
27
28
  import { workflowLabel } from "./workflow-ui.js";
28
29
 
29
30
  export function showSubagentStatus(
@@ -51,32 +52,30 @@ export function statusLines(runtime: SubagentSettingsRuntime): string[] {
51
52
  return formatStatus(runtime.getRuntimeStatus(), snapshot, runtime).split("\n");
52
53
  }
53
54
 
54
- export function helpLines(runtime: SubagentSettingsRuntime): string[] {
55
- const snapshot = inspectCompletionDeliverySettings();
56
- const cwdPolicy = inspectCwdPolicySettings();
57
- const parallelLimit = inspectBlockingParallelLimitSettings();
58
- const detachedLimits = inspectStatefulLimitSettings();
59
- const transport = inspectStatefulTransportSettings();
55
+ export function helpLines(_runtime: SubagentSettingsRuntime): string[] {
60
56
  return [
61
- "/subagents — choose delegation workflow, manage current agents, and configure agent tools",
62
- "/subagents settings configure target locations, trusted resources, and async completion",
63
- "/subagents status show current-session and user-setting values",
64
- "/subagents help show this help",
65
- "Target policies control startup directories and resources, not filesystem access or sandboxing.",
66
- "Manage saved folder trust with Pi /trust and restart Pi after changing it.",
67
- `Runtime consultation target: ${consultationCwdLabel(runtime.getConsultationCwdPolicy())}`,
68
- `Configured consultation target: ${consultationCwdLabel(cwdPolicy.consultation.value)} (${cwdPolicy.consultation.source})`,
69
- `Runtime delegation target: ${delegationCwdLabel(runtime.getDelegationCwdPolicy())}`,
70
- `Configured delegation target: ${delegationCwdLabel(cwdPolicy.delegation.value)} (${cwdPolicy.delegation.source})`,
71
- `Maximum parallel workers: ${runtime.getMaxParallelTasks()} per blocking call`,
72
- `Configured parallel limit: ${parallelLimit.value} (${parallelLimit.source})`,
73
- `Detached limits: ${formatDetachedLimitSummary(runtime.getRuntimeStatus())}`,
74
- `Configured transport: ${transport.value} (${transport.source})`,
75
- ...(detachedLimits.values
76
- ? [`Configured detached limits: ${formatConfiguredDetachedLimits(detachedLimits.values)}`]
77
- : ["Configured detached limits: unavailable; repair user settings"]),
78
- "Detached limits and transport apply after /reload; clear retained agents first if their work must not be interrupted.",
79
- `User settings: ${safeTerminalText(snapshot.path)}`,
57
+ "Start here",
58
+ " 1. Open How subagents run.",
59
+ " 2. Choose the workflow that matches the tools and blocking behavior you need.",
60
+ " 3. Open Completion and privacy if Pi must use background results in the current answer.",
61
+ "The blocking subagent tool is deprecated and remains available only in compatibility workflows.",
62
+ "subagent_consult and subagent_await remain supported.",
63
+ "Current subagents shows work in progress and subagents saved for follow-up.",
64
+ "Settings",
65
+ " Folders and trusted resources — choose where subagents start and what consultations load.",
66
+ " Completion and privacy choose what Pi does when work finishes and whether usage is recorded.",
67
+ " Agent defaults choose tools, model, thinking effort, and time limit for each subagent.",
68
+ " Advanced runtime settings optional transport and capacity controls.",
69
+ "Changes are saved immediately.",
70
+ "Transport and background-agent limits apply after /reload.",
71
+ "Commands",
72
+ " /subagents open the manager",
73
+ " /subagents settings open Settings",
74
+ " /subagents status show detailed diagnostics",
75
+ " /subagents help — show this help",
76
+ "Safety",
77
+ "Folder choices control starting locations and loaded resources; they do not sandbox files, commands, or network access.",
78
+ "Manage saved folder trust with Pi /trust, then restart Pi.",
80
79
  ];
81
80
  }
82
81
 
@@ -86,34 +85,20 @@ export function formatManagerSummary(
86
85
  configured: ReturnType<typeof inspectDelegationWorkflowSettings>,
87
86
  ): string {
88
87
  const current = currentWorkflow(runtime, status);
89
- const cwdPolicy = inspectCwdPolicySettings();
90
- const consult = inspectConsultResourceSettings();
91
88
  const detachedLimits = inspectStatefulLimitSettings();
92
- const transport = inspectStatefulTransportSettings();
93
89
  const detachedDivergence = detachedLimits.values
94
90
  ? formatConfiguredDetachedLimitDivergence(status, detachedLimits.values)
95
91
  : undefined;
96
92
  return [
97
- `Delegation: ${workflowLabel(current)}`,
98
- `Completion: ${completionLabel(status.completionDelivery)}`,
99
- `Consult target: ${consultationCwdLabel(runtime.getConsultationCwdPolicy())}`,
100
- `Delegation target: ${delegationCwdLabel(runtime.getDelegationCwdPolicy())}`,
101
- `Consult resources: ${consultResourceLabel(runtime.getConsultResourcePolicy())}`,
102
- `Parallel workers: max ${runtime.getMaxParallelTasks()} per blocking call`,
103
- `Detached limits: ${formatDetachedLimitSummary(status)}`,
104
- `Transport: ${status.transport}`,
105
- `Configured transport: ${transport.value} · ${transport.source}`,
106
- `Configured consult target: ${consultationCwdLabel(cwdPolicy.consultation.value)} · ${cwdPolicy.consultation.source}`,
107
- `Configured delegation target: ${delegationCwdLabel(cwdPolicy.delegation.value)} · ${cwdPolicy.delegation.source}`,
108
- `Configured consult resources: ${consultResourceLabel(consult.value)} · ${consult.source}`,
109
- `Settings: ${safeTerminalText(cwdPolicy.path)}`,
110
- `Agents: ${status.activeAgents} active · ${status.retainedAgents} retained`,
111
- ...(detachedDivergence ? [detachedDivergence] : []),
93
+ `How subagents run: ${workflowLabel(current)}`,
94
+ `Subagents: ${status.activeAgents} working · ${status.retainedAgents} saved for follow-up`,
95
+ `When work finishes: ${completionLabel(status.completionDelivery)}`,
112
96
  ...(configured.value !== current
113
97
  ? [`Configured after reload: ${workflowLabel(configured.value)}`]
114
98
  : []),
99
+ ...(detachedDivergence ? [detachedDivergence] : []),
115
100
  ...(configured.error || detachedLimits.error
116
- ? ["Settings need repair; open Advanced settings for details."]
101
+ ? ["Action needed: Repair user settings. Open Diagnostics for details."]
117
102
  : []),
118
103
  ].join("\n");
119
104
  }
@@ -129,27 +114,33 @@ function formatStatus(
129
114
  const parallelLimit = inspectBlockingParallelLimitSettings();
130
115
  const detachedLimits = inspectStatefulLimitSettings();
131
116
  const transport = inspectStatefulTransportSettings();
117
+ const usageRecording = inspectUsageRecordingSettings();
132
118
  const current = runtime ? currentWorkflow(runtime, status) : configuredWorkflow.value;
119
+ const usageStatus = runtime?.getUsageRecordingStatus?.();
133
120
  return [
134
- "Current session",
135
- ` Delegation: ${workflowLabel(current)}`,
136
- ` Async runtime: ${status.initialized ? "initialized" : status.enabled ? "not initialized" : "disabled"}`,
121
+ "Current Session",
122
+ ` How subagents run: ${workflowLabel(current)}`,
123
+ ` Background runtime: ${status.initialized ? "initialized" : status.enabled ? "not initialized" : "disabled"}`,
137
124
  ` Transport: ${status.transport}`,
138
125
  ` Configured transport: ${transport.value} (${transport.source})`,
139
- ` Completion: ${completionLabel(status.completionDelivery)}`,
140
- ` Consultation target: ${consultationCwdLabel(runtime?.getConsultationCwdPolicy() ?? cwdPolicy.consultation.value)}`,
141
- ` Delegation target: ${delegationCwdLabel(runtime?.getDelegationCwdPolicy() ?? cwdPolicy.delegation.value)}`,
142
- ` Consultation resources: ${consultResourceLabel(runtime?.getConsultResourcePolicy() ?? consult.value)}`,
143
- ` Maximum parallel workers: ${runtime?.getMaxParallelTasks() ?? parallelLimit.value} per blocking call`,
144
- ` Detached limits: ${formatDetachedLimitSummary(status)}`,
145
- ` Agents: ${status.activeAgents} active, ${status.retainedAgents} retained`,
146
- "User settings",
147
- ` Delegation source: ${configuredWorkflow.source}`,
148
- ` Configured delegation: ${workflowLabel(configuredWorkflow.value)}`,
126
+ ` When work finishes: ${completionLabel(status.completionDelivery)}`,
127
+ ` Read-only consultation folders: ${consultationCwdLabel(runtime?.getConsultationCwdPolicy() ?? cwdPolicy.consultation.value)}`,
128
+ ` Subagent folders: ${delegationCwdLabel(runtime?.getDelegationCwdPolicy() ?? cwdPolicy.delegation.value)}`,
129
+ ` Read-only consultation resources: ${consultResourceLabel(runtime?.getConsultResourcePolicy() ?? consult.value)}`,
130
+ ` Blocking worker limit: ${runtime?.getMaxParallelTasks() ?? parallelLimit.value} per request`,
131
+ ` Background-agent limits: ${formatDetachedLimitSummary(status)}`,
132
+ ` Subagents: ${status.activeAgents} working, ${status.retainedAgents} saved for follow-up`,
133
+ ` Local usage recording: ${usageStatus?.enabled ? "enabled" : "disabled"}`,
134
+ ` Recorded events this session: ${usageStatus?.recordedEvents ?? 0}`,
135
+ ` Usage retention: ${usageStatus?.retentionDays ?? USAGE_RECORDING_RETENTION_DAYS} days`,
136
+ ` Usage path: ${safeTerminalText(usageStatus?.path ?? "unavailable")}`,
137
+ "User Settings",
138
+ ` Workflow source: ${configuredWorkflow.source}`,
139
+ ` Configured workflow: ${workflowLabel(configuredWorkflow.value)}`,
149
140
  ` Completion source: ${snapshot.source}`,
150
141
  ` Configured completion: ${completionLabel(snapshot.value)}`,
151
- ` Configured parallel limit: ${parallelLimit.value}`,
152
- ` Parallel limit source: ${parallelLimit.source}`,
142
+ ` Configured blocking worker limit: ${parallelLimit.value}`,
143
+ ` Blocking worker limit source: ${parallelLimit.source}`,
153
144
  ...(detachedLimits.values
154
145
  ? STATEFUL_LIMIT_DEFINITIONS.map((definition) => {
155
146
  const configured = detachedLimits.values?.[definition.field];
@@ -162,17 +153,20 @@ function formatStatus(
162
153
  ` Delegation target source: ${cwdPolicy.delegation.source}`,
163
154
  ` Configured consultation resources: ${consultResourceLabel(consult.value)}`,
164
155
  ` Consultation resource source: ${consult.source}`,
156
+ ` Configured usage recording: ${usageRecording.enabled ? "enabled" : "disabled"}`,
157
+ ` Usage recording source: ${usageRecording.source}`,
165
158
  ` Path: ${safeTerminalText(snapshot.path)}`,
166
159
  configuredWorkflow.error ||
167
160
  snapshot.error ||
168
161
  cwdPolicy.error ||
169
162
  parallelLimit.error ||
170
163
  detachedLimits.error ||
171
- transport.error
172
- ? ` Warning: ${safeTerminalText(configuredWorkflow.error ?? snapshot.error ?? cwdPolicy.error ?? parallelLimit.error ?? detachedLimits.error ?? transport.error ?? "invalid settings")}`
164
+ transport.error ||
165
+ usageRecording.error
166
+ ? ` Warning: ${safeTerminalText(configuredWorkflow.error ?? snapshot.error ?? cwdPolicy.error ?? parallelLimit.error ?? detachedLimits.error ?? transport.error ?? usageRecording.error ?? "invalid settings")}`
173
167
  : " Warning: none",
174
168
  configuredWorkflow.value !== current
175
- ? "Configured delegation differs from this session. Run /reload to apply it."
169
+ ? "The configured workflow differs from this session. Run /reload to apply it."
176
170
  : "Manual file changes require /reload.",
177
171
  ].join("\n");
178
172
  }
@@ -189,23 +183,25 @@ export function currentWorkflow(
189
183
  }
190
184
 
191
185
  export function completionLabel(value: CompletionDelivery): string {
192
- return value === "auto-resume" ? "Resume automatically when finished" : "Wait until my next turn";
186
+ return value === "auto-resume"
187
+ ? "Continue automatically when work finishes"
188
+ : "Wait for my next message";
193
189
  }
194
190
 
195
191
  export function consultationCwdLabel(value: ConsultationCwdPolicy): string {
196
192
  return value === "current-workspace"
197
- ? "Current workspace only"
198
- : "Anywhere · untrusted targets inherit nothing";
193
+ ? "This workspace only"
194
+ : "Any folder · no project resources when untrusted";
199
195
  }
200
196
 
201
197
  export function delegationCwdLabel(value: DelegationCwdPolicy): string {
202
198
  switch (value) {
203
199
  case "trusted-targets":
204
- return "Current or saved-trusted folders";
200
+ return "This workspace or saved-trusted folders";
205
201
  case "current-workspace":
206
- return "Current workspace only";
202
+ return "This workspace only";
207
203
  case "anywhere":
208
- return "Anywhere · normal Pi permissions";
204
+ return "Any folder Pi can access";
209
205
  }
210
206
  }
211
207
 
@@ -214,7 +210,7 @@ export function consultResourceLabel(value: ConsultResourcePolicy): string {
214
210
  case "project-context":
215
211
  return "Project context only";
216
212
  case "none":
217
- return "No inherited resources";
213
+ return "No project resources";
218
214
  case "all":
219
215
  return "All trusted resources";
220
216
  }