@timmyjl12/pi-subagents 0.20.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/CHANGELOG.md +862 -827
  2. package/README.md +1125 -1080
  3. package/dist/active-agents-prompt.d.ts +31 -9
  4. package/dist/active-agents-prompt.js +73 -9
  5. package/dist/agent-color.js +9 -1
  6. package/dist/agent-file-toggle.d.ts +1 -1
  7. package/dist/agent-manager.d.ts +405 -18
  8. package/dist/agent-manager.js +1661 -131
  9. package/dist/agent-runner.d.ts +45 -6
  10. package/dist/agent-runner.js +109 -18
  11. package/dist/agent-types.d.ts +30 -7
  12. package/dist/agent-types.js +38 -9
  13. package/dist/awaited-result.d.ts +37 -0
  14. package/dist/awaited-result.js +150 -0
  15. package/dist/child-session-shutdown.d.ts +19 -1
  16. package/dist/child-session-shutdown.js +60 -11
  17. package/dist/cleanup-plans.d.ts +10 -0
  18. package/dist/cleanup-plans.js +112 -0
  19. package/dist/cross-extension-rpc.d.ts +8 -1
  20. package/dist/cross-extension-rpc.js +59 -5
  21. package/dist/custom-agents.d.ts +34 -9
  22. package/dist/custom-agents.js +308 -111
  23. package/dist/default-agents.d.ts +1 -1
  24. package/dist/env.d.ts +1 -1
  25. package/dist/error-log.d.ts +6 -0
  26. package/dist/error-log.js +8 -0
  27. package/dist/force-main-model.d.ts +21 -0
  28. package/dist/force-main-model.js +28 -0
  29. package/dist/goal-bridge.d.ts +155 -0
  30. package/dist/goal-bridge.js +305 -0
  31. package/dist/group-join.d.ts +5 -1
  32. package/dist/group-join.js +52 -7
  33. package/dist/index.d.ts +5 -5
  34. package/dist/index.js +2827 -333
  35. package/dist/invocation-config.d.ts +30 -3
  36. package/dist/invocation-config.js +30 -1
  37. package/dist/memory.d.ts +1 -1
  38. package/dist/mention-clone.d.ts +1 -1
  39. package/dist/model-scope.d.ts +1 -1
  40. package/dist/nested-tools.d.ts +22 -1
  41. package/dist/nested-tools.js +120 -26
  42. package/dist/output-file.d.ts +15 -4
  43. package/dist/output-file.js +146 -43
  44. package/dist/prompts.d.ts +1 -1
  45. package/dist/recovery.d.ts +1 -1
  46. package/dist/report-cleanup.d.ts +204 -0
  47. package/dist/report-cleanup.js +1632 -0
  48. package/dist/report-store.d.ts +738 -0
  49. package/dist/report-store.js +3616 -0
  50. package/dist/schedule-store.d.ts +14 -6
  51. package/dist/schedule-store.js +88 -58
  52. package/dist/schedule.d.ts +20 -8
  53. package/dist/schedule.js +135 -74
  54. package/dist/settings.d.ts +39 -11
  55. package/dist/settings.js +22 -5
  56. package/dist/status-note.d.ts +1 -1
  57. package/dist/structured-output.d.ts +1 -1
  58. package/dist/types.d.ts +32 -3
  59. package/dist/ui/agent-mention.d.ts +2 -2
  60. package/dist/ui/agent-widget.d.ts +82 -13
  61. package/dist/ui/agent-widget.js +155 -37
  62. package/dist/ui/cleanup-preview.d.ts +59 -0
  63. package/dist/ui/cleanup-preview.js +466 -0
  64. package/dist/ui/conversation-viewer.d.ts +4 -4
  65. package/dist/ui/conversation-viewer.js +10 -6
  66. package/dist/ui/fleet-list.d.ts +3 -3
  67. package/dist/ui/fleet-list.js +3 -3
  68. package/dist/ui/fleet-overlay.d.ts +37 -6
  69. package/dist/ui/fleet-overlay.js +214 -18
  70. package/dist/ui/hub-feed.d.ts +52 -0
  71. package/dist/ui/hub-feed.js +148 -0
  72. package/dist/ui/native-transcript.js +5 -1
  73. package/dist/ui/schedule-menu.d.ts +1 -1
  74. package/dist/ui/schedule-menu.js +1 -1
  75. package/dist/ui/workflow-card.d.ts +4 -4
  76. package/dist/ui/workflow-dialog.d.ts +4 -4
  77. package/dist/ui/workflow-dialog.js +8 -3
  78. package/dist/ui/workflow-menu.d.ts +2 -2
  79. package/dist/usage.d.ts +12 -0
  80. package/dist/usage.js +28 -1
  81. package/dist/workflow/entry.d.ts +3 -3
  82. package/dist/workflow/host.d.ts +7 -4
  83. package/dist/workflow/host.js +162 -48
  84. package/dist/workflow/journal.d.ts +23 -7
  85. package/dist/workflow/journal.js +80 -23
  86. package/dist/workflow/progress.d.ts +1 -1
  87. package/dist/workflow/runtime.d.ts +45 -6
  88. package/dist/workflow/runtime.js +105 -16
  89. package/dist/workflow/task.d.ts +13 -4
  90. package/dist/workflow/task.js +7 -1
  91. package/dist/workflow/tool-description.d.ts +7 -2
  92. package/dist/workflow/tool-description.js +10 -5
  93. package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
  94. package/docs/artifacts.md +93 -0
  95. package/docs/rpc.md +252 -189
  96. package/docs/runtime-performance.md +53 -0
  97. package/docs/workflows.md +48 -18
  98. package/examples/agent-tool-description.md +2 -2
  99. package/examples/workflows/review-panel.js +6 -3
  100. package/package.json +5 -5
  101. package/src/active-agents-prompt.ts +115 -39
  102. package/src/agent-color.ts +10 -2
  103. package/src/agent-file-toggle.ts +2 -2
  104. package/src/agent-manager.ts +3312 -1601
  105. package/src/agent-runner.ts +164 -36
  106. package/src/agent-types.ts +56 -11
  107. package/src/awaited-result.ts +187 -0
  108. package/src/child-session-shutdown.ts +114 -46
  109. package/src/cleanup-plans.ts +112 -0
  110. package/src/cross-extension-rpc.ts +68 -9
  111. package/src/custom-agents.ts +384 -112
  112. package/src/default-agents.ts +1 -1
  113. package/src/enabled-models.ts +1 -1
  114. package/src/env.ts +1 -1
  115. package/src/error-log.ts +10 -1
  116. package/src/force-main-model.ts +29 -0
  117. package/src/goal-bridge.ts +468 -0
  118. package/src/group-join.ts +56 -9
  119. package/src/index.ts +2987 -349
  120. package/src/invocation-config.ts +50 -4
  121. package/src/memory.ts +1 -1
  122. package/src/mention-clone.ts +3 -3
  123. package/src/model-scope.ts +1 -1
  124. package/src/nested-tools.ts +164 -33
  125. package/src/output-file.ts +168 -46
  126. package/src/prompts.ts +1 -1
  127. package/src/recovery.ts +2 -2
  128. package/src/report-cleanup.ts +2044 -0
  129. package/src/report-store.ts +4133 -0
  130. package/src/schedule-store.ts +244 -201
  131. package/src/schedule.ts +144 -80
  132. package/src/settings.ts +61 -16
  133. package/src/skill-loader.ts +1 -1
  134. package/src/standalone-fallback.ts +2 -2
  135. package/src/status-note.ts +1 -1
  136. package/src/structured-output.ts +1 -1
  137. package/src/types.ts +33 -3
  138. package/src/ui/agent-mention.ts +3 -3
  139. package/src/ui/agent-widget.ts +179 -45
  140. package/src/ui/cleanup-preview.ts +518 -0
  141. package/src/ui/conversation-viewer.ts +19 -15
  142. package/src/ui/fleet-list.ts +7 -7
  143. package/src/ui/fleet-overlay.ts +1048 -847
  144. package/src/ui/hub-feed.ts +179 -0
  145. package/src/ui/native-transcript.ts +7 -3
  146. package/src/ui/schedule-menu.ts +4 -4
  147. package/src/ui/workflow-card.ts +4 -4
  148. package/src/ui/workflow-dialog.ts +10 -6
  149. package/src/ui/workflow-menu.ts +4 -4
  150. package/src/usage.ts +53 -3
  151. package/src/workflow/collisions.ts +1 -1
  152. package/src/workflow/entry.ts +3 -3
  153. package/src/workflow/host.ts +174 -54
  154. package/src/workflow/journal.ts +80 -23
  155. package/src/workflow/progress.ts +1 -1
  156. package/src/workflow/runtime.ts +146 -23
  157. package/src/workflow/saved.ts +3 -3
  158. package/src/workflow/task.ts +18 -7
  159. package/src/workflow/tool-description.ts +10 -5
@@ -16,8 +16,11 @@
16
16
  * on completion: `resume` reaches back to a child that has already
17
17
  * finished.
18
18
  * - **agent type and model.** Resolved through `resolveSpawnType` and
19
- * `getAgentConfig` — the same dispatch the `Agent` tool uses — so a
20
- * workflow and a tool call disagree about nothing.
19
+ * `resolveAgentInvocationConfig` — the same dispatch and the same
20
+ * pin-outranks-call precedence the `Agent` tool uses — so a workflow and a
21
+ * tool call use the same pin precedence. Unresolved pins and unconfigured
22
+ * economical defaults fail rather than inherit the parent's model;
23
+ * deliberately selected twins/custom roles remain supported.
21
24
  * - **failure.** A strict worktree-isolation failure throws out of
22
25
  * `spawnAndWait`; the script must see that as an agent that failed
23
26
  * (`{ok: false}` → `null`), not as an unhandled rejection that takes the
@@ -33,6 +36,8 @@
33
36
  */
34
37
  import { existsSync } from "node:fs";
35
38
  import { getAgentConfig, resolveSpawnType } from "../agent-types.js";
39
+ import { isForceMainModel } from "../force-main-model.js";
40
+ import { resolveAgentInvocationConfig, resolvePinnedModel } from "../invocation-config.js";
36
41
  import { resolveModel } from "../model-resolver.js";
37
42
  import { checkModelScope } from "../model-scope.js";
38
43
  import { getLifetimeTotal } from "../usage.js";
@@ -60,6 +65,24 @@ function childCwd(record) {
60
65
  const path = record.worktree?.path;
61
66
  return path !== undefined && existsSync(path) ? path : undefined;
62
67
  }
68
+ /**
69
+ * What the script sees when it named a role with no model pin and passed no
70
+ * model of its own.
71
+ *
72
+ * Deliberately actionable rather than a bare refusal: the script is told the
73
+ * three ways out — name a pinned role, pass a model, or deliberately twin the
74
+ * main model — because the one thing this host will not do is inherit the
75
+ * parent's model silently.
76
+ */
77
+ function missingModelMessage(agentType) {
78
+ return `No model for agent "${agentType}": its definition pins none and nothing named one. `
79
+ + "Pin a model in the role's file, pass `{ model: \"<provider/id>\" }` to `agent()`, "
80
+ + "or select `general-purpose` to deliberately use the main model. "
81
+ + "task/explore never inherit the parent implicitly, even when explicitly selected; "
82
+ + "other explicitly selected unpinned roles may do so. "
83
+ + "A role reached only through the workflow default must be pinned, so a default cannot "
84
+ + "silently run the parent's model; `/subagents off` runs the main model deliberately.";
85
+ }
63
86
  /**
64
87
  * Whether a settled child succeeded — the same condition {@link toSpawnResult}
65
88
  * turns into `ok`. The pre-cleanup hook receives the computed terminal status
@@ -124,6 +147,11 @@ function toSpawnResult(record) {
124
147
  }
125
148
  /** Shell used to run a `gate` command, mirroring how a user would type it. */
126
149
  const GATE_SHELL = process.platform === "win32" ? ["cmd", "/c"] : ["sh", "-c"];
150
+ /**
151
+ * The documented parent twin: its definition IS the main model, so choosing it
152
+ * is choosing that model — in any position, default or explicit.
153
+ */
154
+ const PARENT_TWIN_TYPE = "general-purpose";
127
155
  export function createWorkflowHost(deps) {
128
156
  const { pi, ctx, manager } = deps;
129
157
  /** Runtime agent id → the manager record it spawned. Never pruned mid-run. */
@@ -160,49 +188,127 @@ export function createWorkflowHost(deps) {
160
188
  return {
161
189
  async spawnAgent(request) {
162
190
  const dispatch = resolveSpawnType(request.agentType);
191
+ // `fatal`, because the role never came into existence: the compiled
192
+ // workflow default is `task`, a fresh install has no such user agent, and
193
+ // a `null` per call would let a whole fan-out of nonexistent roles read as
194
+ // completed work. A configured fallback can resolve a requested role;
195
+ // the workflow-specific safety check below still guards default choices.
163
196
  if (!dispatch.ok)
164
- return { ok: false, error: dispatch.message };
165
- // Same precedence as the Agent tool: the caller's model wins, the agent
166
- // definition's is next, and the parent's is the floor. A model the script
167
- // named and we cannot resolve is an error; one the definition named falls
168
- // back to the parent silently, because the script never asked for it.
169
- let model = ctx.model;
197
+ return { ok: false, fatal: true, error: dispatch.message };
198
+ const twinForced = isForceMainModel();
199
+ const requestedRole = request.agentType.trim().toLowerCase();
200
+ const economicalRequest = requestedRole === "task" || requestedRole === "explore";
201
+ if (!twinForced && dispatch.fellBackFrom !== undefined && (request.agentTypeExplicit !== true || economicalRequest)) {
202
+ return {
203
+ ok: false,
204
+ fatal: true,
205
+ error: `Workflow role "${request.agentType}" is unavailable; refusing fallback to "${dispatch.type}". Configure an available workflow default or explicitly select another agentType.`,
206
+ };
207
+ }
170
208
  const config = getAgentConfig(dispatch.type);
171
- const modelInput = request.model ?? config?.model;
172
- if (modelInput !== undefined) {
173
- const resolved = resolveModel(modelInput, ctx.modelRegistry);
174
- if (typeof resolved === "string") {
175
- if (request.model !== undefined)
176
- return { ok: false, error: resolved };
209
+ // Same precedence as the Agent tool: the agent definition's model and
210
+ // thinking pins are authoritative and the call's values are what gets
211
+ // recorded as *requested* when a pin outranked them. `/subagents off`
212
+ // skips the whole model resolution below, and this only computes what
213
+ // would otherwise have been asked for.
214
+ const invocation = resolveAgentInvocationConfig(config, {
215
+ model: request.model,
216
+ thinking: request.effort,
217
+ });
218
+ // `/subagents off` is an intentional main-model twin: pins, caller
219
+ // overrides and the scope check all give way, because the child runs the
220
+ // model the session already runs. Everything below is the deliberate
221
+ // alternative — never a silent parent substitution.
222
+ /** The model this child is authorized to run on. */
223
+ let model = ctx.model;
224
+ if (!twinForced) {
225
+ if (invocation.modelInput === undefined) {
226
+ // No pin and no model on the call. The parent model is an answer only
227
+ // when the call or run explicitly chose this non-economical role,
228
+ // or when the role IS the parent twin: selecting an
229
+ // unpinned role is the Agent tool's "caller or parent" case. A role
230
+ // reached only through the run/setting default is not, and inheriting
231
+ // there is exactly the silent premium fan-out this refusal stops.
232
+ const role = dispatch.type.toLowerCase();
233
+ const economicalRole = role === "task" || role === "explore";
234
+ const twinChosen = !economicalRole && (request.agentTypeExplicit === true ||
235
+ role === PARENT_TWIN_TYPE);
236
+ if (!twinChosen) {
237
+ return { ok: false, fatal: true, error: missingModelMessage(dispatch.type) };
238
+ }
239
+ // Explicit twin: `model` stays the parent's.
177
240
  }
178
241
  else {
242
+ // Pins are strict, built-in defaults included: `resolvePinnedModel` is
243
+ // called without `isBuiltInDefault`/`parentModel`, so an unavailable
244
+ // pin returns an error string rather than a parent-model substitute.
245
+ // A caller-named model keeps `resolveModel`'s fuzzy policy.
246
+ const resolved = invocation.modelFromParams
247
+ ? resolveModel(invocation.modelInput, ctx.modelRegistry)
248
+ : resolvePinnedModel(invocation.modelInput, ctx.modelRegistry);
249
+ if (typeof resolved === "string") {
250
+ // A configuration failure for the same reason as a missing pin: the
251
+ // fix (change the pin/file, or name a model that exists) is the
252
+ // same for every sibling, and `fatal` makes the run say so instead
253
+ // of handing the script a `null` it may mistake for a result.
254
+ return {
255
+ ok: false,
256
+ fatal: true,
257
+ error: invocation.modelFromParams
258
+ ? resolved
259
+ : `Cannot start agent "${dispatch.type}" with model pin "${invocation.modelInput}". ${resolved}`,
260
+ };
261
+ }
179
262
  model = resolved;
180
263
  }
181
264
  }
182
265
  // Same scopeModels policy as the Agent tool and the nested delegation
183
266
  // tools: a script's `agent({ model })` is a runtime LLM choice, and the
184
267
  // script is written by the model, so it must not reach a model the user's
185
- // enabledModels list excludes. `callerSupplied` keys off `request.model`
186
- // and NOT `modelInput` — the latter has already absorbed the agent file's
187
- // own `model:`, which is user-authored config and so earns the
188
- // warn-and-proceed branch rather than a refusal.
189
- const scopeVerdict = checkModelScope({
190
- model,
191
- cwd: ctx.cwd,
192
- modelRegistry: ctx.modelRegistry,
193
- callerSupplied: request.model !== undefined,
194
- agentLabel: config?.displayName ?? dispatch.type,
195
- modelInput,
196
- });
197
- // This agent's failure, not the run's — the same shape a bad agent type
198
- // takes above. The script sees `null` and its siblings carry on, which is
199
- // the difference between one refused model and a discarded fan-out.
200
- if (scopeVerdict.kind === "error")
201
- return { ok: false, error: scopeVerdict.message };
202
- if (scopeVerdict.kind === "warn" && !warnedScopeMessages.has(scopeVerdict.message)) {
203
- warnedScopeMessages.add(scopeVerdict.message);
204
- ctx.ui.notify(scopeVerdict.message, "warning");
268
+ // enabledModels list excludes. `callerSupplied` keys off
269
+ // `modelFromParams`, not `request.model`: a caller option the agent file's
270
+ // pin outranked never took effect, so it must not turn the pin into a hard
271
+ // refusal. Nor off `modelInput`, which has already absorbed the pin itself
272
+ // — user-authored config, and so the warn-and-proceed branch.
273
+ if (!twinForced) {
274
+ const scopeVerdict = checkModelScope({
275
+ model,
276
+ cwd: ctx.cwd,
277
+ modelRegistry: ctx.modelRegistry,
278
+ callerSupplied: invocation.modelFromParams,
279
+ agentLabel: config?.displayName ?? dispatch.type,
280
+ modelInput: invocation.modelInput,
281
+ });
282
+ // Scope refusal stays local to this agent. Unlike a missing role/model,
283
+ // the script sees `null` and its siblings carry on, which is
284
+ // the difference between one refused model and a discarded fan-out.
285
+ if (scopeVerdict.kind === "error")
286
+ return { ok: false, error: scopeVerdict.message };
287
+ if (scopeVerdict.kind === "warn" && !warnedScopeMessages.has(scopeVerdict.message)) {
288
+ warnedScopeMessages.add(scopeVerdict.message);
289
+ ctx.ui.notify(scopeVerdict.message, "warning");
290
+ }
205
291
  }
292
+ /**
293
+ * The caller's `model` spelling, kept only when it names a DIFFERENT model
294
+ * than the pin that won — the workflow half of #182.
295
+ *
296
+ * `request.model` alone is not enough: a pin of `anthropic/claude-opus-4-6`
297
+ * outranks a caller's `"opus"`, and fuzzy model input means the two spell
298
+ * the same model. Comparing the strings would disclose an override that
299
+ * never happened, so the caller's spelling is resolved and compared by
300
+ * provider/id, exactly as the Agent tool does. A spelling that resolves to
301
+ * nothing is still disclosed: it cannot have taken effect.
302
+ */
303
+ const askedModel = (() => {
304
+ const asked = request.model;
305
+ if (asked === undefined || invocation.modelFromParams || twinForced)
306
+ return undefined;
307
+ const resolvedAsked = resolveModel(asked, ctx.modelRegistry);
308
+ if (typeof resolvedAsked === "string")
309
+ return asked;
310
+ return resolvedAsked.provider === model?.provider && resolvedAsked.id === model?.id ? undefined : asked;
311
+ })();
206
312
  /**
207
313
  * The gate's verdict, set only if the hook below actually ran the command.
208
314
  * Its presence is what stops the runtime running the gate a second time,
@@ -269,23 +375,27 @@ export function createWorkflowHost(deps) {
269
375
  // never queued behind it.
270
376
  ...(deps.workflowId !== undefined ? { workflowId: deps.workflowId } : {}),
271
377
  ...(model !== undefined ? { model } : {}),
272
- // Validated worker-side against the same list pi accepts, so the
273
- // cast asserts what the boundary has already checked. Left unset,
274
- // the agent definition's `thinking` (then the parent's) still wins —
275
- // same precedence as `model` above.
276
- ...(request.effort !== undefined ? { thinkingLevel: request.effort } : {}),
277
- // Seeded with the REQUEST, not the outcome. The manager overwrites
278
- // the effective half at session creation; without a seed there is
279
- // nothing for it to compare against, so a level pi clamped would be
280
- // indistinguishable from one that was honoured.
378
+ // The EFFECTIVE level, so an agent definition's `thinking` pin
379
+ // outranks the call's `effort` here exactly as it does for `model`
380
+ // above. Validated worker-side against the same list pi accepts,
381
+ // which is what the cast asserts.
382
+ ...(invocation.thinking !== undefined ? { thinkingLevel: invocation.thinking } : {}),
383
+ // Seeded with the REQUESTED values, not the outcome. The manager
384
+ // overwrites the effective half at session creation; without a seed
385
+ // there is nothing for it to compare against, so a level pi clamped
386
+ // would be indistinguishable from one that was honoured (#182).
281
387
  //
282
- // Only the level. #182's other half — a caller parameter an agent
283
- // file outranked — cannot arise here: this path resolves
284
- // `request.model ?? config?.model`, so the script always wins and
285
- // therefore always got what it asked for. Seeding a `requestedModel`
286
- // would describe a precedence this path does not have.
388
+ // Both halves matter now that the role pin outranks the call: a
389
+ // caller `effort` the pin replaced is seeded as `thinking` so the
390
+ // manager records it as `requestedThinking` once the session
391
+ // reports the pin's level, and a caller `model` the pin replaced is
392
+ // seeded as `requestedModel` so the row can say "(asked X)".
393
+ // `askedModel` is undefined when the caller asked for what the pin
394
+ // resolves to (fuzzy spellings included), so nothing is disclosed
395
+ // that was in fact honored.
287
396
  invocation: {
288
397
  ...(request.effort !== undefined ? { thinking: request.effort } : {}),
398
+ ...(askedModel !== undefined ? { requestedModel: askedModel } : {}),
289
399
  },
290
400
  // Fires once the child's session exists, which is where the model
291
401
  // and the clamped thinking level first become knowable.
@@ -334,6 +444,10 @@ export function createWorkflowHost(deps) {
334
444
  error: `Agent ${id} has no session left to resume — records are dropped ten minutes after they finish.`,
335
445
  };
336
446
  }
447
+ // Deliberately no model or thinking resolution here: resume continues the
448
+ // session the child already has, model included, so a pin that has since
449
+ // become unavailable must not refuse the continuation or substitute
450
+ // another model underneath it.
337
451
  // The resumed row is built from scratch, so it has to be told the same
338
452
  // thing the first one was — the child's session already exists, so this is
339
453
  // simply read back rather than waited for. The id goes first for the same
@@ -40,8 +40,10 @@
40
40
  * the key is checked as well as the position: a run that interleaves
41
41
  * differently loses cache hits, it never returns another agent's answer.
42
42
  *
43
- * The file is JSON Lines, appended as each agent settles, so a run that is
44
- * killed mid-flight still leaves everything it had finished.
43
+ * The file is JSON Lines, appended as each agent settles and flushed before
44
+ * the run reports completion or cancellation, so an orderly stop leaves
45
+ * everything it had finished. A hard process kill can lose records still
46
+ * queued for the disk — nothing can flush those.
45
47
  */
46
48
  /** One settled agent call, as replayed. */
47
49
  export interface WorkflowJournalEntry {
@@ -76,6 +78,8 @@ export interface JournalKeyInput {
76
78
  label?: string;
77
79
  model?: string;
78
80
  agentType?: string;
81
+ /** Explicit/default selection changes the host's model/fallback authorization. */
82
+ agentTypeExplicit?: boolean;
79
83
  effort?: string;
80
84
  isolation?: string;
81
85
  gate?: string;
@@ -83,15 +87,27 @@ export interface JournalKeyInput {
83
87
  /** Serialized `agent({ schema })`, when the call asked for one. */
84
88
  schema?: string;
85
89
  }
86
- /** Stable hash of a call's payload. Field order is fixed here, not by the caller. */
87
- export declare function journalKey(input: JournalKeyInput): string;
90
+ /** Stable hash of a call's payload; legacy keys remain readable without re-paying. */
91
+ export declare function journalKey(input: JournalKeyInput, format?: "current" | "legacy"): string;
88
92
  /**
89
93
  * Read a journal file into position order.
90
94
  *
91
95
  * Never throws: a missing, truncated or hand-mangled journal means "nothing to
92
96
  * replay", which costs tokens. Refusing to run would cost the whole run.
93
97
  * A partial last line is normal — the file is appended to while agents settle.
98
+ *
99
+ * Asynchronous so a reader never blocks the host, and ordered behind any
100
+ * appends already accepted for the same path: an immediate resume sees every
101
+ * record the run before it flushed. A large journal yields between chunks
102
+ * rather than blocking the event loop for the whole parse.
103
+ */
104
+ export declare function readJournal(path: string): Promise<WorkflowJournalEntry[]>;
105
+ /**
106
+ * Append one settled call. Failure to write is not failure to run.
107
+ *
108
+ * The entry is serialized before this function returns, so a caller that
109
+ * reuses or mutates its object afterwards cannot change what lands on disk.
110
+ * Writes are chained per path and a failed write is swallowed before the next
111
+ * record, so one unwritable entry does not drop the records after it.
94
112
  */
95
- export declare function readJournal(path: string): WorkflowJournalEntry[];
96
- /** Append one settled call. Failure to write is not failure to run. */
97
- export declare function appendJournal(path: string, entry: WorkflowJournalEntry): void;
113
+ export declare function appendJournal(path: string, entry: WorkflowJournalEntry): Promise<void>;
@@ -40,14 +40,16 @@
40
40
  * the key is checked as well as the position: a run that interleaves
41
41
  * differently loses cache hits, it never returns another agent's answer.
42
42
  *
43
- * The file is JSON Lines, appended as each agent settles, so a run that is
44
- * killed mid-flight still leaves everything it had finished.
43
+ * The file is JSON Lines, appended as each agent settles and flushed before
44
+ * the run reports completion or cancellation, so an orderly stop leaves
45
+ * everything it had finished. A hard process kill can lose records still
46
+ * queued for the disk — nothing can flush those.
45
47
  */
46
48
  import { createHash } from "node:crypto";
47
- import { appendFileSync, readFileSync } from "node:fs";
48
- /** Stable hash of a call's payload. Field order is fixed here, not by the caller. */
49
- export function journalKey(input) {
50
- const canonical = JSON.stringify([
49
+ import { appendFile, readFile } from "node:fs/promises";
50
+ /** Stable hash of a call's payload; legacy keys remain readable without re-paying. */
51
+ export function journalKey(input, format = "current") {
52
+ const fields = [
51
53
  input.prompt,
52
54
  input.label ?? null,
53
55
  input.model ?? null,
@@ -56,14 +58,17 @@ export function journalKey(input) {
56
58
  input.isolation ?? null,
57
59
  input.gate ?? null,
58
60
  input.resume ?? null,
59
- // Appended only when present, which looks like a hack and is not: adding a
60
- // ninth slot unconditionally would change the canonical form of every entry
61
- // and invalidate every journal already on disk. Conditional, a schema-less
62
- // call keys exactly as it always did, and adding or changing a schema still
63
- // produces a different key.
64
- ...(input.schema !== undefined ? [input.schema] : []),
65
- ]);
66
- return createHash("sha256").update(canonical).digest("hex").slice(0, 32);
61
+ ];
62
+ if (format === "legacy") {
63
+ // Old schema-less keys have eight slots, not a ninth null. Preserve that
64
+ // shape so an upgrade does not silently turn a cache hit into paid work.
65
+ if (input.schema !== undefined)
66
+ fields.push(input.schema);
67
+ }
68
+ else {
69
+ fields.push(input.schema ?? null, input.agentTypeExplicit === true);
70
+ }
71
+ return createHash("sha256").update(JSON.stringify(fields)).digest("hex").slice(0, 32);
67
72
  }
68
73
  /**
69
74
  * Read a journal file into position order.
@@ -71,41 +76,93 @@ export function journalKey(input) {
71
76
  * Never throws: a missing, truncated or hand-mangled journal means "nothing to
72
77
  * replay", which costs tokens. Refusing to run would cost the whole run.
73
78
  * A partial last line is normal — the file is appended to while agents settle.
79
+ *
80
+ * Asynchronous so a reader never blocks the host, and ordered behind any
81
+ * appends already accepted for the same path: an immediate resume sees every
82
+ * record the run before it flushed. A large journal yields between chunks
83
+ * rather than blocking the event loop for the whole parse.
74
84
  */
75
- export function readJournal(path) {
85
+ export async function readJournal(path) {
86
+ const pending = pendingAppends.get(path);
87
+ if (pending !== undefined)
88
+ await pending;
76
89
  let raw;
77
90
  try {
78
- raw = readFileSync(path, "utf-8");
91
+ raw = await readFile(path, "utf-8");
79
92
  }
80
93
  catch {
81
94
  return [];
82
95
  }
83
96
  const entries = [];
84
- for (const line of raw.split("\n")) {
97
+ let lineStart = 0;
98
+ let records = 0;
99
+ while (lineStart < raw.length) {
100
+ const newline = raw.indexOf("\n", lineStart);
101
+ const lineEnd = newline === -1 ? raw.length : newline;
102
+ const line = raw.slice(lineStart, lineEnd);
103
+ lineStart = newline === -1 ? raw.length : newline + 1;
85
104
  if (line.trim() === "")
86
105
  continue;
87
106
  try {
88
107
  const parsed = JSON.parse(line);
89
- if (!isEntry(parsed))
90
- continue;
91
- entries.push(parsed);
108
+ if (isEntry(parsed))
109
+ entries.push(parsed);
92
110
  }
93
111
  catch {
94
112
  // A half-written final line, or someone editing the file. Skipping it
95
113
  // keeps what came before, and a shorter prefix is still a useful one.
96
114
  }
115
+ records++;
116
+ if (records % 512 === 0) {
117
+ await new Promise(resolve => {
118
+ setImmediate(resolve);
119
+ });
120
+ }
97
121
  }
98
122
  entries.sort((a, b) => a.index - b.index);
99
123
  return entries;
100
124
  }
101
- /** Append one settled call. Failure to write is not failure to run. */
125
+ /**
126
+ * The tail of each path's append chain.
127
+ *
128
+ * One path is written by one chain: two agents settling at the same moment
129
+ * must not interleave partial lines, and `readJournal` has something concrete
130
+ * to await. Kept per path so unrelated runs never serialize each other.
131
+ */
132
+ const pendingAppends = new Map();
133
+ /**
134
+ * Append one settled call. Failure to write is not failure to run.
135
+ *
136
+ * The entry is serialized before this function returns, so a caller that
137
+ * reuses or mutates its object afterwards cannot change what lands on disk.
138
+ * Writes are chained per path and a failed write is swallowed before the next
139
+ * record, so one unwritable entry does not drop the records after it.
140
+ */
102
141
  export function appendJournal(path, entry) {
142
+ let line;
103
143
  try {
104
- appendFileSync(path, `${JSON.stringify(entry)}\n`, "utf-8");
144
+ line = `${JSON.stringify(entry)}\n`;
105
145
  }
106
146
  catch {
107
- // A journal that cannot be written costs a future resume, nothing more.
147
+ // An entry that cannot be represented as JSON is one resume record lost,
148
+ // not a failed agent: the run keeps going and reports its own result.
149
+ return Promise.resolve();
108
150
  }
151
+ const previous = pendingAppends.get(path) ?? Promise.resolve();
152
+ const write = previous.then(async () => {
153
+ try {
154
+ await appendFile(path, line, "utf-8");
155
+ }
156
+ catch {
157
+ // A journal that cannot be written costs a future resume, nothing more.
158
+ }
159
+ });
160
+ pendingAppends.set(path, write);
161
+ void write.then(() => {
162
+ if (pendingAppends.get(path) === write)
163
+ pendingAppends.delete(path);
164
+ });
165
+ return write;
109
166
  }
110
167
  function isEntry(value) {
111
168
  if (typeof value !== "object" || value === null)
@@ -19,7 +19,7 @@
19
19
  * Everything in this file is pure and framework-free so the whole model is
20
20
  * unit-testable without a terminal.
21
21
  */
22
- import type { WorkflowMeta, WorkflowPhaseMeta } from "./meta.js";
22
+ import type { WorkflowMeta, WorkflowPhaseMeta } from "./meta.ts";
23
23
  /** Raw entry lifecycle, as written by the runtime. */
24
24
  export type WorkflowEntryState = "start" | "progress" | "done" | "error";
25
25
  /** Derived per-agent state, as rendered. */
@@ -12,12 +12,14 @@
12
12
  * test; a {@link WorkflowHost} stub is a dozen lines. The adapter that binds this
13
13
  * to the real manager lives at the call site.
14
14
  */
15
- import { type WorkflowJournalEntry } from "./journal.js";
16
- import { type CompiledSchema } from "./json-schema.js";
17
- import { type WorkflowMeta } from "./meta.js";
18
- import type { WorkflowEntry } from "./progress.js";
15
+ import { type WorkflowJournalEntry } from "./journal.ts";
16
+ import { type CompiledSchema } from "./json-schema.ts";
17
+ import { type WorkflowMeta } from "./meta.ts";
18
+ import type { WorkflowEntry } from "./progress.ts";
19
19
  /** Matches the `script` field's `maxLength` in the tool schema. */
20
20
  export declare const MAX_SCRIPT_LENGTH = 524288;
21
+ /** Economical workflow role; explicit run and per-call roles take precedence. */
22
+ export declare const DEFAULT_WORKFLOW_AGENT_TYPE = "task";
21
23
  /** Agents one run may schedule, in total. */
22
24
  export declare const WORKFLOW_AGENT_CAP = 1000;
23
25
  /** Items one `parallel()` or `pipeline()` call may take. */
@@ -42,6 +44,12 @@ export interface WorkflowSpawnRequest {
42
44
  prompt: string;
43
45
  label: string;
44
46
  agentType: string;
47
+ /**
48
+ * True when the call's opts.agentType or the run's agentType selected a role.
49
+ * A setting-derived default is not explicit, and a configured generic
50
+ * fallback must not turn that default into an authorized premium request.
51
+ */
52
+ agentTypeExplicit?: boolean;
45
53
  model?: string;
46
54
  /**
47
55
  * Reasoning effort for this child, as one of pi's thinking levels.
@@ -110,6 +118,8 @@ export interface WorkflowSpawnResult {
110
118
  text?: string;
111
119
  /** Why it failed. Present when not `ok`. */
112
120
  error?: string;
121
+ /** Configuration failures must not be swallowed as a null pipeline item. */
122
+ fatal?: boolean;
113
123
  /** The user dismissed it rather than it failing; renders as skipped. */
114
124
  skipped?: boolean;
115
125
  tokens?: number;
@@ -255,6 +265,10 @@ export interface RunWorkflowOptions {
255
265
  /** Full script source, starting with `export const meta = { … }`. */
256
266
  script: string;
257
267
  args?: unknown;
268
+ /** Used only when an agent() call does not name its own role. */
269
+ defaultAgentType?: string;
270
+ /** True when the run's `agentType` named that default — see {@link WorkflowSpawnRequest.agentTypeExplicit}. */
271
+ defaultAgentTypeExplicit?: boolean;
258
272
  host: WorkflowHost;
259
273
  signal?: AbortSignal;
260
274
  /** Fired per batch, not per entry — see the worker's progress batching. */
@@ -288,9 +302,34 @@ export interface RunWorkflowOptions {
288
302
  journal?: {
289
303
  /** A previous run's settled calls, in position order. Empty replays nothing. */
290
304
  entries?: readonly WorkflowJournalEntry[];
291
- /** Called as each call of *this* run settles, so it can be resumed in turn. */
292
- append?(entry: WorkflowJournalEntry): void;
305
+ /**
306
+ * Called as each call of *this* run settles, so it can be resumed in turn.
307
+ *
308
+ * May return a promise. The runtime accepts records synchronously and
309
+ * writes them through one ordered chain, so a slow disk never blocks an
310
+ * agent's response and a failed write never drops the records after it.
311
+ * {@link onJournalDrain} is how a caller waits for that chain: this callback
312
+ * only runs once the record reaches the front of it.
313
+ */
314
+ append?(entry: WorkflowJournalEntry): void | Promise<void>;
293
315
  };
316
+ /**
317
+ * The run's accepted-write drain, handed over before any work starts.
318
+ *
319
+ * Whatever {@link journal.append} is given is queued inside this run first, so
320
+ * a record can be accepted long before the journal module has been handed it
321
+ * — and `readJournal` can only wait for appends it was given. A caller that
322
+ * reads the journal back (a paused run being resumed, a shutdown that must
323
+ * not lose the tail) needs to wait for the *queue*. The handle delivered here
324
+ * resolves once every record accepted so far has settled, and keeps following
325
+ * the queue if a call settles while it is waiting. Nothing accepted is ever
326
+ * dropped, and a failed write is still swallowed rather than failing the wait:
327
+ * this is the same best-effort treatment `append` gets.
328
+ *
329
+ * Called once, before the worker exists. A handle delivered later could miss
330
+ * a call that had already settled for a run nobody had been told about yet.
331
+ */
332
+ onJournalDrain?(drain: () => Promise<void>): void;
294
333
  }
295
334
  export interface WorkflowRunResult {
296
335
  status: "completed" | "failed" | "killed";