@timmyjl12/pi-subagents 0.20.0 → 0.21.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 (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 +3612 -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 +4130 -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
@@ -20,6 +20,8 @@ import { extractMeta } from "./meta.js";
20
20
  import { WORKER_SOURCE } from "./worker-source.js";
21
21
  /** Matches the `script` field's `maxLength` in the tool schema. */
22
22
  export const MAX_SCRIPT_LENGTH = 524_288;
23
+ /** Economical workflow role; explicit run and per-call roles take precedence. */
24
+ export const DEFAULT_WORKFLOW_AGENT_TYPE = "task";
23
25
  /** Agents one run may schedule, in total. */
24
26
  export const WORKFLOW_AGENT_CAP = 1000;
25
27
  /** Items one `parallel()` or `pipeline()` call may take. */
@@ -243,6 +245,9 @@ export async function runWorkflow(options) {
243
245
  const { script, host } = options;
244
246
  assertBoundarySafe(options.args, "args");
245
247
  const { meta, body } = validateScript(script);
248
+ const defaultAgentType = (options.defaultAgentType ?? DEFAULT_WORKFLOW_AGENT_TYPE).trim();
249
+ if (defaultAgentType === "")
250
+ throw new WorkflowRuntimeError("Workflow defaultAgentType must be a non-empty agent name.");
246
251
  const agentCap = options.agentCap ?? WORKFLOW_AGENT_CAP;
247
252
  const itemCap = options.itemCap ?? WORKFLOW_ITEM_CAP;
248
253
  const semaphore = new Semaphore(options.concurrency ?? workflowConcurrency());
@@ -265,7 +270,62 @@ export async function runWorkflow(options) {
265
270
  let settled = false;
266
271
  /* --- resume state ---------------------------------------------------- */
267
272
  const journalEntries = options.journal?.entries ?? [];
268
- const recordJournal = options.journal?.append;
273
+ const appendJournalEntry = options.journal?.append;
274
+ /**
275
+ * Whether this run still accepts journal records.
276
+ *
277
+ * Closed synchronously by `finish` before any abort or termination work, so a
278
+ * call that settles during teardown cannot append to a journal the run is
279
+ * already reporting as finished.
280
+ */
281
+ let journalAccepting = true;
282
+ /** The accepted records, in settlement order. Never rejects. */
283
+ let journalWrites = Promise.resolve();
284
+ /**
285
+ * Accept one record into the run's single ordered write chain.
286
+ *
287
+ * Deliberately synchronous: the agent path answers the script immediately and
288
+ * `finish` only has to await writes that were accepted before it closed the
289
+ * gate. `appendJournalEntry` may be sync or promise-returning; either way its
290
+ * failure is swallowed here so later records still get written and a
291
+ * best-effort journal can never fail the run.
292
+ */
293
+ const recordJournal = (entry) => {
294
+ if (!journalAccepting || appendJournalEntry === undefined)
295
+ return;
296
+ journalWrites = journalWrites.then(async () => {
297
+ try {
298
+ await appendJournalEntry(entry);
299
+ }
300
+ catch {
301
+ // A journal that cannot be written costs a future resume, nothing more.
302
+ // Staying on this chain is what keeps the later records alive.
303
+ }
304
+ });
305
+ };
306
+ /**
307
+ * Wait for every record this run has accepted so far.
308
+ *
309
+ * The tail is re-read after each wait: a call that settles while this is
310
+ * suspended appends a new link, and resolving on the tail observed first
311
+ * would hand back exactly the half-written journal this exists to prevent.
312
+ * The chain swallows its own write failures as it goes — see `recordJournal`
313
+ * — so waiting on it never rejects and a failed record never strands the
314
+ * ones behind it. Called after the run settles it resolves immediately: the
315
+ * chain is closed, settled and stable, so a shutdown that arrives late has
316
+ * nothing special to do.
317
+ */
318
+ const drainJournal = async () => {
319
+ let tail = journalWrites;
320
+ await tail;
321
+ while (tail !== journalWrites) {
322
+ tail = journalWrites;
323
+ await tail;
324
+ }
325
+ };
326
+ // Registered before the worker exists, because the worker is what settles
327
+ // calls: a handle delivered any later could miss a record already accepted.
328
+ options.onJournalDrain?.(drainJournal);
269
329
  /**
270
330
  * Whether the replayable prefix is still intact.
271
331
  *
@@ -343,11 +403,12 @@ export async function runWorkflow(options) {
343
403
  },
344
404
  });
345
405
  /** The journal entry to reuse at `index`, or undefined to run it live. */
346
- function replayAt(index, key) {
406
+ function replayAt(index, key, input) {
347
407
  if (!prefixIntact)
348
408
  return undefined;
349
409
  const entry = journalEntries[index];
350
- if (entry === undefined || entry.index !== index || entry.key !== key || !entry.ok) {
410
+ if (entry === undefined || entry.index !== index || !entry.ok ||
411
+ (entry.key !== key && entry.key !== journalKey(input, "legacy"))) {
351
412
  prefixIntact = false;
352
413
  return undefined;
353
414
  }
@@ -384,6 +445,10 @@ export async function runWorkflow(options) {
384
445
  if (settled)
385
446
  return;
386
447
  settled = true;
448
+ // Closed before anything else can run: every record accepted so far is
449
+ // captured, and none accepted afterwards can reach the journal.
450
+ journalAccepting = false;
451
+ const acceptedJournalWrites = journalWrites;
387
452
  options.signal?.removeEventListener("abort", onAbort);
388
453
  // Symmetric with `semaphore.drain()` below: everything parked is woken so
389
454
  // it observes the settle and unwinds. Nothing depends on it — the run's
@@ -394,10 +459,12 @@ export async function runWorkflow(options) {
394
459
  host.abortAgent(agentId);
395
460
  inflight.clear();
396
461
  semaphore.drain();
397
- // Resolve only once the thread is actually down, so a caller that awaits
398
- // runWorkflow() is guaranteed not to be leaking one.
462
+ // Resolve only once the thread is actually down AND the records this run
463
+ // accepted are flushed. The chain contains only append callbacks, never a
464
+ // child/provider promise, so a hung agent cannot delay the result while
465
+ // an immediate resume still cannot miss a write.
399
466
  const settle = () => resolve({ ...result, meta, progress, agentCount, replayedCount });
400
- void worker.terminate().then(settle, settle);
467
+ void Promise.allSettled([acceptedJournalWrites, worker.terminate()]).then(settle);
401
468
  };
402
469
  function onAbort() {
403
470
  aborted = true;
@@ -473,7 +540,8 @@ export async function runWorkflow(options) {
473
540
  // reads the same as the row it continues.
474
541
  const agentId = resumed?.agentId ?? `wf-agent-${index}`;
475
542
  const label = payload.label ?? resumed?.label ?? derivedLabel(payload.prompt);
476
- const agentType = resumed?.agentType ?? payload.agentType ?? "general-purpose";
543
+ const agentType = resumed?.agentType ?? payload.agentType ?? defaultAgentType;
544
+ const agentTypeExplicit = payload.agentType !== undefined || options.defaultAgentTypeExplicit === true;
477
545
  const model = resumed !== undefined ? resumed.model : payload.model;
478
546
  const isolation = resumed !== undefined ? resumed.isolation : payload.isolation;
479
547
  openLaunches.set(callId, label);
@@ -500,9 +568,12 @@ export async function runWorkflow(options) {
500
568
  // so the spread is narrowed rather than passed through.
501
569
  const keyInput = {
502
570
  ...payload,
571
+ agentType,
572
+ agentTypeExplicit,
503
573
  schema: payload.schema !== undefined ? JSON.stringify(payload.schema) : undefined,
504
574
  };
505
- let replayed = replayAt(index, journalKey(keyInput));
575
+ const key = journalKey(keyInput);
576
+ let replayed = replayAt(index, key, keyInput);
506
577
  // A replayed answer still has to satisfy the schema. The key covers a
507
578
  // schema that *changed*, but not a journal that was hand-edited, and not
508
579
  // the empty text a torn entry leaves behind — either would hand the
@@ -537,15 +608,14 @@ export async function runWorkflow(options) {
537
608
  // Re-recorded so this run's journal is complete on its own terms: a
538
609
  // resume of a resume must not have to walk back through a chain of
539
610
  // earlier files to find the prefix.
540
- recordJournal?.({ index, key: replayed.key, ok: true, text: replayedText });
611
+ recordJournal({ index, key: replayed.key, ok: true, text: replayedText });
541
612
  respond(callId, true, replayedText);
542
613
  return;
543
614
  }
544
- const key = journalKey(keyInput);
545
615
  const resumeMark = payload.resume !== undefined ? { resumed: true } : {};
546
616
  /** A skip the user asked for, before the child ever started. */
547
617
  const settleSkipped = (extra) => {
548
- recordJournal?.({ index, key, ok: false, ...resumeMark });
618
+ recordJournal({ index, key, ok: false, ...resumeMark });
549
619
  emit([{ ...base, queuedAt, ...extra, state: "error", skipped: true, error: "Skipped by user." }]);
550
620
  // `null`, exactly as a terminal failure gives — a skipped agent is one
551
621
  // the script's `.filter(Boolean)` was already written to survive.
@@ -636,6 +706,7 @@ export async function runWorkflow(options) {
636
706
  prompt: payload.prompt,
637
707
  label,
638
708
  agentType,
709
+ ...(agentTypeExplicit ? { agentTypeExplicit: true } : {}),
639
710
  ...(model !== undefined ? { model } : {}),
640
711
  ...(payload.effort !== undefined ? { effort: payload.effort } : {}),
641
712
  ...(compiledSchema !== undefined ? { schema: compiledSchema } : {}),
@@ -710,14 +781,14 @@ export async function runWorkflow(options) {
710
781
  if (result.ok) {
711
782
  const text = result.text ?? "";
712
783
  emit([{ ...common, state: "done", resultPreview: preview(text) }]);
713
- recordJournal?.({ index, key, ok: true, text, ...resumeMark });
784
+ recordJournal({ index, key, ok: true, text, ...resumeMark });
714
785
  respond(callId, true, text);
715
786
  return;
716
787
  }
717
788
  // Recorded as a failure rather than left out: a gap would be read as an
718
789
  // unchanged prefix on the next resume, silently skipping the retry this
719
790
  // whole mechanism exists to make cheap.
720
- recordJournal?.({ index, key, ok: false, ...resumeMark });
791
+ recordJournal({ index, key, ok: false, ...resumeMark });
721
792
  // A dead agent is a null in the script, not a thrown error: Claude Code
722
793
  // scripts .filter(Boolean) rather than try/catch around every call.
723
794
  emit([
@@ -732,7 +803,12 @@ export async function runWorkflow(options) {
732
803
  ...(result.skipped ? { skipped: true } : {}),
733
804
  },
734
805
  ]);
735
- respond(callId, true, null);
806
+ if (result.fatal) {
807
+ respond(callId, false, undefined, result.error ?? "Agent configuration failed.", true);
808
+ }
809
+ else {
810
+ respond(callId, true, null);
811
+ }
736
812
  return;
737
813
  }
738
814
  }
@@ -813,9 +889,22 @@ export async function runWorkflow(options) {
813
889
  });
814
890
  break;
815
891
  }
816
- case "error":
817
- finish({ status: "failed", error: message.message });
892
+ case "error": {
893
+ const frames = message.stack?.split("\n")
894
+ .filter(line => /(?:workflow\.js|workflow:[^\r\n]+?\.js):\d+/.test(line))
895
+ .slice(0, 3) ?? [];
896
+ let error = [message.message, ...frames].join("\n");
897
+ if (!frames[0]?.includes("workflow:") && /Cannot read properties|is not (?:a function|iterable)|expects an array/.test(message.message)) {
898
+ if (options.args === undefined) {
899
+ error += "\nNo workflow args were supplied. If this script expects inputs, pass an actual JSON value, e.g. args: { probes: [...] }. Re-pass args when re-running a scriptPath.";
900
+ }
901
+ else if (typeof options.args === "string") {
902
+ error += "\nWorkflow args is a string. If this script expects an object or array, pass the actual JSON value, not a JSON-encoded string, e.g. args: { probes: [...] }. Strings are not automatically parsed.";
903
+ }
904
+ }
905
+ finish({ status: "failed", error });
818
906
  break;
907
+ }
819
908
  }
820
909
  });
821
910
  worker.on("error", error => {
@@ -13,10 +13,10 @@
13
13
  * incremented as entries arrive — a re-emitted agent entry replaces its
14
14
  * predecessor, and adding its tokens on top would double-count them.
15
15
  */
16
- import type { WorkflowJournalEntry } from "./journal.js";
17
- import type { WorkflowMeta } from "./meta.js";
18
- import { type WorkflowEntry, type WorkflowRunStatus } from "./progress.js";
19
- import type { WorkflowControl, WorkflowRunResult } from "./runtime.js";
16
+ import type { WorkflowJournalEntry } from "./journal.ts";
17
+ import type { WorkflowMeta } from "./meta.ts";
18
+ import { type WorkflowEntry, type WorkflowRunStatus } from "./progress.ts";
19
+ import { type WorkflowControl, type WorkflowRunResult } from "./runtime.ts";
20
20
  /** `wf_` + hex, matching Claude Code's `^wf_[a-z0-9-]{6,}$` run ids. */
21
21
  export declare function workflowRunId(): string;
22
22
  export interface WorkflowTask {
@@ -28,6 +28,10 @@ export interface WorkflowTask {
28
28
  /** Where the script can be edited and re-run from. */
29
29
  scriptPath?: string;
30
30
  args?: unknown;
31
+ /** Frozen for the lifetime of this run and reused on resume. */
32
+ defaultAgentType: string;
33
+ /** Whether the run's `agentType` named that default — see {@link WorkflowTask.defaultAgentType}. */
34
+ defaultAgentTypeExplicit: boolean;
31
35
  meta?: WorkflowMeta;
32
36
  workflowName?: string;
33
37
  /** The `tool_use_id` of the call that started this, when one did. */
@@ -80,6 +84,8 @@ export declare function createWorkflowTask(init: {
80
84
  script: string;
81
85
  scriptPath?: string;
82
86
  args?: unknown;
87
+ defaultAgentType?: string;
88
+ defaultAgentTypeExplicit?: boolean;
83
89
  meta?: WorkflowMeta;
84
90
  toolCallId?: string;
85
91
  startTime?: number;
@@ -128,6 +134,9 @@ export declare function resolveResumeTarget(runId: string | undefined, tasks: Re
128
134
  runId: string;
129
135
  journalPath: string;
130
136
  scriptPath: string;
137
+ args: unknown;
138
+ defaultAgentType: string;
139
+ defaultAgentTypeExplicit: boolean;
131
140
  } | {
132
141
  ok: false;
133
142
  message: string;
@@ -16,6 +16,7 @@
16
16
  import { randomUUID } from "node:crypto";
17
17
  import { escapeXml } from "../xml.js";
18
18
  import { collapse, elapsedMs, stats } from "./progress.js";
19
+ import { DEFAULT_WORKFLOW_AGENT_TYPE } from "./runtime.js";
19
20
  /** `wf_` + hex, matching Claude Code's `^wf_[a-z0-9-]{6,}$` run ids. */
20
21
  export function workflowRunId() {
21
22
  return `wf_${randomUUID().replace(/-/g, "").slice(0, 12)}`;
@@ -28,6 +29,8 @@ export function createWorkflowTask(init) {
28
29
  script: init.script,
29
30
  scriptPath: init.scriptPath,
30
31
  args: init.args,
32
+ defaultAgentType: init.defaultAgentType ?? DEFAULT_WORKFLOW_AGENT_TYPE,
33
+ defaultAgentTypeExplicit: init.defaultAgentTypeExplicit ?? false,
31
34
  meta: init.meta,
32
35
  workflowName: init.meta?.name,
33
36
  toolCallId: init.toolCallId,
@@ -184,6 +187,9 @@ export function resolveResumeTarget(runId, tasks) {
184
187
  // The persisted copy, which is what `scriptPath` holds when the call had
185
188
  // no file of its own.
186
189
  scriptPath: prior.scriptPath ?? "",
190
+ args: prior.args,
191
+ defaultAgentType: prior.defaultAgentType,
192
+ defaultAgentTypeExplicit: prior.defaultAgentTypeExplicit,
187
193
  };
188
194
  }
189
195
  /** `<task-notification>`, in the same shape a finished background agent sends. */
@@ -200,7 +206,7 @@ export function formatWorkflowNotification(task, now = Date.now()) {
200
206
  task.scriptPath ? `<script>${escapeXml(task.scriptPath)}</script>` : null,
201
207
  `<status>${escapeXml(status)}</status>`,
202
208
  `<summary>Workflow "${escapeXml(task.workflowName ?? task.id)}" ${task.status} — ${totals.done}/${totals.total} agents${task.replayedCount > 0 ? `, ${task.replayedCount} replayed from ${escapeXml(task.resumedFrom ?? "an earlier run")}` : ""}</summary>`,
203
- `<result>${escapeXml(result.length > 4000 ? `${result.slice(0, 4000)}\n...(truncated)` : result)}</result>`,
209
+ `<result>${escapeXml(result)}</result>`,
204
210
  `<usage><total_tokens>${task.totalTokens}</total_tokens><tool_uses>${task.totalToolCalls}</tool_uses><duration_ms>${elapsedMs(task, now)}</duration_ms></usage>`,
205
211
  `</task-notification>`,
206
212
  ].filter(Boolean).join("\n");
@@ -18,7 +18,12 @@
18
18
  * pi's `AgentSession`, so a child can decline and the call returns null.
19
19
  * - `budget.total` is always null; pi has no token-target directive.
20
20
  * - `parallel` propagates a fatal run error instead of folding it to null.
21
- * - `effort` inherits the agent definition's level, then the parent's.
21
+ * - role `model`/`thinking` pins outrank the script's `model`/`effort`; an
22
+ * task/explore need model configuration even when selected explicitly.
23
+ * Other unpinned roles may use the parent when selected explicitly;
24
+ * `general-purpose` is the selectable parent twin.
25
+ * - the default workflow role is the user-defined `task`, not a built-in; an
26
+ * unresolvable default is refused rather than replaced with general-purpose.
22
27
  * - `isolation` removes the worktree on settle, changes kept on a branch.
23
28
  * Additions with no upstream counterpart: `gate`, `resume`, `effort: "minimal"`,
24
29
  * the saved-workflow directories, and the reject-unknown-options guarantee.
@@ -35,4 +40,4 @@
35
40
  * `agent()` option set, the `resume` exclusions, the effort levels, the caps,
36
41
  * and that every example here uses options the runtime actually accepts.
37
42
  */
38
- export declare const fullWorkflowToolDescription = "Execute a workflow script that orchestrates multiple subagents deterministically. Workflows run in the background \u2014 this tool returns immediately with a task ID, and you are notified when the workflow completes. Use /agents \u2192 Workflows to watch live progress.\n\nA workflow structures work across many agents \u2014 to be comprehensive (decompose and cover in parallel), to be confident (independent perspectives and adversarial checks before committing), or to take on scale one context can't hold (migrations, audits, broad sweeps). The script is where you encode that structure: what fans out, what verifies, what synthesizes.\n\nONLY call this tool when the user has explicitly opted into multi-agent orchestration. Workflows can spawn dozens of agents and consume a large amount of tokens; the user must request that scale, not have it inferred. Explicit opt-in means one of:\n- The user directly asked you to run a workflow or use multi-agent orchestration in their own words (\"use a workflow\", \"run a workflow\", \"fan out agents\", \"orchestrate this with subagents\"). The ask must be in the user's words \u2014 a task that would merely benefit from a workflow does not count.\n- The user invoked a skill or slash command whose instructions tell you to call SubagentWorkflow.\n- The user asked you to run a specific named or saved workflow.\n\nFor any other task \u2014 even one that would clearly benefit from parallelism \u2014 do NOT call this tool. Use the Agent tool for individual subagents, or briefly describe what a multi-agent workflow could do and how much it would roughly cost, and ask the user whether to run it. Mention they can ask for one with \"use a workflow\" in a future message to skip the ask.\n\nWhen you do call it, the right move is often **hybrid**: scout inline first (list the files, find the channels, scope the diff) to discover the work-list, then call SubagentWorkflow to pipeline over it. You don't need to know the shape before the *task* \u2014 only before the *orchestration step*.\n\nCommon single-phase workflows you can chain across turns:\n- **Understand** \u2014 parallel readers over relevant subsystems \u2192 structured map\n- **Design** \u2014 judge panel of N independent approaches \u2192 scored synthesis\n- **Review** \u2014 dimensions \u2192 find \u2192 adversarially verify (example below)\n- **Research** \u2014 multi-modal sweep \u2192 deep-read \u2192 synthesize\n- **Migrate** \u2014 discover sites \u2192 transform each (worktree isolation) \u2192 verify\n\nFor larger work, run several in sequence \u2014 read each result before deciding the next phase. You stay in the loop; each workflow is one well-scoped fan-out.\n\nPass the script inline via `script` \u2014 do not Write it to a file first. Every invocation automatically persists its script to a file under the session directory and returns the path in the tool result. To iterate on a workflow, edit that file with Write/Edit and re-invoke SubagentWorkflow with `{scriptPath: \"<path>\"}` instead of resending the full script. A script you will run more than once belongs in `.pi/workflows/<name>.js` (or `.agents/workflows/`, or `<agent dir>/workflows/` for one that follows the user everywhere); call it with `name: \"<name>\"` instead of re-sending the source.\n\nEvery script must begin with `export const meta = {...}`:\n export const meta = {\n name: 'find-flaky-tests',\n description: 'Find flaky tests and propose fixes', // one-line, shown in permission dialog\n phases: [ // one entry per phase() call\n { title: 'Scan', detail: 'grep test logs for retries' },\n { title: 'Fix', detail: 'one agent per flaky test' },\n ],\n }\n // script body starts here \u2014 use agent()/parallel()/pipeline()/phase()/log()\n phase('Scan')\n const flaky = await agent('grep CI logs for retry markers', {schema: FLAKY_SCHEMA})\n ...\n\nThe `meta` object must be a PURE LITERAL \u2014 no variables, function calls, spreads, or template interpolation. Required fields: `name`, `description`. Optional: `whenToUse` (shown in the workflow list), `phases`. Use the SAME phase titles in meta.phases as in phase() calls \u2014 titles are matched exactly; a phase() call with no matching meta entry just gets its own progress group. Add `model` to a phase entry when that phase uses a specific model override.\n\nScript body hooks:\n- agent(prompt: string, opts?: {label?: string, phase?: string, schema?: object, model?: string, effort?: string, isolation?: 'worktree', agentType?: string, gate?: string, resume?: string}): Promise<any> \u2014 spawn a subagent. Without schema, returns its final text as a string. With schema (a JSON Schema), the subagent is given a StructuredOutput tool built from it and agent() returns the validated object \u2014 no parsing needed. A payload that does not match is rejected back to the child, which corrects it; a child that never answers through the tool gets one more prompt and then fails, so the call returns null \u2014 filter after every schema stage. Returns null if the user skips the agent mid-run or the subagent dies on a terminal API error after retries (filter with .filter(Boolean)). opts.label overrides the display label. opts.phase explicitly assigns this agent to a progress group (use this inside pipeline()/parallel() stages to avoid races on the global phase() state \u2014 same phase string \u2192 same group box). opts.model overrides the model for this agent call. Default to omitting it \u2014 the agent inherits the main-loop model (the resolved session model), which is almost always correct. Only set it when you're highly confident a different tier fits the task; when unsure, omit. opts.effort overrides the reasoning effort for this agent call ('minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max') \u2014 omit to inherit the agent definition's own level, then the parent's; use 'low' for cheap mechanical stages and higher tiers only for the hardest verify/judge stages. opts.isolation: 'worktree' runs the agent in a fresh git worktree \u2014 EXPENSIVE (setup time + disk per agent), use ONLY when agents mutate files in parallel and would otherwise conflict; the worktree is removed when the agent settles, its changes preserved on a branch. opts.gate: '<command>' runs a shell command after the agent finishes and requires it to pass \u2014 a non-zero exit marks the agent failed and the command's output becomes the error; prefer gate: 'npm test' over asking another agent whether the code looks right. opts.resume: '<label>' continues the child that ran under that label instead of starting fresh, so an iterative loop keeps its context \u2014 it cannot be combined with agentType, model, effort, isolation, gate or schema. opts.agentType uses a custom subagent type instead of the default workflow subagent \u2014 resolved from the same registry as the Agent tool; composes with schema. Available types:\n{{typeList}}\n- pipeline(items, stage1, stage2, ...): Promise<any[]> \u2014 run each item through all stages independently, NO barrier between stages. Item A can be in stage 3 while item B is still in stage 1. This is the DEFAULT for multi-stage work. Wall-clock = slowest single-item chain, not sum-of-slowest-per-stage. Every stage callback receives (prevResult, originalItem, index) \u2014 use originalItem/index in later stages to label work without threading context through stage 1's return value. A stage that throws drops that item to `null` and skips its remaining stages.\n- parallel(thunks: Array<() => Promise<any>>): Promise<any[]> \u2014 run tasks concurrently. This is a BARRIER: awaits all thunks before returning. A thunk that throws (or whose agent errors) resolves to `null` in the result array, so `.filter(Boolean)` before using the results; only a fatal run error \u2014 a cap breach, or a nested workflow that could not load \u2014 propagates instead of being folded into a null. Use ONLY when you genuinely need all results together.\n- log(message: string): void \u2014 emit a progress message to the user (shown as a narrator line above the progress tree)\n- phase(title: string): void \u2014 start a new phase; subsequent agent() calls are grouped under this title in the progress display\n- args: any \u2014 the value passed as SubagentWorkflow's `args` input, verbatim (undefined if not provided). Pass arrays/objects as actual JSON values in the tool call, NOT as a JSON-encoded string \u2014 `args: [\"a.ts\", \"b.ts\"]`, not `args: \"[\\\"a.ts\\\", ...]\"` (a stringified list reaches the script as one string, so `args.filter`/`args.map` throw). Use this to parameterize named workflows \u2014 e.g. pass a research question, target path, or config object directly instead of via a side-channel file.\n- budget: {total: number|null, spent(): number, remaining(): number} \u2014 `budget.total` is always null here: it comes from a token-target directive pi does not have, so guards like `while (budget.total && budget.remaining() > 50_000) { ... }` correctly do not fire rather than throwing on a missing global. `budget.spent()` returns output tokens spent by this run's agents. `budget.remaining()` returns `Infinity` with no target.\n- workflow(nameOrRef: string | {scriptPath: string}, args?: any): Promise<any> \u2014 run another workflow inline as a sub-step and return whatever it returns. Pass a name to invoke a saved workflow (same registry as {name: \"...\"}), or {scriptPath} to run a script file you Wrote earlier. The child shares this run's concurrency cap, agent counter, abort signal, and token budget \u2014 its agents appear under a \"\u25B8 name\" group in /agents \u2192 Workflows and its tokens count toward budget.spent(). The args param becomes the child's `args` global. Nesting is one level only: workflow() inside a child throws. Throws on unknown name / unreadable scriptPath / child syntax error; catch to handle gracefully.\n\nAny agent() option not listed above is rejected by name at the call.\n\nSubagents are told their final text IS the return value (not a human-facing message), so they return raw data. For structured output, use the schema option \u2014 validation happens at the tool-call layer so the model retries on mismatch.\n\nScripts are plain JavaScript, NOT TypeScript \u2014 type annotations (`: string[]`), interfaces, and generics fail to parse. The script body runs in an async context \u2014 use await directly. Standard JS built-ins (JSON, Math, Array, etc.) are available \u2014 EXCEPT `Date.now()`/`Math.random()`/argless `new Date()`, which throw (they would break resume); pass timestamps in via `args`, stamp results after the workflow returns, and for randomness vary the agent prompt/label by index. `eval` and `Function(...)` throw. No filesystem or Node.js API access.\n\nDEFAULT TO pipeline(). Only reach for a barrier (parallel between stages) when you genuinely need ALL prior-stage results together.\n\nA barrier is correct ONLY when stage N needs cross-item context from all of stage N-1:\n- Dedup/merge across the full result set before expensive downstream work\n- Early-exit if the total count is zero (\"0 bugs found \u2192 skip verification entirely\")\n- Stage N's prompt references \"the other findings\" for comparison\n\nA barrier is NOT justified by:\n- \"I need to flatten/map/filter first\" \u2014 do it inside a pipeline stage: pipeline(items, stageA, r => transform([r]).flat(), stageB)\n- \"The stages are conceptually separate\" \u2014 that's what pipeline() models. Separate stages \u2260 synchronized stages.\n- \"It's cleaner code\" \u2014 barrier latency is real. If 5 finders run and the slowest takes 3\u00D7 the fastest, a barrier wastes 2/3 of the fast finders' idle time.\n\nSmell test: if you wrote\n const a = await parallel(...)\n const b = transform(a) // flatten, map, filter \u2014 no cross-item dependency\n const c = await parallel(b.map(...))\nthat middle transform doesn't need the barrier. Rewrite as a pipeline with the transform inside a stage. When in doubt: pipeline.\n\nConcurrent agent() calls are capped at min(16, available CPUs - 2) per workflow \u2014 excess calls queue and run as slots free up. You can still pass 100 items to parallel()/pipeline() and they all complete; only ~10 run at any moment. Total agent count across a workflow's lifetime is capped at 1000 \u2014 a runaway-loop backstop set far above any real workflow. A single parallel()/pipeline() call accepts at most 4096 items; passing more is an explicit error, not a silent truncation.\n\nThe canonical multi-stage pattern \u2014 pipeline by default, each dimension verifies as soon as its review completes:\n export const meta = {\n name: 'review-changes',\n description: 'Review changed files across dimensions, verify each finding',\n phases: [{ title: 'Review' }, { title: 'Verify' }],\n }\n const DIMENSIONS = [{key: 'bugs', prompt: '...'}, {key: 'perf', prompt: '...'}]\n const results = await pipeline(\n DIMENSIONS,\n d => agent(d.prompt, {label: `review:${d.key}`, phase: 'Review', schema: FINDINGS_SCHEMA}),\n review => parallel(review.findings.map(f => () =>\n agent(`Adversarially verify: ${f.title}`, {label: `verify:${f.file}`, phase: 'Verify', schema: VERDICT_SCHEMA})\n .then(v => ({...f, verdict: v}))\n ))\n )\n const confirmed = results.flat().filter(Boolean).filter(f => f.verdict?.isReal)\n return { confirmed }\n // Dimension 'bugs' findings verify while dimension 'perf' is still reviewing. No wasted wall-clock.\n\nWhen a barrier IS correct \u2014 dedup across all findings before expensive verification:\n const all = await parallel(DIMENSIONS.map(d => () => agent(d.prompt, {schema: FINDINGS_SCHEMA})))\n const deduped = dedupeByFileAndLine(all.filter(Boolean).flatMap(r => r.findings)) // <-- genuinely needs ALL at once\n const verified = await parallel(deduped.map(f => () => agent(verifyPrompt(f), {schema: VERDICT_SCHEMA})))\n\nLoop-until-count pattern \u2014 accumulate to a target:\n const bugs = []\n while (bugs.length < 10) {\n const result = await agent(\"Find bugs in this codebase.\", {schema: BUGS_SCHEMA})\n bugs.push(...result.bugs)\n log(`${bugs.length}/10 found`)\n }\n\nGate-and-retry pattern \u2014 verify by running, and keep the agent's context across attempts:\n let fixed = await agent('Find and fix the failing test.', {label: 'fix', gate: 'npm test'})\n if (fixed === null) { // a non-zero exit failed the agent\n // Resume keeps everything the child already learned. It cannot carry the\n // gate, so re-verification needs its own gated call, in the same tree.\n fixed = await agent('`npm test` is still failing. Fix the cause.', {label: 'fix', resume: 'fix'})\n const verified = await agent('Run `npm test` and report the result. Change nothing.',\n {label: 'verify', phase: 'Verify', gate: 'npm test', effort: 'low'})\n return { passed: verified !== null, summary: fixed }\n }\n return { passed: true, summary: fixed }\n // An LLM judging whether a fix works is a weaker signal than the test suite.\n\nComposing patterns \u2014 exhaustive review (find \u2192 dedup vs seen \u2192 diverse-lens panel \u2192 loop-until-dry):\n const seen = new Set(), confirmed = []\n let dry = 0\n while (dry < 2) { // loop-until-dry\n const found = (await parallel(FINDERS.map(f => () => // barrier: collect all finders this round\n agent(f.prompt, {phase: 'Find', schema: BUGS})))).filter(Boolean).flatMap(r => r.bugs)\n const fresh = found.filter(b => !seen.has(key(b))) // dedup vs ALL seen \u2014 plain code, not an agent\n if (!fresh.length) { dry++; continue }\n dry = 0; fresh.forEach(b => seen.add(key(b)))\n const judged = await parallel(fresh.map(b => () => // every fresh bug judged concurrently...\n parallel(['correctness','security','repro'].map(lens => () => // ...each by 3 distinct lenses\n agent(`Judge \"${b.desc}\" via the ${lens} lens \u2014 real?`, {phase: 'Verify', schema: VERDICT})))\n .then(vs => ({ b, real: vs.filter(Boolean).filter(v => v.real).length >= 2 }))))\n confirmed.push(...judged.filter(v => v.real).map(v => v.b))\n }\n return confirmed\n // dedup vs `seen`, NOT `confirmed` \u2014 else judge-rejected findings reappear every round and it never converges.\n\nQuality patterns \u2014 common shapes; pick by task and compose freely:\n- Adversarial verify: spawn N independent skeptics per finding, each prompted to REFUTE. Kill if \u2265majority refute. Prevents plausible-but-wrong findings from surviving.\n const votes = await parallel(Array.from({length: 3}, () => () =>\n agent(`Try to refute: ${claim}. Default to refuted=true if uncertain.`, {schema: VERDICT})))\n const survives = votes.filter(Boolean).filter(v => !v.refuted).length >= 2\n- Verify by running, not by asking: when a claim is testable, `gate` it rather than asking another model whether it holds.\n- Perspective-diverse verify: when a finding can fail in more than one way, give each verifier a distinct lens (correctness, security, perf, does-it-reproduce) instead of N identical refuters \u2014 diversity catches failure modes redundancy can't.\n- Judge panel: generate N independent attempts from different angles (e.g. MVP-first, risk-first, user-first), score with parallel judges, synthesize from the winner while grafting the best ideas from runners-up. Beats one-attempt-iterated when the solution space is wide.\n- Loop-until-dry: for unknown-size discovery (bugs, issues, edge cases), keep spawning finders until K consecutive rounds return nothing new. Simple counters (while count < N) miss the tail.\n- Multi-modal sweep: parallel agents each searching a different way (by-container, by-content, by-entity, by-time). Each is blind to what the others surface; useful when one search angle won't find everything.\n- Completeness critic: a final agent that asks \"what's missing \u2014 modality not run, claim unverified, source unread?\" What it finds becomes the next round of work.\n- No silent caps: if a workflow bounds coverage (top-N, no-retry, sampling), `log()` what was dropped \u2014 silent truncation reads as \"covered everything\" when it didn't.\n\nScale to what the user asked for. \"find any bugs\" \u2192 a few finders, single-vote verify. \"thoroughly audit this\" or \"be comprehensive\" \u2192 larger finder pool, 3\u20135 vote adversarial pass, synthesis stage. When unsure, lean toward thoroughness for research/review/audit requests and toward brevity for quick checks.\n\nThese patterns aren't exhaustive \u2014 compose novel harnesses when the task calls for it (tournament brackets, self-repair loops, staged escalation, whatever fits).\n\nUse this tool for multi-step orchestration where control flow should be deterministic (loops, conditionals, fan-out) rather than model-driven.\n\n## Resume\n\nThe tool result includes a runId. To resume after a pause, kill, or script edit, relaunch with SubagentWorkflow({scriptPath, resumeFromRunId}) \u2014 the longest unchanged prefix of agent() calls returns cached results instantly; the first edited/new call and everything after it runs live. Same script + same args \u2192 100% cache hit. It is a prefix and not a lookup: a later call that still matches is not reused once an earlier one has changed. A journaled failure ends the prefix, so resuming a run that died at agent 5 retries exactly agent 5. Same session only, and the run must have finished \u2014 stop it from /agents \u2192 Workflows first. Before diagnosing why a completed workflow returned an empty or unexpected result, Read the run's `<run id>.workflow.jsonl` beside its script \u2014 it records each agent's actual return value; do not assume cached results are non-empty. Date.now()/Math.random()/new Date() are unavailable in scripts (they would break this) \u2014 stamp results after the workflow returns, or pass timestamps via args.";
43
+ export declare const fullWorkflowToolDescription = "Execute a workflow script that orchestrates multiple subagents deterministically. Workflows run in the background \u2014 this tool returns immediately with a task ID, and you are notified when the workflow completes. Use /agents \u2192 Workflows to watch live progress.\n\nA workflow structures work across many agents \u2014 to be comprehensive (decompose and cover in parallel), to be confident (independent perspectives and adversarial checks before committing), or to take on scale one context can't hold (migrations, audits, broad sweeps). The script is where you encode that structure: what fans out, what verifies, what synthesizes.\n\nONLY call this tool when the user has explicitly opted into multi-agent orchestration. Workflows can spawn dozens of agents and consume a large amount of tokens; the user must request that scale, not have it inferred. Explicit opt-in means one of:\n- The user directly asked you to run a workflow or use multi-agent orchestration in their own words (\"use a workflow\", \"run a workflow\", \"fan out agents\", \"orchestrate this with subagents\"). The ask must be in the user's words \u2014 a task that would merely benefit from a workflow does not count.\n- The user invoked a skill or slash command whose instructions tell you to call SubagentWorkflow.\n- The user asked you to run a specific named or saved workflow.\n\nFor any other task \u2014 even one that would clearly benefit from parallelism \u2014 do NOT call this tool. Use the Agent tool for individual subagents, or briefly describe what a multi-agent workflow could do and how much it would roughly cost, and ask the user whether to run it. Mention they can ask for one with \"use a workflow\" in a future message to skip the ask.\n\nWhen you do call it, the right move is often **hybrid**: scout inline first (list the files, find the channels, scope the diff) to discover the work-list, then call SubagentWorkflow to pipeline over it. You don't need to know the shape before the *task* \u2014 only before the *orchestration step*.\n\nCommon single-phase workflows you can chain across turns:\n- **Understand** \u2014 parallel readers over relevant subsystems \u2192 structured map\n- **Design** \u2014 judge panel of N independent approaches \u2192 scored synthesis\n- **Review** \u2014 dimensions \u2192 find \u2192 adversarially verify (example below)\n- **Research** \u2014 multi-modal sweep \u2192 deep-read \u2192 synthesize\n- **Migrate** \u2014 discover sites \u2192 transform each (worktree isolation) \u2192 verify\n\nFor larger work, run several in sequence \u2014 read each result before deciding the next phase. You stay in the loop; each workflow is one well-scoped fan-out.\n\nPass the script inline via `script` \u2014 do not Write it to a file first. Every invocation automatically persists its script to a file under the session directory and returns the path in the tool result. To iterate on a workflow, edit that file with Write/Edit, wait for that edit tool call to complete, then re-invoke SubagentWorkflow with `{scriptPath: \"<path>\"}` in a later step. Never issue the edit and this call in the same parallel tool batch: the runtime cannot order unrelated file tools, and there is no hash or version check, so `scriptPath` can otherwise read the previous file or a partially written one. A script you will run more than once belongs in `.pi/workflows/<name>.js` (or `.agents/workflows/`, or `<agent dir>/workflows/` for one that follows the user everywhere); call it with `name: \"<name>\"` instead of re-sending the source.\n\nEvery script must begin with `export const meta = {...}`:\n export const meta = {\n name: 'find-flaky-tests',\n description: 'Find flaky tests and propose fixes', // one-line, shown in permission dialog\n phases: [ // one entry per phase() call\n { title: 'Scan', detail: 'grep test logs for retries' },\n { title: 'Fix', detail: 'one agent per flaky test' },\n ],\n }\n // script body starts here \u2014 use agent()/parallel()/pipeline()/phase()/log()\n phase('Scan')\n const flaky = await agent('grep CI logs for retry markers', {schema: FLAKY_SCHEMA})\n ...\n\nThe `meta` object must be a PURE LITERAL \u2014 no variables, function calls, spreads, or template interpolation. Required fields: `name`, `description`. Optional: `whenToUse` (shown in the workflow list), `phases`. Use the SAME phase titles in meta.phases as in phase() calls \u2014 titles are matched exactly; a phase() call with no matching meta entry just gets its own progress group. Add `model` to a phase entry when that phase uses a specific model override.\n\nScript body hooks:\n- agent(prompt: string, opts?: {label?: string, phase?: string, schema?: object, model?: string, effort?: string, isolation?: 'worktree', agentType?: string, gate?: string, resume?: string}): Promise<any> \u2014 spawn a subagent. Without schema, returns its final text as a string. With schema (a JSON Schema), the subagent is given a StructuredOutput tool built from it and agent() returns the validated object \u2014 no parsing needed. A payload that does not match is rejected back to the child, which corrects it; a child that never answers through the tool gets one more prompt and then fails, so the call returns null \u2014 filter after every schema stage. Returns null if the user skips the agent mid-run or the subagent dies on a terminal API error after retries (filter with .filter(Boolean)). opts.label overrides the display label. opts.phase explicitly assigns this agent to a progress group (use this inside pipeline()/parallel() stages to avoid races on the global phase() state \u2014 same phase string \u2192 same group box). opts.model supplies a model only for a role with no `model:` pin \u2014 a role pin always wins. task/explore require a model pin or explicit opts.model even when selected explicitly; they never implicitly inherit the parent. Other explicitly selected unpinned roles may use the parent, and general-purpose is the selectable main-model twin. Missing workflow defaults and task/explore requests never use the generic fallbackSubagent; explicit other role requests retain that policy. An unavailable pin fails the workflow \u2014 built-in pins included. Prefer an exact `provider/modelId`; pi's fuzzy shorthand (`\"haiku\"`, `\"sonnet\"`) is also accepted. Choose a different tier only when you are confident it fits; `/subagents off` is the one exception and forces the session's main model regardless. opts.effort requests the reasoning effort for this agent call ('minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max') \u2014 a role's `thinking:` pin always wins; omit to use that pin, or the run's normal thinking default when it has none. Use 'low' for cheap mechanical stages and higher tiers only for the hardest verify/judge stages. opts.isolation: 'worktree' runs the agent in a fresh git worktree \u2014 EXPENSIVE (setup time + disk per agent), use ONLY when agents mutate files in parallel and would otherwise conflict; the worktree is removed when the agent settles, its changes preserved on a branch. opts.gate: '<command>' runs a shell command after the agent finishes and requires it to pass \u2014 a non-zero exit marks the agent failed and the command's output becomes the error; prefer gate: 'npm test' over asking another agent whether the code looks right. opts.resume: '<label>' continues the child that ran under that label instead of starting fresh, so an iterative loop keeps its context \u2014 it cannot be combined with agentType, model, effort, isolation, gate or schema. opts.agentType selects this call's role and wins over the run default \u2014 resolved from the same registry as the Agent tool; composes with schema. Without it, agents use the run's agentType (the SubagentWorkflow call), else workflowDefaultAgentType (default \"task\"). \"task\" is user-defined, not a built-in: define it with a model pin, or point workflowDefaultAgentType at an available pinned role. If a default or task/explore role is missing/disabled, the spawn is refused rather than replaced with another role. A blank run agentType is rejected instead of inheriting a resumed role. Role choice comes from this value, not from the user's wording alone \u2014 when the user names a role (\"use explore for this workflow\"), pass it here. Use premium or explicit-only roles (for example a user-defined principal_engineer) only when the user asks for them, and `general-purpose` only when the user asks for the main model (it is the parent twin). Available types:\n{{typeList}}\n- pipeline(items, stage1, stage2, ...): Promise<any[]> \u2014 run each item through all stages independently, NO barrier between stages. Item A can be in stage 3 while item B is still in stage 1. This is the DEFAULT for multi-stage work. Wall-clock = slowest single-item chain, not sum-of-slowest-per-stage. Every stage callback receives (prevResult, originalItem, index) \u2014 use originalItem/index in later stages to label work without threading context through stage 1's return value. A stage that throws drops that item to `null` and skips its remaining stages.\n- parallel(thunks: Array<() => Promise<any>>): Promise<any[]> \u2014 run tasks concurrently. This is a BARRIER: awaits all thunks before returning. A thunk that throws (or whose agent errors) resolves to `null` in the result array, so `.filter(Boolean)` before using the results; only a fatal run error \u2014 a cap breach, or a nested workflow that could not load \u2014 propagates instead of being folded into a null. Use ONLY when you genuinely need all results together.\n- log(message: string): void \u2014 emit a progress message to the user (shown as a narrator line above the progress tree)\n- phase(title: string): void \u2014 start a new phase; subsequent agent() calls are grouped under this title in the progress display\n- args: any \u2014 the value passed as SubagentWorkflow's `args` input, verbatim (undefined if not provided). Any JSON value is valid \u2014 object, array, string, number, boolean, null \u2014 and it is not coerced, parsed or stringified. Pass arrays/objects as actual JSON values in the tool call, NOT as a JSON-encoded string \u2014 `args: [\"a.ts\", \"b.ts\"]` or `args: {probes: [...]}`, not `args: \"[\\\"a.ts\\\", ...]\"` (a stringified value reaches the script as one string, so `args.filter`/`args.map` and property access throw; the failure reports the script line that used it). Use this to parameterize named workflows \u2014 e.g. pass a research question, target path, or config object directly instead of via a side-channel file.\n- budget: {total: number|null, spent(): number, remaining(): number} \u2014 `budget.total` is always null here: it comes from a token-target directive pi does not have, so guards like `while (budget.total && budget.remaining() > 50_000) { ... }` correctly do not fire rather than throwing on a missing global. `budget.spent()` returns output tokens spent by this run's agents. `budget.remaining()` returns `Infinity` with no target.\n- workflow(nameOrRef: string | {scriptPath: string}, args?: any): Promise<any> \u2014 run another workflow inline as a sub-step and return whatever it returns. Pass a name to invoke a saved workflow (same registry as {name: \"...\"}), or {scriptPath} to run a script file you Wrote earlier. The child shares this run's concurrency cap, agent counter, abort signal, and token budget \u2014 its agents appear under a \"\u25B8 name\" group in /agents \u2192 Workflows and its tokens count toward budget.spent(). The args param becomes the child's `args` global. Nesting is one level only: workflow() inside a child throws. Throws on unknown name / unreadable scriptPath / child syntax error; catch to handle gracefully.\n\nAny agent() option not listed above is rejected by name at the call.\n\nSubagents are told their final text IS the return value (not a human-facing message), so they return raw data. For structured output, use the schema option \u2014 validation happens at the tool-call layer so the model retries on mismatch.\n\nScripts are plain JavaScript, NOT TypeScript \u2014 type annotations (`: string[]`), interfaces, and generics fail to parse. The script body runs in an async context \u2014 use await directly. Standard JS built-ins (JSON, Math, Array, etc.) are available \u2014 EXCEPT `Date.now()`/`Math.random()`/argless `new Date()`, which throw (they would break resume); pass timestamps in via `args`, stamp results after the workflow returns, and for randomness vary the agent prompt/label by index. `eval` and `Function(...)` throw. No filesystem or Node.js API access.\n\nDEFAULT TO pipeline(). Only reach for a barrier (parallel between stages) when you genuinely need ALL prior-stage results together.\n\nA barrier is correct ONLY when stage N needs cross-item context from all of stage N-1:\n- Dedup/merge across the full result set before expensive downstream work\n- Early-exit if the total count is zero (\"0 bugs found \u2192 skip verification entirely\")\n- Stage N's prompt references \"the other findings\" for comparison\n\nA barrier is NOT justified by:\n- \"I need to flatten/map/filter first\" \u2014 do it inside a pipeline stage: pipeline(items, stageA, r => transform([r]).flat(), stageB)\n- \"The stages are conceptually separate\" \u2014 that's what pipeline() models. Separate stages \u2260 synchronized stages.\n- \"It's cleaner code\" \u2014 barrier latency is real. If 5 finders run and the slowest takes 3\u00D7 the fastest, a barrier wastes 2/3 of the fast finders' idle time.\n\nSmell test: if you wrote\n const a = await parallel(...)\n const b = transform(a) // flatten, map, filter \u2014 no cross-item dependency\n const c = await parallel(b.map(...))\nthat middle transform doesn't need the barrier. Rewrite as a pipeline with the transform inside a stage. When in doubt: pipeline.\n\nConcurrent agent() calls are capped at min(16, available CPUs - 2) per workflow \u2014 excess calls queue and run as slots free up. You can still pass 100 items to parallel()/pipeline() and they all complete; only ~10 run at any moment. Total agent count across a workflow's lifetime is capped at 1000 \u2014 a runaway-loop backstop set far above any real workflow. A single parallel()/pipeline() call accepts at most 4096 items; passing more is an explicit error, not a silent truncation.\n\nThe canonical multi-stage pattern \u2014 pipeline by default, each dimension verifies as soon as its review completes:\n export const meta = {\n name: 'review-changes',\n description: 'Review changed files across dimensions, verify each finding',\n phases: [{ title: 'Review' }, { title: 'Verify' }],\n }\n const DIMENSIONS = [{key: 'bugs', prompt: '...'}, {key: 'perf', prompt: '...'}]\n const results = await pipeline(\n DIMENSIONS,\n d => agent(d.prompt, {label: `review:${d.key}`, phase: 'Review', schema: FINDINGS_SCHEMA}),\n review => parallel(review.findings.map(f => () =>\n agent(`Adversarially verify: ${f.title}`, {label: `verify:${f.file}`, phase: 'Verify', schema: VERDICT_SCHEMA})\n .then(v => ({...f, verdict: v}))\n ))\n )\n const confirmed = results.flat().filter(Boolean).filter(f => f.verdict?.isReal)\n return { confirmed }\n // Dimension 'bugs' findings verify while dimension 'perf' is still reviewing. No wasted wall-clock.\n\nWhen a barrier IS correct \u2014 dedup across all findings before expensive verification:\n const all = await parallel(DIMENSIONS.map(d => () => agent(d.prompt, {schema: FINDINGS_SCHEMA})))\n const deduped = dedupeByFileAndLine(all.filter(Boolean).flatMap(r => r.findings)) // <-- genuinely needs ALL at once\n const verified = await parallel(deduped.map(f => () => agent(verifyPrompt(f), {schema: VERDICT_SCHEMA})))\n\nLoop-until-count pattern \u2014 accumulate to a target:\n const bugs = []\n while (bugs.length < 10) {\n const result = await agent(\"Find bugs in this codebase.\", {schema: BUGS_SCHEMA})\n bugs.push(...result.bugs)\n log(`${bugs.length}/10 found`)\n }\n\nGate-and-retry pattern \u2014 verify by running, and keep the agent's context across attempts:\n let fixed = await agent('Find and fix the failing test.', {label: 'fix', gate: 'npm test'})\n if (fixed === null) { // a non-zero exit failed the agent\n // Resume keeps everything the child already learned. It cannot carry the\n // gate, so re-verification needs its own gated call, in the same tree.\n fixed = await agent('`npm test` is still failing. Fix the cause.', {label: 'fix', resume: 'fix'})\n const verified = await agent('Run `npm test` and report the result. Change nothing.',\n {label: 'verify', phase: 'Verify', gate: 'npm test', effort: 'low'})\n return { passed: verified !== null, summary: fixed }\n }\n return { passed: true, summary: fixed }\n // An LLM judging whether a fix works is a weaker signal than the test suite.\n\nComposing patterns \u2014 exhaustive review (find \u2192 dedup vs seen \u2192 diverse-lens panel \u2192 loop-until-dry):\n const seen = new Set(), confirmed = []\n let dry = 0\n while (dry < 2) { // loop-until-dry\n const found = (await parallel(FINDERS.map(f => () => // barrier: collect all finders this round\n agent(f.prompt, {phase: 'Find', schema: BUGS})))).filter(Boolean).flatMap(r => r.bugs)\n const fresh = found.filter(b => !seen.has(key(b))) // dedup vs ALL seen \u2014 plain code, not an agent\n if (!fresh.length) { dry++; continue }\n dry = 0; fresh.forEach(b => seen.add(key(b)))\n const judged = await parallel(fresh.map(b => () => // every fresh bug judged concurrently...\n parallel(['correctness','security','repro'].map(lens => () => // ...each by 3 distinct lenses\n agent(`Judge \"${b.desc}\" via the ${lens} lens \u2014 real?`, {phase: 'Verify', schema: VERDICT})))\n .then(vs => ({ b, real: vs.filter(Boolean).filter(v => v.real).length >= 2 }))))\n confirmed.push(...judged.filter(v => v.real).map(v => v.b))\n }\n return confirmed\n // dedup vs `seen`, NOT `confirmed` \u2014 else judge-rejected findings reappear every round and it never converges.\n\nQuality patterns \u2014 common shapes; pick by task and compose freely:\n- Adversarial verify: spawn N independent skeptics per finding, each prompted to REFUTE. Kill if \u2265majority refute. Prevents plausible-but-wrong findings from surviving.\n const votes = await parallel(Array.from({length: 3}, () => () =>\n agent(`Try to refute: ${claim}. Default to refuted=true if uncertain.`, {schema: VERDICT})))\n const survives = votes.filter(Boolean).filter(v => !v.refuted).length >= 2\n- Verify by running, not by asking: when a claim is testable, `gate` it rather than asking another model whether it holds.\n- Perspective-diverse verify: when a finding can fail in more than one way, give each verifier a distinct lens (correctness, security, perf, does-it-reproduce) instead of N identical refuters \u2014 diversity catches failure modes redundancy can't.\n- Judge panel: generate N independent attempts from different angles (e.g. MVP-first, risk-first, user-first), score with parallel judges, synthesize from the winner while grafting the best ideas from runners-up. Beats one-attempt-iterated when the solution space is wide.\n- Loop-until-dry: for unknown-size discovery (bugs, issues, edge cases), keep spawning finders until K consecutive rounds return nothing new. Simple counters (while count < N) miss the tail.\n- Multi-modal sweep: parallel agents each searching a different way (by-container, by-content, by-entity, by-time). Each is blind to what the others surface; useful when one search angle won't find everything.\n- Completeness critic: a final agent that asks \"what's missing \u2014 modality not run, claim unverified, source unread?\" What it finds becomes the next round of work.\n- No silent caps: if a workflow bounds coverage (top-N, no-retry, sampling), `log()` what was dropped \u2014 silent truncation reads as \"covered everything\" when it didn't.\n\nScale to what the user asked for. \"find any bugs\" \u2192 a few finders, single-vote verify. \"thoroughly audit this\" or \"be comprehensive\" \u2192 larger finder pool, 3\u20135 vote adversarial pass, synthesis stage. When unsure, lean toward thoroughness for research/review/audit requests and toward brevity for quick checks.\n\nThese patterns aren't exhaustive \u2014 compose novel harnesses when the task calls for it (tournament brackets, self-repair loops, staged escalation, whatever fits).\n\nUse this tool for multi-step orchestration where control flow should be deterministic (loops, conditionals, fan-out) rather than model-driven.\n\n## Resume\n\nThe tool result includes a runId. To resume after a pause, kill, or script edit, relaunch with SubagentWorkflow({scriptPath, resumeFromRunId}) \u2014 the longest unchanged prefix of agent() calls returns cached results instantly; the first edited/new call and everything after it runs live. Same script + same args \u2192 100% cache hit. A resumed run keeps its recorded default role and args unless this call explicitly supplies agentType or args. It is a prefix and not a lookup: a later call that still matches is not reused once an earlier one has changed. A journaled failure ends the prefix, so resuming a run that died at agent 5 retries exactly agent 5. Same session only, and the run must have finished \u2014 stop it from /agents \u2192 Workflows first. Before diagnosing why a completed workflow returned an empty or unexpected result, Read the run's `<run id>.workflow.jsonl` beside its script \u2014 it records each agent's actual return value; do not assume cached results are non-empty. Date.now()/Math.random()/new Date() are unavailable in scripts (they would break this) \u2014 stamp results after the workflow returns, or pass timestamps via args.";
@@ -18,7 +18,12 @@
18
18
  * pi's `AgentSession`, so a child can decline and the call returns null.
19
19
  * - `budget.total` is always null; pi has no token-target directive.
20
20
  * - `parallel` propagates a fatal run error instead of folding it to null.
21
- * - `effort` inherits the agent definition's level, then the parent's.
21
+ * - role `model`/`thinking` pins outrank the script's `model`/`effort`; an
22
+ * task/explore need model configuration even when selected explicitly.
23
+ * Other unpinned roles may use the parent when selected explicitly;
24
+ * `general-purpose` is the selectable parent twin.
25
+ * - the default workflow role is the user-defined `task`, not a built-in; an
26
+ * unresolvable default is refused rather than replaced with general-purpose.
22
27
  * - `isolation` removes the worktree on settle, changes kept on a branch.
23
28
  * Additions with no upstream counterpart: `gate`, `resume`, `effort: "minimal"`,
24
29
  * the saved-workflow directories, and the reject-unknown-options guarantee.
@@ -57,7 +62,7 @@ Common single-phase workflows you can chain across turns:
57
62
 
58
63
  For larger work, run several in sequence — read each result before deciding the next phase. You stay in the loop; each workflow is one well-scoped fan-out.
59
64
 
60
- Pass the script inline via \`script\` — do not Write it to a file first. Every invocation automatically persists its script to a file under the session directory and returns the path in the tool result. To iterate on a workflow, edit that file with Write/Edit and re-invoke SubagentWorkflow with \`{scriptPath: "<path>"}\` instead of resending the full script. A script you will run more than once belongs in \`.pi/workflows/<name>.js\` (or \`.agents/workflows/\`, or \`<agent dir>/workflows/\` for one that follows the user everywhere); call it with \`name: "<name>"\` instead of re-sending the source.
65
+ Pass the script inline via \`script\` — do not Write it to a file first. Every invocation automatically persists its script to a file under the session directory and returns the path in the tool result. To iterate on a workflow, edit that file with Write/Edit, wait for that edit tool call to complete, then re-invoke SubagentWorkflow with \`{scriptPath: "<path>"}\` in a later step. Never issue the edit and this call in the same parallel tool batch: the runtime cannot order unrelated file tools, and there is no hash or version check, so \`scriptPath\` can otherwise read the previous file or a partially written one. A script you will run more than once belongs in \`.pi/workflows/<name>.js\` (or \`.agents/workflows/\`, or \`<agent dir>/workflows/\` for one that follows the user everywhere); call it with \`name: "<name>"\` instead of re-sending the source.
61
66
 
62
67
  Every script must begin with \`export const meta = {...}\`:
63
68
  export const meta = {
@@ -76,13 +81,13 @@ Every script must begin with \`export const meta = {...}\`:
76
81
  The \`meta\` object must be a PURE LITERAL — no variables, function calls, spreads, or template interpolation. Required fields: \`name\`, \`description\`. Optional: \`whenToUse\` (shown in the workflow list), \`phases\`. Use the SAME phase titles in meta.phases as in phase() calls — titles are matched exactly; a phase() call with no matching meta entry just gets its own progress group. Add \`model\` to a phase entry when that phase uses a specific model override.
77
82
 
78
83
  Script body hooks:
79
- - agent(prompt: string, opts?: {label?: string, phase?: string, schema?: object, model?: string, effort?: string, isolation?: 'worktree', agentType?: string, gate?: string, resume?: string}): Promise<any> — spawn a subagent. Without schema, returns its final text as a string. With schema (a JSON Schema), the subagent is given a StructuredOutput tool built from it and agent() returns the validated object — no parsing needed. A payload that does not match is rejected back to the child, which corrects it; a child that never answers through the tool gets one more prompt and then fails, so the call returns null — filter after every schema stage. Returns null if the user skips the agent mid-run or the subagent dies on a terminal API error after retries (filter with .filter(Boolean)). opts.label overrides the display label. opts.phase explicitly assigns this agent to a progress group (use this inside pipeline()/parallel() stages to avoid races on the global phase() state — same phase string → same group box). opts.model overrides the model for this agent call. Default to omitting it — the agent inherits the main-loop model (the resolved session model), which is almost always correct. Only set it when you're highly confident a different tier fits the task; when unsure, omit. opts.effort overrides the reasoning effort for this agent call ('minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max') — omit to inherit the agent definition's own level, then the parent's; use 'low' for cheap mechanical stages and higher tiers only for the hardest verify/judge stages. opts.isolation: 'worktree' runs the agent in a fresh git worktree — EXPENSIVE (setup time + disk per agent), use ONLY when agents mutate files in parallel and would otherwise conflict; the worktree is removed when the agent settles, its changes preserved on a branch. opts.gate: '<command>' runs a shell command after the agent finishes and requires it to pass — a non-zero exit marks the agent failed and the command's output becomes the error; prefer gate: 'npm test' over asking another agent whether the code looks right. opts.resume: '<label>' continues the child that ran under that label instead of starting fresh, so an iterative loop keeps its context — it cannot be combined with agentType, model, effort, isolation, gate or schema. opts.agentType uses a custom subagent type instead of the default workflow subagent — resolved from the same registry as the Agent tool; composes with schema. Available types:
84
+ - agent(prompt: string, opts?: {label?: string, phase?: string, schema?: object, model?: string, effort?: string, isolation?: 'worktree', agentType?: string, gate?: string, resume?: string}): Promise<any> — spawn a subagent. Without schema, returns its final text as a string. With schema (a JSON Schema), the subagent is given a StructuredOutput tool built from it and agent() returns the validated object — no parsing needed. A payload that does not match is rejected back to the child, which corrects it; a child that never answers through the tool gets one more prompt and then fails, so the call returns null — filter after every schema stage. Returns null if the user skips the agent mid-run or the subagent dies on a terminal API error after retries (filter with .filter(Boolean)). opts.label overrides the display label. opts.phase explicitly assigns this agent to a progress group (use this inside pipeline()/parallel() stages to avoid races on the global phase() state — same phase string → same group box). opts.model supplies a model only for a role with no \`model:\` pin — a role pin always wins. task/explore require a model pin or explicit opts.model even when selected explicitly; they never implicitly inherit the parent. Other explicitly selected unpinned roles may use the parent, and general-purpose is the selectable main-model twin. Missing workflow defaults and task/explore requests never use the generic fallbackSubagent; explicit other role requests retain that policy. An unavailable pin fails the workflow — built-in pins included. Prefer an exact \`provider/modelId\`; pi's fuzzy shorthand (\`"haiku"\`, \`"sonnet"\`) is also accepted. Choose a different tier only when you are confident it fits; \`/subagents off\` is the one exception and forces the session's main model regardless. opts.effort requests the reasoning effort for this agent call ('minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max') — a role's \`thinking:\` pin always wins; omit to use that pin, or the run's normal thinking default when it has none. Use 'low' for cheap mechanical stages and higher tiers only for the hardest verify/judge stages. opts.isolation: 'worktree' runs the agent in a fresh git worktree — EXPENSIVE (setup time + disk per agent), use ONLY when agents mutate files in parallel and would otherwise conflict; the worktree is removed when the agent settles, its changes preserved on a branch. opts.gate: '<command>' runs a shell command after the agent finishes and requires it to pass — a non-zero exit marks the agent failed and the command's output becomes the error; prefer gate: 'npm test' over asking another agent whether the code looks right. opts.resume: '<label>' continues the child that ran under that label instead of starting fresh, so an iterative loop keeps its context — it cannot be combined with agentType, model, effort, isolation, gate or schema. opts.agentType selects this call's role and wins over the run default — resolved from the same registry as the Agent tool; composes with schema. Without it, agents use the run's agentType (the SubagentWorkflow call), else workflowDefaultAgentType (default "task"). "task" is user-defined, not a built-in: define it with a model pin, or point workflowDefaultAgentType at an available pinned role. If a default or task/explore role is missing/disabled, the spawn is refused rather than replaced with another role. A blank run agentType is rejected instead of inheriting a resumed role. Role choice comes from this value, not from the user's wording alone — when the user names a role ("use explore for this workflow"), pass it here. Use premium or explicit-only roles (for example a user-defined principal_engineer) only when the user asks for them, and \`general-purpose\` only when the user asks for the main model (it is the parent twin). Available types:
80
85
  {{typeList}}
81
86
  - pipeline(items, stage1, stage2, ...): Promise<any[]> — run each item through all stages independently, NO barrier between stages. Item A can be in stage 3 while item B is still in stage 1. This is the DEFAULT for multi-stage work. Wall-clock = slowest single-item chain, not sum-of-slowest-per-stage. Every stage callback receives (prevResult, originalItem, index) — use originalItem/index in later stages to label work without threading context through stage 1's return value. A stage that throws drops that item to \`null\` and skips its remaining stages.
82
87
  - parallel(thunks: Array<() => Promise<any>>): Promise<any[]> — run tasks concurrently. This is a BARRIER: awaits all thunks before returning. A thunk that throws (or whose agent errors) resolves to \`null\` in the result array, so \`.filter(Boolean)\` before using the results; only a fatal run error — a cap breach, or a nested workflow that could not load — propagates instead of being folded into a null. Use ONLY when you genuinely need all results together.
83
88
  - log(message: string): void — emit a progress message to the user (shown as a narrator line above the progress tree)
84
89
  - phase(title: string): void — start a new phase; subsequent agent() calls are grouped under this title in the progress display
85
- - args: any — the value passed as SubagentWorkflow's \`args\` input, verbatim (undefined if not provided). Pass arrays/objects as actual JSON values in the tool call, NOT as a JSON-encoded string — \`args: ["a.ts", "b.ts"]\`, not \`args: "[\\"a.ts\\", ...]"\` (a stringified list reaches the script as one string, so \`args.filter\`/\`args.map\` throw). Use this to parameterize named workflows — e.g. pass a research question, target path, or config object directly instead of via a side-channel file.
90
+ - args: any — the value passed as SubagentWorkflow's \`args\` input, verbatim (undefined if not provided). Any JSON value is valid — object, array, string, number, boolean, null — and it is not coerced, parsed or stringified. Pass arrays/objects as actual JSON values in the tool call, NOT as a JSON-encoded string — \`args: ["a.ts", "b.ts"]\` or \`args: {probes: [...]}\`, not \`args: "[\\"a.ts\\", ...]"\` (a stringified value reaches the script as one string, so \`args.filter\`/\`args.map\` and property access throw; the failure reports the script line that used it). Use this to parameterize named workflows — e.g. pass a research question, target path, or config object directly instead of via a side-channel file.
86
91
  - budget: {total: number|null, spent(): number, remaining(): number} — \`budget.total\` is always null here: it comes from a token-target directive pi does not have, so guards like \`while (budget.total && budget.remaining() > 50_000) { ... }\` correctly do not fire rather than throwing on a missing global. \`budget.spent()\` returns output tokens spent by this run's agents. \`budget.remaining()\` returns \`Infinity\` with no target.
87
92
  - workflow(nameOrRef: string | {scriptPath: string}, args?: any): Promise<any> — run another workflow inline as a sub-step and return whatever it returns. Pass a name to invoke a saved workflow (same registry as {name: "..."}), or {scriptPath} to run a script file you Wrote earlier. The child shares this run's concurrency cap, agent counter, abort signal, and token budget — its agents appear under a "▸ name" group in /agents → Workflows and its tokens count toward budget.spent(). The args param becomes the child's \`args\` global. Nesting is one level only: workflow() inside a child throws. Throws on unknown name / unreadable scriptPath / child syntax error; catch to handle gracefully.
88
93
 
@@ -196,4 +201,4 @@ Use this tool for multi-step orchestration where control flow should be determin
196
201
 
197
202
  ## Resume
198
203
 
199
- The tool result includes a runId. To resume after a pause, kill, or script edit, relaunch with SubagentWorkflow({scriptPath, resumeFromRunId}) — the longest unchanged prefix of agent() calls returns cached results instantly; the first edited/new call and everything after it runs live. Same script + same args → 100% cache hit. It is a prefix and not a lookup: a later call that still matches is not reused once an earlier one has changed. A journaled failure ends the prefix, so resuming a run that died at agent 5 retries exactly agent 5. Same session only, and the run must have finished — stop it from /agents → Workflows first. Before diagnosing why a completed workflow returned an empty or unexpected result, Read the run's \`<run id>.workflow.jsonl\` beside its script — it records each agent's actual return value; do not assume cached results are non-empty. Date.now()/Math.random()/new Date() are unavailable in scripts (they would break this) — stamp results after the workflow returns, or pass timestamps via args.`;
204
+ The tool result includes a runId. To resume after a pause, kill, or script edit, relaunch with SubagentWorkflow({scriptPath, resumeFromRunId}) — the longest unchanged prefix of agent() calls returns cached results instantly; the first edited/new call and everything after it runs live. Same script + same args → 100% cache hit. A resumed run keeps its recorded default role and args unless this call explicitly supplies agentType or args. It is a prefix and not a lookup: a later call that still matches is not reused once an earlier one has changed. A journaled failure ends the prefix, so resuming a run that died at agent 5 retries exactly agent 5. Same session only, and the run must have finished — stop it from /agents → Workflows first. Before diagnosing why a completed workflow returned an empty or unexpected result, Read the run's \`<run id>.workflow.jsonl\` beside its script — it records each agent's actual return value; do not assume cached results are non-empty. Date.now()/Math.random()/new Date() are unavailable in scripts (they would break this) — stamp results after the workflow returns, or pass timestamps via args.`;
@@ -1,4 +1,4 @@
1
- # Local fork provenance and development
1
+ # Provenance and development
2
2
 
3
3
  Audience: developers maintaining `@timmyjl12/pi-subagents` alongside custom Pi extensions.
4
4
 
@@ -8,7 +8,7 @@ Audience: developers maintaining `@timmyjl12/pi-subagents` alongside custom Pi e
8
8
  - Initial baseline: `e955e29` (upstream package 0.19.0).
9
9
  - Package: `@timmyjl12/pi-subagents` on npm, first released as `0.20.0`.
10
10
  - Repository: `github.com/timmyjl12/pi-subagents` (`origin`). Upstream is kept as the `upstream` remote, and upstream Git history, license and attribution are retained.
11
- - Local fork maintainer: Tim L / timmyjl12.
11
+ - Maintainer: Tim L / timmyjl12.
12
12
  - oh-my-pi is a design reference, not a vendored dependency. Its core focus controller cannot be dropped into stock Pi, which does not expose that private session-focus API.
13
13
 
14
14
  ## Intended integration
@@ -29,7 +29,7 @@ npm run test:e2e
29
29
 
30
30
  Development dependencies target Pi 1.1.0; the peer floor stays at 0.86.1. Scripted tests should use fake providers, not paid live requests. Report timeout/skipped suites separately. Do not interpret a passing renderer unit test as a visual test in a real terminal.
31
31
 
32
- For an isolated manual test, use a fresh `PI_CODING_AGENT_DIR` and a scratch working directory. Explicitly load the local fork and local fallback extension; do not load upstream at the same time. Leave the ordinary global configuration untouched until activation is approved.
32
+ For an isolated manual test, use a fresh `PI_CODING_AGENT_DIR` and a scratch working directory. Explicitly load the local checkout and the local fallback extension; do not load another subagents extension at the same time. Leave the ordinary global configuration untouched until activation is approved.
33
33
 
34
34
  ## Releasing
35
35
 
@@ -37,4 +37,4 @@ Publish with `npm publish` after `npm run check` passes (`prepublishOnly` also r
37
37
 
38
38
  ## Upstream maintenance
39
39
 
40
- Review incoming upstream changes against this fork's recovery and UI tests before merging. Avoid renaming established event namespaces merely to change package branding. Preserve original notices for any subsequently copied code; do not assume design inspiration grants permission to omit license attribution.
40
+ If you bring in changes from tintinweb/pi-subagents, review them against our recovery and UI tests before merging. Avoid renaming established event namespaces merely to change package branding. Preserve original notices for any subsequently copied code; do not assume design inspiration grants permission to omit license attribution.