@narumitw/pi-subagents 2.0.5 → 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
@@ -0,0 +1,532 @@
1
+ export const ASYNC_SUBAGENT_BENCHMARK_VERSION = "pi-subagents:async-surface-benchmark:v1" as const;
2
+
3
+ export const BENCHMARK_RESULT_PREFIX = "BENCHMARK_RESULT_JSON:";
4
+ export const BENCHMARK_MODES = ["quick", "extended"] as const;
5
+ export const BENCHMARK_ARMS = ["sync", "async"] as const;
6
+ export const BENCHMARK_THINKING_LEVELS = [
7
+ "off",
8
+ "minimal",
9
+ "low",
10
+ "medium",
11
+ "high",
12
+ "xhigh",
13
+ "max",
14
+ ] as const;
15
+
16
+ export type AsyncSubagentBenchmarkMode = (typeof BENCHMARK_MODES)[number];
17
+ export type AsyncSubagentBenchmarkArm = (typeof BENCHMARK_ARMS)[number];
18
+ export type AsyncSubagentBenchmarkThinkingLevel = (typeof BENCHMARK_THINKING_LEVELS)[number];
19
+ export type AsyncSubagentTerminalOutcome =
20
+ | "completed"
21
+ | "invalid-output"
22
+ | "timed-out"
23
+ | "readiness-timeout"
24
+ | "process-error"
25
+ | "protocol-error";
26
+
27
+ export const FIXED_BENCHMARK_TASK = [
28
+ "Inspect only packages/pi-subagents/src/registry.ts, packages/pi-subagents/src/completion-delivery.ts, and packages/pi-subagents/src/stateful-registration.ts.",
29
+ "Report what AgentRegistry.wait races, how completion IDs prevent duplicate delivery, and which session hook closes retained completion delivery state.",
30
+ "Cite each finding with its repository-relative source path and exact symbol or operation.",
31
+ "Do not modify files.",
32
+ ].join("\n");
33
+
34
+ export const FIXED_EVIDENCE_RUBRIC = [
35
+ {
36
+ id: "registry-wait-race",
37
+ terms: ["packages/pi-subagents/src/registry.ts", "promise.race"],
38
+ },
39
+ {
40
+ id: "completion-id-deduplication",
41
+ terms: ["packages/pi-subagents/src/completion-delivery.ts", "completionid"],
42
+ },
43
+ {
44
+ id: "session-shutdown-cleanup",
45
+ terms: ["packages/pi-subagents/src/stateful-registration.ts", "session_shutdown"],
46
+ },
47
+ ] as const;
48
+
49
+ export interface AsyncSubagentBenchmarkOptions {
50
+ mode: AsyncSubagentBenchmarkMode;
51
+ model: string;
52
+ thinkingLevel: AsyncSubagentBenchmarkThinkingLevel;
53
+ timeoutMs: number;
54
+ readinessTimeoutMs: number;
55
+ outputPath?: string;
56
+ run: boolean;
57
+ piCommand: string;
58
+ workspace?: string;
59
+ extension?: string;
60
+ }
61
+
62
+ export interface AsyncSubagentBenchmarkTrialPlan {
63
+ pairIndex: number;
64
+ orderIndex: number;
65
+ arm: AsyncSubagentBenchmarkArm;
66
+ }
67
+
68
+ export interface AsyncSubagentEventAnalysis {
69
+ completionObserved: boolean;
70
+ evidenceScore: number;
71
+ matchedEvidence: string[];
72
+ prematureFinalCount: number;
73
+ finalAnswer?: string;
74
+ resultMarker?: Record<string, unknown>;
75
+ }
76
+
77
+ export interface AsyncSubagentBenchmarkTrialRecord extends AsyncSubagentEventAnalysis {
78
+ version: typeof ASYNC_SUBAGENT_BENCHMARK_VERSION;
79
+ pairIndex: number;
80
+ orderIndex: number;
81
+ arm: AsyncSubagentBenchmarkArm;
82
+ outcome: AsyncSubagentTerminalOutcome;
83
+ readinessMs: number;
84
+ elapsedMs: number;
85
+ cost: number | null;
86
+ startedAt: string;
87
+ completedAt: string;
88
+ events: unknown[];
89
+ stderr?: string;
90
+ error?: string;
91
+ }
92
+
93
+ export interface DistributionSummary {
94
+ median: number;
95
+ p95: number;
96
+ }
97
+
98
+ export interface AsyncSubagentArmSummary {
99
+ trials: number;
100
+ completionCoverage: number;
101
+ evidenceScore: number;
102
+ prematureFinalCount: number;
103
+ terminalOutcomes: Record<AsyncSubagentTerminalOutcome, number>;
104
+ latencyMs: DistributionSummary | null;
105
+ cost: {
106
+ available: number;
107
+ total: number;
108
+ median: number;
109
+ p95: number;
110
+ } | null;
111
+ }
112
+
113
+ export interface AsyncSubagentBenchmarkSummary {
114
+ version: typeof ASYNC_SUBAGENT_BENCHMARK_VERSION;
115
+ pairs: number;
116
+ arms: Record<AsyncSubagentBenchmarkArm, AsyncSubagentArmSummary>;
117
+ }
118
+
119
+ export class BenchmarkDeadlineError extends Error {
120
+ constructor(message: string) {
121
+ super(message);
122
+ this.name = "BenchmarkDeadlineError";
123
+ }
124
+ }
125
+
126
+ export function parseAsyncSubagentBenchmarkArgs(
127
+ args: readonly string[],
128
+ ): AsyncSubagentBenchmarkOptions {
129
+ let mode: AsyncSubagentBenchmarkMode = "quick";
130
+ let model = "";
131
+ let thinkingLevel: AsyncSubagentBenchmarkThinkingLevel = "medium";
132
+ let timeoutMs = 120_000;
133
+ let readinessTimeoutMs = 15_000;
134
+ let outputPath: string | undefined;
135
+ let run = false;
136
+ let piCommand = "pi";
137
+ let workspace: string | undefined;
138
+ let extension: string | undefined;
139
+
140
+ for (let index = 0; index < args.length; index++) {
141
+ const argument = args[index];
142
+ if (argument === "--run") {
143
+ run = true;
144
+ continue;
145
+ }
146
+ const value = args[index + 1];
147
+ if (!value || value.startsWith("--")) throw new Error(`${argument} requires a value`);
148
+ index++;
149
+ switch (argument) {
150
+ case "--mode":
151
+ if (!isOneOf(value, BENCHMARK_MODES)) throw new Error("--mode must be quick or extended");
152
+ mode = value;
153
+ break;
154
+ case "--model":
155
+ model = value.trim();
156
+ break;
157
+ case "--thinking":
158
+ if (!isOneOf(value, BENCHMARK_THINKING_LEVELS)) {
159
+ throw new Error(`Unsupported thinking level: ${value}`);
160
+ }
161
+ thinkingLevel = value;
162
+ break;
163
+ case "--timeout-ms":
164
+ timeoutMs = positiveInteger(value, "--timeout-ms");
165
+ break;
166
+ case "--readiness-timeout-ms":
167
+ readinessTimeoutMs = positiveInteger(value, "--readiness-timeout-ms");
168
+ break;
169
+ case "--output":
170
+ outputPath = value;
171
+ break;
172
+ case "--pi":
173
+ piCommand = value;
174
+ break;
175
+ case "--workspace":
176
+ workspace = value;
177
+ break;
178
+ case "--extension":
179
+ extension = value;
180
+ break;
181
+ default:
182
+ throw new Error(`Unknown benchmark argument: ${argument}`);
183
+ }
184
+ }
185
+ if (!model) throw new Error("--model is required so every paired trial uses one fixed model");
186
+ if (run && !outputPath) throw new Error("--output is required with --run");
187
+ return {
188
+ mode,
189
+ model,
190
+ thinkingLevel,
191
+ timeoutMs,
192
+ readinessTimeoutMs,
193
+ outputPath,
194
+ run,
195
+ piCommand,
196
+ ...(workspace ? { workspace } : {}),
197
+ ...(extension ? { extension } : {}),
198
+ };
199
+ }
200
+
201
+ export function benchmarkPairCount(mode: AsyncSubagentBenchmarkMode): number {
202
+ return mode === "quick" ? 3 : 10;
203
+ }
204
+
205
+ export function createAlternatingTrialPlan(
206
+ mode: AsyncSubagentBenchmarkMode,
207
+ ): AsyncSubagentBenchmarkTrialPlan[] {
208
+ const trials: AsyncSubagentBenchmarkTrialPlan[] = [];
209
+ for (let pairIndex = 0; pairIndex < benchmarkPairCount(mode); pairIndex++) {
210
+ const order: readonly AsyncSubagentBenchmarkArm[] =
211
+ pairIndex % 2 === 0 ? ["sync", "async"] : ["async", "sync"];
212
+ for (const [orderIndex, arm] of order.entries()) {
213
+ trials.push({ pairIndex, orderIndex, arm });
214
+ }
215
+ }
216
+ return trials;
217
+ }
218
+
219
+ export function buildAsyncSubagentBenchmarkPrompt(
220
+ arm: AsyncSubagentBenchmarkArm,
221
+ thinkingLevel: AsyncSubagentBenchmarkThinkingLevel = "medium",
222
+ ): string {
223
+ const orchestration =
224
+ arm === "sync"
225
+ ? [
226
+ "Use the deprecated subagent tool in single mode exactly once with agent explorer.",
227
+ `Set thinkingLevel to ${thinkingLevel}, pass the fixed task below, and wait for the blocking result.`,
228
+ ]
229
+ : [
230
+ "Use subagent_spawn exactly once with agent explorer, context none, and completionRequirement required.",
231
+ `Set thinkingLevel to ${thinkingLevel}, continue only useful non-overlapping local work, and rely on automatic completion delivery without calling any blocking or inspection tool.`,
232
+ "Do not provide the benchmark result before the retained completion is visible or terminal.",
233
+ ];
234
+ return [
235
+ "This is a non-interactive paired benchmark.",
236
+ ...orchestration,
237
+ "Use the configured model without changing it.",
238
+ "Fixed child task:",
239
+ FIXED_BENCHMARK_TASK,
240
+ "After observing the child result, answer concisely with all three requested findings.",
241
+ `End with one single-line marker in this exact form: ${BENCHMARK_RESULT_PREFIX} {"complete":true}`,
242
+ ].join("\n\n");
243
+ }
244
+
245
+ export function parseBenchmarkJsonLines(source: string): unknown[] {
246
+ const values: unknown[] = [];
247
+ for (const [index, rawLine] of source.split("\n").entries()) {
248
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
249
+ if (!line) continue;
250
+ try {
251
+ values.push(JSON.parse(line));
252
+ } catch {
253
+ throw new Error(`Invalid benchmark JSONL at line ${index + 1}`);
254
+ }
255
+ }
256
+ return values;
257
+ }
258
+
259
+ export function analyzeBenchmarkEvents(
260
+ arm: AsyncSubagentBenchmarkArm,
261
+ events: readonly unknown[],
262
+ ): AsyncSubagentEventAnalysis {
263
+ let completionIndex = -1;
264
+ let spawnObserved = false;
265
+ let prematureFinalCount = 0;
266
+ let finalAnswer: string | undefined;
267
+ let resultMarker: Record<string, unknown> | undefined;
268
+ let finalIndex = -1;
269
+
270
+ for (const [index, value] of events.entries()) {
271
+ if (!isRecord(value)) continue;
272
+ const message =
273
+ value.type === "message_end" && isRecord(value.message) ? value.message : undefined;
274
+ if (!message) continue;
275
+ if (message.role === "custom" && message.customType === "pi-subagent-completion") {
276
+ if (completionIndex < 0) completionIndex = index;
277
+ continue;
278
+ }
279
+ if (message.role === "toolResult") {
280
+ const toolName = typeof message.toolName === "string" ? message.toolName : "";
281
+ const details = isRecord(message.details) ? message.details : undefined;
282
+ if (toolName === "subagent_spawn" && message.isError !== true) spawnObserved = true;
283
+ if (
284
+ message.isError !== true &&
285
+ details?.timedOut !== true &&
286
+ ((arm === "sync" && toolName === "subagent") ||
287
+ (arm === "async" && toolName === "subagent_await"))
288
+ ) {
289
+ if (completionIndex < 0) completionIndex = index;
290
+ }
291
+ continue;
292
+ }
293
+ if (message.role !== "assistant") continue;
294
+ const content = Array.isArray(message.content) ? message.content : [];
295
+ const hasToolCall = content.some(
296
+ (item) => isRecord(item) && item.type === "toolCall" && typeof item.name === "string",
297
+ );
298
+ if (
299
+ content.some(
300
+ (item) => isRecord(item) && item.type === "toolCall" && item.name === "subagent_spawn",
301
+ )
302
+ ) {
303
+ spawnObserved = true;
304
+ }
305
+ const text = messageText(message);
306
+ const marker = extractResultMarker(text);
307
+ if (marker) {
308
+ if (arm === "async" && spawnObserved && completionIndex < 0) prematureFinalCount++;
309
+ finalAnswer = text;
310
+ resultMarker = marker;
311
+ finalIndex = index;
312
+ } else if (
313
+ arm === "async" &&
314
+ spawnObserved &&
315
+ completionIndex < 0 &&
316
+ text.trim() &&
317
+ !hasToolCall &&
318
+ scoreBenchmarkEvidence(text).score > 0
319
+ ) {
320
+ prematureFinalCount++;
321
+ }
322
+ }
323
+
324
+ const score = scoreBenchmarkEvidence(finalAnswer ?? "");
325
+ return {
326
+ completionObserved: completionIndex >= 0 && (finalIndex < 0 || completionIndex < finalIndex),
327
+ evidenceScore: score.score,
328
+ matchedEvidence: score.matched,
329
+ prematureFinalCount,
330
+ ...(finalAnswer ? { finalAnswer } : {}),
331
+ ...(resultMarker ? { resultMarker } : {}),
332
+ };
333
+ }
334
+
335
+ export function scoreBenchmarkEvidence(text: string): { score: number; matched: string[] } {
336
+ const normalized = text.toLowerCase().replaceAll("`", "");
337
+ const matched = FIXED_EVIDENCE_RUBRIC.filter((item) =>
338
+ item.terms.every((term) => normalized.includes(term.toLowerCase())),
339
+ ).map((item) => item.id);
340
+ return {
341
+ score: round(matched.length / FIXED_EVIDENCE_RUBRIC.length),
342
+ matched,
343
+ };
344
+ }
345
+
346
+ export function percentile(values: readonly number[], quantile: number): number {
347
+ if (values.length === 0) throw new Error("Cannot calculate a percentile without values");
348
+ if (!Number.isFinite(quantile) || quantile < 0 || quantile > 1) {
349
+ throw new Error("Percentile quantile must be between zero and one");
350
+ }
351
+ const sorted = [...values].sort((left, right) => left - right);
352
+ const position = (sorted.length - 1) * quantile;
353
+ const lower = Math.floor(position);
354
+ const upper = Math.ceil(position);
355
+ if (lower === upper) return round(sorted[lower]);
356
+ return round(sorted[lower] + (sorted[upper] - sorted[lower]) * (position - lower));
357
+ }
358
+
359
+ export function summarizeAsyncSubagentBenchmark(
360
+ records: readonly AsyncSubagentBenchmarkTrialRecord[],
361
+ ): AsyncSubagentBenchmarkSummary {
362
+ const summarizeArm = (arm: AsyncSubagentBenchmarkArm): AsyncSubagentArmSummary => {
363
+ const selected = records.filter((record) => record.arm === arm);
364
+ const completed = selected.filter((record) => record.outcome === "completed");
365
+ const costs = selected.flatMap((record) => (record.cost === null ? [] : [record.cost]));
366
+ const terminalOutcomes = emptyTerminalOutcomes();
367
+ for (const record of selected) terminalOutcomes[record.outcome]++;
368
+ return {
369
+ trials: selected.length,
370
+ completionCoverage:
371
+ selected.length === 0
372
+ ? 0
373
+ : round(selected.filter((record) => record.completionObserved).length / selected.length),
374
+ evidenceScore:
375
+ selected.length === 0
376
+ ? 0
377
+ : round(
378
+ selected.reduce((sum, record) => sum + record.evidenceScore, 0) / selected.length,
379
+ ),
380
+ prematureFinalCount: selected.reduce((sum, record) => sum + record.prematureFinalCount, 0),
381
+ terminalOutcomes,
382
+ latencyMs:
383
+ completed.length === 0
384
+ ? null
385
+ : {
386
+ median: percentile(
387
+ completed.map((record) => record.elapsedMs),
388
+ 0.5,
389
+ ),
390
+ p95: percentile(
391
+ completed.map((record) => record.elapsedMs),
392
+ 0.95,
393
+ ),
394
+ },
395
+ cost:
396
+ costs.length === 0
397
+ ? null
398
+ : {
399
+ available: costs.length,
400
+ total: round(costs.reduce((sum, value) => sum + value, 0)),
401
+ median: percentile(costs, 0.5),
402
+ p95: percentile(costs, 0.95),
403
+ },
404
+ };
405
+ };
406
+ return {
407
+ version: ASYNC_SUBAGENT_BENCHMARK_VERSION,
408
+ pairs: new Set(records.map((record) => record.pairIndex)).size,
409
+ arms: { sync: summarizeArm("sync"), async: summarizeArm("async") },
410
+ };
411
+ }
412
+
413
+ export async function runAfterReadinessWithDeadline<T>(
414
+ readiness: Promise<unknown>,
415
+ run: () => Promise<T>,
416
+ timeoutMs: number,
417
+ ): Promise<T> {
418
+ await readiness;
419
+ return await withDeadline(run(), timeoutMs, "Benchmark trial timed out");
420
+ }
421
+
422
+ export async function withDeadline<T>(
423
+ operation: Promise<T>,
424
+ timeoutMs: number,
425
+ message: string,
426
+ ): Promise<T> {
427
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 1) throw new Error("Deadline must be positive");
428
+ let timer: NodeJS.Timeout | undefined;
429
+ try {
430
+ return await Promise.race([
431
+ operation,
432
+ new Promise<never>((_resolve, reject) => {
433
+ timer = setTimeout(() => reject(new BenchmarkDeadlineError(message)), timeoutMs);
434
+ }),
435
+ ]);
436
+ } finally {
437
+ if (timer) clearTimeout(timer);
438
+ }
439
+ }
440
+
441
+ export function redactBenchmarkValue(value: unknown): unknown {
442
+ return redactValue(value, new WeakSet<object>());
443
+ }
444
+
445
+ function extractResultMarker(text: string): Record<string, unknown> | undefined {
446
+ for (const line of text.split("\n").reverse()) {
447
+ const markerIndex = line.indexOf(BENCHMARK_RESULT_PREFIX);
448
+ if (markerIndex < 0) continue;
449
+ const source = line.slice(markerIndex + BENCHMARK_RESULT_PREFIX.length).trim();
450
+ try {
451
+ const parsed: unknown = JSON.parse(source);
452
+ if (isRecord(parsed) && parsed.complete === true) return parsed;
453
+ } catch {
454
+ return undefined;
455
+ }
456
+ }
457
+ return undefined;
458
+ }
459
+
460
+ function messageText(message: Record<string, unknown>): string {
461
+ if (typeof message.content === "string") return message.content;
462
+ if (!Array.isArray(message.content)) return "";
463
+ return message.content
464
+ .flatMap((item) =>
465
+ isRecord(item) && item.type === "text" && typeof item.text === "string" ? [item.text] : [],
466
+ )
467
+ .join("\n");
468
+ }
469
+
470
+ function emptyTerminalOutcomes(): Record<AsyncSubagentTerminalOutcome, number> {
471
+ return {
472
+ completed: 0,
473
+ "invalid-output": 0,
474
+ "timed-out": 0,
475
+ "readiness-timeout": 0,
476
+ "process-error": 0,
477
+ "protocol-error": 0,
478
+ };
479
+ }
480
+
481
+ function redactValue(value: unknown, seen: WeakSet<object>): unknown {
482
+ if (typeof value === "string") return redactString(value);
483
+ if (Array.isArray(value)) return value.map((item) => redactValue(item, seen));
484
+ if (!isRecord(value)) return value;
485
+ if (seen.has(value)) return "[circular]";
486
+ seen.add(value);
487
+ const redacted: Record<string, unknown> = {};
488
+ for (const [key, item] of Object.entries(value)) {
489
+ redacted[key] = sensitiveKey(key) ? "[redacted]" : redactValue(item, seen);
490
+ }
491
+ return redacted;
492
+ }
493
+
494
+ function redactString(value: string): string {
495
+ const home = process.env.HOME;
496
+ let redacted = value.replace(/<private>[\s\S]*?<\/private>/giu, "[private content omitted]");
497
+ redacted = redacted.replace(/\bBearer\s+[A-Za-z0-9._~+/-]+=*/giu, "Bearer [redacted]");
498
+ redacted = redacted.replace(/\b(sk-[A-Za-z0-9_-]{12,})\b/gu, "[redacted-key]");
499
+ redacted = redacted.replace(
500
+ /\b([A-Z][A-Z0-9_]*(?:TOKEN|SECRET|PASSWORD|API_KEY))=([^\s]+)/gu,
501
+ "$1=[redacted]",
502
+ );
503
+ if (home) redacted = redacted.split(home).join("$HOME");
504
+ const limit = 16 * 1024;
505
+ return redacted.length <= limit ? redacted : `${redacted.slice(0, limit)}\n[truncated]`;
506
+ }
507
+
508
+ function sensitiveKey(key: string): boolean {
509
+ return /^(?:authorization|api[-_]?key|token|secret|password|headers|environment|env)$/iu.test(
510
+ key,
511
+ );
512
+ }
513
+
514
+ function positiveInteger(value: string, name: string): number {
515
+ const parsed = Number(value);
516
+ if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > 2_147_483_647) {
517
+ throw new Error(`${name} must be a positive integer`);
518
+ }
519
+ return parsed;
520
+ }
521
+
522
+ function isRecord(value: unknown): value is Record<string, unknown> {
523
+ return typeof value === "object" && value !== null && !Array.isArray(value);
524
+ }
525
+
526
+ function isOneOf<const T extends readonly string[]>(value: string, values: T): value is T[number] {
527
+ return values.includes(value);
528
+ }
529
+
530
+ function round(value: number): number {
531
+ return Number(value.toFixed(3));
532
+ }
@@ -1,6 +1,7 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import type { CompletionDelivery } from "./agents/types.js";
3
3
  import { SUBAGENT_COMPLETION_MESSAGE_TYPE } from "./completion-render.js";
4
+ import { requirementForCompletion } from "./completion-requirement.js";
4
5
  import { redactPrivateText } from "./context.js";
5
6
  import { DEFAULT_MAX_CONTEXT_BYTES, MAX_TOOL_MESSAGE_BYTES, truncateUtf8 } from "./limits.js";
6
7
  import type { AgentTurnCompletion, ManagedAgent } from "./registry.js";
@@ -9,6 +10,7 @@ import { PI_SUBAGENTS_RPC_PROTOCOL } from "./transport-types.js";
9
10
 
10
11
  const MAX_COMPLETION_ERROR_BYTES = 512;
11
12
  const MAX_COMPLETIONS_PER_MESSAGE = 16;
13
+ const MAX_ACKNOWLEDGED_COMPLETION_IDS = 2_048;
12
14
  const COMPLETION_BATCH_DELAY_MS = 10;
13
15
 
14
16
  interface CompletionMetadata {
@@ -26,6 +28,7 @@ interface CompletionMetadata {
26
28
  structuredResult?: ManagedAgent["structuredResult"];
27
29
  outcome?: ManagedAgent["outcome"];
28
30
  capabilityGrant?: ManagedAgent["capabilityGrant"];
31
+ completionRequirement?: NonNullable<ManagedAgent["completionRequirements"]>[number];
29
32
  }
30
33
 
31
34
  interface CompletionMessage {
@@ -45,6 +48,14 @@ type CompletionPi = Pick<ExtensionAPI, "sendMessage">;
45
48
 
46
49
  export interface CompletionDeliveryBrokerOptions {
47
50
  onDeliveryError?: (error: unknown) => void;
51
+ onDeliveryAttempt?: (
52
+ completions: readonly AgentTurnCompletion[],
53
+ input: {
54
+ delivery: "steer" | "nextTurn";
55
+ triggerTurn: boolean;
56
+ outcome: "accepted" | "failed";
57
+ },
58
+ ) => void;
48
59
  onAcknowledged?: (completions: readonly AgentTurnCompletion[], acknowledgedAt: number) => void;
49
60
  now?: () => number;
50
61
  }
@@ -53,6 +64,7 @@ export interface CompletionDeliveryBrokerOptions {
53
64
  export class CompletionDeliveryBroker {
54
65
  private pending: AgentTurnCompletion[] = [];
55
66
  private readonly knownCompletionIds = new Set<string>();
67
+ private readonly acknowledgedCompletionIds = new Set<string>();
56
68
  private awaitingParentAck: AgentTurnCompletion[] = [];
57
69
  private flushTimer?: NodeJS.Timeout;
58
70
  private wakeInFlight = false;
@@ -66,7 +78,13 @@ export class CompletionDeliveryBroker {
66
78
  ) {}
67
79
 
68
80
  enqueue(completion: AgentTurnCompletion): void {
69
- if (this.closed || this.knownCompletionIds.has(completion.completionId)) return;
81
+ if (
82
+ this.closed ||
83
+ this.knownCompletionIds.has(completion.completionId) ||
84
+ this.acknowledgedCompletionIds.has(completion.completionId)
85
+ ) {
86
+ return;
87
+ }
70
88
  this.knownCompletionIds.add(completion.completionId);
71
89
  this.pending.push(completion);
72
90
  this.scheduleFlush();
@@ -99,7 +117,6 @@ export class CompletionDeliveryBroker {
99
117
  if (this.closed || this.pending.length === 0) return;
100
118
  if (this.flushTimer) clearTimeout(this.flushTimer);
101
119
  this.flushTimer = undefined;
102
- if (this.delivery === "auto-resume" && !this.isRootIdle()) return;
103
120
 
104
121
  const completions = this.pending.splice(0);
105
122
  const batches = chunkCompletions(completions);
@@ -116,14 +133,34 @@ export class CompletionDeliveryBroker {
116
133
  deliverAs: "steer",
117
134
  ...(triggerTurn ? { triggerTurn: true } : {}),
118
135
  });
136
+ this.notifyDeliveryAttempt(batch, {
137
+ delivery: "steer",
138
+ triggerTurn,
139
+ outcome: "accepted",
140
+ });
119
141
  } catch (primaryError) {
142
+ this.notifyDeliveryAttempt(batch, {
143
+ delivery: "steer",
144
+ triggerTurn,
145
+ outcome: "failed",
146
+ });
120
147
  this.removeAwaiting(batch);
121
148
  if (triggerTurn) this.wakeInFlight = false;
122
149
  canWake = false;
123
150
  this.awaitingParentAck.push(...batch);
124
151
  try {
125
152
  this.pi.sendMessage(message, { deliverAs: "nextTurn", triggerTurn: false });
153
+ this.notifyDeliveryAttempt(batch, {
154
+ delivery: "nextTurn",
155
+ triggerTurn: false,
156
+ outcome: "accepted",
157
+ });
126
158
  } catch (fallbackError) {
159
+ this.notifyDeliveryAttempt(batch, {
160
+ delivery: "nextTurn",
161
+ triggerTurn: false,
162
+ outcome: "failed",
163
+ });
127
164
  this.removeAwaiting(batch);
128
165
  this.pending = [...batches.slice(index).flat(), ...this.pending];
129
166
  try {
@@ -149,6 +186,7 @@ export class CompletionDeliveryBroker {
149
186
  this.pending = [];
150
187
  this.awaitingParentAck = [];
151
188
  this.knownCompletionIds.clear();
189
+ this.acknowledgedCompletionIds.clear();
152
190
  }
153
191
 
154
192
  private scheduleFlush(): void {
@@ -172,7 +210,10 @@ export class CompletionDeliveryBroker {
172
210
  this.pending = this.pending.filter(
173
211
  (completion) => !acknowledgedIds.has(completion.completionId),
174
212
  );
175
- for (const completion of completions) this.knownCompletionIds.delete(completion.completionId);
213
+ for (const completion of completions) {
214
+ this.knownCompletionIds.delete(completion.completionId);
215
+ this.rememberAcknowledged(completion.completionId);
216
+ }
176
217
  try {
177
218
  this.options.onAcknowledged?.(completions, (this.options.now ?? Date.now)());
178
219
  } catch {
@@ -180,6 +221,15 @@ export class CompletionDeliveryBroker {
180
221
  }
181
222
  }
182
223
 
224
+ private rememberAcknowledged(completionId: string): void {
225
+ this.acknowledgedCompletionIds.add(completionId);
226
+ while (this.acknowledgedCompletionIds.size > MAX_ACKNOWLEDGED_COMPLETION_IDS) {
227
+ const oldest = this.acknowledgedCompletionIds.values().next().value;
228
+ if (typeof oldest !== "string") return;
229
+ this.acknowledgedCompletionIds.delete(oldest);
230
+ }
231
+ }
232
+
183
233
  private removeAwaiting(completions: readonly AgentTurnCompletion[]): void {
184
234
  const removed = new Set(completions.map((completion) => completion.completionId));
185
235
  this.awaitingParentAck = this.awaitingParentAck.filter(
@@ -187,6 +237,21 @@ export class CompletionDeliveryBroker {
187
237
  );
188
238
  }
189
239
 
240
+ private notifyDeliveryAttempt(
241
+ completions: readonly AgentTurnCompletion[],
242
+ input: {
243
+ delivery: "steer" | "nextTurn";
244
+ triggerTurn: boolean;
245
+ outcome: "accepted" | "failed";
246
+ },
247
+ ): void {
248
+ try {
249
+ this.options.onDeliveryAttempt?.(completions, input);
250
+ } catch {
251
+ // Delivery already succeeded, so an observer cannot retract it.
252
+ }
253
+ }
254
+
190
255
  private isRootIdle(): boolean {
191
256
  try {
192
257
  return this.ctx.isIdle();
@@ -196,7 +261,7 @@ export class CompletionDeliveryBroker {
196
261
  }
197
262
 
198
263
  private shouldWakeRoot(): boolean {
199
- if (this.delivery !== "auto-resume" || this.wakeInFlight) return false;
264
+ if (this.delivery !== "auto-resume" || this.wakeInFlight || !this.isRootIdle()) return false;
200
265
  try {
201
266
  return !this.ctx.hasPendingMessages();
202
267
  } catch {
@@ -276,6 +341,7 @@ function buildCompletionMessage(completions: AgentTurnCompletion[]): CompletionM
276
341
  }
277
342
 
278
343
  function completionMetadata(completion: AgentTurnCompletion): CompletionMetadata {
344
+ const completionRequirement = requirementForCompletion(completion.agent, completion.completionId);
279
345
  return {
280
346
  protocol: PI_SUBAGENTS_RPC_PROTOCOL,
281
347
  completionId: completion.completionId,
@@ -297,6 +363,7 @@ function completionMetadata(completion: AgentTurnCompletion): CompletionMetadata
297
363
  ...(completion.agent.capabilityGrant
298
364
  ? { capabilityGrant: completion.agent.capabilityGrant }
299
365
  : {}),
366
+ ...(completionRequirement ? { completionRequirement } : {}),
300
367
  };
301
368
  }
302
369