@timmyjl12/pi-subagents 0.0.0-stage → 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 (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +40 -0
  9. package/dist/active-agents-prompt.js +98 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +131 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -0,0 +1,477 @@
1
+ /**
2
+ * host.ts — binds a workflow run to the real `AgentManager`.
3
+ *
4
+ * `runtime.ts` deliberately knows nothing about this extension: its only seam is
5
+ * the injected {@link WorkflowHost}, which is what keeps the runtime's tests
6
+ * free of sessions, models and git. This file is the other half of that seam —
7
+ * everything the script can reach through `agent()`, `resume` and `gate` ends up
8
+ * here, and nowhere else.
9
+ *
10
+ * Four mappings carry most of the weight:
11
+ *
12
+ * - **ids.** The runtime hands out its own `wf-agent-N` handles before
13
+ * anything spawns, because it needs a stable progress-entry identity. The
14
+ * manager issues a different id when the child actually starts. `records`
15
+ * is the translation, and it is kept for the whole run rather than cleared
16
+ * on completion: `resume` reaches back to a child that has already
17
+ * finished.
18
+ * - **agent type and model.** Resolved through `resolveSpawnType` and
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.
24
+ * - **failure.** A strict worktree-isolation failure throws out of
25
+ * `spawnAndWait`; the script must see that as an agent that failed
26
+ * (`{ok: false}` → `null`), not as an unhandled rejection that takes the
27
+ * run down.
28
+ * - **when a `gate` runs.** For an isolated child it cannot wait until the
29
+ * spawn resolves: the manager commits the worktree to a branch and deletes
30
+ * the copy inside the child's own settle, so by then the only tree left to
31
+ * run `npm test` in is the main one — which would report on code the child
32
+ * never wrote. So the gate runs from `onBeforeWorktreeCleanup`, inside that
33
+ * settle, and the verdict travels back on the spawn result. `runGate` still
34
+ * exists for a child that had no worktree; the runtime uses whichever of
35
+ * the two happened, never both.
36
+ */
37
+ import { existsSync } from "node:fs";
38
+ import { getAgentConfig, resolveSpawnType } from "../agent-types.js";
39
+ import { isForceMainModel } from "../force-main-model.js";
40
+ import { resolveAgentInvocationConfig, resolvePinnedModel } from "../invocation-config.js";
41
+ import { resolveModel } from "../model-resolver.js";
42
+ import { checkModelScope } from "../model-scope.js";
43
+ import { getLifetimeTotal } from "../usage.js";
44
+ import { resolveWorkflowSource } from "./saved.js";
45
+ /**
46
+ * Wall-clock bound on a `gate` command. Generous — a gate is routinely a test
47
+ * suite — but not unbounded: `pi.exec` reports a timeout as `killed`, and a
48
+ * gate that hangs forever would wedge the agent slot it is holding.
49
+ */
50
+ export const DEFAULT_GATE_TIMEOUT_MS = 10 * 60_000;
51
+ /**
52
+ * Where the child worked, when that directory still exists.
53
+ *
54
+ * The guard is not defensive padding. `cleanupWorktree` commits the child's
55
+ * changes to a branch and *removes* the copy before `spawnAndWait` resolves, so
56
+ * an isolated child's worktree is normally already gone by the time a result is
57
+ * built. That is exactly why a gate cannot wait until here — it runs from
58
+ * `onBeforeWorktreeCleanup` instead — and why this reports nothing rather than
59
+ * a path that no longer exists: handing a stale path to a command would fail
60
+ * every gated worktree agent with a spawn error instead of a test result.
61
+ */
62
+ function childCwd(record) {
63
+ // `path`, not `workPath`: a workflow spawn never passes a cwd, so the manager
64
+ // runs the child at the copied repo's root.
65
+ const path = record.worktree?.path;
66
+ return path !== undefined && existsSync(path) ? path : undefined;
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
+ }
86
+ /**
87
+ * Whether a settled child succeeded — the same condition {@link toSpawnResult}
88
+ * turns into `ok`. The pre-cleanup hook receives the computed terminal status
89
+ * separately because the live record stays running until cleanup finishes.
90
+ */
91
+ function succeeded(record) {
92
+ return record?.status === "completed" || record?.status === "steered";
93
+ }
94
+ /** Translate a settled record into what the script sees. */
95
+ /**
96
+ * The effective-configuration half of a record, in the runtime's pi-free shape.
97
+ *
98
+ * `AgentRecord.invocation` is the one authoritative place for it (#168); this
99
+ * only renames the fields across the boundary. Returns undefined until the
100
+ * child's session has reported a model, which is when any of it is knowable.
101
+ */
102
+ function resolvedInfo(record) {
103
+ const invocation = record?.invocation;
104
+ if (invocation?.modelName === undefined)
105
+ return undefined;
106
+ return {
107
+ modelName: invocation.modelName,
108
+ modelId: invocation.modelId,
109
+ thinking: invocation.thinking,
110
+ requestedThinking: invocation.requestedThinking,
111
+ requestedModel: invocation.requestedModel,
112
+ };
113
+ }
114
+ function toSpawnResult(record) {
115
+ const tokens = getLifetimeTotal(record.lifetimeUsage);
116
+ // Reported separately from `tokens`, which is the lifetime total. The script's
117
+ // `budget` counts *output* tokens, as Claude Code's does — billing the input
118
+ // and cache reads a fan-out re-sends would over-report it by an order of
119
+ // magnitude and make the documented guards useless.
120
+ const outputTokens = record.lifetimeUsage?.output ?? 0;
121
+ const cwd = childCwd(record);
122
+ const common = {
123
+ ...(tokens > 0 ? { tokens } : {}),
124
+ ...(outputTokens > 0 ? { outputTokens } : {}),
125
+ ...(record.toolUses > 0 ? { toolCalls: record.toolUses } : {}),
126
+ ...(cwd !== undefined ? { cwd } : {}),
127
+ };
128
+ if (succeeded(record)) {
129
+ return {
130
+ ...common,
131
+ ok: true,
132
+ // The schema'd payload when there is one: `result` is prose, and for a
133
+ // worktree child it has had the branch note appended, so it would not
134
+ // parse. A child asked for a schema that produced none never reaches
135
+ // here — `runAgent` reports that through `failure`.
136
+ text: record.structuredJson ?? record.result ?? "",
137
+ ...(record.structuredRetried ? { structuredRetried: true } : {}),
138
+ };
139
+ }
140
+ // "stopped" is someone reaching in and stopping this child — /agents, the
141
+ // fleet list, a workflow abort. That is the same thing the workflows dialog's
142
+ // skip action means, so it renders as skipped rather than failed.
143
+ if (record.status === "stopped") {
144
+ return { ...common, ok: false, skipped: true, error: record.error ?? "Stopped." };
145
+ }
146
+ return { ...common, ok: false, error: record.error ?? `Agent ${record.status}.` };
147
+ }
148
+ /** Shell used to run a `gate` command, mirroring how a user would type it. */
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";
155
+ export function createWorkflowHost(deps) {
156
+ const { pi, ctx, manager } = deps;
157
+ /** Runtime agent id → the manager record it spawned. Never pruned mid-run. */
158
+ const records = new Map();
159
+ /**
160
+ * scopeModels warnings already toasted, so a fan-out that pins one
161
+ * out-of-scope agent file raises one notification rather than one per child.
162
+ * Kept for the whole run: the same message is the same warning at agent 200
163
+ * as it was at agent 1.
164
+ */
165
+ const warnedScopeMessages = new Set();
166
+ /**
167
+ * Run a gate command in `cwd`. The only place a gate is executed — `runGate`
168
+ * and the pre-cleanup hook both come through here — so "gate passed" is
169
+ * decided from one behaviour, whichever route the command took.
170
+ */
171
+ async function executeGate(command, cwd) {
172
+ const result = await pi.exec(GATE_SHELL[0], [GATE_SHELL[1], command], {
173
+ cwd,
174
+ timeout: deps.gateTimeoutMs ?? DEFAULT_GATE_TIMEOUT_MS,
175
+ ...(deps.signal !== undefined ? { signal: deps.signal } : {}),
176
+ });
177
+ const output = [result.stdout, result.stderr]
178
+ .map(stream => stream.trim())
179
+ .filter(Boolean)
180
+ .join("\n");
181
+ // `pi.exec` reports a timeout as `killed` with exit code 0, so the code
182
+ // alone would read a killed gate as a passing one.
183
+ if (result.killed) {
184
+ return { ok: false, output: output || `Gate command timed out: ${command}` };
185
+ }
186
+ return { ok: result.code === 0, output };
187
+ }
188
+ return {
189
+ async spawnAgent(request) {
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.
196
+ if (!dispatch.ok)
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
+ }
208
+ const config = getAgentConfig(dispatch.type);
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.
240
+ }
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
+ }
262
+ model = resolved;
263
+ }
264
+ }
265
+ // Same scopeModels policy as the Agent tool and the nested delegation
266
+ // tools: a script's `agent({ model })` is a runtime LLM choice, and the
267
+ // script is written by the model, so it must not reach a model the user's
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
+ }
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
+ })();
312
+ /**
313
+ * The gate's verdict, set only if the hook below actually ran the command.
314
+ * Its presence is what stops the runtime running the gate a second time,
315
+ * so it is set on the failure route too — a gate we tried and could not
316
+ * complete is a failed gate, never an un-run one that then re-runs
317
+ * against the wrong tree.
318
+ */
319
+ let gate;
320
+ let spawnedId;
321
+ /**
322
+ * Hand the child's EFFECTIVE configuration back to the run.
323
+ *
324
+ * `AgentRecord.invocation` is the one authoritative place for it (#168),
325
+ * filled by the manager the moment the child's session exists — which is
326
+ * before this fires, so it is populated by the time we read it. Reading it
327
+ * rather than re-deriving "the session, else the request" is the whole
328
+ * point of that field existing.
329
+ */
330
+ let sessionReady = false;
331
+ const reportResolved = () => {
332
+ // Called from BOTH the session hook and the spawn hook, because their
333
+ // order is not guaranteed: the manager fires `onSpawned` after
334
+ // `runAgent` returns, but `runAgent` decides when its own
335
+ // `onSessionCreated` fires — synchronously, for a stub. Each fires once,
336
+ // so the first call finds a half missing and returns, and the second is
337
+ // the one that reports.
338
+ if (!sessionReady || spawnedId === undefined)
339
+ return;
340
+ const info = resolvedInfo(manager.getRecord(spawnedId));
341
+ if (info !== undefined)
342
+ request.onResolved?.(info);
343
+ };
344
+ const command = request.gate;
345
+ /**
346
+ * Verify the child's work while its worktree still exists.
347
+ *
348
+ * The manager destroys that copy inside the child's own settle, so this
349
+ * is the last (and only) moment at which `npm test` can mean "the code
350
+ * this child just wrote" rather than "whatever is in the main tree".
351
+ */
352
+ const onBeforeWorktreeCleanup = command === undefined
353
+ ? undefined
354
+ : async (worktreePath, terminalStatus) => {
355
+ // The record stays running until worktree cleanup finishes; only
356
+ // the computed outcome tells us whether this child needs a gate.
357
+ const record = spawnedId === undefined ? undefined : manager.getRecord(spawnedId);
358
+ if (!record || record.status === "stopped" || (terminalStatus !== "completed" && terminalStatus !== "steered"))
359
+ return;
360
+ try {
361
+ gate = await executeGate(command, worktreePath);
362
+ }
363
+ catch (error) {
364
+ gate = { ok: false, output: error instanceof Error ? error.message : String(error) };
365
+ }
366
+ };
367
+ try {
368
+ const { record } = await manager.spawnAndWait(pi, ctx, dispatch.type, request.prompt, {
369
+ description: request.label,
370
+ // The stamp is what keeps this child out of the session's
371
+ // `maxConcurrent` pool — see `occupiesPoolSlot`. The run already
372
+ // bounds how many of its agents run at once, and counting them
373
+ // twice would let one fan-out starve everything else the user is
374
+ // doing. No `bypassQueue` needed: an agent outside the pool is
375
+ // never queued behind it.
376
+ ...(deps.workflowId !== undefined ? { workflowId: deps.workflowId } : {}),
377
+ ...(model !== undefined ? { model } : {}),
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).
387
+ //
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.
396
+ invocation: {
397
+ ...(request.effort !== undefined ? { thinking: request.effort } : {}),
398
+ ...(askedModel !== undefined ? { requestedModel: askedModel } : {}),
399
+ },
400
+ // Fires once the child's session exists, which is where the model
401
+ // and the clamped thinking level first become knowable.
402
+ onSessionCreated: () => { sessionReady = true; reportResolved(); },
403
+ ...(request.schema !== undefined ? { structuredOutput: request.schema } : {}),
404
+ ...(request.isolation !== undefined ? { isolation: request.isolation } : {}),
405
+ ...(deps.signal !== undefined ? { signal: deps.signal } : {}),
406
+ ...(deps.rootSessionId !== undefined ? { rootSessionId: deps.rootSessionId } : {}),
407
+ ...(onBeforeWorktreeCleanup !== undefined ? { onBeforeWorktreeCleanup } : {}),
408
+ }, id => {
409
+ spawnedId = id;
410
+ records.set(request.agentId, id);
411
+ // Ahead of `reportResolved`, and not folded into it: that one waits
412
+ // for the child's session so it can name the effective model, while
413
+ // the record id is known here and is what the inspector opens a
414
+ // conversation on. A child that fails before its session resolves
415
+ // would otherwise never be openable at all.
416
+ request.onResolved?.({ recordId: id });
417
+ reportResolved();
418
+ });
419
+ return { ...toSpawnResult(record), ...(gate !== undefined ? { gate } : {}) };
420
+ }
421
+ catch (error) {
422
+ // Strict worktree isolation rejects out of `awaitStartup` — the child
423
+ // never ran. That is this agent's failure, not the run's: the script
424
+ // sees `null` and its siblings carry on.
425
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
426
+ }
427
+ },
428
+ abortAgent(agentId) {
429
+ const id = records.get(agentId);
430
+ // Nothing to abort before the manager has issued an id — the child is
431
+ // still in startup, and the run's own signal reaches it there.
432
+ if (id !== undefined)
433
+ manager.abort(id);
434
+ },
435
+ async resumeAgent(agentId, prompt, onResolved) {
436
+ const id = records.get(agentId);
437
+ if (id === undefined) {
438
+ return { ok: false, error: `Cannot resume "${agentId}" — it never started.` };
439
+ }
440
+ const record = await manager.resume(id, prompt, deps.signal);
441
+ if (record === undefined) {
442
+ return {
443
+ ok: false,
444
+ error: `Agent ${id} has no session left to resume — records are dropped ten minutes after they finish.`,
445
+ };
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.
451
+ // The resumed row is built from scratch, so it has to be told the same
452
+ // thing the first one was — the child's session already exists, so this is
453
+ // simply read back rather than waited for. The id goes first for the same
454
+ // reason it does on the spawn path: it is knowable even when the rest is
455
+ // not.
456
+ onResolved?.({ recordId: id });
457
+ const info = resolvedInfo(record);
458
+ if (info !== undefined)
459
+ onResolved?.(info);
460
+ return toSpawnResult(record);
461
+ },
462
+ /**
463
+ * Resolve a nested `workflow()` reference. The runtime decides whether what
464
+ * comes back is a workflow; this only finds it.
465
+ */
466
+ loadWorkflow(ref) {
467
+ return resolveWorkflowSource(ref, ctx.cwd);
468
+ },
469
+ // Reached only for a gate the spawn did not already run — a child with no
470
+ // worktree of its own, or a host wired without the pre-cleanup hook.
471
+ async runGate(command, gate) {
472
+ // The child's worktree when it had one and it survived; otherwise the
473
+ // session's own directory, which is where a non-isolated child worked.
474
+ return await executeGate(command, gate.cwd ?? ctx.cwd);
475
+ },
476
+ };
477
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * journal.ts — the record a workflow run leaves so a later run can skip work.
3
+ *
4
+ * ## What resume actually buys
5
+ *
6
+ * The documented iteration loop is "edit the persisted script and re-run it".
7
+ * Without a journal that re-pays every agent from scratch, which for a 40-agent
8
+ * audit is the entire cost of the run — to change one line of the last stage.
9
+ * With one, the unchanged prefix comes back from disk and only the edit runs.
10
+ *
11
+ * ## Why a *prefix*, and not a lookup table
12
+ *
13
+ * Each entry is keyed by both its position in the run and a hash of everything
14
+ * that decides what that agent does. A replay walks positions in order and
15
+ * stops reusing at the first entry that does not match — every call from there
16
+ * on runs live. Reusing later matches out of order would be reusing a result
17
+ * produced under different upstream conditions: the same prompt at position 12
18
+ * of a *different* run is not the same work, because what fed it changed.
19
+ *
20
+ * A failed agent is journaled as a failure and never replayed as one. Resuming
21
+ * a run that died at agent 5 exists to retry agent 5, so the prefix ends there
22
+ * and 5 onwards run live — the alternative would make a failure permanent.
23
+ *
24
+ * ## Runs that use `agent({ resume })`
25
+ *
26
+ * Those are not replayed at all. A replayed agent is text from a file, not a
27
+ * live child, so there is no conversation in this run for a later `resume` to
28
+ * continue — and the id map that would find one belongs to the run that did
29
+ * the spawning. Rather than replay a prefix that strands the first `resume`
30
+ * call, a journal carrying one declines the whole cache and the run pays in
31
+ * full. Coarse on purpose: the alternative is tracking which label each entry
32
+ * ran under and capping the prefix below the earliest one that gets resumed,
33
+ * which is a second key concept for a case that costs one run.
34
+ *
35
+ * ## Ordering under concurrency
36
+ *
37
+ * Positions are assigned as calls arrive, and with `pipeline` that order
38
+ * depends on which agent finished first. A replay usually reproduces it, since
39
+ * cached calls answer in journal order, but it is not guaranteed. That is why
40
+ * the key is checked as well as the position: a run that interleaves
41
+ * differently loses cache hits, it never returns another agent's answer.
42
+ *
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.
47
+ */
48
+ /** One settled agent call, as replayed. */
49
+ export interface WorkflowJournalEntry {
50
+ /** Position in the run — the same counter that names `wf-agent-N`. */
51
+ index: number;
52
+ /** Hash of the call's payload; a mismatch ends the replayable prefix. */
53
+ key: string;
54
+ /** Whether the agent succeeded. A failure ends the prefix on replay. */
55
+ ok: boolean;
56
+ /** The agent's answer, when it had one. */
57
+ text?: string;
58
+ /**
59
+ * Whether the call continued an earlier child (`agent({ resume })`).
60
+ *
61
+ * A replayed agent leaves no session behind in the run that replays it — the
62
+ * conversation belongs to the run that actually spawned it, and the host's
63
+ * id map is per-run — so a later `resume` would have nothing to continue.
64
+ * Recording it lets the next run decline to replay at all rather than fail
65
+ * partway through, which is why the flag is on the journal and not derived.
66
+ */
67
+ resumed?: true;
68
+ }
69
+ /**
70
+ * The fields that decide what an agent does.
71
+ *
72
+ * Deliberately not the whole payload: `phaseIndex` and `phaseTitle` move the
73
+ * row around in the progress tree without changing a single token the agent
74
+ * sees, so re-grouping phases should not throw away an hour of results.
75
+ */
76
+ export interface JournalKeyInput {
77
+ prompt: string;
78
+ label?: string;
79
+ model?: string;
80
+ agentType?: string;
81
+ /** Explicit/default selection changes the host's model/fallback authorization. */
82
+ agentTypeExplicit?: boolean;
83
+ effort?: string;
84
+ isolation?: string;
85
+ gate?: string;
86
+ resume?: string;
87
+ /** Serialized `agent({ schema })`, when the call asked for one. */
88
+ schema?: string;
89
+ }
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;
92
+ /**
93
+ * Read a journal file into position order.
94
+ *
95
+ * Never throws: a missing, truncated or hand-mangled journal means "nothing to
96
+ * replay", which costs tokens. Refusing to run would cost the whole run.
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.
112
+ */
113
+ export declare function appendJournal(path: string, entry: WorkflowJournalEntry): Promise<void>;