@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
@@ -34,14 +37,16 @@
34
37
 
35
38
  import { existsSync } from "node:fs";
36
39
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
37
- import type { AgentManager } from "../agent-manager.js";
38
- import { getAgentConfig, resolveSpawnType } from "../agent-types.js";
39
- import { resolveModel } from "../model-resolver.js";
40
- import { checkModelScope } from "../model-scope.js";
41
- import type { AgentRecord, ThinkingLevel } from "../types.js";
42
- import { getLifetimeTotal } from "../usage.js";
43
- import type { WorkflowGateResult, WorkflowHost, WorkflowSpawnResult } from "./runtime.js";
44
- import { resolveWorkflowSource } from "./saved.js";
40
+ import type { AgentManager } from "../agent-manager.ts";
41
+ import { getAgentConfig, resolveSpawnType } from "../agent-types.ts";
42
+ import { isForceMainModel } from "../force-main-model.ts";
43
+ import { resolveAgentInvocationConfig, resolvePinnedModel } from "../invocation-config.ts";
44
+ import { resolveModel } from "../model-resolver.ts";
45
+ import { checkModelScope } from "../model-scope.ts";
46
+ import type { AgentRecord, ThinkingLevel } from "../types.ts";
47
+ import { getLifetimeTotal } from "../usage.ts";
48
+ import type { WorkflowGateResult, WorkflowHost, WorkflowSpawnResult } from "./runtime.ts";
49
+ import { resolveWorkflowSource } from "./saved.ts";
45
50
 
46
51
  /**
47
52
  * Wall-clock bound on a `gate` command. Generous — a gate is routinely a test
@@ -88,6 +93,25 @@ function childCwd(record: AgentRecord): string | undefined {
88
93
  return path !== undefined && existsSync(path) ? path : undefined;
89
94
  }
90
95
 
96
+ /**
97
+ * What the script sees when it named a role with no model pin and passed no
98
+ * model of its own.
99
+ *
100
+ * Deliberately actionable rather than a bare refusal: the script is told the
101
+ * three ways out — name a pinned role, pass a model, or deliberately twin the
102
+ * main model — because the one thing this host will not do is inherit the
103
+ * parent's model silently.
104
+ */
105
+ function missingModelMessage(agentType: string): string {
106
+ return `No model for agent "${agentType}": its definition pins none and nothing named one. `
107
+ + "Pin a model in the role's file, pass `{ model: \"<provider/id>\" }` to `agent()`, "
108
+ + "or select `general-purpose` to deliberately use the main model. "
109
+ + "task/explore never inherit the parent implicitly, even when explicitly selected; "
110
+ + "other explicitly selected unpinned roles may do so. "
111
+ + "A role reached only through the workflow default must be pinned, so a default cannot "
112
+ + "silently run the parent's model; `/subagents off` runs the main model deliberately.";
113
+ }
114
+
91
115
  /**
92
116
  * Whether a settled child succeeded — the same condition {@link toSpawnResult}
93
117
  * turns into `ok`. The pre-cleanup hook receives the computed terminal status
@@ -157,6 +181,12 @@ function toSpawnResult(record: AgentRecord): WorkflowSpawnResult {
157
181
  const GATE_SHELL: readonly [string, string] =
158
182
  process.platform === "win32" ? ["cmd", "/c"] : ["sh", "-c"];
159
183
 
184
+ /**
185
+ * The documented parent twin: its definition IS the main model, so choosing it
186
+ * is choosing that model — in any position, default or explicit.
187
+ */
188
+ const PARENT_TWIN_TYPE = "general-purpose";
189
+
160
190
  export function createWorkflowHost(deps: WorkflowHostOptions): WorkflowHost {
161
191
  const { pi, ctx, manager } = deps;
162
192
  /** Runtime agent id → the manager record it spawned. Never pruned mid-run. */
@@ -195,20 +225,80 @@ export function createWorkflowHost(deps: WorkflowHostOptions): WorkflowHost {
195
225
  return {
196
226
  async spawnAgent(request) {
197
227
  const dispatch = resolveSpawnType(request.agentType);
198
- if (!dispatch.ok) return { ok: false, error: dispatch.message };
228
+ // `fatal`, because the role never came into existence: the compiled
229
+ // workflow default is `task`, a fresh install has no such user agent, and
230
+ // a `null` per call would let a whole fan-out of nonexistent roles read as
231
+ // completed work. A configured fallback can resolve a requested role;
232
+ // the workflow-specific safety check below still guards default choices.
233
+ if (!dispatch.ok) return { ok: false, fatal: true, error: dispatch.message };
234
+
235
+ const twinForced = isForceMainModel();
236
+ const requestedRole = request.agentType.trim().toLowerCase();
237
+ const economicalRequest = requestedRole === "task" || requestedRole === "explore";
238
+ if (!twinForced && dispatch.fellBackFrom !== undefined && (request.agentTypeExplicit !== true || economicalRequest)) {
239
+ return {
240
+ ok: false,
241
+ fatal: true,
242
+ error: `Workflow role "${request.agentType}" is unavailable; refusing fallback to "${dispatch.type}". Configure an available workflow default or explicitly select another agentType.`,
243
+ };
244
+ }
199
245
 
200
- // Same precedence as the Agent tool: the caller's model wins, the agent
201
- // definition's is next, and the parent's is the floor. A model the script
202
- // named and we cannot resolve is an error; one the definition named falls
203
- // back to the parent silently, because the script never asked for it.
204
- let model = ctx.model;
205
246
  const config = getAgentConfig(dispatch.type);
206
- const modelInput = request.model ?? config?.model;
207
- if (modelInput !== undefined) {
208
- const resolved = resolveModel(modelInput, ctx.modelRegistry);
209
- if (typeof resolved === "string") {
210
- if (request.model !== undefined) return { ok: false, error: resolved };
247
+ // Same precedence as the Agent tool: the agent definition's model and
248
+ // thinking pins are authoritative and the call's values are what gets
249
+ // recorded as *requested* when a pin outranked them. `/subagents off`
250
+ // skips the whole model resolution below, and this only computes what
251
+ // would otherwise have been asked for.
252
+ const invocation = resolveAgentInvocationConfig(config, {
253
+ model: request.model,
254
+ thinking: request.effort,
255
+ });
256
+
257
+ // `/subagents off` is an intentional main-model twin: pins, caller
258
+ // overrides and the scope check all give way, because the child runs the
259
+ // model the session already runs. Everything below is the deliberate
260
+ // alternative — never a silent parent substitution.
261
+ /** The model this child is authorized to run on. */
262
+ let model = ctx.model;
263
+ if (!twinForced) {
264
+ if (invocation.modelInput === undefined) {
265
+ // No pin and no model on the call. The parent model is an answer only
266
+ // when the call or run explicitly chose this non-economical role,
267
+ // or when the role IS the parent twin: selecting an
268
+ // unpinned role is the Agent tool's "caller or parent" case. A role
269
+ // reached only through the run/setting default is not, and inheriting
270
+ // there is exactly the silent premium fan-out this refusal stops.
271
+ const role = dispatch.type.toLowerCase();
272
+ const economicalRole = role === "task" || role === "explore";
273
+ const twinChosen = !economicalRole && (
274
+ request.agentTypeExplicit === true ||
275
+ role === PARENT_TWIN_TYPE
276
+ );
277
+ if (!twinChosen) {
278
+ return { ok: false, fatal: true, error: missingModelMessage(dispatch.type) };
279
+ }
280
+ // Explicit twin: `model` stays the parent's.
211
281
  } else {
282
+ // Pins are strict, built-in defaults included: `resolvePinnedModel` is
283
+ // called without `isBuiltInDefault`/`parentModel`, so an unavailable
284
+ // pin returns an error string rather than a parent-model substitute.
285
+ // A caller-named model keeps `resolveModel`'s fuzzy policy.
286
+ const resolved = invocation.modelFromParams
287
+ ? resolveModel(invocation.modelInput, ctx.modelRegistry)
288
+ : resolvePinnedModel(invocation.modelInput, ctx.modelRegistry);
289
+ if (typeof resolved === "string") {
290
+ // A configuration failure for the same reason as a missing pin: the
291
+ // fix (change the pin/file, or name a model that exists) is the
292
+ // same for every sibling, and `fatal` makes the run say so instead
293
+ // of handing the script a `null` it may mistake for a result.
294
+ return {
295
+ ok: false,
296
+ fatal: true,
297
+ error: invocation.modelFromParams
298
+ ? resolved
299
+ : `Cannot start agent "${dispatch.type}" with model pin "${invocation.modelInput}". ${resolved}`,
300
+ };
301
+ }
212
302
  model = resolved;
213
303
  }
214
304
  }
@@ -216,27 +306,49 @@ export function createWorkflowHost(deps: WorkflowHostOptions): WorkflowHost {
216
306
  // Same scopeModels policy as the Agent tool and the nested delegation
217
307
  // tools: a script's `agent({ model })` is a runtime LLM choice, and the
218
308
  // script is written by the model, so it must not reach a model the user's
219
- // enabledModels list excludes. `callerSupplied` keys off `request.model`
220
- // and NOT `modelInput` — the latter has already absorbed the agent file's
221
- // own `model:`, which is user-authored config and so earns the
222
- // warn-and-proceed branch rather than a refusal.
223
- const scopeVerdict = checkModelScope({
224
- model,
225
- cwd: ctx.cwd,
226
- modelRegistry: ctx.modelRegistry,
227
- callerSupplied: request.model !== undefined,
228
- agentLabel: config?.displayName ?? dispatch.type,
229
- modelInput,
230
- });
231
- // This agent's failure, not the run's — the same shape a bad agent type
232
- // takes above. The script sees `null` and its siblings carry on, which is
233
- // the difference between one refused model and a discarded fan-out.
234
- if (scopeVerdict.kind === "error") return { ok: false, error: scopeVerdict.message };
235
- if (scopeVerdict.kind === "warn" && !warnedScopeMessages.has(scopeVerdict.message)) {
236
- warnedScopeMessages.add(scopeVerdict.message);
237
- ctx.ui.notify(scopeVerdict.message, "warning");
309
+ // enabledModels list excludes. `callerSupplied` keys off
310
+ // `modelFromParams`, not `request.model`: a caller option the agent file's
311
+ // pin outranked never took effect, so it must not turn the pin into a hard
312
+ // refusal. Nor off `modelInput`, which has already absorbed the pin itself
313
+ // — user-authored config, and so the warn-and-proceed branch.
314
+ if (!twinForced) {
315
+ const scopeVerdict = checkModelScope({
316
+ model,
317
+ cwd: ctx.cwd,
318
+ modelRegistry: ctx.modelRegistry,
319
+ callerSupplied: invocation.modelFromParams,
320
+ agentLabel: config?.displayName ?? dispatch.type,
321
+ modelInput: invocation.modelInput,
322
+ });
323
+ // Scope refusal stays local to this agent. Unlike a missing role/model,
324
+ // the script sees `null` and its siblings carry on, which is
325
+ // the difference between one refused model and a discarded fan-out.
326
+ if (scopeVerdict.kind === "error") return { ok: false, error: scopeVerdict.message };
327
+ if (scopeVerdict.kind === "warn" && !warnedScopeMessages.has(scopeVerdict.message)) {
328
+ warnedScopeMessages.add(scopeVerdict.message);
329
+ ctx.ui.notify(scopeVerdict.message, "warning");
330
+ }
238
331
  }
239
332
 
333
+ /**
334
+ * The caller's `model` spelling, kept only when it names a DIFFERENT model
335
+ * than the pin that won — the workflow half of #182.
336
+ *
337
+ * `request.model` alone is not enough: a pin of `anthropic/claude-opus-4-6`
338
+ * outranks a caller's `"opus"`, and fuzzy model input means the two spell
339
+ * the same model. Comparing the strings would disclose an override that
340
+ * never happened, so the caller's spelling is resolved and compared by
341
+ * provider/id, exactly as the Agent tool does. A spelling that resolves to
342
+ * nothing is still disclosed: it cannot have taken effect.
343
+ */
344
+ const askedModel = (() => {
345
+ const asked = request.model;
346
+ if (asked === undefined || invocation.modelFromParams || twinForced) return undefined;
347
+ const resolvedAsked = resolveModel(asked, ctx.modelRegistry);
348
+ if (typeof resolvedAsked === "string") return asked;
349
+ return resolvedAsked.provider === model?.provider && resolvedAsked.id === model?.id ? undefined : asked;
350
+ })();
351
+
240
352
  /**
241
353
  * The gate's verdict, set only if the hook below actually ran the command.
242
354
  * Its presence is what stops the runtime running the gate a second time,
@@ -307,23 +419,27 @@ export function createWorkflowHost(deps: WorkflowHostOptions): WorkflowHost {
307
419
  // never queued behind it.
308
420
  ...(deps.workflowId !== undefined ? { workflowId: deps.workflowId } : {}),
309
421
  ...(model !== undefined ? { model } : {}),
310
- // Validated worker-side against the same list pi accepts, so the
311
- // cast asserts what the boundary has already checked. Left unset,
312
- // the agent definition's `thinking` (then the parent's) still wins —
313
- // same precedence as `model` above.
314
- ...(request.effort !== undefined ? { thinkingLevel: request.effort as ThinkingLevel } : {}),
315
- // Seeded with the REQUEST, not the outcome. The manager overwrites
316
- // the effective half at session creation; without a seed there is
317
- // nothing for it to compare against, so a level pi clamped would be
318
- // indistinguishable from one that was honoured.
422
+ // The EFFECTIVE level, so an agent definition's `thinking` pin
423
+ // outranks the call's `effort` here exactly as it does for `model`
424
+ // above. Validated worker-side against the same list pi accepts,
425
+ // which is what the cast asserts.
426
+ ...(invocation.thinking !== undefined ? { thinkingLevel: invocation.thinking } : {}),
427
+ // Seeded with the REQUESTED values, not the outcome. The manager
428
+ // overwrites the effective half at session creation; without a seed
429
+ // there is nothing for it to compare against, so a level pi clamped
430
+ // would be indistinguishable from one that was honoured (#182).
319
431
  //
320
- // Only the level. #182's other half — a caller parameter an agent
321
- // file outranked — cannot arise here: this path resolves
322
- // `request.model ?? config?.model`, so the script always wins and
323
- // therefore always got what it asked for. Seeding a `requestedModel`
324
- // would describe a precedence this path does not have.
432
+ // Both halves matter now that the role pin outranks the call: a
433
+ // caller `effort` the pin replaced is seeded as `thinking` so the
434
+ // manager records it as `requestedThinking` once the session
435
+ // reports the pin's level, and a caller `model` the pin replaced is
436
+ // seeded as `requestedModel` so the row can say "(asked X)".
437
+ // `askedModel` is undefined when the caller asked for what the pin
438
+ // resolves to (fuzzy spellings included), so nothing is disclosed
439
+ // that was in fact honored.
325
440
  invocation: {
326
441
  ...(request.effort !== undefined ? { thinking: request.effort as ThinkingLevel } : {}),
442
+ ...(askedModel !== undefined ? { requestedModel: askedModel } : {}),
327
443
  },
328
444
  // Fires once the child's session exists, which is where the model
329
445
  // and the clamped thinking level first become knowable.
@@ -374,6 +490,10 @@ export function createWorkflowHost(deps: WorkflowHostOptions): WorkflowHost {
374
490
  error: `Agent ${id} has no session left to resume — records are dropped ten minutes after they finish.`,
375
491
  };
376
492
  }
493
+ // Deliberately no model or thinking resolution here: resume continues the
494
+ // session the child already has, model included, so a pin that has since
495
+ // become unavailable must not refuse the continuation or substitute
496
+ // another model underneath it.
377
497
  // The resumed row is built from scratch, so it has to be told the same
378
498
  // thing the first one was — the child's session already exists, so this is
379
499
  // simply read back rather than waited for. The id goes first for the same
@@ -40,12 +40,14 @@
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
 
47
49
  import { createHash } from "node:crypto";
48
- import { appendFileSync, readFileSync } from "node:fs";
50
+ import { appendFile, readFile } from "node:fs/promises";
49
51
 
50
52
  /** One settled agent call, as replayed. */
51
53
  export interface WorkflowJournalEntry {
@@ -81,6 +83,8 @@ export interface JournalKeyInput {
81
83
  label?: string;
82
84
  model?: string;
83
85
  agentType?: string;
86
+ /** Explicit/default selection changes the host's model/fallback authorization. */
87
+ agentTypeExplicit?: boolean;
84
88
  effort?: string;
85
89
  isolation?: string;
86
90
  gate?: string;
@@ -89,9 +93,9 @@ export interface JournalKeyInput {
89
93
  schema?: string;
90
94
  }
91
95
 
92
- /** Stable hash of a call's payload. Field order is fixed here, not by the caller. */
93
- export function journalKey(input: JournalKeyInput): string {
94
- const canonical = JSON.stringify([
96
+ /** Stable hash of a call's payload; legacy keys remain readable without re-paying. */
97
+ export function journalKey(input: JournalKeyInput, format: "current" | "legacy" = "current"): string {
98
+ const fields: (string | boolean | null)[] = [
95
99
  input.prompt,
96
100
  input.label ?? null,
97
101
  input.model ?? null,
@@ -100,14 +104,15 @@ export function journalKey(input: JournalKeyInput): string {
100
104
  input.isolation ?? null,
101
105
  input.gate ?? null,
102
106
  input.resume ?? null,
103
- // Appended only when present, which looks like a hack and is not: adding a
104
- // ninth slot unconditionally would change the canonical form of every entry
105
- // and invalidate every journal already on disk. Conditional, a schema-less
106
- // call keys exactly as it always did, and adding or changing a schema still
107
- // produces a different key.
108
- ...(input.schema !== undefined ? [input.schema] : []),
109
- ]);
110
- return createHash("sha256").update(canonical).digest("hex").slice(0, 32);
107
+ ];
108
+ if (format === "legacy") {
109
+ // Old schema-less keys have eight slots, not a ninth null. Preserve that
110
+ // shape so an upgrade does not silently turn a cache hit into paid work.
111
+ if (input.schema !== undefined) fields.push(input.schema);
112
+ } else {
113
+ fields.push(input.schema ?? null, input.agentTypeExplicit === true);
114
+ }
115
+ return createHash("sha256").update(JSON.stringify(fields)).digest("hex").slice(0, 32);
111
116
  }
112
117
 
113
118
  /**
@@ -116,38 +121,90 @@ export function journalKey(input: JournalKeyInput): string {
116
121
  * Never throws: a missing, truncated or hand-mangled journal means "nothing to
117
122
  * replay", which costs tokens. Refusing to run would cost the whole run.
118
123
  * A partial last line is normal — the file is appended to while agents settle.
124
+ *
125
+ * Asynchronous so a reader never blocks the host, and ordered behind any
126
+ * appends already accepted for the same path: an immediate resume sees every
127
+ * record the run before it flushed. A large journal yields between chunks
128
+ * rather than blocking the event loop for the whole parse.
119
129
  */
120
- export function readJournal(path: string): WorkflowJournalEntry[] {
130
+ export async function readJournal(path: string): Promise<WorkflowJournalEntry[]> {
131
+ const pending = pendingAppends.get(path);
132
+ if (pending !== undefined) await pending;
133
+
121
134
  let raw: string;
122
135
  try {
123
- raw = readFileSync(path, "utf-8");
136
+ raw = await readFile(path, "utf-8");
124
137
  } catch {
125
138
  return [];
126
139
  }
127
140
 
128
141
  const entries: WorkflowJournalEntry[] = [];
129
- for (const line of raw.split("\n")) {
142
+ let lineStart = 0;
143
+ let records = 0;
144
+ while (lineStart < raw.length) {
145
+ const newline = raw.indexOf("\n", lineStart);
146
+ const lineEnd = newline === -1 ? raw.length : newline;
147
+ const line = raw.slice(lineStart, lineEnd);
148
+ lineStart = newline === -1 ? raw.length : newline + 1;
130
149
  if (line.trim() === "") continue;
131
150
  try {
132
151
  const parsed = JSON.parse(line) as unknown;
133
- if (!isEntry(parsed)) continue;
134
- entries.push(parsed);
152
+ if (isEntry(parsed)) entries.push(parsed);
135
153
  } catch {
136
154
  // A half-written final line, or someone editing the file. Skipping it
137
155
  // keeps what came before, and a shorter prefix is still a useful one.
138
156
  }
157
+ records++;
158
+ if (records % 512 === 0) {
159
+ await new Promise<void>(resolve => {
160
+ setImmediate(resolve);
161
+ });
162
+ }
139
163
  }
140
164
  entries.sort((a, b) => a.index - b.index);
141
165
  return entries;
142
166
  }
143
167
 
144
- /** Append one settled call. Failure to write is not failure to run. */
145
- export function appendJournal(path: string, entry: WorkflowJournalEntry): void {
168
+ /**
169
+ * The tail of each path's append chain.
170
+ *
171
+ * One path is written by one chain: two agents settling at the same moment
172
+ * must not interleave partial lines, and `readJournal` has something concrete
173
+ * to await. Kept per path so unrelated runs never serialize each other.
174
+ */
175
+ const pendingAppends = new Map<string, Promise<void>>();
176
+
177
+ /**
178
+ * Append one settled call. Failure to write is not failure to run.
179
+ *
180
+ * The entry is serialized before this function returns, so a caller that
181
+ * reuses or mutates its object afterwards cannot change what lands on disk.
182
+ * Writes are chained per path and a failed write is swallowed before the next
183
+ * record, so one unwritable entry does not drop the records after it.
184
+ */
185
+ export function appendJournal(path: string, entry: WorkflowJournalEntry): Promise<void> {
186
+ let line: string;
146
187
  try {
147
- appendFileSync(path, `${JSON.stringify(entry)}\n`, "utf-8");
188
+ line = `${JSON.stringify(entry)}\n`;
148
189
  } catch {
149
- // A journal that cannot be written costs a future resume, nothing more.
190
+ // An entry that cannot be represented as JSON is one resume record lost,
191
+ // not a failed agent: the run keeps going and reports its own result.
192
+ return Promise.resolve();
150
193
  }
194
+
195
+ const previous = pendingAppends.get(path) ?? Promise.resolve();
196
+ const write = previous.then(async () => {
197
+ try {
198
+ await appendFile(path, line, "utf-8");
199
+ } catch {
200
+ // A journal that cannot be written costs a future resume, nothing more.
201
+ }
202
+ });
203
+ pendingAppends.set(path, write);
204
+ void write.then(() => {
205
+ if (pendingAppends.get(path) === write) pendingAppends.delete(path);
206
+ });
207
+ return write;
151
208
  }
152
209
 
153
210
  function isEntry(value: unknown): value is WorkflowJournalEntry {
@@ -20,7 +20,7 @@
20
20
  * unit-testable without a terminal.
21
21
  */
22
22
 
23
- import type { WorkflowMeta, WorkflowPhaseMeta } from "./meta.js";
23
+ import type { WorkflowMeta, WorkflowPhaseMeta } from "./meta.ts";
24
24
 
25
25
  /** Raw entry lifecycle, as written by the runtime. */
26
26
  export type WorkflowEntryState = "start" | "progress" | "done" | "error";