@timmyjl12/pi-subagents 0.20.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/CHANGELOG.md +862 -827
  2. package/README.md +1125 -1080
  3. package/dist/active-agents-prompt.d.ts +31 -9
  4. package/dist/active-agents-prompt.js +73 -9
  5. package/dist/agent-color.js +9 -1
  6. package/dist/agent-file-toggle.d.ts +1 -1
  7. package/dist/agent-manager.d.ts +405 -18
  8. package/dist/agent-manager.js +1661 -131
  9. package/dist/agent-runner.d.ts +45 -6
  10. package/dist/agent-runner.js +109 -18
  11. package/dist/agent-types.d.ts +30 -7
  12. package/dist/agent-types.js +38 -9
  13. package/dist/awaited-result.d.ts +37 -0
  14. package/dist/awaited-result.js +150 -0
  15. package/dist/child-session-shutdown.d.ts +19 -1
  16. package/dist/child-session-shutdown.js +60 -11
  17. package/dist/cleanup-plans.d.ts +10 -0
  18. package/dist/cleanup-plans.js +112 -0
  19. package/dist/cross-extension-rpc.d.ts +8 -1
  20. package/dist/cross-extension-rpc.js +59 -5
  21. package/dist/custom-agents.d.ts +34 -9
  22. package/dist/custom-agents.js +308 -111
  23. package/dist/default-agents.d.ts +1 -1
  24. package/dist/env.d.ts +1 -1
  25. package/dist/error-log.d.ts +6 -0
  26. package/dist/error-log.js +8 -0
  27. package/dist/force-main-model.d.ts +21 -0
  28. package/dist/force-main-model.js +28 -0
  29. package/dist/goal-bridge.d.ts +155 -0
  30. package/dist/goal-bridge.js +305 -0
  31. package/dist/group-join.d.ts +5 -1
  32. package/dist/group-join.js +52 -7
  33. package/dist/index.d.ts +5 -5
  34. package/dist/index.js +2827 -333
  35. package/dist/invocation-config.d.ts +30 -3
  36. package/dist/invocation-config.js +30 -1
  37. package/dist/memory.d.ts +1 -1
  38. package/dist/mention-clone.d.ts +1 -1
  39. package/dist/model-scope.d.ts +1 -1
  40. package/dist/nested-tools.d.ts +22 -1
  41. package/dist/nested-tools.js +120 -26
  42. package/dist/output-file.d.ts +15 -4
  43. package/dist/output-file.js +146 -43
  44. package/dist/prompts.d.ts +1 -1
  45. package/dist/recovery.d.ts +1 -1
  46. package/dist/report-cleanup.d.ts +204 -0
  47. package/dist/report-cleanup.js +1632 -0
  48. package/dist/report-store.d.ts +738 -0
  49. package/dist/report-store.js +3616 -0
  50. package/dist/schedule-store.d.ts +14 -6
  51. package/dist/schedule-store.js +88 -58
  52. package/dist/schedule.d.ts +20 -8
  53. package/dist/schedule.js +135 -74
  54. package/dist/settings.d.ts +39 -11
  55. package/dist/settings.js +22 -5
  56. package/dist/status-note.d.ts +1 -1
  57. package/dist/structured-output.d.ts +1 -1
  58. package/dist/types.d.ts +32 -3
  59. package/dist/ui/agent-mention.d.ts +2 -2
  60. package/dist/ui/agent-widget.d.ts +82 -13
  61. package/dist/ui/agent-widget.js +155 -37
  62. package/dist/ui/cleanup-preview.d.ts +59 -0
  63. package/dist/ui/cleanup-preview.js +466 -0
  64. package/dist/ui/conversation-viewer.d.ts +4 -4
  65. package/dist/ui/conversation-viewer.js +10 -6
  66. package/dist/ui/fleet-list.d.ts +3 -3
  67. package/dist/ui/fleet-list.js +3 -3
  68. package/dist/ui/fleet-overlay.d.ts +37 -6
  69. package/dist/ui/fleet-overlay.js +214 -18
  70. package/dist/ui/hub-feed.d.ts +52 -0
  71. package/dist/ui/hub-feed.js +148 -0
  72. package/dist/ui/native-transcript.js +5 -1
  73. package/dist/ui/schedule-menu.d.ts +1 -1
  74. package/dist/ui/schedule-menu.js +1 -1
  75. package/dist/ui/workflow-card.d.ts +4 -4
  76. package/dist/ui/workflow-dialog.d.ts +4 -4
  77. package/dist/ui/workflow-dialog.js +8 -3
  78. package/dist/ui/workflow-menu.d.ts +2 -2
  79. package/dist/usage.d.ts +12 -0
  80. package/dist/usage.js +28 -1
  81. package/dist/workflow/entry.d.ts +3 -3
  82. package/dist/workflow/host.d.ts +7 -4
  83. package/dist/workflow/host.js +162 -48
  84. package/dist/workflow/journal.d.ts +23 -7
  85. package/dist/workflow/journal.js +80 -23
  86. package/dist/workflow/progress.d.ts +1 -1
  87. package/dist/workflow/runtime.d.ts +45 -6
  88. package/dist/workflow/runtime.js +105 -16
  89. package/dist/workflow/task.d.ts +13 -4
  90. package/dist/workflow/task.js +7 -1
  91. package/dist/workflow/tool-description.d.ts +7 -2
  92. package/dist/workflow/tool-description.js +10 -5
  93. package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
  94. package/docs/artifacts.md +93 -0
  95. package/docs/rpc.md +252 -189
  96. package/docs/runtime-performance.md +53 -0
  97. package/docs/workflows.md +48 -18
  98. package/examples/agent-tool-description.md +2 -2
  99. package/examples/workflows/review-panel.js +6 -3
  100. package/package.json +5 -5
  101. package/src/active-agents-prompt.ts +115 -39
  102. package/src/agent-color.ts +10 -2
  103. package/src/agent-file-toggle.ts +2 -2
  104. package/src/agent-manager.ts +3312 -1601
  105. package/src/agent-runner.ts +164 -36
  106. package/src/agent-types.ts +56 -11
  107. package/src/awaited-result.ts +187 -0
  108. package/src/child-session-shutdown.ts +114 -46
  109. package/src/cleanup-plans.ts +112 -0
  110. package/src/cross-extension-rpc.ts +68 -9
  111. package/src/custom-agents.ts +384 -112
  112. package/src/default-agents.ts +1 -1
  113. package/src/enabled-models.ts +1 -1
  114. package/src/env.ts +1 -1
  115. package/src/error-log.ts +10 -1
  116. package/src/force-main-model.ts +29 -0
  117. package/src/goal-bridge.ts +468 -0
  118. package/src/group-join.ts +56 -9
  119. package/src/index.ts +2987 -349
  120. package/src/invocation-config.ts +50 -4
  121. package/src/memory.ts +1 -1
  122. package/src/mention-clone.ts +3 -3
  123. package/src/model-scope.ts +1 -1
  124. package/src/nested-tools.ts +164 -33
  125. package/src/output-file.ts +168 -46
  126. package/src/prompts.ts +1 -1
  127. package/src/recovery.ts +2 -2
  128. package/src/report-cleanup.ts +2044 -0
  129. package/src/report-store.ts +4133 -0
  130. package/src/schedule-store.ts +244 -201
  131. package/src/schedule.ts +144 -80
  132. package/src/settings.ts +61 -16
  133. package/src/skill-loader.ts +1 -1
  134. package/src/standalone-fallback.ts +2 -2
  135. package/src/status-note.ts +1 -1
  136. package/src/structured-output.ts +1 -1
  137. package/src/types.ts +33 -3
  138. package/src/ui/agent-mention.ts +3 -3
  139. package/src/ui/agent-widget.ts +179 -45
  140. package/src/ui/cleanup-preview.ts +518 -0
  141. package/src/ui/conversation-viewer.ts +19 -15
  142. package/src/ui/fleet-list.ts +7 -7
  143. package/src/ui/fleet-overlay.ts +1048 -847
  144. package/src/ui/hub-feed.ts +179 -0
  145. package/src/ui/native-transcript.ts +7 -3
  146. package/src/ui/schedule-menu.ts +4 -4
  147. package/src/ui/workflow-card.ts +4 -4
  148. package/src/ui/workflow-dialog.ts +10 -6
  149. package/src/ui/workflow-menu.ts +4 -4
  150. package/src/usage.ts +53 -3
  151. package/src/workflow/collisions.ts +1 -1
  152. package/src/workflow/entry.ts +3 -3
  153. package/src/workflow/host.ts +174 -54
  154. package/src/workflow/journal.ts +80 -23
  155. package/src/workflow/progress.ts +1 -1
  156. package/src/workflow/runtime.ts +146 -23
  157. package/src/workflow/saved.ts +3 -3
  158. package/src/workflow/task.ts +18 -7
  159. package/src/workflow/tool-description.ts +10 -5
@@ -9,9 +9,10 @@ import { appendFileSync, chmodSync, mkdirSync, writeFileSync } from "node:fs";
9
9
  import { appendFile } from "node:fs/promises";
10
10
  import { tmpdir } from "node:os";
11
11
  import { join } from "node:path";
12
+ import { setImmediate as yieldToEventLoop } from "node:timers/promises";
12
13
  import type { AgentSession, AgentSessionEvent } from "@earendil-works/pi-coding-agent";
13
- import { logSubagentIssue } from "./error-log.js";
14
- import { assistantDiagnosticContext, sanitizeDiagnosticText } from "./output-diagnostics.js";
14
+ import { logSubagentIssue } from "./error-log.ts";
15
+ import { assistantDiagnosticContext, sanitizeDiagnosticText } from "./output-diagnostics.ts";
15
16
 
16
17
  /**
17
18
  * Project/global default for writing a subagent's `.output` transcript; a custom
@@ -97,21 +98,118 @@ export function writeInitialEntry(path: string, agentId: string, prompt: string,
97
98
  }
98
99
 
99
100
  /**
100
- * Serialized write chains for transcript files: at most one in-flight append
101
- * per file. A drain coalesces everything queued while it writes — a burst of
102
- * finalized messages costs one append syscall per batch, not per message — and
103
- * a resume subscribing a second stream to the same transcript chains after the
104
- * previous stream's pending writes instead of interleaving with them.
101
+ * Lossless per-path output queues. Finalized lines are stringified at event
102
+ * time (snapshot semantics below) and appended by exactly one drain per file,
103
+ * so a resume subscribing a second stream to the same transcript queues behind
104
+ * the previous stream instead of interleaving. `pendingBytes` counts both
105
+ * queued and in-flight serialized bytes; appends are sliced into bounded
106
+ * batches, but a single oversized record is never split.
105
107
  */
106
- const writeChains = new Map<string, Promise<void>>();
108
+ const OUTPUT_HIGH_WATER_BYTES = 1024 * 1024;
109
+ const OUTPUT_BATCH_BYTES = 256 * 1024;
110
+ const OUTPUT_BATCH_RECORDS = 64;
107
111
 
108
- function chainWrite(path: string, run: () => Promise<void>): Promise<void> {
109
- const chained = (writeChains.get(path) ?? Promise.resolve()).then(run);
110
- writeChains.set(path, chained);
111
- void chained.finally(() => {
112
- if (writeChains.get(path) === chained) writeChains.delete(path);
113
- });
114
- return chained;
112
+ interface QueuedLine {
113
+ text: string;
114
+ bytes: number;
115
+ }
116
+
117
+ const CONSUMED_LINE: QueuedLine = { text: "", bytes: 0 };
118
+
119
+ interface DrainWaiter {
120
+ /** Resolve only once pending serialized bytes are strictly below this. */
121
+ below: number;
122
+ resolve: () => void;
123
+ }
124
+
125
+ interface PathQueue {
126
+ lines: QueuedLine[];
127
+ head: number;
128
+ pendingBytes: number;
129
+ draining: boolean;
130
+ waiters: Set<DrainWaiter>;
131
+ }
132
+
133
+ const outputQueues = new Map<string, PathQueue>();
134
+
135
+ function resolveWaiters(queue: PathQueue): void {
136
+ for (const waiter of [...queue.waiters]) {
137
+ if (queue.pendingBytes >= waiter.below) continue;
138
+ queue.waiters.delete(waiter);
139
+ waiter.resolve();
140
+ }
141
+ }
142
+
143
+ /** Wait until a path's accepted output falls below `below` bytes. No polling. */
144
+ function waitForOutput(path: string, below: number): Promise<void> {
145
+ const queue = outputQueues.get(path);
146
+ if (!queue || queue.pendingBytes < below) return Promise.resolve();
147
+ return new Promise<void>((resolve) => { queue.waiters.add({ below, resolve }); });
148
+ }
149
+
150
+ /**
151
+ * Write accepted records one batch at a time. Each append chunk is at most 256
152
+ * KiB or 64 records; the only exception is one larger indivisible record,
153
+ * which is written whole. Accounting is decremented in `finally`, so a failed
154
+ * best-effort write cannot strand pending bytes or waiters.
155
+ */
156
+ function drainQueue(path: string, queue: PathQueue): void {
157
+ if (queue.draining) return;
158
+ queue.draining = true;
159
+ void (async () => {
160
+ try {
161
+ while (queue.head < queue.lines.length) {
162
+ let records = 0;
163
+ let bytes = 0;
164
+ while (records < queue.lines.length - queue.head) {
165
+ const next = queue.lines[queue.head + records];
166
+ if (records > 0
167
+ && (records >= OUTPUT_BATCH_RECORDS || bytes + next.bytes > OUTPUT_BATCH_BYTES)) break;
168
+ bytes += next.bytes;
169
+ records += 1;
170
+ }
171
+ const end = queue.head + records;
172
+ const chunk = queue.lines.slice(queue.head, end);
173
+ // Release consumed payloads immediately; a long-lived busy path must not
174
+ // retain written strings. Compact geometrically instead of shifting the
175
+ // whole remaining queue for every bounded append (quadratic copying).
176
+ for (let index = queue.head; index < end; index++) queue.lines[index] = CONSUMED_LINE;
177
+ queue.head = end;
178
+ if (queue.head === queue.lines.length) {
179
+ queue.lines = [];
180
+ queue.head = 0;
181
+ } else if (queue.head >= OUTPUT_BATCH_RECORDS && queue.head * 2 >= queue.lines.length) {
182
+ queue.lines = queue.lines.slice(queue.head);
183
+ queue.head = 0;
184
+ }
185
+ try {
186
+ await appendFile(path, chunk.map(line => line.text).join(""), "utf-8");
187
+ } catch { /* best-effort file output; never write raw errors into the TUI */ }
188
+ finally {
189
+ queue.pendingBytes -= bytes;
190
+ resolveWaiters(queue);
191
+ }
192
+ }
193
+ } finally {
194
+ queue.draining = false;
195
+ if (queue.pendingBytes === 0 && queue.head === queue.lines.length) {
196
+ if (outputQueues.get(path) === queue) outputQueues.delete(path);
197
+ resolveWaiters(queue);
198
+ }
199
+ }
200
+ })();
201
+ }
202
+
203
+ function enqueueOutput(path: string, text: string): void {
204
+ let queue = outputQueues.get(path);
205
+ if (!queue) {
206
+ queue = { lines: [], head: 0, pendingBytes: 0, draining: false, waiters: new Set() };
207
+ outputQueues.set(path, queue);
208
+ }
209
+ const bytes = Buffer.byteLength(text, "utf-8");
210
+ queue.lines.push({ text, bytes });
211
+ queue.pendingBytes += bytes;
212
+ drainQueue(path, queue);
115
213
  }
116
214
 
117
215
  /**
@@ -120,19 +218,33 @@ function chainWrite(path: string, run: () => Promise<void>): Promise<void> {
120
218
  * so a caller can await the final flush.
121
219
  */
122
220
  export function drainOutputFile(path: string): Promise<void> {
123
- return writeChains.get(path) ?? Promise.resolve();
221
+ return waitForOutput(path, 1);
222
+ }
223
+
224
+ /** Diagnostic only: serialized bytes accepted for a path but not yet written. */
225
+ export function pendingOutputBytes(path: string): number {
226
+ return outputQueues.get(path)?.pendingBytes ?? 0;
124
227
  }
125
228
 
229
+ type OutputSession = Pick<AgentSession, "messages" | "retryAttempt" | "subscribe"> & {
230
+ agent?: Pick<AgentSession["agent"], "subscribe">;
231
+ };
232
+
126
233
  /**
127
234
  * Persist finalized events before retries can remove them from session.messages.
128
235
  * Snapshot flushes also preserve eventless SDK additions (e.g. bashExecution).
129
236
  * Lines are stringified at event time but written through an async per-file
130
- * queue (see chainWrite), so message-sized JSON work never blocks the loop.
131
- * Returns an idempotent final flush/unsubscribe that resolves once the flushed
132
- * writes are on disk; never changes retry policy.
237
+ * queue (see drainQueue). JSON serialization remains synchronous; disk waits
238
+ * and bounded producer checkpoints are asynchronous.
239
+ * A real Agent session also gets a producer listener registered after the
240
+ * session observer: it waits below the high-water mark at message_end and
241
+ * forces a drain at turn/run settlement, so slow disk stops the producer
242
+ * instead of growing an unbounded in-memory queue. Returns an idempotent final
243
+ * flush/unsubscribe that resolves once the flushed writes are on disk; never
244
+ * changes retry policy.
133
245
  */
134
246
  export function streamToOutputFile(
135
- session: AgentSession,
247
+ session: OutputSession,
136
248
  path: string,
137
249
  agentId: string,
138
250
  cwd: string,
@@ -141,7 +253,7 @@ export function streamToOutputFile(
141
253
  // agent type pass it (the index.ts spawn paths); nested-tools.ts does not,
142
254
  // so central-log records from that path carry agentId/session names only.
143
255
  agentType?: string,
144
- ): () => void {
256
+ ): () => Promise<void> {
145
257
  type Message = AgentSession["messages"][number];
146
258
  const initial = session.messages;
147
259
  // A resume supplies its pre-run boundary. Existing history on a reopened
@@ -154,26 +266,10 @@ export function streamToOutputFile(
154
266
  let lastAssistant: ReturnType<typeof assistantDiagnosticContext> | undefined;
155
267
  let closed = false;
156
268
 
157
- // Queued lines are stringified at event time — messages are live SDK state,
158
- // and a write must snapshot the finalized message, not a later mutation. The
159
- // drain coalesces everything queued while a write is in flight.
160
- let batch: string[] = [];
161
- let draining = false;
162
-
163
- const drain = async (): Promise<void> => {
164
- try {
165
- while (batch.length > 0) {
166
- const chunk = batch;
167
- batch = [];
168
- try {
169
- await appendFile(path, chunk.join(""), "utf-8");
170
- } catch { /* best-effort file output; never write raw errors into the TUI */ }
171
- }
172
- } finally {
173
- draining = false;
174
- }
175
- };
176
-
269
+ // Lines are stringified at event time — messages are live SDK state, and a
270
+ // write must snapshot the finalized message, not a later mutation. enqueue
271
+ // adds the completed line to the shared per-path queue (one append in flight,
272
+ // bounded batches).
177
273
  const append = (fields: Record<string, unknown>) => {
178
274
  let line: string;
179
275
  try {
@@ -181,11 +277,7 @@ export function streamToOutputFile(
181
277
  isSidechain: true, agentId, ...fields, timestamp: new Date().toISOString(), cwd,
182
278
  }) + "\n";
183
279
  } catch { /* best-effort file output; never write raw errors into the TUI */ return; }
184
- batch.push(line);
185
- if (!draining) {
186
- draining = true;
187
- void chainWrite(path, drain);
188
- }
280
+ enqueueOutput(path, line);
189
281
  };
190
282
 
191
283
  const capture = (msg: Message) => {
@@ -219,6 +311,10 @@ export function streamToOutputFile(
219
311
  };
220
312
  const flush = () => { for (const msg of session.messages) capture(msg); };
221
313
 
314
+ // Observation snapshots happen synchronously in the session listener, before
315
+ // the producer listener below is registered. AgentSession installs its own
316
+ // agent listener in the constructor, so this is also the public observer order
317
+ // Agent.processEvents awaits.
222
318
  const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
223
319
  if (closed) return;
224
320
  if (event.type === "message_end") capture(event.message);
@@ -248,10 +344,36 @@ export function streamToOutputFile(
248
344
  }
249
345
  });
250
346
 
347
+ // Attach after the observation subscription so capture (snapshot) precedes
348
+ // pressure. The producer hook is optional so legacy structural session
349
+ // doubles keep working; only the real SDK session supplies `session.agent`.
350
+ const producer = session.agent;
351
+ let finalizedSinceYield = 0;
352
+ const unsubscribeProducer = producer && typeof producer.subscribe === "function"
353
+ ? producer.subscribe(async (event) => {
354
+ if (closed) return;
355
+ if (event.type === "message_end") {
356
+ if (pendingOutputBytes(path) >= OUTPUT_HIGH_WATER_BYTES) {
357
+ await waitForOutput(path, OUTPUT_HIGH_WATER_BYTES);
358
+ finalizedSinceYield = 0;
359
+ } else if (++finalizedSinceYield >= OUTPUT_BATCH_RECORDS) {
360
+ // Awaiting already-resolved promises is not an event-loop yield.
361
+ // Small records also need periodic macrotask progress below HWM.
362
+ finalizedSinceYield = 0;
363
+ await yieldToEventLoop();
364
+ }
365
+ } else if (event.type === "turn_end" || event.type === "agent_end") {
366
+ await drainOutputFile(path);
367
+ finalizedSinceYield = 0;
368
+ }
369
+ })
370
+ : undefined;
371
+
251
372
  return () => {
252
373
  if (closed) return drainOutputFile(path);
253
374
  closed = true;
254
375
  unsubscribe();
376
+ unsubscribeProducer?.();
255
377
  flush();
256
378
  return drainOutputFile(path);
257
379
  };
package/src/prompts.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * prompts.ts — System prompt builder for agents.
3
3
  */
4
4
 
5
- import type { AgentConfig, EnvInfo } from "./types.js";
5
+ import type { AgentConfig, EnvInfo } from "./types.ts";
6
6
 
7
7
  /** Extra sections to inject into the system prompt (memory, skills, etc.). */
8
8
  export interface PromptExtras {
package/src/recovery.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /** Child-local recovery: the producer owns retries whenever installed/observed. */
2
2
  import type { AssistantMessage } from "@earendil-works/pi-ai";
3
3
  import type { AgentSession, EventBus, ExtensionError } from "@earendil-works/pi-coding-agent";
4
- import { logSubagentIssue } from "./error-log.js";
5
- import { isTransientProviderFailure, STANDALONE_CONTINUATION, type StandalonePolicy } from "./standalone-fallback.js";
4
+ import { logSubagentIssue } from "./error-log.ts";
5
+ import { isTransientProviderFailure, STANDALONE_CONTINUATION, type StandalonePolicy } from "./standalone-fallback.ts";
6
6
 
7
7
  export const RECOVERY_CHANNEL = "pi-fallback-chains:recovery";
8
8