@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.
- package/CHANGELOG.md +862 -0
- package/CONTRIBUTING.md +72 -0
- package/LICENSE +21 -0
- package/README.md +1125 -3
- package/SECURITY.md +97 -0
- package/dist/abortable.d.ts +12 -0
- package/dist/abortable.js +42 -0
- package/dist/active-agents-prompt.d.ts +40 -0
- package/dist/active-agents-prompt.js +98 -0
- package/dist/advisor-status.d.ts +16 -0
- package/dist/advisor-status.js +74 -0
- package/dist/agent-color.d.ts +35 -0
- package/dist/agent-color.js +131 -0
- package/dist/agent-file-toggle.d.ts +125 -0
- package/dist/agent-file-toggle.js +264 -0
- package/dist/agent-manager.d.ts +872 -0
- package/dist/agent-manager.js +2910 -0
- package/dist/agent-runner.d.ts +358 -0
- package/dist/agent-runner.js +1219 -0
- package/dist/agent-types.d.ts +142 -0
- package/dist/agent-types.js +315 -0
- package/dist/awaited-result.d.ts +37 -0
- package/dist/awaited-result.js +150 -0
- package/dist/child-context.d.ts +15 -0
- package/dist/child-context.js +181 -0
- package/dist/child-session-shutdown.d.ts +21 -0
- package/dist/child-session-shutdown.js +97 -0
- package/dist/cleanup-plans.d.ts +10 -0
- package/dist/cleanup-plans.js +112 -0
- package/dist/context.d.ts +12 -0
- package/dist/context.js +56 -0
- package/dist/cross-extension-rpc.d.ts +73 -0
- package/dist/cross-extension-rpc.js +192 -0
- package/dist/custom-agents.d.ts +79 -0
- package/dist/custom-agents.js +583 -0
- package/dist/default-agents.d.ts +7 -0
- package/dist/default-agents.js +125 -0
- package/dist/enabled-models.d.ts +49 -0
- package/dist/enabled-models.js +145 -0
- package/dist/env.d.ts +6 -0
- package/dist/env.js +28 -0
- package/dist/error-log.d.ts +64 -0
- package/dist/error-log.js +176 -0
- package/dist/force-main-model.d.ts +21 -0
- package/dist/force-main-model.js +28 -0
- package/dist/goal-bridge.d.ts +155 -0
- package/dist/goal-bridge.js +305 -0
- package/dist/group-join.d.ts +36 -0
- package/dist/group-join.js +161 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.js +6390 -0
- package/dist/invocation-config.d.ts +164 -0
- package/dist/invocation-config.js +158 -0
- package/dist/memory.d.ts +53 -0
- package/dist/memory.js +165 -0
- package/dist/mention-clone.d.ts +87 -0
- package/dist/mention-clone.js +178 -0
- package/dist/mention.d.ts +81 -0
- package/dist/mention.js +131 -0
- package/dist/model-resolver.d.ts +36 -0
- package/dist/model-resolver.js +95 -0
- package/dist/model-scope.d.ts +49 -0
- package/dist/model-scope.js +48 -0
- package/dist/nested-tools.d.ts +76 -0
- package/dist/nested-tools.js +393 -0
- package/dist/output-diagnostics.d.ts +11 -0
- package/dist/output-diagnostics.js +64 -0
- package/dist/output-file.d.ts +64 -0
- package/dist/output-file.js +351 -0
- package/dist/prompts.d.ts +61 -0
- package/dist/prompts.js +94 -0
- package/dist/recovery.d.ts +56 -0
- package/dist/recovery.js +341 -0
- package/dist/report-cleanup.d.ts +204 -0
- package/dist/report-cleanup.js +1632 -0
- package/dist/report-store.d.ts +738 -0
- package/dist/report-store.js +3612 -0
- package/dist/schedule-store.d.ts +52 -0
- package/dist/schedule-store.js +240 -0
- package/dist/schedule.d.ts +121 -0
- package/dist/schedule.js +420 -0
- package/dist/settings.d.ts +388 -0
- package/dist/settings.js +268 -0
- package/dist/skill-loader.d.ts +24 -0
- package/dist/skill-loader.js +93 -0
- package/dist/standalone-fallback.d.ts +30 -0
- package/dist/standalone-fallback.js +239 -0
- package/dist/status-note.d.ts +61 -0
- package/dist/status-note.js +85 -0
- package/dist/structured-output.d.ts +61 -0
- package/dist/structured-output.js +112 -0
- package/dist/terminal-progress.d.ts +115 -0
- package/dist/terminal-progress.js +206 -0
- package/dist/types.d.ts +411 -0
- package/dist/types.js +5 -0
- package/dist/ui/agent-mention.d.ts +82 -0
- package/dist/ui/agent-mention.js +187 -0
- package/dist/ui/agent-widget.d.ts +304 -0
- package/dist/ui/agent-widget.js +770 -0
- package/dist/ui/cleanup-preview.d.ts +59 -0
- package/dist/ui/cleanup-preview.js +466 -0
- package/dist/ui/conversation-viewer.d.ts +105 -0
- package/dist/ui/conversation-viewer.js +544 -0
- package/dist/ui/fleet-list.d.ts +183 -0
- package/dist/ui/fleet-list.js +494 -0
- package/dist/ui/fleet-overlay.d.ts +203 -0
- package/dist/ui/fleet-overlay.js +887 -0
- package/dist/ui/hub-feed.d.ts +52 -0
- package/dist/ui/hub-feed.js +148 -0
- package/dist/ui/native-transcript.d.ts +33 -0
- package/dist/ui/native-transcript.js +234 -0
- package/dist/ui/schedule-menu.d.ts +16 -0
- package/dist/ui/schedule-menu.js +94 -0
- package/dist/ui/select-item.d.ts +27 -0
- package/dist/ui/select-item.js +34 -0
- package/dist/ui/tool-progress.d.ts +22 -0
- package/dist/ui/tool-progress.js +56 -0
- package/dist/ui/viewer-keys.d.ts +20 -0
- package/dist/ui/viewer-keys.js +17 -0
- package/dist/ui/workflow-card.d.ts +175 -0
- package/dist/ui/workflow-card.js +332 -0
- package/dist/ui/workflow-dialog.d.ts +305 -0
- package/dist/ui/workflow-dialog.js +848 -0
- package/dist/ui/workflow-menu.d.ts +60 -0
- package/dist/ui/workflow-menu.js +147 -0
- package/dist/usage.d.ts +147 -0
- package/dist/usage.js +147 -0
- package/dist/workflow/collisions.d.ts +95 -0
- package/dist/workflow/collisions.js +88 -0
- package/dist/workflow/entry.d.ts +32 -0
- package/dist/workflow/entry.js +29 -0
- package/dist/workflow/host.d.ts +65 -0
- package/dist/workflow/host.js +477 -0
- package/dist/workflow/journal.d.ts +113 -0
- package/dist/workflow/journal.js +177 -0
- package/dist/workflow/json-schema.d.ts +51 -0
- package/dist/workflow/json-schema.js +111 -0
- package/dist/workflow/meta.d.ts +67 -0
- package/dist/workflow/meta.js +317 -0
- package/dist/workflow/progress.d.ts +224 -0
- package/dist/workflow/progress.js +361 -0
- package/dist/workflow/runtime.d.ts +373 -0
- package/dist/workflow/runtime.js +919 -0
- package/dist/workflow/saved.d.ts +90 -0
- package/dist/workflow/saved.js +203 -0
- package/dist/workflow/task.d.ts +145 -0
- package/dist/workflow/task.js +213 -0
- package/dist/workflow/tool-description.d.ts +43 -0
- package/dist/workflow/tool-description.js +204 -0
- package/dist/workflow/worker-source.d.ts +47 -0
- package/dist/workflow/worker-source.js +778 -0
- package/dist/worktree.d.ts +52 -0
- package/dist/worktree.js +164 -0
- package/dist/xml.d.ts +10 -0
- package/dist/xml.js +12 -0
- package/docs/DEVELOPMENT.md +40 -0
- package/docs/artifacts.md +93 -0
- package/docs/recovery.md +62 -0
- package/docs/rpc.md +252 -0
- package/docs/runtime-performance.md +53 -0
- package/docs/workflows.md +467 -0
- package/examples/agent-tool-description.md +43 -0
- package/examples/workflows/compose.js +51 -0
- package/examples/workflows/fan-out-audit.js +47 -0
- package/examples/workflows/gated-fix.js +60 -0
- package/examples/workflows/lib/count-child.js +27 -0
- package/examples/workflows/review-panel.js +66 -0
- package/examples/workflows/structured-findings.js +78 -0
- package/package.json +75 -6
- package/src/abortable.ts +43 -0
- package/src/active-agents-prompt.ts +115 -0
- package/src/advisor-status.ts +74 -0
- package/src/agent-color.ts +169 -0
- package/src/agent-file-toggle.ts +273 -0
- package/src/agent-manager.ts +3312 -0
- package/src/agent-runner.ts +1500 -0
- package/src/agent-types.ts +390 -0
- package/src/awaited-result.ts +187 -0
- package/src/child-context.ts +173 -0
- package/src/child-session-shutdown.ts +114 -0
- package/src/cleanup-plans.ts +112 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +257 -0
- package/src/custom-agents.ts +689 -0
- package/src/default-agents.ts +129 -0
- package/src/enabled-models.ts +180 -0
- package/src/env.ts +33 -0
- package/src/error-log.ts +202 -0
- package/src/force-main-model.ts +29 -0
- package/src/goal-bridge.ts +468 -0
- package/src/group-join.ts +188 -0
- package/src/index.ts +6856 -0
- package/src/invocation-config.ts +276 -0
- package/src/memory.ts +179 -0
- package/src/mention-clone.ts +221 -0
- package/src/mention.ts +141 -0
- package/src/model-resolver.ts +118 -0
- package/src/model-scope.ts +70 -0
- package/src/nested-tools.ts +553 -0
- package/src/output-diagnostics.ts +68 -0
- package/src/output-file.ts +380 -0
- package/src/prompts.ts +151 -0
- package/src/recovery.ts +320 -0
- package/src/report-cleanup.ts +2044 -0
- package/src/report-store.ts +4130 -0
- package/src/schedule-store.ts +244 -0
- package/src/schedule.ts +450 -0
- package/src/settings.ts +632 -0
- package/src/skill-loader.ts +102 -0
- package/src/standalone-fallback.ts +195 -0
- package/src/status-note.ts +90 -0
- package/src/structured-output.ts +130 -0
- package/src/terminal-progress.ts +215 -0
- package/src/types.ts +424 -0
- package/src/ui/agent-mention.ts +216 -0
- package/src/ui/agent-widget.ts +866 -0
- package/src/ui/cleanup-preview.ts +518 -0
- package/src/ui/conversation-viewer.ts +527 -0
- package/src/ui/fleet-list.ts +563 -0
- package/src/ui/fleet-overlay.ts +1048 -0
- package/src/ui/hub-feed.ts +179 -0
- package/src/ui/native-transcript.ts +224 -0
- package/src/ui/schedule-menu.ts +105 -0
- package/src/ui/select-item.ts +45 -0
- package/src/ui/tool-progress.ts +67 -0
- package/src/ui/viewer-keys.ts +39 -0
- package/src/ui/workflow-card.ts +470 -0
- package/src/ui/workflow-dialog.ts +1119 -0
- package/src/ui/workflow-menu.ts +193 -0
- package/src/usage.ts +217 -0
- package/src/workflow/collisions.ts +123 -0
- package/src/workflow/entry.ts +47 -0
- package/src/workflow/host.ts +524 -0
- package/src/workflow/journal.ts +221 -0
- package/src/workflow/json-schema.ts +128 -0
- package/src/workflow/meta.ts +325 -0
- package/src/workflow/progress.ts +550 -0
- package/src/workflow/runtime.ts +1342 -0
- package/src/workflow/saved.ts +217 -0
- package/src/workflow/task.ts +313 -0
- package/src/workflow/tool-description.ts +205 -0
- package/src/workflow/worker-source.ts +781 -0
- package/src/worktree.ts +205 -0
- package/src/xml.ts +13 -0
|
@@ -0,0 +1,524 @@
|
|
|
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
|
+
|
|
38
|
+
import { existsSync } from "node:fs";
|
|
39
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
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";
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Wall-clock bound on a `gate` command. Generous — a gate is routinely a test
|
|
53
|
+
* suite — but not unbounded: `pi.exec` reports a timeout as `killed`, and a
|
|
54
|
+
* gate that hangs forever would wedge the agent slot it is holding.
|
|
55
|
+
*/
|
|
56
|
+
export const DEFAULT_GATE_TIMEOUT_MS = 10 * 60_000;
|
|
57
|
+
|
|
58
|
+
export interface WorkflowHostOptions {
|
|
59
|
+
pi: ExtensionAPI;
|
|
60
|
+
ctx: ExtensionContext;
|
|
61
|
+
manager: AgentManager;
|
|
62
|
+
/** The run's abort signal, so killing the workflow kills its children. */
|
|
63
|
+
signal?: AbortSignal;
|
|
64
|
+
/** Groups child transcripts under the parent session. */
|
|
65
|
+
rootSessionId?: string;
|
|
66
|
+
/**
|
|
67
|
+
* The run id every child is stamped with.
|
|
68
|
+
*
|
|
69
|
+
* What makes them the workflow's rather than the session's: stamped children
|
|
70
|
+
* are filtered out of the fleet list, the widget, the `/agents` menus and
|
|
71
|
+
* `@handle` resolution, and they take no `maxConcurrent` slot. The run
|
|
72
|
+
* reports for them, and it has its own concurrency cap.
|
|
73
|
+
*/
|
|
74
|
+
workflowId?: string;
|
|
75
|
+
gateTimeoutMs?: number;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Where the child worked, when that directory still exists.
|
|
80
|
+
*
|
|
81
|
+
* The guard is not defensive padding. `cleanupWorktree` commits the child's
|
|
82
|
+
* changes to a branch and *removes* the copy before `spawnAndWait` resolves, so
|
|
83
|
+
* an isolated child's worktree is normally already gone by the time a result is
|
|
84
|
+
* built. That is exactly why a gate cannot wait until here — it runs from
|
|
85
|
+
* `onBeforeWorktreeCleanup` instead — and why this reports nothing rather than
|
|
86
|
+
* a path that no longer exists: handing a stale path to a command would fail
|
|
87
|
+
* every gated worktree agent with a spawn error instead of a test result.
|
|
88
|
+
*/
|
|
89
|
+
function childCwd(record: AgentRecord): string | undefined {
|
|
90
|
+
// `path`, not `workPath`: a workflow spawn never passes a cwd, so the manager
|
|
91
|
+
// runs the child at the copied repo's root.
|
|
92
|
+
const path = record.worktree?.path;
|
|
93
|
+
return path !== undefined && existsSync(path) ? path : undefined;
|
|
94
|
+
}
|
|
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
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Whether a settled child succeeded — the same condition {@link toSpawnResult}
|
|
117
|
+
* turns into `ok`. The pre-cleanup hook receives the computed terminal status
|
|
118
|
+
* separately because the live record stays running until cleanup finishes.
|
|
119
|
+
*/
|
|
120
|
+
function succeeded(record: AgentRecord | undefined): boolean {
|
|
121
|
+
return record?.status === "completed" || record?.status === "steered";
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Translate a settled record into what the script sees. */
|
|
125
|
+
/**
|
|
126
|
+
* The effective-configuration half of a record, in the runtime's pi-free shape.
|
|
127
|
+
*
|
|
128
|
+
* `AgentRecord.invocation` is the one authoritative place for it (#168); this
|
|
129
|
+
* only renames the fields across the boundary. Returns undefined until the
|
|
130
|
+
* child's session has reported a model, which is when any of it is knowable.
|
|
131
|
+
*/
|
|
132
|
+
function resolvedInfo(record: AgentRecord | undefined) {
|
|
133
|
+
const invocation = record?.invocation;
|
|
134
|
+
if (invocation?.modelName === undefined) return undefined;
|
|
135
|
+
return {
|
|
136
|
+
modelName: invocation.modelName,
|
|
137
|
+
modelId: invocation.modelId,
|
|
138
|
+
thinking: invocation.thinking,
|
|
139
|
+
requestedThinking: invocation.requestedThinking,
|
|
140
|
+
requestedModel: invocation.requestedModel,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function toSpawnResult(record: AgentRecord): WorkflowSpawnResult {
|
|
145
|
+
const tokens = getLifetimeTotal(record.lifetimeUsage);
|
|
146
|
+
// Reported separately from `tokens`, which is the lifetime total. The script's
|
|
147
|
+
// `budget` counts *output* tokens, as Claude Code's does — billing the input
|
|
148
|
+
// and cache reads a fan-out re-sends would over-report it by an order of
|
|
149
|
+
// magnitude and make the documented guards useless.
|
|
150
|
+
const outputTokens = record.lifetimeUsage?.output ?? 0;
|
|
151
|
+
const cwd = childCwd(record);
|
|
152
|
+
const common = {
|
|
153
|
+
...(tokens > 0 ? { tokens } : {}),
|
|
154
|
+
...(outputTokens > 0 ? { outputTokens } : {}),
|
|
155
|
+
...(record.toolUses > 0 ? { toolCalls: record.toolUses } : {}),
|
|
156
|
+
...(cwd !== undefined ? { cwd } : {}),
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
if (succeeded(record)) {
|
|
160
|
+
return {
|
|
161
|
+
...common,
|
|
162
|
+
ok: true,
|
|
163
|
+
// The schema'd payload when there is one: `result` is prose, and for a
|
|
164
|
+
// worktree child it has had the branch note appended, so it would not
|
|
165
|
+
// parse. A child asked for a schema that produced none never reaches
|
|
166
|
+
// here — `runAgent` reports that through `failure`.
|
|
167
|
+
text: record.structuredJson ?? record.result ?? "",
|
|
168
|
+
...(record.structuredRetried ? { structuredRetried: true } : {}),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
// "stopped" is someone reaching in and stopping this child — /agents, the
|
|
172
|
+
// fleet list, a workflow abort. That is the same thing the workflows dialog's
|
|
173
|
+
// skip action means, so it renders as skipped rather than failed.
|
|
174
|
+
if (record.status === "stopped") {
|
|
175
|
+
return { ...common, ok: false, skipped: true, error: record.error ?? "Stopped." };
|
|
176
|
+
}
|
|
177
|
+
return { ...common, ok: false, error: record.error ?? `Agent ${record.status}.` };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Shell used to run a `gate` command, mirroring how a user would type it. */
|
|
181
|
+
const GATE_SHELL: readonly [string, string] =
|
|
182
|
+
process.platform === "win32" ? ["cmd", "/c"] : ["sh", "-c"];
|
|
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
|
+
|
|
190
|
+
export function createWorkflowHost(deps: WorkflowHostOptions): WorkflowHost {
|
|
191
|
+
const { pi, ctx, manager } = deps;
|
|
192
|
+
/** Runtime agent id → the manager record it spawned. Never pruned mid-run. */
|
|
193
|
+
const records = new Map<string, string>();
|
|
194
|
+
/**
|
|
195
|
+
* scopeModels warnings already toasted, so a fan-out that pins one
|
|
196
|
+
* out-of-scope agent file raises one notification rather than one per child.
|
|
197
|
+
* Kept for the whole run: the same message is the same warning at agent 200
|
|
198
|
+
* as it was at agent 1.
|
|
199
|
+
*/
|
|
200
|
+
const warnedScopeMessages = new Set<string>();
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Run a gate command in `cwd`. The only place a gate is executed — `runGate`
|
|
204
|
+
* and the pre-cleanup hook both come through here — so "gate passed" is
|
|
205
|
+
* decided from one behaviour, whichever route the command took.
|
|
206
|
+
*/
|
|
207
|
+
async function executeGate(command: string, cwd: string): Promise<WorkflowGateResult> {
|
|
208
|
+
const result = await pi.exec(GATE_SHELL[0], [GATE_SHELL[1], command], {
|
|
209
|
+
cwd,
|
|
210
|
+
timeout: deps.gateTimeoutMs ?? DEFAULT_GATE_TIMEOUT_MS,
|
|
211
|
+
...(deps.signal !== undefined ? { signal: deps.signal } : {}),
|
|
212
|
+
});
|
|
213
|
+
const output = [result.stdout, result.stderr]
|
|
214
|
+
.map(stream => stream.trim())
|
|
215
|
+
.filter(Boolean)
|
|
216
|
+
.join("\n");
|
|
217
|
+
// `pi.exec` reports a timeout as `killed` with exit code 0, so the code
|
|
218
|
+
// alone would read a killed gate as a passing one.
|
|
219
|
+
if (result.killed) {
|
|
220
|
+
return { ok: false, output: output || `Gate command timed out: ${command}` };
|
|
221
|
+
}
|
|
222
|
+
return { ok: result.code === 0, output };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
return {
|
|
226
|
+
async spawnAgent(request) {
|
|
227
|
+
const dispatch = resolveSpawnType(request.agentType);
|
|
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
|
+
}
|
|
245
|
+
|
|
246
|
+
const config = getAgentConfig(dispatch.type);
|
|
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.
|
|
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
|
+
}
|
|
302
|
+
model = resolved;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// Same scopeModels policy as the Agent tool and the nested delegation
|
|
307
|
+
// tools: a script's `agent({ model })` is a runtime LLM choice, and the
|
|
308
|
+
// script is written by the model, so it must not reach a model the user's
|
|
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
|
+
}
|
|
331
|
+
}
|
|
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
|
+
|
|
352
|
+
/**
|
|
353
|
+
* The gate's verdict, set only if the hook below actually ran the command.
|
|
354
|
+
* Its presence is what stops the runtime running the gate a second time,
|
|
355
|
+
* so it is set on the failure route too — a gate we tried and could not
|
|
356
|
+
* complete is a failed gate, never an un-run one that then re-runs
|
|
357
|
+
* against the wrong tree.
|
|
358
|
+
*/
|
|
359
|
+
let gate: WorkflowGateResult | undefined;
|
|
360
|
+
let spawnedId: string | undefined;
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Hand the child's EFFECTIVE configuration back to the run.
|
|
364
|
+
*
|
|
365
|
+
* `AgentRecord.invocation` is the one authoritative place for it (#168),
|
|
366
|
+
* filled by the manager the moment the child's session exists — which is
|
|
367
|
+
* before this fires, so it is populated by the time we read it. Reading it
|
|
368
|
+
* rather than re-deriving "the session, else the request" is the whole
|
|
369
|
+
* point of that field existing.
|
|
370
|
+
*/
|
|
371
|
+
let sessionReady = false;
|
|
372
|
+
const reportResolved = () => {
|
|
373
|
+
// Called from BOTH the session hook and the spawn hook, because their
|
|
374
|
+
// order is not guaranteed: the manager fires `onSpawned` after
|
|
375
|
+
// `runAgent` returns, but `runAgent` decides when its own
|
|
376
|
+
// `onSessionCreated` fires — synchronously, for a stub. Each fires once,
|
|
377
|
+
// so the first call finds a half missing and returns, and the second is
|
|
378
|
+
// the one that reports.
|
|
379
|
+
if (!sessionReady || spawnedId === undefined) return;
|
|
380
|
+
const info = resolvedInfo(manager.getRecord(spawnedId));
|
|
381
|
+
if (info !== undefined) request.onResolved?.(info);
|
|
382
|
+
};
|
|
383
|
+
const command = request.gate;
|
|
384
|
+
/**
|
|
385
|
+
* Verify the child's work while its worktree still exists.
|
|
386
|
+
*
|
|
387
|
+
* The manager destroys that copy inside the child's own settle, so this
|
|
388
|
+
* is the last (and only) moment at which `npm test` can mean "the code
|
|
389
|
+
* this child just wrote" rather than "whatever is in the main tree".
|
|
390
|
+
*/
|
|
391
|
+
const onBeforeWorktreeCleanup =
|
|
392
|
+
command === undefined
|
|
393
|
+
? undefined
|
|
394
|
+
: async (worktreePath: string, terminalStatus: AgentRecord["status"]): Promise<void> => {
|
|
395
|
+
// The record stays running until worktree cleanup finishes; only
|
|
396
|
+
// the computed outcome tells us whether this child needs a gate.
|
|
397
|
+
const record = spawnedId === undefined ? undefined : manager.getRecord(spawnedId);
|
|
398
|
+
if (!record || record.status === "stopped" || (terminalStatus !== "completed" && terminalStatus !== "steered")) return;
|
|
399
|
+
try {
|
|
400
|
+
gate = await executeGate(command, worktreePath);
|
|
401
|
+
} catch (error) {
|
|
402
|
+
gate = { ok: false, output: error instanceof Error ? error.message : String(error) };
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
try {
|
|
407
|
+
const { record } = await manager.spawnAndWait(
|
|
408
|
+
pi,
|
|
409
|
+
ctx,
|
|
410
|
+
dispatch.type,
|
|
411
|
+
request.prompt,
|
|
412
|
+
{
|
|
413
|
+
description: request.label,
|
|
414
|
+
// The stamp is what keeps this child out of the session's
|
|
415
|
+
// `maxConcurrent` pool — see `occupiesPoolSlot`. The run already
|
|
416
|
+
// bounds how many of its agents run at once, and counting them
|
|
417
|
+
// twice would let one fan-out starve everything else the user is
|
|
418
|
+
// doing. No `bypassQueue` needed: an agent outside the pool is
|
|
419
|
+
// never queued behind it.
|
|
420
|
+
...(deps.workflowId !== undefined ? { workflowId: deps.workflowId } : {}),
|
|
421
|
+
...(model !== undefined ? { model } : {}),
|
|
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).
|
|
431
|
+
//
|
|
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.
|
|
440
|
+
invocation: {
|
|
441
|
+
...(request.effort !== undefined ? { thinking: request.effort as ThinkingLevel } : {}),
|
|
442
|
+
...(askedModel !== undefined ? { requestedModel: askedModel } : {}),
|
|
443
|
+
},
|
|
444
|
+
// Fires once the child's session exists, which is where the model
|
|
445
|
+
// and the clamped thinking level first become knowable.
|
|
446
|
+
onSessionCreated: () => { sessionReady = true; reportResolved(); },
|
|
447
|
+
...(request.schema !== undefined ? { structuredOutput: request.schema } : {}),
|
|
448
|
+
...(request.isolation !== undefined ? { isolation: request.isolation } : {}),
|
|
449
|
+
...(deps.signal !== undefined ? { signal: deps.signal } : {}),
|
|
450
|
+
...(deps.rootSessionId !== undefined ? { rootSessionId: deps.rootSessionId } : {}),
|
|
451
|
+
...(onBeforeWorktreeCleanup !== undefined ? { onBeforeWorktreeCleanup } : {}),
|
|
452
|
+
},
|
|
453
|
+
id => {
|
|
454
|
+
spawnedId = id;
|
|
455
|
+
records.set(request.agentId, id);
|
|
456
|
+
// Ahead of `reportResolved`, and not folded into it: that one waits
|
|
457
|
+
// for the child's session so it can name the effective model, while
|
|
458
|
+
// the record id is known here and is what the inspector opens a
|
|
459
|
+
// conversation on. A child that fails before its session resolves
|
|
460
|
+
// would otherwise never be openable at all.
|
|
461
|
+
request.onResolved?.({ recordId: id });
|
|
462
|
+
reportResolved();
|
|
463
|
+
},
|
|
464
|
+
);
|
|
465
|
+
return { ...toSpawnResult(record), ...(gate !== undefined ? { gate } : {}) };
|
|
466
|
+
} catch (error) {
|
|
467
|
+
// Strict worktree isolation rejects out of `awaitStartup` — the child
|
|
468
|
+
// never ran. That is this agent's failure, not the run's: the script
|
|
469
|
+
// sees `null` and its siblings carry on.
|
|
470
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
471
|
+
}
|
|
472
|
+
},
|
|
473
|
+
|
|
474
|
+
abortAgent(agentId) {
|
|
475
|
+
const id = records.get(agentId);
|
|
476
|
+
// Nothing to abort before the manager has issued an id — the child is
|
|
477
|
+
// still in startup, and the run's own signal reaches it there.
|
|
478
|
+
if (id !== undefined) manager.abort(id);
|
|
479
|
+
},
|
|
480
|
+
|
|
481
|
+
async resumeAgent(agentId, prompt, onResolved) {
|
|
482
|
+
const id = records.get(agentId);
|
|
483
|
+
if (id === undefined) {
|
|
484
|
+
return { ok: false, error: `Cannot resume "${agentId}" — it never started.` };
|
|
485
|
+
}
|
|
486
|
+
const record = await manager.resume(id, prompt, deps.signal);
|
|
487
|
+
if (record === undefined) {
|
|
488
|
+
return {
|
|
489
|
+
ok: false,
|
|
490
|
+
error: `Agent ${id} has no session left to resume — records are dropped ten minutes after they finish.`,
|
|
491
|
+
};
|
|
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.
|
|
497
|
+
// The resumed row is built from scratch, so it has to be told the same
|
|
498
|
+
// thing the first one was — the child's session already exists, so this is
|
|
499
|
+
// simply read back rather than waited for. The id goes first for the same
|
|
500
|
+
// reason it does on the spawn path: it is knowable even when the rest is
|
|
501
|
+
// not.
|
|
502
|
+
onResolved?.({ recordId: id });
|
|
503
|
+
const info = resolvedInfo(record);
|
|
504
|
+
if (info !== undefined) onResolved?.(info);
|
|
505
|
+
return toSpawnResult(record);
|
|
506
|
+
},
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* Resolve a nested `workflow()` reference. The runtime decides whether what
|
|
510
|
+
* comes back is a workflow; this only finds it.
|
|
511
|
+
*/
|
|
512
|
+
loadWorkflow(ref) {
|
|
513
|
+
return resolveWorkflowSource(ref, ctx.cwd);
|
|
514
|
+
},
|
|
515
|
+
|
|
516
|
+
// Reached only for a gate the spawn did not already run — a child with no
|
|
517
|
+
// worktree of its own, or a host wired without the pre-cleanup hook.
|
|
518
|
+
async runGate(command, gate) {
|
|
519
|
+
// The child's worktree when it had one and it survived; otherwise the
|
|
520
|
+
// session's own directory, which is where a non-isolated child worked.
|
|
521
|
+
return await executeGate(command, gate.cwd ?? ctx.cwd);
|
|
522
|
+
},
|
|
523
|
+
};
|
|
524
|
+
}
|