@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
@@ -15,15 +15,18 @@
15
15
 
16
16
  import { cpus } from "node:os";
17
17
  import { Worker } from "node:worker_threads";
18
- import { type JournalKeyInput, journalKey, type WorkflowJournalEntry } from "./journal.js";
19
- import { type CompiledSchema, compileJsonSchema } from "./json-schema.js";
20
- import { extractMeta, type WorkflowMeta } from "./meta.js";
21
- import type { WorkflowAgentEntry, WorkflowEntry } from "./progress.js";
22
- import { WORKER_SOURCE } from "./worker-source.js";
18
+ import { type JournalKeyInput, journalKey, type WorkflowJournalEntry } from "./journal.ts";
19
+ import { type CompiledSchema, compileJsonSchema } from "./json-schema.ts";
20
+ import { extractMeta, type WorkflowMeta } from "./meta.ts";
21
+ import type { WorkflowAgentEntry, WorkflowEntry } from "./progress.ts";
22
+ import { WORKER_SOURCE } from "./worker-source.ts";
23
23
 
24
24
  /** Matches the `script` field's `maxLength` in the tool schema. */
25
25
  export const MAX_SCRIPT_LENGTH = 524_288;
26
26
 
27
+ /** Economical workflow role; explicit run and per-call roles take precedence. */
28
+ export const DEFAULT_WORKFLOW_AGENT_TYPE = "task";
29
+
27
30
  /** Agents one run may schedule, in total. */
28
31
  export const WORKFLOW_AGENT_CAP = 1000;
29
32
 
@@ -57,6 +60,12 @@ export interface WorkflowSpawnRequest {
57
60
  prompt: string;
58
61
  label: string;
59
62
  agentType: string;
63
+ /**
64
+ * True when the call's opts.agentType or the run's agentType selected a role.
65
+ * A setting-derived default is not explicit, and a configured generic
66
+ * fallback must not turn that default into an authorized premium request.
67
+ */
68
+ agentTypeExplicit?: boolean;
60
69
  model?: string;
61
70
  /**
62
71
  * Reasoning effort for this child, as one of pi's thinking levels.
@@ -126,6 +135,8 @@ export interface WorkflowSpawnResult {
126
135
  text?: string;
127
136
  /** Why it failed. Present when not `ok`. */
128
137
  error?: string;
138
+ /** Configuration failures must not be swallowed as a null pipeline item. */
139
+ fatal?: boolean;
129
140
  /** The user dismissed it rather than it failing; renders as skipped. */
130
141
  skipped?: boolean;
131
142
  tokens?: number;
@@ -272,6 +283,10 @@ export interface RunWorkflowOptions {
272
283
  /** Full script source, starting with `export const meta = { … }`. */
273
284
  script: string;
274
285
  args?: unknown;
286
+ /** Used only when an agent() call does not name its own role. */
287
+ defaultAgentType?: string;
288
+ /** True when the run's `agentType` named that default — see {@link WorkflowSpawnRequest.agentTypeExplicit}. */
289
+ defaultAgentTypeExplicit?: boolean;
275
290
  host: WorkflowHost;
276
291
  signal?: AbortSignal;
277
292
  /** Fired per batch, not per entry — see the worker's progress batching. */
@@ -305,9 +320,34 @@ export interface RunWorkflowOptions {
305
320
  journal?: {
306
321
  /** A previous run's settled calls, in position order. Empty replays nothing. */
307
322
  entries?: readonly WorkflowJournalEntry[];
308
- /** Called as each call of *this* run settles, so it can be resumed in turn. */
309
- append?(entry: WorkflowJournalEntry): void;
323
+ /**
324
+ * Called as each call of *this* run settles, so it can be resumed in turn.
325
+ *
326
+ * May return a promise. The runtime accepts records synchronously and
327
+ * writes them through one ordered chain, so a slow disk never blocks an
328
+ * agent's response and a failed write never drops the records after it.
329
+ * {@link onJournalDrain} is how a caller waits for that chain: this callback
330
+ * only runs once the record reaches the front of it.
331
+ */
332
+ append?(entry: WorkflowJournalEntry): void | Promise<void>;
310
333
  };
334
+ /**
335
+ * The run's accepted-write drain, handed over before any work starts.
336
+ *
337
+ * Whatever {@link journal.append} is given is queued inside this run first, so
338
+ * a record can be accepted long before the journal module has been handed it
339
+ * — and `readJournal` can only wait for appends it was given. A caller that
340
+ * reads the journal back (a paused run being resumed, a shutdown that must
341
+ * not lose the tail) needs to wait for the *queue*. The handle delivered here
342
+ * resolves once every record accepted so far has settled, and keeps following
343
+ * the queue if a call settles while it is waiting. Nothing accepted is ever
344
+ * dropped, and a failed write is still swallowed rather than failing the wait:
345
+ * this is the same best-effort treatment `append` gets.
346
+ *
347
+ * Called once, before the worker exists. A handle delivered later could miss
348
+ * a call that had already settled for a run nobody had been told about yet.
349
+ */
350
+ onJournalDrain?(drain: () => Promise<void>): void;
311
351
  }
312
352
 
313
353
  export interface WorkflowRunResult {
@@ -588,6 +628,8 @@ export async function runWorkflow(options: RunWorkflowOptions): Promise<Workflow
588
628
  assertBoundarySafe(options.args, "args");
589
629
 
590
630
  const { meta, body } = validateScript(script);
631
+ const defaultAgentType = (options.defaultAgentType ?? DEFAULT_WORKFLOW_AGENT_TYPE).trim();
632
+ if (defaultAgentType === "") throw new WorkflowRuntimeError("Workflow defaultAgentType must be a non-empty agent name.");
591
633
  const agentCap = options.agentCap ?? WORKFLOW_AGENT_CAP;
592
634
  const itemCap = options.itemCap ?? WORKFLOW_ITEM_CAP;
593
635
  const semaphore = new Semaphore(options.concurrency ?? workflowConcurrency());
@@ -613,7 +655,61 @@ export async function runWorkflow(options: RunWorkflowOptions): Promise<Workflow
613
655
  /* --- resume state ---------------------------------------------------- */
614
656
 
615
657
  const journalEntries = options.journal?.entries ?? [];
616
- const recordJournal = options.journal?.append;
658
+ const appendJournalEntry = options.journal?.append;
659
+ /**
660
+ * Whether this run still accepts journal records.
661
+ *
662
+ * Closed synchronously by `finish` before any abort or termination work, so a
663
+ * call that settles during teardown cannot append to a journal the run is
664
+ * already reporting as finished.
665
+ */
666
+ let journalAccepting = true;
667
+ /** The accepted records, in settlement order. Never rejects. */
668
+ let journalWrites: Promise<void> = Promise.resolve();
669
+
670
+ /**
671
+ * Accept one record into the run's single ordered write chain.
672
+ *
673
+ * Deliberately synchronous: the agent path answers the script immediately and
674
+ * `finish` only has to await writes that were accepted before it closed the
675
+ * gate. `appendJournalEntry` may be sync or promise-returning; either way its
676
+ * failure is swallowed here so later records still get written and a
677
+ * best-effort journal can never fail the run.
678
+ */
679
+ const recordJournal = (entry: WorkflowJournalEntry): void => {
680
+ if (!journalAccepting || appendJournalEntry === undefined) return;
681
+ journalWrites = journalWrites.then(async () => {
682
+ try {
683
+ await appendJournalEntry(entry);
684
+ } catch {
685
+ // A journal that cannot be written costs a future resume, nothing more.
686
+ // Staying on this chain is what keeps the later records alive.
687
+ }
688
+ });
689
+ };
690
+ /**
691
+ * Wait for every record this run has accepted so far.
692
+ *
693
+ * The tail is re-read after each wait: a call that settles while this is
694
+ * suspended appends a new link, and resolving on the tail observed first
695
+ * would hand back exactly the half-written journal this exists to prevent.
696
+ * The chain swallows its own write failures as it goes — see `recordJournal`
697
+ * — so waiting on it never rejects and a failed record never strands the
698
+ * ones behind it. Called after the run settles it resolves immediately: the
699
+ * chain is closed, settled and stable, so a shutdown that arrives late has
700
+ * nothing special to do.
701
+ */
702
+ const drainJournal = async (): Promise<void> => {
703
+ let tail = journalWrites;
704
+ await tail;
705
+ while (tail !== journalWrites) {
706
+ tail = journalWrites;
707
+ await tail;
708
+ }
709
+ };
710
+ // Registered before the worker exists, because the worker is what settles
711
+ // calls: a handle delivered any later could miss a record already accepted.
712
+ options.onJournalDrain?.(drainJournal);
617
713
  /**
618
714
  * Whether the replayable prefix is still intact.
619
715
  *
@@ -706,10 +802,11 @@ export async function runWorkflow(options: RunWorkflowOptions): Promise<Workflow
706
802
  });
707
803
 
708
804
  /** The journal entry to reuse at `index`, or undefined to run it live. */
709
- function replayAt(index: number, key: string): WorkflowJournalEntry | undefined {
805
+ function replayAt(index: number, key: string, input: JournalKeyInput): WorkflowJournalEntry | undefined {
710
806
  if (!prefixIntact) return undefined;
711
807
  const entry = journalEntries[index];
712
- if (entry === undefined || entry.index !== index || entry.key !== key || !entry.ok) {
808
+ if (entry === undefined || entry.index !== index || !entry.ok ||
809
+ (entry.key !== key && entry.key !== journalKey(input, "legacy"))) {
713
810
  prefixIntact = false;
714
811
  return undefined;
715
812
  }
@@ -747,6 +844,10 @@ export async function runWorkflow(options: RunWorkflowOptions): Promise<Workflow
747
844
  const finish = (result: Omit<WorkflowRunResult, "meta" | "progress" | "agentCount" | "replayedCount">) => {
748
845
  if (settled) return;
749
846
  settled = true;
847
+ // Closed before anything else can run: every record accepted so far is
848
+ // captured, and none accepted afterwards can reach the journal.
849
+ journalAccepting = false;
850
+ const acceptedJournalWrites = journalWrites;
750
851
  options.signal?.removeEventListener("abort", onAbort);
751
852
  // Symmetric with `semaphore.drain()` below: everything parked is woken so
752
853
  // it observes the settle and unwinds. Nothing depends on it — the run's
@@ -756,10 +857,12 @@ export async function runWorkflow(options: RunWorkflowOptions): Promise<Workflow
756
857
  for (const agentId of inflight) host.abortAgent(agentId);
757
858
  inflight.clear();
758
859
  semaphore.drain();
759
- // Resolve only once the thread is actually down, so a caller that awaits
760
- // runWorkflow() is guaranteed not to be leaking one.
860
+ // Resolve only once the thread is actually down AND the records this run
861
+ // accepted are flushed. The chain contains only append callbacks, never a
862
+ // child/provider promise, so a hung agent cannot delay the result while
863
+ // an immediate resume still cannot miss a write.
761
864
  const settle = () => resolve({ ...result, meta, progress, agentCount, replayedCount });
762
- void worker.terminate().then(settle, settle);
865
+ void Promise.allSettled([acceptedJournalWrites, worker.terminate()]).then(settle);
763
866
  };
764
867
 
765
868
  function onAbort() {
@@ -849,7 +952,8 @@ export async function runWorkflow(options: RunWorkflowOptions): Promise<Workflow
849
952
  // reads the same as the row it continues.
850
953
  const agentId = resumed?.agentId ?? `wf-agent-${index}`;
851
954
  const label = payload.label ?? resumed?.label ?? derivedLabel(payload.prompt);
852
- const agentType = resumed?.agentType ?? payload.agentType ?? "general-purpose";
955
+ const agentType = resumed?.agentType ?? payload.agentType ?? defaultAgentType;
956
+ const agentTypeExplicit = payload.agentType !== undefined || options.defaultAgentTypeExplicit === true;
853
957
  const model = resumed !== undefined ? resumed.model : payload.model;
854
958
  const isolation = resumed !== undefined ? resumed.isolation : payload.isolation;
855
959
  openLaunches.set(callId, label);
@@ -879,9 +983,12 @@ export async function runWorkflow(options: RunWorkflowOptions): Promise<Workflow
879
983
  // so the spread is narrowed rather than passed through.
880
984
  const keyInput: JournalKeyInput = {
881
985
  ...payload,
986
+ agentType,
987
+ agentTypeExplicit,
882
988
  schema: payload.schema !== undefined ? JSON.stringify(payload.schema) : undefined,
883
989
  };
884
- let replayed = replayAt(index, journalKey(keyInput));
990
+ const key = journalKey(keyInput);
991
+ let replayed = replayAt(index, key, keyInput);
885
992
  // A replayed answer still has to satisfy the schema. The key covers a
886
993
  // schema that *changed*, but not a journal that was hand-edited, and not
887
994
  // the empty text a torn entry leaves behind — either would hand the
@@ -916,17 +1023,16 @@ export async function runWorkflow(options: RunWorkflowOptions): Promise<Workflow
916
1023
  // Re-recorded so this run's journal is complete on its own terms: a
917
1024
  // resume of a resume must not have to walk back through a chain of
918
1025
  // earlier files to find the prefix.
919
- recordJournal?.({ index, key: replayed.key, ok: true, text: replayedText });
1026
+ recordJournal({ index, key: replayed.key, ok: true, text: replayedText });
920
1027
  respond(callId, true, replayedText);
921
1028
  return;
922
1029
  }
923
1030
 
924
- const key = journalKey(keyInput);
925
1031
  const resumeMark = payload.resume !== undefined ? ({ resumed: true } as const) : {};
926
1032
 
927
1033
  /** A skip the user asked for, before the child ever started. */
928
1034
  const settleSkipped = (extra: Partial<WorkflowAgentEntry>) => {
929
- recordJournal?.({ index, key, ok: false, ...resumeMark });
1035
+ recordJournal({ index, key, ok: false, ...resumeMark });
930
1036
  emit([{ ...base, queuedAt, ...extra, state: "error", skipped: true, error: "Skipped by user." }]);
931
1037
  // `null`, exactly as a terminal failure gives — a skipped agent is one
932
1038
  // the script's `.filter(Boolean)` was already written to survive.
@@ -1023,6 +1129,7 @@ export async function runWorkflow(options: RunWorkflowOptions): Promise<Workflow
1023
1129
  prompt: payload.prompt,
1024
1130
  label,
1025
1131
  agentType,
1132
+ ...(agentTypeExplicit ? { agentTypeExplicit: true } : {}),
1026
1133
  ...(model !== undefined ? { model } : {}),
1027
1134
  ...(payload.effort !== undefined ? { effort: payload.effort } : {}),
1028
1135
  ...(compiledSchema !== undefined ? { schema: compiledSchema } : {}),
@@ -1099,14 +1206,14 @@ export async function runWorkflow(options: RunWorkflowOptions): Promise<Workflow
1099
1206
  if (result.ok) {
1100
1207
  const text = result.text ?? "";
1101
1208
  emit([{ ...common, state: "done", resultPreview: preview(text) }]);
1102
- recordJournal?.({ index, key, ok: true, text, ...resumeMark });
1209
+ recordJournal({ index, key, ok: true, text, ...resumeMark });
1103
1210
  respond(callId, true, text);
1104
1211
  return;
1105
1212
  }
1106
1213
  // Recorded as a failure rather than left out: a gap would be read as an
1107
1214
  // unchanged prefix on the next resume, silently skipping the retry this
1108
1215
  // whole mechanism exists to make cheap.
1109
- recordJournal?.({ index, key, ok: false, ...resumeMark });
1216
+ recordJournal({ index, key, ok: false, ...resumeMark });
1110
1217
  // A dead agent is a null in the script, not a thrown error: Claude Code
1111
1218
  // scripts .filter(Boolean) rather than try/catch around every call.
1112
1219
  emit([
@@ -1121,7 +1228,11 @@ export async function runWorkflow(options: RunWorkflowOptions): Promise<Workflow
1121
1228
  ...(result.skipped ? { skipped: true } : {}),
1122
1229
  },
1123
1230
  ]);
1124
- respond(callId, true, null);
1231
+ if (result.fatal) {
1232
+ respond(callId, false, undefined, result.error ?? "Agent configuration failed.", true);
1233
+ } else {
1234
+ respond(callId, true, null);
1235
+ }
1125
1236
  return;
1126
1237
  }
1127
1238
  } finally {
@@ -1200,9 +1311,21 @@ export async function runWorkflow(options: RunWorkflowOptions): Promise<Workflow
1200
1311
  });
1201
1312
  break;
1202
1313
  }
1203
- case "error":
1204
- finish({ status: "failed", error: message.message });
1314
+ case "error": {
1315
+ const frames = message.stack?.split("\n")
1316
+ .filter(line => /(?:workflow\.js|workflow:[^\r\n]+?\.js):\d+/.test(line))
1317
+ .slice(0, 3) ?? [];
1318
+ let error = [message.message, ...frames].join("\n");
1319
+ if (!frames[0]?.includes("workflow:") && /Cannot read properties|is not (?:a function|iterable)|expects an array/.test(message.message)) {
1320
+ if (options.args === undefined) {
1321
+ 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.";
1322
+ } else if (typeof options.args === "string") {
1323
+ 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.";
1324
+ }
1325
+ }
1326
+ finish({ status: "failed", error });
1205
1327
  break;
1328
+ }
1206
1329
  }
1207
1330
  });
1208
1331
 
@@ -40,9 +40,9 @@
40
40
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
41
41
  import { isAbsolute, join } from "node:path";
42
42
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
43
- import { isSymlink, isUnsafeName, safeReadFile } from "../memory.js";
44
- import { hasMetaDeclaration } from "./meta.js";
45
- import { MAX_SCRIPT_LENGTH } from "./runtime.js";
43
+ import { isSymlink, isUnsafeName, safeReadFile } from "../memory.ts";
44
+ import { hasMetaDeclaration } from "./meta.ts";
45
+ import { MAX_SCRIPT_LENGTH } from "./runtime.ts";
46
46
 
47
47
  /** Extension a saved workflow file carries. */
48
48
  const WORKFLOW_EXTENSION = ".js";
@@ -15,11 +15,11 @@
15
15
  */
16
16
 
17
17
  import { randomUUID } from "node:crypto";
18
- import { escapeXml } from "../xml.js";
19
- import type { WorkflowJournalEntry } from "./journal.js";
20
- import type { WorkflowMeta } from "./meta.js";
21
- import { collapse, elapsedMs, stats, type WorkflowEntry, type WorkflowRunStatus } from "./progress.js";
22
- import type { WorkflowControl, WorkflowRunResult } from "./runtime.js";
18
+ import { escapeXml } from "../xml.ts";
19
+ import type { WorkflowJournalEntry } from "./journal.ts";
20
+ import type { WorkflowMeta } from "./meta.ts";
21
+ import { collapse, elapsedMs, stats, type WorkflowEntry, type WorkflowRunStatus } from "./progress.ts";
22
+ import { DEFAULT_WORKFLOW_AGENT_TYPE, type WorkflowControl, type WorkflowRunResult } from "./runtime.ts";
23
23
 
24
24
  /** `wf_` + hex, matching Claude Code's `^wf_[a-z0-9-]{6,}$` run ids. */
25
25
  export function workflowRunId(): string {
@@ -35,6 +35,10 @@ export interface WorkflowTask {
35
35
  /** Where the script can be edited and re-run from. */
36
36
  scriptPath?: string;
37
37
  args?: unknown;
38
+ /** Frozen for the lifetime of this run and reused on resume. */
39
+ defaultAgentType: string;
40
+ /** Whether the run's `agentType` named that default — see {@link WorkflowTask.defaultAgentType}. */
41
+ defaultAgentTypeExplicit: boolean;
38
42
  meta?: WorkflowMeta;
39
43
  workflowName?: string;
40
44
  /** The `tool_use_id` of the call that started this, when one did. */
@@ -93,6 +97,8 @@ export function createWorkflowTask(init: {
93
97
  script: string;
94
98
  scriptPath?: string;
95
99
  args?: unknown;
100
+ defaultAgentType?: string;
101
+ defaultAgentTypeExplicit?: boolean;
96
102
  meta?: WorkflowMeta;
97
103
  toolCallId?: string;
98
104
  startTime?: number;
@@ -107,6 +113,8 @@ export function createWorkflowTask(init: {
107
113
  script: init.script,
108
114
  scriptPath: init.scriptPath,
109
115
  args: init.args,
116
+ defaultAgentType: init.defaultAgentType ?? DEFAULT_WORKFLOW_AGENT_TYPE,
117
+ defaultAgentTypeExplicit: init.defaultAgentTypeExplicit ?? false,
110
118
  meta: init.meta,
111
119
  workflowName: init.meta?.name,
112
120
  toolCallId: init.toolCallId,
@@ -242,7 +250,7 @@ export function resolveResumeTarget(
242
250
  tasks: ReadonlyMap<string, WorkflowTask>,
243
251
  ):
244
252
  | undefined
245
- | { ok: true; runId: string; journalPath: string; scriptPath: string }
253
+ | { ok: true; runId: string; journalPath: string; scriptPath: string; args: unknown; defaultAgentType: string; defaultAgentTypeExplicit: boolean }
246
254
  | { ok: false; message: string } {
247
255
  const id = runId?.trim();
248
256
  if (id === undefined || id === "") return undefined;
@@ -275,6 +283,9 @@ export function resolveResumeTarget(
275
283
  // The persisted copy, which is what `scriptPath` holds when the call had
276
284
  // no file of its own.
277
285
  scriptPath: prior.scriptPath ?? "",
286
+ args: prior.args,
287
+ defaultAgentType: prior.defaultAgentType,
288
+ defaultAgentTypeExplicit: prior.defaultAgentTypeExplicit,
278
289
  };
279
290
  }
280
291
 
@@ -295,7 +306,7 @@ export function formatWorkflowNotification(task: WorkflowTask, now = Date.now())
295
306
  `<summary>Workflow "${escapeXml(task.workflowName ?? task.id)}" ${task.status} — ${totals.done}/${totals.total} agents${
296
307
  task.replayedCount > 0 ? `, ${task.replayedCount} replayed from ${escapeXml(task.resumedFrom ?? "an earlier run")}` : ""
297
308
  }</summary>`,
298
- `<result>${escapeXml(result.length > 4000 ? `${result.slice(0, 4000)}\n...(truncated)` : result)}</result>`,
309
+ `<result>${escapeXml(result)}</result>`,
299
310
  `<usage><total_tokens>${task.totalTokens}</total_tokens><tool_uses>${task.totalToolCalls}</tool_uses><duration_ms>${elapsedMs(task, now)}</duration_ms></usage>`,
300
311
  `</task-notification>`,
301
312
  ].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.
@@ -58,7 +63,7 @@ Common single-phase workflows you can chain across turns:
58
63
 
59
64
  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.
60
65
 
61
- 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.
66
+ 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.
62
67
 
63
68
  Every script must begin with \`export const meta = {...}\`:
64
69
  export const meta = {
@@ -77,13 +82,13 @@ Every script must begin with \`export const meta = {...}\`:
77
82
  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.
78
83
 
79
84
  Script body hooks:
80
- - 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:
85
+ - 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:
81
86
  {{typeList}}
82
87
  - 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.
83
88
  - 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.
84
89
  - log(message: string): void — emit a progress message to the user (shown as a narrator line above the progress tree)
85
90
  - phase(title: string): void — start a new phase; subsequent agent() calls are grouped under this title in the progress display
86
- - 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.
91
+ - 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.
87
92
  - 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.
88
93
  - 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.
89
94
 
@@ -197,4 +202,4 @@ Use this tool for multi-step orchestration where control flow should be determin
197
202
 
198
203
  ## Resume
199
204
 
200
- 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.`;
205
+ 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.`;