@lukstei/dsh-yaml-workflow 0.0.0-stage → 0.2.2-rc.5.3
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/LICENSE +21 -0
- package/README.md +452 -2
- package/cordis.patch.yml +4 -0
- package/dist/client.js +1746 -0
- package/dist/index.js +3495 -0
- package/examples/gate.yml +4 -0
- package/examples/parametrized-wf.yml +20 -0
- package/examples/wf.yml +3 -0
- package/package.json +114 -3
- package/src/boolean.ts +96 -0
- package/src/client/WorkflowCommandCard.tsx +217 -0
- package/src/client/WorkflowErrorCard.tsx +99 -0
- package/src/client/WorkflowMarkdown.tsx +28 -0
- package/src/client/WorkflowMarkdownResult.tsx +86 -0
- package/src/client/WorkflowPrintStep.tsx +46 -0
- package/src/client/WorkflowResumeButton.tsx +159 -0
- package/src/client/WorkflowStepRow.tsx +106 -0
- package/src/client/WorkflowStyles.tsx +10 -0
- package/src/client/actions.ts +113 -0
- package/src/client/context.ts +30 -0
- package/src/client/dsh.d.ts +33 -0
- package/src/client/icons.tsx +91 -0
- package/src/client/index.tsx +186 -0
- package/src/client/store.ts +655 -0
- package/src/client/styles.ts +340 -0
- package/src/effects.ts +696 -0
- package/src/fold.ts +201 -0
- package/src/index.ts +468 -0
- package/src/parser.ts +1146 -0
- package/src/requests.ts +85 -0
- package/src/rules.ts +647 -0
- package/src/runner.ts +1955 -0
- package/src/skill.ts +67 -0
- package/src/transitions.ts +357 -0
- package/src/types.ts +604 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,3495 @@
|
|
|
1
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
2
|
+
import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { ReasoningEffortId, createUserMessage } from "@deepseek-ai/dsh-llm";
|
|
6
|
+
import { parentAgentOptionsForDelegation } from "@deepseek-ai/dsh-subagent";
|
|
7
|
+
import { z } from "zod";
|
|
8
|
+
import { parse } from "yaml";
|
|
9
|
+
import crypto from "node:crypto";
|
|
10
|
+
// src/skill.ts
|
|
11
|
+
const WORKFLOW_SKILL_NAME = "yaml-workflow";
|
|
12
|
+
const WORKFLOW_SKILL_DESCRIPTION = "Author, validate, and execute declarative multi-step YAML prompt workflows in DSH.";
|
|
13
|
+
const WORKFLOW_SKILL_CONTENT = `
|
|
14
|
+
# YAML Workflow Skill
|
|
15
|
+
|
|
16
|
+
Author, validate, and execute multi-step prompt workflows defined in YAML files.
|
|
17
|
+
Workflows provide sequential agent orchestration, typed argument interpolation, human review gates, zero-token status printing, and delegated subagent execution.
|
|
18
|
+
|
|
19
|
+
## Commands
|
|
20
|
+
|
|
21
|
+
- \`/wf <workflow.yaml> [key=value ...] [instructions]\`: Execute a workflow.
|
|
22
|
+
- \`/wf-resume [instructions]\`: Resume an interrupted workflow or continue from a human review gate.
|
|
23
|
+
- \`/wf-abort\`: Discard an active or paused workflow.
|
|
24
|
+
- \`/wf-list\`: Discover and list workflows in project (\`.agents/wf\`) and user (\`~/.agents/wf\`) directories.
|
|
25
|
+
- \`/wf-validate <workflow.yaml> [key=value ...]\`: Validate syntax and argument coverage without running.
|
|
26
|
+
|
|
27
|
+
## Agent Tools
|
|
28
|
+
|
|
29
|
+
- \`wf_validate\`: Validate a workflow file programmatically without executing it:
|
|
30
|
+
\`\`\`json
|
|
31
|
+
{ "target": "deploy.yaml", "args": "env=production version=1.0.0" }
|
|
32
|
+
\`\`\`
|
|
33
|
+
- \`save_output\`: Save a declared output value during a workflow prompt step:
|
|
34
|
+
- For string output: \`{ "name": "tag", "value": "v1.2.0" }\`
|
|
35
|
+
- For list output: \`{ "name": "items", "value": "[\\"item1\\", \\"item2\\"]" }\`
|
|
36
|
+
|
|
37
|
+
## Workflow File Schema
|
|
38
|
+
|
|
39
|
+
\`\`\`yaml
|
|
40
|
+
name: "Deploy Service"
|
|
41
|
+
description: "Build and deploy service to target environment"
|
|
42
|
+
args:
|
|
43
|
+
env:
|
|
44
|
+
type: string
|
|
45
|
+
description: "Target environment (staging | production)"
|
|
46
|
+
required: true
|
|
47
|
+
dryRun:
|
|
48
|
+
type: bool
|
|
49
|
+
default: false
|
|
50
|
+
steps:
|
|
51
|
+
- kind: prompt
|
|
52
|
+
name: "Prepare"
|
|
53
|
+
prompt: "Prepare deployment artifacts for {{args.env}}."
|
|
54
|
+
outputs:
|
|
55
|
+
release_tag:
|
|
56
|
+
type: string
|
|
57
|
+
description: "Computed release tag"
|
|
58
|
+
|
|
59
|
+
- kind: print
|
|
60
|
+
name: "Status"
|
|
61
|
+
text: "Artifact ready: {{outputs.release_tag}}"
|
|
62
|
+
|
|
63
|
+
- name: "Approval"
|
|
64
|
+
gate: "Approve deployment to {{args.env}} with tag {{outputs.release_tag}}?"
|
|
65
|
+
|
|
66
|
+
- kind: prompt
|
|
67
|
+
name: "Deploy"
|
|
68
|
+
prompt: "Execute deployment for {{outputs.release_tag}}."
|
|
69
|
+
\`\`\`
|
|
70
|
+
|
|
71
|
+
## Best Practices
|
|
72
|
+
|
|
73
|
+
1. **Always Validate First**: Before running or scheduling a workflow, test it with the \`wf_validate\` tool to catch schema errors, missing arguments, or invalid template references.
|
|
74
|
+
2. **Output Recording**: Prompt steps with declared outputs require calling \`save_output\` for each output before completing the turn.
|
|
75
|
+
`.trim();
|
|
76
|
+
// src/fold.ts
|
|
77
|
+
const WORKFLOW_EVENT_NAME = "wf-event";
|
|
78
|
+
function isValidInitPayload(payload) {
|
|
79
|
+
return payload.action === "init" && Boolean(payload.workflow && payload.invocation && payload.invocation.runId === payload.runId);
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Purpose: Pure fold over session command/run events to derive the latest workflow run.
|
|
83
|
+
* Contract:
|
|
84
|
+
* - Inputs: events array in chronological log order, optional targetRunId string.
|
|
85
|
+
* - Outputs: latest WorkflowRun if a workflow was initiated, or null.
|
|
86
|
+
* - Throws: None.
|
|
87
|
+
*/
|
|
88
|
+
function foldWorkflowState(events, targetRunId) {
|
|
89
|
+
let current = null;
|
|
90
|
+
for (const { type, data } of events) {
|
|
91
|
+
if (type !== "command/run") continue;
|
|
92
|
+
if (!data || typeof data !== "object") continue;
|
|
93
|
+
const cmd = data;
|
|
94
|
+
if (cmd.name !== "wf-event" || typeof cmd.args !== "string") continue;
|
|
95
|
+
try {
|
|
96
|
+
const payload = JSON.parse(cmd.args);
|
|
97
|
+
if (!payload.runId) continue;
|
|
98
|
+
if (targetRunId && payload.runId !== targetRunId) continue;
|
|
99
|
+
if (isValidInitPayload(payload)) current = {
|
|
100
|
+
workflow: payload.workflow,
|
|
101
|
+
invocation: payload.invocation,
|
|
102
|
+
state: {
|
|
103
|
+
stepIndex: 0,
|
|
104
|
+
status: "running"
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
else if (payload.action === "state" && current && payload.runId === current.invocation.runId) {
|
|
108
|
+
const { action: _, sessionId: _sessionId, runId: _runId, ...delta } = payload;
|
|
109
|
+
const nextState = {
|
|
110
|
+
...current.state,
|
|
111
|
+
...delta
|
|
112
|
+
};
|
|
113
|
+
if (delta.status !== void 0 && delta.status !== "aborted") delete nextState.error;
|
|
114
|
+
current = {
|
|
115
|
+
workflow: current.workflow,
|
|
116
|
+
invocation: current.invocation,
|
|
117
|
+
state: nextState
|
|
118
|
+
};
|
|
119
|
+
} else if (payload.action === "output" && current && payload.runId === current.invocation.runId) {
|
|
120
|
+
const outputValue = payload.outputType === "list" ? JSON.parse(payload.value) : payload.value;
|
|
121
|
+
const nextOutputs = {
|
|
122
|
+
...current.state.outputs ?? {},
|
|
123
|
+
[payload.name]: outputValue
|
|
124
|
+
};
|
|
125
|
+
const nextState = {
|
|
126
|
+
...current.state,
|
|
127
|
+
outputs: nextOutputs
|
|
128
|
+
};
|
|
129
|
+
current = {
|
|
130
|
+
workflow: current.workflow,
|
|
131
|
+
invocation: current.invocation,
|
|
132
|
+
state: nextState
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
} catch {}
|
|
136
|
+
}
|
|
137
|
+
return current;
|
|
138
|
+
}
|
|
139
|
+
function initialWorkflowRunSummary() {
|
|
140
|
+
return {
|
|
141
|
+
status: "idle",
|
|
142
|
+
skillInvoked: false
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
function foldWorkflowEvent(state, event) {
|
|
146
|
+
if (event.type === "tool/call") {
|
|
147
|
+
if (state.skillInvoked) return state;
|
|
148
|
+
if (event.data.name === "skill") try {
|
|
149
|
+
if (JSON.parse(event.data.arguments).name === "yaml-workflow") return {
|
|
150
|
+
...state,
|
|
151
|
+
skillInvoked: true
|
|
152
|
+
};
|
|
153
|
+
} catch {}
|
|
154
|
+
return state;
|
|
155
|
+
}
|
|
156
|
+
if (event.type !== "command/run") return state;
|
|
157
|
+
if (event.data.name !== "wf-event") {
|
|
158
|
+
if (event.data.name === "wf" || event.data.name === "wf-validate" || event.data.name === "wf-resume" || event.data.name === "wf-abort" || event.data.name === "wf-list") {
|
|
159
|
+
if (state.skillInvoked) return state;
|
|
160
|
+
return {
|
|
161
|
+
...state,
|
|
162
|
+
skillInvoked: true
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
return state;
|
|
166
|
+
}
|
|
167
|
+
if (typeof event.data.args !== "string") return state;
|
|
168
|
+
try {
|
|
169
|
+
const payload = JSON.parse(event.data.args);
|
|
170
|
+
if (!payload.runId) return state;
|
|
171
|
+
if (isValidInitPayload(payload)) return {
|
|
172
|
+
status: "running",
|
|
173
|
+
runId: payload.runId,
|
|
174
|
+
stepIndex: 0,
|
|
175
|
+
skillInvoked: state.skillInvoked
|
|
176
|
+
};
|
|
177
|
+
if (payload.action === "state" && state.runId === payload.runId) return {
|
|
178
|
+
...state,
|
|
179
|
+
status: payload.status ?? state.status,
|
|
180
|
+
stepIndex: payload.stepIndex ?? state.stepIndex
|
|
181
|
+
};
|
|
182
|
+
} catch {}
|
|
183
|
+
return state;
|
|
184
|
+
}
|
|
185
|
+
function toWorkflowRunSummaryRecord(summary) {
|
|
186
|
+
return summary.status !== "idle" || summary.skillInvoked ? summary : null;
|
|
187
|
+
}
|
|
188
|
+
// src/types.ts
|
|
189
|
+
const FlatChoiceMappingSchema = z.record(z.string().min(1, "Choice key cannot be empty"), z.string()).refine((val) => Object.keys(val).length > 0, { message: "Choice mapping cannot be empty" });
|
|
190
|
+
const NestedChoiceMappingSchema = z.record(z.string().min(1, "Derived argument name cannot be empty"), z.record(z.string().min(1, "Choice key cannot be empty"), z.string()).refine((val) => Object.keys(val).length > 0, { message: "Choice mapping cannot be empty" })).refine((val) => Object.keys(val).length > 0, { message: "Choice mapping cannot be empty" });
|
|
191
|
+
const ChoiceMappingSchema = z.union([FlatChoiceMappingSchema, NestedChoiceMappingSchema]);
|
|
192
|
+
const WorkflowArgSchema = z.discriminatedUnion("type", [
|
|
193
|
+
z.object({
|
|
194
|
+
type: z.literal("string"),
|
|
195
|
+
description: z.string().optional(),
|
|
196
|
+
default: z.string().optional(),
|
|
197
|
+
required: z.boolean().optional()
|
|
198
|
+
}).strict(),
|
|
199
|
+
z.object({
|
|
200
|
+
type: z.literal("choice"),
|
|
201
|
+
description: z.string().optional(),
|
|
202
|
+
choices: z.array(z.string().min(1, "Choice values cannot be empty")).min(1, "Choice argument must define at least one option"),
|
|
203
|
+
default: z.string().optional(),
|
|
204
|
+
required: z.boolean().optional(),
|
|
205
|
+
mapping: ChoiceMappingSchema.optional(),
|
|
206
|
+
mappings: ChoiceMappingSchema.optional()
|
|
207
|
+
}).strict(),
|
|
208
|
+
z.object({
|
|
209
|
+
type: z.literal("bool"),
|
|
210
|
+
description: z.string().optional(),
|
|
211
|
+
default: z.union([z.boolean(), z.string()]).optional(),
|
|
212
|
+
required: z.boolean().optional()
|
|
213
|
+
}).strict()
|
|
214
|
+
]).refine((data) => {
|
|
215
|
+
if (data.type === "choice" && data.default !== void 0) return data.choices.includes(data.default);
|
|
216
|
+
if (data.type === "bool" && data.default !== void 0) {
|
|
217
|
+
if (typeof data.default === "boolean") return true;
|
|
218
|
+
if (typeof data.default === "string") {
|
|
219
|
+
const lower = data.default.trim().toLowerCase();
|
|
220
|
+
return lower === "true" || lower === "false";
|
|
221
|
+
}
|
|
222
|
+
return false;
|
|
223
|
+
}
|
|
224
|
+
return true;
|
|
225
|
+
}, {
|
|
226
|
+
message: "Default value must be valid for the specified argument type",
|
|
227
|
+
path: ["default"]
|
|
228
|
+
}).refine((data) => {
|
|
229
|
+
if (data.type === "choice" && data.mapping !== void 0 && data.mappings !== void 0) return false;
|
|
230
|
+
return true;
|
|
231
|
+
}, {
|
|
232
|
+
message: "Cannot specify both 'mapping' and 'mappings'",
|
|
233
|
+
path: ["mappings"]
|
|
234
|
+
});
|
|
235
|
+
const SubagentConfigSchema = z.object({
|
|
236
|
+
provider: z.string().min(1, "Provider name cannot be empty").optional(),
|
|
237
|
+
llmProvider: z.string().min(1, "LLM provider name cannot be empty").optional(),
|
|
238
|
+
preset: z.string().min(1, "Preset name cannot be empty").optional(),
|
|
239
|
+
model: z.string().min(1, "Model name cannot be empty").optional(),
|
|
240
|
+
thinking: z.string().min(1, "Thinking level cannot be empty").optional()
|
|
241
|
+
});
|
|
242
|
+
const FileOutputBaseSchema = z.enum(["scratch", "workspace"]);
|
|
243
|
+
const StepOutputDefSchema = z.discriminatedUnion("type", [
|
|
244
|
+
z.object({
|
|
245
|
+
type: z.literal("file"),
|
|
246
|
+
path: z.string().min(1, "File path cannot be empty"),
|
|
247
|
+
base: FileOutputBaseSchema.optional()
|
|
248
|
+
}),
|
|
249
|
+
z.object({
|
|
250
|
+
type: z.literal("string"),
|
|
251
|
+
description: z.string().optional()
|
|
252
|
+
}),
|
|
253
|
+
z.object({
|
|
254
|
+
type: z.literal("list"),
|
|
255
|
+
description: z.string().optional(),
|
|
256
|
+
min: z.number().int().nonnegative().optional(),
|
|
257
|
+
max: z.number().int().nonnegative().optional()
|
|
258
|
+
})
|
|
259
|
+
]).refine((data) => {
|
|
260
|
+
if (data.type === "list") {
|
|
261
|
+
if (data.min !== void 0 && data.max !== void 0 && data.min > data.max) return false;
|
|
262
|
+
}
|
|
263
|
+
return true;
|
|
264
|
+
}, {
|
|
265
|
+
message: "'min' cannot be greater than 'max'",
|
|
266
|
+
path: ["min"]
|
|
267
|
+
});
|
|
268
|
+
const StepOutputsMapSchema = z.record(z.string().min(1, "Output name cannot be empty"), StepOutputDefSchema);
|
|
269
|
+
const WorkflowFileStepSchema = z.union([
|
|
270
|
+
z.string().min(1, "Prompt cannot be empty"),
|
|
271
|
+
z.looseObject({
|
|
272
|
+
kind: z.literal("prompt").optional(),
|
|
273
|
+
name: z.string().optional(),
|
|
274
|
+
if: z.string().min(1, "If condition cannot be empty").optional(),
|
|
275
|
+
prompt: z.string().min(1, "Prompt cannot be empty"),
|
|
276
|
+
gate: z.union([z.boolean(), z.string().min(1, "Gate description cannot be empty")]).optional(),
|
|
277
|
+
subagent: z.union([
|
|
278
|
+
z.boolean(),
|
|
279
|
+
z.string().trim().min(1, "Subagent descriptor cannot be empty"),
|
|
280
|
+
SubagentConfigSchema
|
|
281
|
+
]).optional(),
|
|
282
|
+
foreach: z.string().min(1, "Foreach cannot be empty").optional(),
|
|
283
|
+
outputs: StepOutputsMapSchema.optional(),
|
|
284
|
+
output: z.string().min(1, "Output name cannot be empty").optional()
|
|
285
|
+
}).refine((data) => !(data.output !== void 0 && data.outputs !== void 0), { message: "Step cannot declare both 'output' and 'outputs'" }).refine((data) => !(data.output !== void 0 && (data.subagent === void 0 || data.subagent === false)), { message: "'output' is only allowed on subagent steps" }).refine((data) => !(data.foreach !== void 0 && (data.subagent === void 0 || data.subagent === false)), { message: "'foreach' is only allowed on subagent steps" }).refine((data) => {
|
|
286
|
+
if (!(data.subagent !== void 0 && data.subagent !== false) || !data.outputs) return true;
|
|
287
|
+
return Object.values(data.outputs).every((def) => def.type !== "list");
|
|
288
|
+
}, { message: "Subagent steps cannot declare outputs of type 'list'" }).refine((data) => {
|
|
289
|
+
if (!(data.foreach !== void 0 && data.subagent !== void 0 && data.subagent !== false) || !data.outputs) return true;
|
|
290
|
+
return Object.values(data.outputs).every((def) => def.type === "string");
|
|
291
|
+
}, { message: "Foreach subagent steps only support string outputs" }),
|
|
292
|
+
z.looseObject({
|
|
293
|
+
kind: z.literal("print").optional(),
|
|
294
|
+
name: z.string().optional(),
|
|
295
|
+
if: z.string().min(1, "If condition cannot be empty").optional(),
|
|
296
|
+
text: z.string().min(1, "Text cannot be empty")
|
|
297
|
+
}).refine((data) => !("output" in data && data.output !== void 0), { message: "'output' is only allowed on subagent steps" }).refine((data) => !("foreach" in data && data.foreach !== void 0), { message: "'foreach' is only allowed on subagent steps" }),
|
|
298
|
+
z.looseObject({
|
|
299
|
+
name: z.string().optional(),
|
|
300
|
+
if: z.string().min(1, "If condition cannot be empty").optional(),
|
|
301
|
+
print: z.string().min(1, "Text cannot be empty")
|
|
302
|
+
}).refine((data) => !("output" in data && data.output !== void 0), { message: "'output' is only allowed on subagent steps" }).refine((data) => !("foreach" in data && data.foreach !== void 0), { message: "'foreach' is only allowed on subagent steps" }),
|
|
303
|
+
z.looseObject({
|
|
304
|
+
name: z.string().optional(),
|
|
305
|
+
if: z.string().min(1, "If condition cannot be empty").optional(),
|
|
306
|
+
gate: z.union([z.boolean(), z.string().min(1, "Gate description cannot be empty")]),
|
|
307
|
+
outputs: StepOutputsMapSchema.optional()
|
|
308
|
+
}).refine((data) => !("output" in data && data.output !== void 0) && !("prompt" in data && data.prompt !== void 0), { message: "'output' is only allowed on subagent steps" }).refine((data) => !("foreach" in data && data.foreach !== void 0), { message: "'foreach' is only allowed on subagent steps" })
|
|
309
|
+
]);
|
|
310
|
+
const WorkflowFileSchema = z.object({
|
|
311
|
+
name: z.string().optional(),
|
|
312
|
+
title: z.string().optional(),
|
|
313
|
+
description: z.string().optional(),
|
|
314
|
+
args: z.record(z.string(), WorkflowArgSchema).optional(),
|
|
315
|
+
steps: z.array(WorkflowFileStepSchema).min(1, "Workflow must contain at least one step")
|
|
316
|
+
}).strict();
|
|
317
|
+
const WorkflowStatusSchema = z.enum([
|
|
318
|
+
"running",
|
|
319
|
+
"paused",
|
|
320
|
+
"aborted",
|
|
321
|
+
"completed"
|
|
322
|
+
]);
|
|
323
|
+
const workflowRunSummarySchema = z.object({
|
|
324
|
+
status: z.enum([
|
|
325
|
+
"idle",
|
|
326
|
+
"running",
|
|
327
|
+
"paused",
|
|
328
|
+
"aborted",
|
|
329
|
+
"completed"
|
|
330
|
+
]),
|
|
331
|
+
runId: z.string().optional(),
|
|
332
|
+
stepIndex: z.number().int().nonnegative().optional(),
|
|
333
|
+
skillInvoked: z.boolean().default(false)
|
|
334
|
+
});
|
|
335
|
+
const WorkflowStateSchema = z.object({
|
|
336
|
+
stepIndex: z.number().int().nonnegative(),
|
|
337
|
+
status: WorkflowStatusSchema,
|
|
338
|
+
pauseReason: z.enum(["gate", "interrupted"]).optional(),
|
|
339
|
+
outputs: z.record(z.string(), z.union([z.string(), z.array(z.string()).readonly()])).readonly().optional(),
|
|
340
|
+
error: z.string().optional()
|
|
341
|
+
});
|
|
342
|
+
// src/effects.ts
|
|
343
|
+
/**
|
|
344
|
+
* PURPOSE: Execution effect boundary and Cordis/DSH runtime implementation.
|
|
345
|
+
* ALLOWED: Async execution, agent followups, subagent activation, event appending.
|
|
346
|
+
* FORBIDDEN: Direct workflow parsing or state transitions (delegate to pure core).
|
|
347
|
+
*/
|
|
348
|
+
/**
|
|
349
|
+
* PURPOSE: Abstract execution effect boundary for workflows.
|
|
350
|
+
* CONTRACT:
|
|
351
|
+
* - Subclasses define runtime-specific I/O (DSH/Cordis vs. in-memory test runner).
|
|
352
|
+
* - Stateless workflow runner delegates all side effects through this contract.
|
|
353
|
+
*/
|
|
354
|
+
var WorkflowEffectContext = class {
|
|
355
|
+
/** Records a verified workflow output in session events */
|
|
356
|
+
recordOutput(stepIndex, name, value, outputType, base, runId) {
|
|
357
|
+
this.emit({
|
|
358
|
+
action: "output",
|
|
359
|
+
stepIndex,
|
|
360
|
+
name,
|
|
361
|
+
value,
|
|
362
|
+
outputType,
|
|
363
|
+
...base ? { base } : {},
|
|
364
|
+
runId
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
/** Retrieves a previously captured output for a step from session events */
|
|
368
|
+
getCapturedOutput(stepIndex, name) {
|
|
369
|
+
const events = this.snapshotEvents();
|
|
370
|
+
for (let i = events.length - 1; i >= 0; i--) {
|
|
371
|
+
const evt = events[i];
|
|
372
|
+
if (evt.type !== "command/run") continue;
|
|
373
|
+
const data = evt.data;
|
|
374
|
+
if (data?.name !== "wf-event" || typeof data.args !== "string") continue;
|
|
375
|
+
try {
|
|
376
|
+
const payload = JSON.parse(data.args);
|
|
377
|
+
if (payload.action === "output" && payload.stepIndex === stepIndex && payload.name === name) return payload.value;
|
|
378
|
+
} catch {}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Purpose: Determines whether a session title has already been set in the event log.
|
|
383
|
+
* Contract:
|
|
384
|
+
* - Inputs: None.
|
|
385
|
+
* - Outputs: True if a session/title event exists; false otherwise.
|
|
386
|
+
*/
|
|
387
|
+
hasTitle() {
|
|
388
|
+
return this.snapshotEvents().some((event) => event.type === "session/title");
|
|
389
|
+
}
|
|
390
|
+
/** Sets the session title */
|
|
391
|
+
setTitle(title) {
|
|
392
|
+
this.appendSessionEvent("session/title", {
|
|
393
|
+
title,
|
|
394
|
+
messageSeqs: [],
|
|
395
|
+
source: { kind: "user" }
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Emits a workflow event as paired command/run and command/done records.
|
|
400
|
+
* CONTRACT:
|
|
401
|
+
* - Inputs: workflow lifecycle, request, step, print, or output payload.
|
|
402
|
+
* - Outputs: appends command/run and command/done records to session.
|
|
403
|
+
*/
|
|
404
|
+
emit(event) {
|
|
405
|
+
const commandId = `wf-${event.action}-${this.snapshotEvents().length}`;
|
|
406
|
+
const payload = {
|
|
407
|
+
...event,
|
|
408
|
+
sessionId: this.sessionId
|
|
409
|
+
};
|
|
410
|
+
this.appendSessionEvent("command/run", {
|
|
411
|
+
commandId,
|
|
412
|
+
name: WORKFLOW_EVENT_NAME,
|
|
413
|
+
args: JSON.stringify(payload),
|
|
414
|
+
source: { kind: "user" }
|
|
415
|
+
});
|
|
416
|
+
this.appendSessionEvent("command/done", {
|
|
417
|
+
commandId,
|
|
418
|
+
kind: "success",
|
|
419
|
+
text: `Workflow action '${event.action}' recorded`
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
/**
|
|
424
|
+
* PURPOSE: Production effect context binding the runner to DeepSeek Harness / Cordis runtime.
|
|
425
|
+
* CONTRACT:
|
|
426
|
+
* - Inputs: DshWorkflowEffectContextOptions containing Context, Agent, and optional Logger.
|
|
427
|
+
* - Side-effects: Dispatches to Cordis services, reads files via fs/promises, appends to Session.
|
|
428
|
+
*/
|
|
429
|
+
var DshWorkflowEffectContext = class extends WorkflowEffectContext {
|
|
430
|
+
sessionId;
|
|
431
|
+
ctx;
|
|
432
|
+
agent;
|
|
433
|
+
log;
|
|
434
|
+
activeAbortController;
|
|
435
|
+
constructor({ ctx, agent, log }) {
|
|
436
|
+
super();
|
|
437
|
+
this.ctx = ctx;
|
|
438
|
+
this.agent = agent;
|
|
439
|
+
this.sessionId = agent.id;
|
|
440
|
+
this.log = log;
|
|
441
|
+
}
|
|
442
|
+
watchAbort(controller) {
|
|
443
|
+
this.activeAbortController = controller;
|
|
444
|
+
const eventDispose = this.ctx.on("session/event", (session, event) => {
|
|
445
|
+
if (session === this.agent.session && event.type === "turn/end") {
|
|
446
|
+
if ((event.data?.reason)?.kind === "aborted") controller.abort({ kind: "pause" });
|
|
447
|
+
}
|
|
448
|
+
});
|
|
449
|
+
return () => {
|
|
450
|
+
this.activeAbortController = void 0;
|
|
451
|
+
eventDispose();
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
async resolveWorkflowFile(targetPath) {
|
|
455
|
+
const cwd = this.agent.session.header.cwd;
|
|
456
|
+
if (!cwd) throw new Error("Session working directory (agent.session.header.cwd) is missing");
|
|
457
|
+
const baseLocations = path.isAbsolute(targetPath) ? [targetPath] : [
|
|
458
|
+
path.resolve(cwd, targetPath),
|
|
459
|
+
path.resolve(cwd, ".agents/wf", targetPath),
|
|
460
|
+
path.resolve(homedir(), ".agents/wf", targetPath)
|
|
461
|
+
];
|
|
462
|
+
const hasExt = targetPath.endsWith(".yaml") || targetPath.endsWith(".yml");
|
|
463
|
+
for (const base of baseLocations) {
|
|
464
|
+
const candidates = hasExt ? [base] : [
|
|
465
|
+
base,
|
|
466
|
+
`${base}.yaml`,
|
|
467
|
+
`${base}.yml`
|
|
468
|
+
];
|
|
469
|
+
for (const candidate of candidates) try {
|
|
470
|
+
if ((await stat(candidate)).isFile()) return candidate;
|
|
471
|
+
} catch (err) {
|
|
472
|
+
const nodeErr = err;
|
|
473
|
+
if (nodeErr.code !== "ENOENT" && nodeErr.code !== "ENOTDIR") throw err;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
throw new Error(`Workflow file not found for target '${targetPath}'. Checked locations relative to cwd and ~/.agents/wf.`);
|
|
477
|
+
}
|
|
478
|
+
async readWorkflow(targetPath) {
|
|
479
|
+
const resolvedPath = await this.resolveWorkflowFile(targetPath);
|
|
480
|
+
return readFile(resolvedPath, "utf8");
|
|
481
|
+
}
|
|
482
|
+
async listWorkflowFiles(scope) {
|
|
483
|
+
const cwd = this.agent.session.header.cwd;
|
|
484
|
+
if (!cwd) throw new Error("Session working directory (agent.session.header.cwd) is missing");
|
|
485
|
+
const dirPath = scope === "local" ? path.resolve(cwd, ".agents/wf") : path.resolve(homedir(), ".agents/wf");
|
|
486
|
+
return (await scanWorkflowDirectory(dirPath, dirPath)).sort((a, b) => a.target.localeCompare(b.target));
|
|
487
|
+
}
|
|
488
|
+
async dispatchPrompt(effect) {
|
|
489
|
+
this.agent.followup(createUserMessage({
|
|
490
|
+
content: [{
|
|
491
|
+
type: "text",
|
|
492
|
+
text: effect.promptText
|
|
493
|
+
}],
|
|
494
|
+
source: {
|
|
495
|
+
kind: "workflow",
|
|
496
|
+
form: "notice",
|
|
497
|
+
summary: effect.stepLabel
|
|
498
|
+
}
|
|
499
|
+
}));
|
|
500
|
+
await this.agent.whenIdle();
|
|
501
|
+
}
|
|
502
|
+
async dispatchSubagent(effect, signal) {
|
|
503
|
+
const provider = effect.config.provider ?? "spawn";
|
|
504
|
+
const subagentSignal = signal ?? new AbortController().signal;
|
|
505
|
+
const result = await (await this.ctx.subagents.startActivation({
|
|
506
|
+
provider,
|
|
507
|
+
label: effect.stepLabel,
|
|
508
|
+
delivery: "caller",
|
|
509
|
+
signal: subagentSignal,
|
|
510
|
+
parent: this.agent,
|
|
511
|
+
prompt: [{
|
|
512
|
+
type: "text",
|
|
513
|
+
text: effect.promptText
|
|
514
|
+
}],
|
|
515
|
+
...effect.config.preset ? { agentPreset: effect.config.preset } : {},
|
|
516
|
+
...effect.config.llmProvider || effect.config.model || effect.config.thinking ? { agentOptions: {
|
|
517
|
+
...effect.config.llmProvider ? { provider: effect.config.llmProvider } : {},
|
|
518
|
+
...effect.config.model ? { model: effect.config.model } : {},
|
|
519
|
+
...effect.config.thinking ? { reasoningEffort: ReasoningEffortId(effect.config.thinking) } : {}
|
|
520
|
+
} } : {},
|
|
521
|
+
...effect.outputSchema ? { outputSchema: effect.outputSchema } : {}
|
|
522
|
+
})).result;
|
|
523
|
+
if (result.stopReason === "aborted") this.activeAbortController?.abort({ kind: "pause" });
|
|
524
|
+
return {
|
|
525
|
+
outputText: result.output.filter((block) => block.type === "text" && Boolean(block.text)).map((block) => block.text).join("\n").trim(),
|
|
526
|
+
structured: result.structured
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
async validateSubagentRoute(config, signal) {
|
|
530
|
+
const provider = config.provider ?? "spawn";
|
|
531
|
+
const subagentProvider = this.ctx.subagents.getProvider(provider);
|
|
532
|
+
if (!subagentProvider) return {
|
|
533
|
+
valid: false,
|
|
534
|
+
message: `Subagent provider '${provider}' is not registered`
|
|
535
|
+
};
|
|
536
|
+
if (config.preset) {
|
|
537
|
+
if (!subagentProvider.capabilities.agentPreset || subagentProvider.inheritsParentContext) return {
|
|
538
|
+
valid: false,
|
|
539
|
+
message: `Subagent provider '${provider}' does not support independent agent preset selection`
|
|
540
|
+
};
|
|
541
|
+
const presets = this.ctx.get("agentPresets");
|
|
542
|
+
if (!presets) return {
|
|
543
|
+
valid: false,
|
|
544
|
+
message: `Cannot validate agent preset '${config.preset}': 'agentPresets' service is unavailable`
|
|
545
|
+
};
|
|
546
|
+
try {
|
|
547
|
+
await presets.readDocument(config.preset);
|
|
548
|
+
} catch (err) {
|
|
549
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
550
|
+
return {
|
|
551
|
+
valid: false,
|
|
552
|
+
message: `Agent preset '${config.preset}' not found: ${message}`
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
if (config.llmProvider || config.model || config.thinking) {
|
|
557
|
+
if (!subagentProvider.capabilities.agentOptions) return {
|
|
558
|
+
valid: false,
|
|
559
|
+
message: `Subagent provider '${provider}' does not support custom model options (agentOptions: false)`
|
|
560
|
+
};
|
|
561
|
+
const llm = this.ctx.get("llm");
|
|
562
|
+
if (!llm) return {
|
|
563
|
+
valid: false,
|
|
564
|
+
message: "Cannot validate subagent model: 'llm' service is unavailable"
|
|
565
|
+
};
|
|
566
|
+
const parentOptions = parentAgentOptionsForDelegation(this.agent);
|
|
567
|
+
const effectiveProvider = config.llmProvider ?? parentOptions.provider;
|
|
568
|
+
const effectiveModel = config.model ?? parentOptions.model;
|
|
569
|
+
if (!effectiveProvider) return {
|
|
570
|
+
valid: false,
|
|
571
|
+
message: "Cannot validate subagent model without an effective LLM provider"
|
|
572
|
+
};
|
|
573
|
+
if (!effectiveModel) return {
|
|
574
|
+
valid: false,
|
|
575
|
+
message: "Cannot validate subagent model without an effective model ID"
|
|
576
|
+
};
|
|
577
|
+
const availableProviders = llm.listProviders();
|
|
578
|
+
if (!availableProviders.some((p) => p.id === effectiveProvider)) return {
|
|
579
|
+
valid: false,
|
|
580
|
+
message: `LLM provider '${effectiveProvider}' is not registered; available providers: ${availableProviders.map((p) => p.id).join(", ") || "(none)"}`
|
|
581
|
+
};
|
|
582
|
+
try {
|
|
583
|
+
await llm.resolveCallConfig({
|
|
584
|
+
provider: effectiveProvider,
|
|
585
|
+
model: effectiveModel,
|
|
586
|
+
...config.thinking ? { reasoningEffort: ReasoningEffortId(config.thinking) } : {}
|
|
587
|
+
}, signal);
|
|
588
|
+
} catch (err) {
|
|
589
|
+
return {
|
|
590
|
+
valid: false,
|
|
591
|
+
message: err instanceof Error ? err.message : String(err)
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return { valid: true };
|
|
596
|
+
}
|
|
597
|
+
logInfo(message) {
|
|
598
|
+
if (this.log) this.log.info(message);
|
|
599
|
+
}
|
|
600
|
+
resolveOutputPath(filePath, base) {
|
|
601
|
+
const cwd = this.agent.session.header.cwd;
|
|
602
|
+
if (!cwd) throw new Error("Session working directory (agent.session.header.cwd) is missing");
|
|
603
|
+
if (base === "workspace") return path.resolve(cwd, filePath);
|
|
604
|
+
return path.resolve(cwd, ".agents/scratch", this.sessionId, filePath);
|
|
605
|
+
}
|
|
606
|
+
async checkFileWritten(resolvedPath) {
|
|
607
|
+
try {
|
|
608
|
+
const s = await stat(resolvedPath);
|
|
609
|
+
return s.isFile() && s.size > 0;
|
|
610
|
+
} catch (err) {
|
|
611
|
+
if (err instanceof Error && "code" in err && (err.code === "ENOENT" || err.code === "ENOTDIR")) return false;
|
|
612
|
+
throw err;
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
async ensureScratchDirectory() {
|
|
616
|
+
const cwd = this.agent.session.header.cwd;
|
|
617
|
+
if (!cwd) throw new Error("Session working directory (agent.session.header.cwd) is missing");
|
|
618
|
+
const baseScratchDir = path.resolve(cwd, ".agents/scratch");
|
|
619
|
+
let baseExists = false;
|
|
620
|
+
try {
|
|
621
|
+
baseExists = (await stat(baseScratchDir)).isDirectory();
|
|
622
|
+
} catch (err) {
|
|
623
|
+
if (!(err instanceof Error && "code" in err && err.code === "ENOENT")) throw err;
|
|
624
|
+
}
|
|
625
|
+
if (!baseExists) {
|
|
626
|
+
await mkdir(baseScratchDir, { recursive: true });
|
|
627
|
+
await writeFile(path.join(baseScratchDir, ".gitignore"), "*\n", "utf8");
|
|
628
|
+
}
|
|
629
|
+
const sessionScratchDir = path.resolve(baseScratchDir, this.sessionId);
|
|
630
|
+
await mkdir(sessionScratchDir, { recursive: true });
|
|
631
|
+
return sessionScratchDir;
|
|
632
|
+
}
|
|
633
|
+
appendSessionEvent(type, data) {
|
|
634
|
+
this.agent.session.append(type, data);
|
|
635
|
+
}
|
|
636
|
+
snapshotEvents() {
|
|
637
|
+
return this.agent.session.snapshotEvents();
|
|
638
|
+
}
|
|
639
|
+
setStatus(status) {
|
|
640
|
+
this.ctx.emit("agent/status", {
|
|
641
|
+
agent: this.agent,
|
|
642
|
+
status
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
whenIdle() {
|
|
646
|
+
return this.agent.whenIdle();
|
|
647
|
+
}
|
|
648
|
+
};
|
|
649
|
+
/**
|
|
650
|
+
* Recursively scans directory for workflow files (.yaml and .yml).
|
|
651
|
+
* CONTRACT:
|
|
652
|
+
* - Inputs: base directory path and current directory path.
|
|
653
|
+
* - Outputs: Array of target identifier relative to base and raw file content.
|
|
654
|
+
* - Throws: Re-throws unexpected filesystem errors; returns [] on ENOENT / ENOTDIR.
|
|
655
|
+
*/
|
|
656
|
+
async function scanWorkflowDirectory(baseDir, currentDir) {
|
|
657
|
+
try {
|
|
658
|
+
const entries = await readdir(currentDir, { withFileTypes: true });
|
|
659
|
+
const results = [];
|
|
660
|
+
for (const entry of entries) {
|
|
661
|
+
const fullPath = path.join(currentDir, entry.name);
|
|
662
|
+
if (entry.isDirectory()) {
|
|
663
|
+
const nested = await scanWorkflowDirectory(baseDir, fullPath);
|
|
664
|
+
results.push(...nested);
|
|
665
|
+
} else if (entry.isFile() && (entry.name.endsWith(".yaml") || entry.name.endsWith(".yml"))) {
|
|
666
|
+
const relPath = path.relative(baseDir, fullPath);
|
|
667
|
+
const content = await readFile(fullPath, "utf8");
|
|
668
|
+
results.push({
|
|
669
|
+
target: relPath,
|
|
670
|
+
content
|
|
671
|
+
});
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
return results;
|
|
675
|
+
} catch (err) {
|
|
676
|
+
const nodeErr = err;
|
|
677
|
+
if (nodeErr.code === "ENOENT" || nodeErr.code === "ENOTDIR") return [];
|
|
678
|
+
throw err;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
// src/boolean.ts
|
|
682
|
+
/**
|
|
683
|
+
* PURPOSE: Pure boolean parsing, template interpolation, and gate resolution helper functions.
|
|
684
|
+
* ALLOWED: Pure computation, string parsing, template interpolation.
|
|
685
|
+
* FORBIDDEN: No I/O, no framework dependencies, no side effects.
|
|
686
|
+
*/
|
|
687
|
+
/**
|
|
688
|
+
* Converts a boolean, string, or unknown value into a strict boolean (true/false) or undefined if not a boolean representation.
|
|
689
|
+
* CONTRACT:
|
|
690
|
+
* - Input: unknown value (boolean, string, undefined, null, etc.).
|
|
691
|
+
* - Output: boolean true for true / "true" (case-insensitive), false for false / "false" (case-insensitive), undefined otherwise.
|
|
692
|
+
*/
|
|
693
|
+
function parseBoolean(value) {
|
|
694
|
+
if (typeof value === "boolean") return value;
|
|
695
|
+
if (typeof value === "string") {
|
|
696
|
+
const trimmed = value.trim().toLowerCase();
|
|
697
|
+
if (trimmed === "true") return true;
|
|
698
|
+
if (trimmed === "false") return false;
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* Interpolates {{args.<name>}} and {{outputs.<name>}} template variables in a text string.
|
|
703
|
+
* CONTRACT:
|
|
704
|
+
* - Input: raw template string, args map, and optional outputs map.
|
|
705
|
+
* - Output: string with all {{args.*}} and {{outputs.*}} variables replaced.
|
|
706
|
+
* - Throws: Error if an {{args.*}} variable is unresolvable.
|
|
707
|
+
*/
|
|
708
|
+
function interpolateTemplate(template, args, outputs, context) {
|
|
709
|
+
let result = template.replace(/\{\{args\.([a-zA-Z0-9_-]+)\}\}/g, (_match, key) => {
|
|
710
|
+
const value = args[key];
|
|
711
|
+
if (value === void 0) throw new Error(`Unresolved workflow argument: {{args.${key}}}`);
|
|
712
|
+
return value;
|
|
713
|
+
});
|
|
714
|
+
if (context?.item !== void 0) result = result.replace(/\{\{item\}\}/g, context.item);
|
|
715
|
+
if (outputs !== void 0) result = result.replace(/\{\{outputs\.([a-zA-Z0-9_-]+)\}\}/g, (_match, key) => {
|
|
716
|
+
const val = outputs[key];
|
|
717
|
+
if (val === void 0) return String(val);
|
|
718
|
+
if (Array.isArray(val)) {
|
|
719
|
+
if (val.length === 0) return "";
|
|
720
|
+
return val.map((item) => `- ${item}`).join("\n");
|
|
721
|
+
}
|
|
722
|
+
return String(val);
|
|
723
|
+
});
|
|
724
|
+
return result;
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Resolves a step gate declaration (boolean, templated string, or explicit description) into an active gate criteria string, or undefined if inactive.
|
|
728
|
+
* CONTRACT:
|
|
729
|
+
* - Input: gate (string | boolean | undefined), args map, optional outputs map, optional fallback stepName.
|
|
730
|
+
* - Output: resolved gate description string if active, or undefined if inactive (false, "false", empty, or undefined).
|
|
731
|
+
*/
|
|
732
|
+
function resolveGate(gate, args = {}, outputs, stepName) {
|
|
733
|
+
if (gate === void 0) return;
|
|
734
|
+
if (typeof gate === "boolean") return gate ? stepName || "Gate" : void 0;
|
|
735
|
+
const interpolated = interpolateTemplate(gate, args, outputs).trim();
|
|
736
|
+
if (interpolated === "") return;
|
|
737
|
+
const interpolatedBool = parseBoolean(interpolated);
|
|
738
|
+
if (interpolatedBool === false) return;
|
|
739
|
+
if (interpolatedBool === true) return stepName || "Gate";
|
|
740
|
+
return interpolated;
|
|
741
|
+
}
|
|
742
|
+
// src/parser.ts
|
|
743
|
+
/**
|
|
744
|
+
* PURPOSE: Pure parsing, argument resolution, templating, and prompt formatting utilities.
|
|
745
|
+
* ALLOWED: Pure computation, string manipulation, YAML parsing, schema validation.
|
|
746
|
+
* FORBIDDEN: No I/O, no filesystem, no runtime state, no agent orchestration.
|
|
747
|
+
*/
|
|
748
|
+
/**
|
|
749
|
+
* Purpose: Parses raw YAML text into a validated WorkflowFile.
|
|
750
|
+
* CONTRACT:
|
|
751
|
+
* - Input: raw YAML string content.
|
|
752
|
+
* - Output: validated WorkflowFile representing valid file format.
|
|
753
|
+
* - Throws: Error when YAML parsing fails or file violates WorkflowFileSchema.
|
|
754
|
+
*/
|
|
755
|
+
function parseWorkflowFile(content) {
|
|
756
|
+
const raw = parse(content);
|
|
757
|
+
const result = WorkflowFileSchema.safeParse(raw);
|
|
758
|
+
if (!result.success) {
|
|
759
|
+
const reasons = result.error.issues.map((issue) => `${issue.path.join(".") || "root"}: ${issue.message}`).join("; ");
|
|
760
|
+
throw new Error(`Invalid workflow schema: ${reasons}`);
|
|
761
|
+
}
|
|
762
|
+
return result.data;
|
|
763
|
+
}
|
|
764
|
+
/** Reserved model value: the child keeps the parent's provider and model. */
|
|
765
|
+
const INHERIT_MODEL = "inherit";
|
|
766
|
+
/**
|
|
767
|
+
* Purpose: Parses concise model/subagent shorthand string [@preset/][llmProvider/]model[:thinking] or :thinking into SubagentConfig.
|
|
768
|
+
* Contract:
|
|
769
|
+
* - Inputs: Non-empty shorthand string.
|
|
770
|
+
* - Outputs: SubagentConfig with parsed preset, llmProvider, model, and thinking fields.
|
|
771
|
+
* - Throws: Error if format contains empty segments, runner prefixes, or invalid syntax.
|
|
772
|
+
*/
|
|
773
|
+
function parseSubagentShorthand(shorthand) {
|
|
774
|
+
const trimmed = shorthand.trim();
|
|
775
|
+
if (!trimmed) throw new Error("Subagent shorthand cannot be empty");
|
|
776
|
+
if (trimmed.includes("+")) throw new Error("Invalid thinking delimiter '+'; use ':thinking' instead (e.g. ':high' or 'model:high')");
|
|
777
|
+
if (trimmed === "fork" || trimmed === "spawn" || trimmed.startsWith("fork:") || trimmed.startsWith("spawn:")) throw new Error("Runner/provider is not supported in model shorthand; configure runner on step definition");
|
|
778
|
+
if (trimmed.includes("::")) throw new Error("Subagent shorthand cannot contain consecutive colons");
|
|
779
|
+
if (trimmed.includes("//")) throw new Error("Subagent shorthand cannot contain consecutive slashes");
|
|
780
|
+
const validateThinking = (thinking) => {
|
|
781
|
+
if (!thinking) throw new Error("Subagent shorthand thinking after ':' cannot be empty");
|
|
782
|
+
if (thinking.includes(":") || thinking.includes("/") || thinking.includes("@")) throw new Error(`Invalid thinking value '${thinking}': cannot contain ':', '/', or '@'`);
|
|
783
|
+
};
|
|
784
|
+
if (trimmed.startsWith(":")) {
|
|
785
|
+
const thinking = trimmed.slice(1).trim();
|
|
786
|
+
validateThinking(thinking);
|
|
787
|
+
return { thinking };
|
|
788
|
+
}
|
|
789
|
+
let remaining = trimmed;
|
|
790
|
+
let thinking;
|
|
791
|
+
const colonIdx = remaining.lastIndexOf(":");
|
|
792
|
+
if (colonIdx !== -1) {
|
|
793
|
+
thinking = remaining.slice(colonIdx + 1).trim();
|
|
794
|
+
validateThinking(thinking);
|
|
795
|
+
remaining = remaining.slice(0, colonIdx).trim();
|
|
796
|
+
if (remaining.includes(":")) throw new Error("Subagent shorthand cannot contain multiple colons");
|
|
797
|
+
}
|
|
798
|
+
let preset;
|
|
799
|
+
if (remaining.startsWith("@")) {
|
|
800
|
+
const firstSlashIdx = remaining.indexOf("/");
|
|
801
|
+
if (firstSlashIdx === -1) {
|
|
802
|
+
const presetName = remaining.slice(1).trim();
|
|
803
|
+
if (!presetName) throw new Error("Preset name after '@' cannot be empty");
|
|
804
|
+
throw new Error(`Preset '@${presetName}' requires an explicit model (e.g. '@${presetName}/model')`);
|
|
805
|
+
}
|
|
806
|
+
preset = remaining.slice(1, firstSlashIdx).trim();
|
|
807
|
+
if (!preset) throw new Error("Preset name after '@' cannot be empty");
|
|
808
|
+
remaining = remaining.slice(firstSlashIdx + 1).trim();
|
|
809
|
+
if (!remaining) throw new Error(`Model name after preset '@${preset}/' cannot be empty`);
|
|
810
|
+
}
|
|
811
|
+
let llmProvider;
|
|
812
|
+
let model;
|
|
813
|
+
if (remaining.includes("/")) {
|
|
814
|
+
const slashIdx = remaining.indexOf("/");
|
|
815
|
+
llmProvider = remaining.slice(0, slashIdx).trim();
|
|
816
|
+
if (!llmProvider) throw new Error("Subagent shorthand LLM provider before '/' cannot be empty");
|
|
817
|
+
const rest = remaining.slice(slashIdx + 1).trim();
|
|
818
|
+
if (!rest) throw new Error("Model name after provider cannot be empty");
|
|
819
|
+
if (rest.includes("/")) throw new Error("Subagent shorthand model path has too many segments");
|
|
820
|
+
model = rest;
|
|
821
|
+
} else model = remaining;
|
|
822
|
+
if (!model) throw new Error("Model name cannot be empty");
|
|
823
|
+
return {
|
|
824
|
+
...preset ? { preset } : {},
|
|
825
|
+
...llmProvider ? { llmProvider } : {},
|
|
826
|
+
model,
|
|
827
|
+
...thinking ? { thinking } : {}
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Purpose: Normalizes a partial subagent configuration or shorthand result into a full SubagentConfig.
|
|
832
|
+
* CONTRACT:
|
|
833
|
+
* - Input: SubagentConfig | undefined
|
|
834
|
+
* - Output: SubagentConfig with guaranteed provider (defaulting to "spawn"); the `inherit` model sentinel resolves to no model
|
|
835
|
+
*/
|
|
836
|
+
function normalizeSubagentConfig(config) {
|
|
837
|
+
const model = config?.model === INHERIT_MODEL ? void 0 : config?.model;
|
|
838
|
+
return {
|
|
839
|
+
provider: config?.provider ?? "spawn",
|
|
840
|
+
...config?.llmProvider ? { llmProvider: config.llmProvider } : {},
|
|
841
|
+
...config?.preset ? { preset: config.preset } : {},
|
|
842
|
+
...model ? { model } : {},
|
|
843
|
+
...config?.thinking ? { thinking: config.thinking } : {}
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Purpose: Interpolates template variables in SubagentConfig fields.
|
|
848
|
+
* CONTRACT:
|
|
849
|
+
* - Inputs: SubagentConfig, optional args record, optional outputs map.
|
|
850
|
+
* - Outputs: New SubagentConfig with string fields interpolated; an interpolated `inherit` model sentinel resolves to no model.
|
|
851
|
+
*/
|
|
852
|
+
function interpolateSubagentConfig(config, args, outputs) {
|
|
853
|
+
const resolvedArgs = args ?? {};
|
|
854
|
+
const model = config.model ? interpolateTemplate(config.model, resolvedArgs, outputs) : void 0;
|
|
855
|
+
return {
|
|
856
|
+
...config.provider ? { provider: interpolateTemplate(config.provider, resolvedArgs, outputs) } : {},
|
|
857
|
+
...config.llmProvider ? { llmProvider: interpolateTemplate(config.llmProvider, resolvedArgs, outputs) } : {},
|
|
858
|
+
...config.preset ? { preset: interpolateTemplate(config.preset, resolvedArgs, outputs) } : {},
|
|
859
|
+
...model && model !== INHERIT_MODEL ? { model } : {},
|
|
860
|
+
...config.thinking ? { thinking: interpolateTemplate(config.thinking, resolvedArgs, outputs) } : {}
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
function normalizeStepOutputs(outputs) {
|
|
864
|
+
if (!outputs) return void 0;
|
|
865
|
+
return Object.fromEntries(Object.entries(outputs).map(([name, def]) => [name, def.type === "file" ? {
|
|
866
|
+
type: "file",
|
|
867
|
+
path: def.path,
|
|
868
|
+
base: def.base ?? "scratch"
|
|
869
|
+
} : def]));
|
|
870
|
+
}
|
|
871
|
+
/**
|
|
872
|
+
* Purpose: Determines whether a ChoiceMapping is flat (direct choice-to-value) or nested (derived variable-to-choices).
|
|
873
|
+
* CONTRACT:
|
|
874
|
+
* - Inputs: ChoiceMapping object.
|
|
875
|
+
* - Outputs: boolean true if flat, false if nested.
|
|
876
|
+
*/
|
|
877
|
+
function isFlatChoiceMapping(mapping) {
|
|
878
|
+
const values = Object.values(mapping);
|
|
879
|
+
if (values.length === 0) return false;
|
|
880
|
+
return typeof values[0] === "string";
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* Purpose: Preprocesses a validated WorkflowFile into an internal runtime WorkflowDocument.
|
|
884
|
+
* CONTRACT:
|
|
885
|
+
* - Input: validated WorkflowFile.
|
|
886
|
+
* - Output: preprocessed WorkflowDocument where every step has a guaranteed name.
|
|
887
|
+
* - Invariant: Assigns "Step N" (1-indexed) to any step without an explicit name.
|
|
888
|
+
*/
|
|
889
|
+
function preprocessWorkflow(file) {
|
|
890
|
+
const normalizedArgs = Object.fromEntries(Object.entries(file.args ?? {}).map(([key, def]) => {
|
|
891
|
+
const normalizedDefault = def.default !== void 0 ? def.type === "bool" ? String(parseBoolean(def.default)) : String(def.default) : void 0;
|
|
892
|
+
if (def.type === "choice") {
|
|
893
|
+
const { mappings, ...rest } = def;
|
|
894
|
+
const normalizedMapping = def.mapping ?? mappings;
|
|
895
|
+
return [key, {
|
|
896
|
+
...rest,
|
|
897
|
+
...normalizedMapping !== void 0 ? { mapping: normalizedMapping } : {},
|
|
898
|
+
default: normalizedDefault,
|
|
899
|
+
required: def.required ?? def.default === void 0
|
|
900
|
+
}];
|
|
901
|
+
}
|
|
902
|
+
return [key, {
|
|
903
|
+
...def,
|
|
904
|
+
default: normalizedDefault,
|
|
905
|
+
required: def.required ?? def.default === void 0
|
|
906
|
+
}];
|
|
907
|
+
}));
|
|
908
|
+
const steps = file.steps.map((raw, index) => {
|
|
909
|
+
const defaultName = `Step ${index + 1}`;
|
|
910
|
+
if (typeof raw === "string") return {
|
|
911
|
+
kind: "prompt",
|
|
912
|
+
name: defaultName,
|
|
913
|
+
prompt: raw
|
|
914
|
+
};
|
|
915
|
+
const record = raw;
|
|
916
|
+
const name = typeof record.name === "string" && record.name.trim().length > 0 ? record.name : defaultName;
|
|
917
|
+
const ifCond = typeof record.if === "string" && record.if.trim().length > 0 ? record.if.trim() : void 0;
|
|
918
|
+
const rawOutputs = record.outputs;
|
|
919
|
+
const rawOutput = typeof record.output === "string" && record.output.trim().length > 0 ? record.output.trim() : void 0;
|
|
920
|
+
const rawForeach = typeof record.foreach === "string" && record.foreach.trim().length > 0 ? record.foreach.trim() : void 0;
|
|
921
|
+
if (rawOutput !== void 0 && rawOutputs !== void 0) throw new Error(`Step ${index + 1} cannot declare both 'output' and 'outputs'`);
|
|
922
|
+
const isSubagent = record.kind === "subagent" || record.subagent !== void 0 && record.subagent !== false;
|
|
923
|
+
if (rawOutput !== void 0 && !isSubagent) throw new Error(`Step ${index + 1} cannot declare 'output' without 'subagent: true'. 'output' is only supported on subagent steps.`);
|
|
924
|
+
const outputs = normalizeStepOutputs(rawOutputs);
|
|
925
|
+
const step = (() => {
|
|
926
|
+
if (record.kind === "print" || typeof record.print === "string") {
|
|
927
|
+
const printText = typeof record.text === "string" ? record.text : record.print;
|
|
928
|
+
return {
|
|
929
|
+
kind: "print",
|
|
930
|
+
name,
|
|
931
|
+
text: printText
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
const extractStepGate = (raw) => {
|
|
935
|
+
if (typeof raw !== "string" && typeof raw !== "boolean") return;
|
|
936
|
+
return parseBoolean(raw) === false ? void 0 : raw;
|
|
937
|
+
};
|
|
938
|
+
if (record.kind === "subagent" && typeof record.prompt === "string") {
|
|
939
|
+
const gate = extractStepGate(record.gate);
|
|
940
|
+
return {
|
|
941
|
+
kind: "subagent",
|
|
942
|
+
name,
|
|
943
|
+
prompt: record.prompt,
|
|
944
|
+
config: record.config,
|
|
945
|
+
...rawForeach ? { foreach: rawForeach } : {},
|
|
946
|
+
...gate !== void 0 ? { gate } : {},
|
|
947
|
+
...outputs ? { outputs } : {},
|
|
948
|
+
...rawOutput ? { output: rawOutput } : {}
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
if (typeof record.prompt === "string") {
|
|
952
|
+
const prompt = record.prompt;
|
|
953
|
+
const gate = extractStepGate(record.gate);
|
|
954
|
+
if (record.subagent !== void 0 && record.subagent !== false) {
|
|
955
|
+
const rawSubagent = typeof record.subagent === "string" && record.subagent.includes("{{") ? record.subagent : void 0;
|
|
956
|
+
const subagentConfig = normalizeSubagentConfig(typeof record.subagent === "string" ? parseSubagentShorthand(record.subagent) : typeof record.subagent === "object" && record.subagent !== null ? record.subagent : void 0);
|
|
957
|
+
return {
|
|
958
|
+
kind: "subagent",
|
|
959
|
+
name,
|
|
960
|
+
prompt,
|
|
961
|
+
config: subagentConfig,
|
|
962
|
+
...rawSubagent ? { rawSubagent } : {},
|
|
963
|
+
...rawForeach ? { foreach: rawForeach } : {},
|
|
964
|
+
...gate !== void 0 ? { gate } : {},
|
|
965
|
+
...outputs ? { outputs } : {},
|
|
966
|
+
...rawOutput ? { output: rawOutput } : {}
|
|
967
|
+
};
|
|
968
|
+
}
|
|
969
|
+
return {
|
|
970
|
+
kind: "prompt",
|
|
971
|
+
name,
|
|
972
|
+
prompt,
|
|
973
|
+
...gate !== void 0 ? { gate } : {},
|
|
974
|
+
...outputs ? { outputs } : {}
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
if (typeof record.gate === "string" || typeof record.gate === "boolean") {
|
|
978
|
+
const gatePrompt = typeof record.gate === "string" ? record.gate : name;
|
|
979
|
+
const gate = extractStepGate(record.gate);
|
|
980
|
+
return {
|
|
981
|
+
kind: "prompt",
|
|
982
|
+
name,
|
|
983
|
+
prompt: gatePrompt,
|
|
984
|
+
isSoloGate: true,
|
|
985
|
+
...gate !== void 0 ? { gate } : {},
|
|
986
|
+
...outputs ? { outputs } : {}
|
|
987
|
+
};
|
|
988
|
+
}
|
|
989
|
+
throw new Error(`Invalid step definition at step ${index + 1}`);
|
|
990
|
+
})();
|
|
991
|
+
return ifCond !== void 0 ? {
|
|
992
|
+
...step,
|
|
993
|
+
if: ifCond
|
|
994
|
+
} : step;
|
|
995
|
+
});
|
|
996
|
+
return {
|
|
997
|
+
...file.name !== void 0 ? { name: file.name } : {},
|
|
998
|
+
...file.title !== void 0 ? { title: file.title } : {},
|
|
999
|
+
...file.description !== void 0 ? { description: file.description } : {},
|
|
1000
|
+
args: normalizedArgs,
|
|
1001
|
+
steps
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
1004
|
+
/**
|
|
1005
|
+
* Parses raw YAML text into a validated and preprocessed WorkflowDocument.
|
|
1006
|
+
* CONTRACT:
|
|
1007
|
+
* - Input: raw YAML string content.
|
|
1008
|
+
* - Output: fully validated and normalized WorkflowDocument.
|
|
1009
|
+
* - Throws: Error when YAML parsing fails or document violates WorkflowFileSchema.
|
|
1010
|
+
*/
|
|
1011
|
+
function parseWorkflowDocument(content) {
|
|
1012
|
+
return preprocessWorkflow(parseWorkflowFile(content));
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Purpose: Parses a saved list output and enforces its declared bounds.
|
|
1016
|
+
* Contract:
|
|
1017
|
+
* - Inputs: Output name, serialized JSON value, and validated list definition.
|
|
1018
|
+
* - Outputs: String array on success or a diagnostic for invalid JSON, items, or bounds.
|
|
1019
|
+
* - Throws: Unexpected parsing errors propagate.
|
|
1020
|
+
*/
|
|
1021
|
+
function parseListOutput(name, value, definition) {
|
|
1022
|
+
let parsed;
|
|
1023
|
+
try {
|
|
1024
|
+
parsed = JSON.parse(value);
|
|
1025
|
+
} catch (err) {
|
|
1026
|
+
if (!(err instanceof SyntaxError)) throw err;
|
|
1027
|
+
return {
|
|
1028
|
+
kind: "error",
|
|
1029
|
+
message: `Output '${name}' is declared as type 'list', but could not parse value as JSON array.`
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
if (!Array.isArray(parsed)) return {
|
|
1033
|
+
kind: "error",
|
|
1034
|
+
message: `Output '${name}' is declared as type 'list', but received non-array value. Expected JSON array string.`
|
|
1035
|
+
};
|
|
1036
|
+
if (!parsed.every((item) => typeof item === "string")) return {
|
|
1037
|
+
kind: "error",
|
|
1038
|
+
message: `Output '${name}' is declared as type 'list', but contains non-string elements. Expected JSON array of strings.`
|
|
1039
|
+
};
|
|
1040
|
+
if (definition.min !== void 0 && parsed.length < definition.min) return {
|
|
1041
|
+
kind: "error",
|
|
1042
|
+
message: `Output '${name}' requires at least ${definition.min} items, but received ${parsed.length}.`
|
|
1043
|
+
};
|
|
1044
|
+
if (definition.max !== void 0 && parsed.length > definition.max) return {
|
|
1045
|
+
kind: "error",
|
|
1046
|
+
message: `Output '${name}' allows at most ${definition.max} items, but received ${parsed.length}.`
|
|
1047
|
+
};
|
|
1048
|
+
return {
|
|
1049
|
+
kind: "success",
|
|
1050
|
+
value: parsed
|
|
1051
|
+
};
|
|
1052
|
+
}
|
|
1053
|
+
/**
|
|
1054
|
+
* Strips surrounding single or double quotes from a string.
|
|
1055
|
+
*/
|
|
1056
|
+
function unquote(text) {
|
|
1057
|
+
return text.replace(/^(['"])(.*)\1$/, "$2");
|
|
1058
|
+
}
|
|
1059
|
+
/**
|
|
1060
|
+
* Parses a CLI command invocation string into a target path, key-value args, and implicit instructions.
|
|
1061
|
+
* CONTRACT:
|
|
1062
|
+
* - Input: rawInput string (e.g., "build.yaml target=prod optimize=true please run tests").
|
|
1063
|
+
* - Output: ParsedInvocation with targetPath, explicitArgs map, and implicitInstructions string.
|
|
1064
|
+
* - Invariant: Leading '@' mentions are stripped; whitespace-only inputs return empty fields.
|
|
1065
|
+
*/
|
|
1066
|
+
function parseInvocationInput(rawInput) {
|
|
1067
|
+
const trimmed = rawInput.trim().replace(/^@/, "");
|
|
1068
|
+
if (!trimmed) return {
|
|
1069
|
+
targetPath: "",
|
|
1070
|
+
explicitArgs: {},
|
|
1071
|
+
implicitInstructions: ""
|
|
1072
|
+
};
|
|
1073
|
+
const matches = trimmed.match(/([a-zA-Z0-9_-]+)=(?:"([^"]*)"|'([^']*)'|([^\s]+))|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^\s]+/g);
|
|
1074
|
+
let targetPath = "";
|
|
1075
|
+
const explicitArgs = {};
|
|
1076
|
+
const implicitTokens = [];
|
|
1077
|
+
let pathConsumed = false;
|
|
1078
|
+
for (const token of matches) {
|
|
1079
|
+
const kvMatch = token.match(/^([a-zA-Z0-9_-]+)=(.*)$/);
|
|
1080
|
+
if (kvMatch) {
|
|
1081
|
+
const key = kvMatch[1];
|
|
1082
|
+
explicitArgs[key] = unquote(kvMatch[2]);
|
|
1083
|
+
} else if (!pathConsumed) {
|
|
1084
|
+
targetPath = unquote(token);
|
|
1085
|
+
pathConsumed = true;
|
|
1086
|
+
} else implicitTokens.push(unquote(token));
|
|
1087
|
+
}
|
|
1088
|
+
return {
|
|
1089
|
+
targetPath,
|
|
1090
|
+
explicitArgs,
|
|
1091
|
+
implicitInstructions: implicitTokens.join(" ")
|
|
1092
|
+
};
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
1095
|
+
* Resolves workflow arguments against declarations, verifying required fields, choices, and defaults.
|
|
1096
|
+
* CONTRACT:
|
|
1097
|
+
* - Input: declarations map, explicit key-value arguments, and unflagged implicit instructions.
|
|
1098
|
+
* - Output: complete map of resolved argument values.
|
|
1099
|
+
* - Throws: Error if undeclared arguments are passed, required arguments are missing, or choices are violated.
|
|
1100
|
+
*/
|
|
1101
|
+
function resolveWorkflowArgs({ declarations = {}, explicitArgs, implicitInstructions }) {
|
|
1102
|
+
const rawValues = { ...explicitArgs };
|
|
1103
|
+
if (implicitInstructions.length > 0) {
|
|
1104
|
+
if (!Object.hasOwn(declarations, "instructions")) throw new Error("Unexpected implicit instructions: workflow does not declare an 'instructions' argument in 'args'");
|
|
1105
|
+
if (rawValues.instructions !== void 0) throw new Error("Cannot specify both explicit 'instructions' argument and implicit trailing instructions");
|
|
1106
|
+
rawValues.instructions = implicitInstructions;
|
|
1107
|
+
}
|
|
1108
|
+
for (const [argName, def] of Object.entries(declarations)) if (def.type === "choice") {
|
|
1109
|
+
const mapping = def.mapping ?? def.mappings;
|
|
1110
|
+
if (mapping && !isFlatChoiceMapping(mapping)) {
|
|
1111
|
+
for (const derivedKey of Object.keys(mapping)) if (Object.hasOwn(explicitArgs, derivedKey)) throw new Error(`Cannot pass explicit argument '${derivedKey}': '${derivedKey}' is derived from choice argument '${argName}'`);
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
for (const key of Object.keys(explicitArgs)) if (!Object.hasOwn(declarations, key)) {
|
|
1115
|
+
const declaredKeys = Object.keys(declarations).join(", ");
|
|
1116
|
+
throw new Error(`Unknown argument '${key}'. Declared arguments: ${declaredKeys}`);
|
|
1117
|
+
}
|
|
1118
|
+
const resolved = {};
|
|
1119
|
+
for (const [name, def] of Object.entries(declarations)) {
|
|
1120
|
+
const rawVal = rawValues[name] ?? (def.default !== void 0 ? String(def.default) : void 0);
|
|
1121
|
+
if (rawVal === void 0) {
|
|
1122
|
+
if (def.required !== false) throw new Error(`Missing required argument '${name}'`);
|
|
1123
|
+
continue;
|
|
1124
|
+
}
|
|
1125
|
+
if (def.type === "choice") {
|
|
1126
|
+
if (!def.choices.includes(rawVal)) throw new Error(`Invalid value '${rawVal}' for argument '${name}'. Allowed choices: ${def.choices.join(", ")}`);
|
|
1127
|
+
resolved[name] = rawVal;
|
|
1128
|
+
} else if (def.type === "bool") {
|
|
1129
|
+
const boolVal = parseBoolean(rawVal);
|
|
1130
|
+
if (boolVal === void 0) throw new Error(`Invalid value '${rawVal}' for bool argument '${name}'. Allowed values: true, false`);
|
|
1131
|
+
resolved[name] = String(boolVal);
|
|
1132
|
+
} else resolved[name] = rawVal;
|
|
1133
|
+
}
|
|
1134
|
+
for (const [argName, def] of Object.entries(declarations)) if (def.type === "choice") {
|
|
1135
|
+
const mapping = def.mapping ?? def.mappings;
|
|
1136
|
+
if (mapping) {
|
|
1137
|
+
const choiceVal = resolved[argName];
|
|
1138
|
+
if (choiceVal !== void 0) {
|
|
1139
|
+
if (isFlatChoiceMapping(mapping)) {
|
|
1140
|
+
if (!Object.hasOwn(mapping, choiceVal)) throw new Error(`Choice '${choiceVal}' for argument '${argName}' is not defined in mapping.`);
|
|
1141
|
+
resolved[argName] = mapping[choiceVal];
|
|
1142
|
+
} else for (const [derivedKey, map] of Object.entries(mapping)) {
|
|
1143
|
+
if (!Object.hasOwn(map, choiceVal)) throw new Error(`Choice '${choiceVal}' for derived argument '${derivedKey}' in '${argName}' mapping is not defined.`);
|
|
1144
|
+
resolved[derivedKey] = map[choiceVal];
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
return resolved;
|
|
1150
|
+
}
|
|
1151
|
+
/**
|
|
1152
|
+
* Purpose: Evaluates a step condition string against resolved arguments and outputs.
|
|
1153
|
+
* CONTRACT:
|
|
1154
|
+
* - Inputs: condition template string, resolved args dictionary, and optional outputs dictionary.
|
|
1155
|
+
* - Outputs: boolean indicating whether the step condition is satisfied.
|
|
1156
|
+
* - Supported patterns:
|
|
1157
|
+
* - Equality / inequality comparison: `<left> == <right>` or `<left> != <right>`
|
|
1158
|
+
* - Negated boolean: `!<expr>`
|
|
1159
|
+
* - Direct boolean: `<expr>` (truthy strictly if "true")
|
|
1160
|
+
*/
|
|
1161
|
+
function evaluateStepCondition(condition, args, outputs) {
|
|
1162
|
+
const trimmed = condition.trim();
|
|
1163
|
+
if (trimmed.length === 0) return false;
|
|
1164
|
+
const cmpMatch = trimmed.match(/^(.*?)\s*(==|!=)\s*(.*?)$/);
|
|
1165
|
+
if (cmpMatch) {
|
|
1166
|
+
const left = unquote(interpolateTemplate(cmpMatch[1].trim(), args, outputs).trim());
|
|
1167
|
+
const op = cmpMatch[2];
|
|
1168
|
+
const right = unquote(interpolateTemplate(cmpMatch[3].trim(), args, outputs).trim());
|
|
1169
|
+
return op === "==" ? left === right : left !== right;
|
|
1170
|
+
}
|
|
1171
|
+
if (trimmed.startsWith("!")) return parseBoolean(unquote(interpolateTemplate(trimmed.slice(1).trim(), args, outputs).trim())) !== true;
|
|
1172
|
+
return parseBoolean(unquote(interpolateTemplate(trimmed, args, outputs).trim())) === true;
|
|
1173
|
+
}
|
|
1174
|
+
/**
|
|
1175
|
+
* Purpose: Formats the complete markdown/XML prompt for an individual workflow step.
|
|
1176
|
+
* CONTRACT:
|
|
1177
|
+
* - Input: FormatStepPromptOptions with step index, totals, prompt body, and flags.
|
|
1178
|
+
* - Output: structured string with <workflow-info>, <step-instructions>, and <rules> blocks.
|
|
1179
|
+
*/
|
|
1180
|
+
function formatStepPrompt(options) {
|
|
1181
|
+
const header = `[STEP ${options.stepIndex + 1} OF ${options.totalSteps}: ${options.stepName}]`;
|
|
1182
|
+
const workflowInfoLines = ["<workflow-info>"];
|
|
1183
|
+
if (options.workflowName) workflowInfoLines.push(`Workflow: "${options.workflowName}"`);
|
|
1184
|
+
workflowInfoLines.push(`Step: ${options.stepIndex + 1} of ${options.totalSteps}`);
|
|
1185
|
+
workflowInfoLines.push("</workflow-info>");
|
|
1186
|
+
const sections = [header, workflowInfoLines.join("\n")];
|
|
1187
|
+
if (options.isResumedStep) sections.push([
|
|
1188
|
+
"<workflow-resume>",
|
|
1189
|
+
`Workflow execution was resumed from an interrupted state at step ${options.stepIndex + 1} of ${options.totalSteps}.`,
|
|
1190
|
+
"Prior steps have completed, and instructions in this step may already be partially or fully done.",
|
|
1191
|
+
"Inspect current workspace and environment state before acting. Do not duplicate already completed operations.",
|
|
1192
|
+
"</workflow-resume>"
|
|
1193
|
+
].join("\n"));
|
|
1194
|
+
if (options.instructions) sections.push(`<user-instructions>\n${options.instructions}\n</user-instructions>`);
|
|
1195
|
+
if (options.outputRequirements && options.outputRequirements.length > 0) {
|
|
1196
|
+
const reqLines = ["<output-requirements>", "This step requires the following outputs to be produced:"];
|
|
1197
|
+
for (const req of options.outputRequirements) if (req.type === "file") reqLines.push(`- File output '${req.name}': write to '${req.resolvedPath}'. Must exist and be non-empty.`);
|
|
1198
|
+
else if (req.type === "list") {
|
|
1199
|
+
const desc = req.description ? ` (${req.description})` : "";
|
|
1200
|
+
const bounds = [];
|
|
1201
|
+
if (req.min !== void 0) bounds.push(`min items: ${req.min}`);
|
|
1202
|
+
if (req.max !== void 0) bounds.push(`max items: ${req.max}`);
|
|
1203
|
+
const boundsStr = bounds.length > 0 ? ` [${bounds.join(", ")}]` : "";
|
|
1204
|
+
reqLines.push(`- List output '${req.name}'${desc}${boundsStr}: call tool 'save_output' with name="${req.name}" and value as a JSON array string.`);
|
|
1205
|
+
} else {
|
|
1206
|
+
const desc = req.description ? ` (${req.description})` : "";
|
|
1207
|
+
reqLines.push(`- String output '${req.name}'${desc}: call tool 'save_output' with name="${req.name}" and value=<your_value>.`);
|
|
1208
|
+
}
|
|
1209
|
+
reqLines.push("</output-requirements>");
|
|
1210
|
+
sections.push(reqLines.join("\n"));
|
|
1211
|
+
}
|
|
1212
|
+
sections.push(`<step-instructions>\n${options.prompt}\n</step-instructions>`);
|
|
1213
|
+
const ruleLines = [
|
|
1214
|
+
"<rules>",
|
|
1215
|
+
"- Perform ONLY the instructions in <step-instructions>.",
|
|
1216
|
+
"- Conclude when complete.",
|
|
1217
|
+
"- Do NOT anticipate or execute any future steps."
|
|
1218
|
+
];
|
|
1219
|
+
if (options.instructions) ruleLines.push("- Incorporate and follow the additional instructions in <user-instructions> while performing this step.");
|
|
1220
|
+
if (options.outputRequirements && options.outputRequirements.length > 0) ruleLines.push("- Ensure all required outputs in <output-requirements> are produced before concluding.", "- Do not present written outputs to the user as they are technical. Conclude with a brief acknowledgement message.");
|
|
1221
|
+
if (options.isResumedStep) ruleLines.push("- Verify existing workspace state before executing to avoid repeating completed work.");
|
|
1222
|
+
ruleLines.push("</rules>");
|
|
1223
|
+
sections.push(ruleLines.join("\n"));
|
|
1224
|
+
return sections.join("\n\n");
|
|
1225
|
+
}
|
|
1226
|
+
/**
|
|
1227
|
+
* Purpose: Formats an automated retry prompt when step output verification fails.
|
|
1228
|
+
*/
|
|
1229
|
+
function formatOutputRetryPrompt({ stepIndex, totalSteps, stepName, missingOutputs, attempt }) {
|
|
1230
|
+
const lines = [
|
|
1231
|
+
`[STEP ${stepIndex + 1} OF ${totalSteps} OUTPUT VERIFICATION FAILED (Attempt ${attempt} of 3)]`,
|
|
1232
|
+
"<output-verification-failure>",
|
|
1233
|
+
`Step '${stepName}' output verification failed. Missing outputs:`
|
|
1234
|
+
];
|
|
1235
|
+
for (const missing of missingOutputs) if (missing.type === "file") lines.push(`- File output '${missing.name}': expected non-empty file at '${missing.resolvedPath}'. Please create or write to this file.`);
|
|
1236
|
+
else if (missing.type === "list") lines.push(`- List output '${missing.name}': tool 'save_output' was not called with name="${missing.name}" and a valid JSON array. Please call tool 'save_output'.`);
|
|
1237
|
+
else lines.push(`- String output '${missing.name}': tool 'save_output' was not called with name="${missing.name}". Please call tool 'save_output'.`);
|
|
1238
|
+
lines.push("</output-verification-failure>");
|
|
1239
|
+
return lines.join("\n");
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* Purpose: Parses workflow YAML text and extracts a summary of metadata and parameters if valid.
|
|
1243
|
+
* Contract:
|
|
1244
|
+
* - Inputs: target path/identifier string and raw YAML string content.
|
|
1245
|
+
* - Outputs: WorkflowSummary object if parsing and validation succeed; null otherwise.
|
|
1246
|
+
* - Throws: None (errors caught and safely returned as null).
|
|
1247
|
+
*/
|
|
1248
|
+
function parseWorkflowSummary(target, content) {
|
|
1249
|
+
try {
|
|
1250
|
+
const raw = parse(content);
|
|
1251
|
+
const result = WorkflowFileSchema.safeParse(raw);
|
|
1252
|
+
if (!result.success) return null;
|
|
1253
|
+
const file = result.data;
|
|
1254
|
+
const params = Object.entries(file.args ?? {}).map(([name, arg]) => ({
|
|
1255
|
+
name,
|
|
1256
|
+
description: arg.description,
|
|
1257
|
+
type: arg.type,
|
|
1258
|
+
required: arg.required ?? arg.default === void 0,
|
|
1259
|
+
default: arg.default !== void 0 ? String(arg.default) : void 0,
|
|
1260
|
+
choices: arg.type === "choice" ? arg.choices : void 0
|
|
1261
|
+
}));
|
|
1262
|
+
return {
|
|
1263
|
+
target,
|
|
1264
|
+
name: file.name,
|
|
1265
|
+
description: file.description,
|
|
1266
|
+
params
|
|
1267
|
+
};
|
|
1268
|
+
} catch {
|
|
1269
|
+
return null;
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
/**
|
|
1273
|
+
* Purpose: Formats a parameter's metadata and description as a Markdown bullet line item.
|
|
1274
|
+
* Contract:
|
|
1275
|
+
* - Inputs: parameter name and metadata object with type, choices, default, required, and description.
|
|
1276
|
+
* - Outputs: Formatted string (e.g. " - `env` (choice, choices: staging, production, default: \"staging\"): Target tier").
|
|
1277
|
+
*/
|
|
1278
|
+
function formatWorkflowParamDescriptor(name, param) {
|
|
1279
|
+
const meta = [param.type];
|
|
1280
|
+
if (param.choices && param.choices.length > 0) meta.push(`choices: ${param.choices.join(", ")}`);
|
|
1281
|
+
if (param.default !== void 0) meta.push(`default: "${param.default}"`);
|
|
1282
|
+
if (param.required) meta.push("required");
|
|
1283
|
+
return ` - \`${name}\`${` (${meta.join(", ")})`}${param.description ? `: ${param.description}` : ""}`;
|
|
1284
|
+
}
|
|
1285
|
+
/**
|
|
1286
|
+
* Purpose: Formats categorized workflow summaries into user-readable Markdown.
|
|
1287
|
+
* Contract:
|
|
1288
|
+
* - Inputs: Array of WorkflowGroup containing group title and WorkflowSummary items.
|
|
1289
|
+
* - Outputs: Formatted Markdown text.
|
|
1290
|
+
* - Throws: None.
|
|
1291
|
+
*/
|
|
1292
|
+
function formatWorkflowList(groups) {
|
|
1293
|
+
const sections = [];
|
|
1294
|
+
for (const group of groups) {
|
|
1295
|
+
const lines = [`### ${group.title}`];
|
|
1296
|
+
if (group.workflows.length === 0) lines.push("*(No workflows found)*");
|
|
1297
|
+
else for (const wf of group.workflows) {
|
|
1298
|
+
const titlePart = wf.name ? `**${wf.name}** (\`${wf.target}\`)` : `\`${wf.target}\``;
|
|
1299
|
+
const descPart = wf.description ? `: ${wf.description}` : "";
|
|
1300
|
+
lines.push(`- ${titlePart}${descPart}`);
|
|
1301
|
+
if (wf.params.length > 0) for (const param of wf.params) lines.push(formatWorkflowParamDescriptor(param.name, param));
|
|
1302
|
+
}
|
|
1303
|
+
sections.push(lines.join("\n"));
|
|
1304
|
+
}
|
|
1305
|
+
return sections.join("\n\n");
|
|
1306
|
+
}
|
|
1307
|
+
/**
|
|
1308
|
+
* Purpose: Formats a diagnostic summary for a validated workflow document and optional resolved arguments.
|
|
1309
|
+
* Contract:
|
|
1310
|
+
* - Inputs: targetPath string, doc WorkflowDocument, optional resolvedArgs dictionary.
|
|
1311
|
+
* - Outputs: Markdown string detailing workflow status, steps, declared arguments, and resolved arguments.
|
|
1312
|
+
* - Throws: None.
|
|
1313
|
+
*/
|
|
1314
|
+
function formatValidationSummary(targetPath, doc, resolvedArgs) {
|
|
1315
|
+
const lines = [`### Workflow Validation: \`${targetPath}\``, "- **Status:** Valid"];
|
|
1316
|
+
if (doc.name) lines.push(`- **Name:** ${doc.name}`);
|
|
1317
|
+
if (doc.title) lines.push(`- **Title:** ${doc.title}`);
|
|
1318
|
+
if (doc.description) lines.push(`- **Description:** ${doc.description}`);
|
|
1319
|
+
lines.push(`- **Steps:** ${doc.steps.length}`);
|
|
1320
|
+
for (let i = 0; i < doc.steps.length; i++) {
|
|
1321
|
+
const step = doc.steps[i];
|
|
1322
|
+
const gateStr = (step.kind === "prompt" || step.kind === "subagent") && step.gate !== void 0 && (typeof step.gate === "boolean" ? step.gate : step.gate.trim() !== "" && parseBoolean(step.gate) !== false) ? " [gate]" : "";
|
|
1323
|
+
lines.push(` ${i + 1}. [${step.kind}] ${step.name}${gateStr}`);
|
|
1324
|
+
if (step.kind === "subagent" && step.output) lines.push(` - Output: \`${step.output}\``);
|
|
1325
|
+
if ((step.kind === "prompt" || step.kind === "subagent") && step.outputs) for (const [outName, outDef] of Object.entries(step.outputs)) {
|
|
1326
|
+
const extra = outDef.type === "file" ? `: ${outDef.path}` : outDef.description ? `: ${outDef.description}` : "";
|
|
1327
|
+
lines.push(` - Output: \`${outName}\` (${outDef.type})${extra}`);
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
const declaredArgs = Object.entries(doc.args);
|
|
1331
|
+
if (declaredArgs.length > 0) {
|
|
1332
|
+
lines.push("- **Declared Arguments:**");
|
|
1333
|
+
for (const [name, def] of declaredArgs) lines.push(formatWorkflowParamDescriptor(name, def));
|
|
1334
|
+
}
|
|
1335
|
+
if (resolvedArgs !== void 0) {
|
|
1336
|
+
lines.push("- **Resolved Arguments:**");
|
|
1337
|
+
for (const [key, val] of Object.entries(resolvedArgs)) lines.push(` - \`${key}\`: "${val}"`);
|
|
1338
|
+
}
|
|
1339
|
+
return lines.join("\n");
|
|
1340
|
+
}
|
|
1341
|
+
/**
|
|
1342
|
+
* Purpose: Constructs an ObjectJsonSchema enforcing structured JSON output for a subagent step.
|
|
1343
|
+
* Contract:
|
|
1344
|
+
* - Inputs: outputs map and resolvedOutputPaths dictionary mapping file output names to absolute paths.
|
|
1345
|
+
* - Outputs: ObjectJsonSchema with string properties and required keys matching all declared outputs.
|
|
1346
|
+
* - Invariant: File outputs become synthetic string parameters requiring the absolute file path.
|
|
1347
|
+
*/
|
|
1348
|
+
function buildSubagentOutputSchema(outputs, resolvedOutputPaths) {
|
|
1349
|
+
const properties = {};
|
|
1350
|
+
const required = [];
|
|
1351
|
+
for (const [name, def] of Object.entries(outputs)) {
|
|
1352
|
+
required.push(name);
|
|
1353
|
+
if (def.type === "string") properties[name] = {
|
|
1354
|
+
type: "string",
|
|
1355
|
+
description: def.description ?? `Output string value for '${name}'`
|
|
1356
|
+
};
|
|
1357
|
+
else properties[name] = {
|
|
1358
|
+
type: "string",
|
|
1359
|
+
description: `Absolute filesystem path of the written file for '${name}'. Must be written to: ${resolvedOutputPaths[name]}`
|
|
1360
|
+
};
|
|
1361
|
+
}
|
|
1362
|
+
return {
|
|
1363
|
+
type: "object",
|
|
1364
|
+
properties,
|
|
1365
|
+
required,
|
|
1366
|
+
additionalProperties: false
|
|
1367
|
+
};
|
|
1368
|
+
}
|
|
1369
|
+
/**
|
|
1370
|
+
* Purpose: Formats instructions for a subagent step, including structured output requirements when declared.
|
|
1371
|
+
* Contract:
|
|
1372
|
+
* - Inputs: interpolated prompt string and optional output requirements array.
|
|
1373
|
+
* - Outputs: formatted prompt text. Returns raw prompt if no output requirements.
|
|
1374
|
+
*/
|
|
1375
|
+
function formatSubagentPrompt({ prompt, outputRequirements }) {
|
|
1376
|
+
if (!outputRequirements || outputRequirements.length === 0) return prompt;
|
|
1377
|
+
const reqLines = ["<output-requirements>", "This step requires structured outputs adhering to the requested JSON schema:"];
|
|
1378
|
+
for (const req of outputRequirements) if (req.type === "file") reqLines.push(`- File output '${req.name}': write the complete file content to '${req.resolvedPath}'. In the returned JSON object, set property '${req.name}' to the exact absolute file path '${req.resolvedPath}'.`);
|
|
1379
|
+
else {
|
|
1380
|
+
const desc = req.description ? ` (${req.description})` : "";
|
|
1381
|
+
reqLines.push(`- String output '${req.name}'${desc}: in the returned JSON object, set property '${req.name}' to the output string value.`);
|
|
1382
|
+
}
|
|
1383
|
+
reqLines.push("</output-requirements>");
|
|
1384
|
+
return `${prompt}\n\n${reqLines.join("\n")}`;
|
|
1385
|
+
}
|
|
1386
|
+
// src/requests.ts
|
|
1387
|
+
/**
|
|
1388
|
+
* PURPOSE: Pure selection of pending workflow requests from command history.
|
|
1389
|
+
* ALLOWED: Schema validation and deterministic event folding.
|
|
1390
|
+
* FORBIDDEN: I/O and framework services.
|
|
1391
|
+
*/
|
|
1392
|
+
const commandEnvelope = z.discriminatedUnion("type", [z.object({
|
|
1393
|
+
type: z.literal("command/run"),
|
|
1394
|
+
data: z.object({
|
|
1395
|
+
commandId: z.string(),
|
|
1396
|
+
name: z.string(),
|
|
1397
|
+
args: z.string().optional()
|
|
1398
|
+
})
|
|
1399
|
+
}), z.object({
|
|
1400
|
+
type: z.literal("command/done"),
|
|
1401
|
+
data: z.object({
|
|
1402
|
+
commandId: z.string(),
|
|
1403
|
+
kind: z.enum(["success", "error"])
|
|
1404
|
+
})
|
|
1405
|
+
})]);
|
|
1406
|
+
const requestPayload = z.discriminatedUnion("action", [z.object({
|
|
1407
|
+
action: z.literal("request"),
|
|
1408
|
+
runId: z.string(),
|
|
1409
|
+
rawInput: z.string()
|
|
1410
|
+
}), z.object({
|
|
1411
|
+
action: z.enum(["init", "request-failed"]),
|
|
1412
|
+
runId: z.string()
|
|
1413
|
+
})]);
|
|
1414
|
+
/**
|
|
1415
|
+
* Purpose: Selects the first accepted workflow request in command-arrival order.
|
|
1416
|
+
* Contract:
|
|
1417
|
+
* - Inputs: chronological command events, including each request's originating /wf command.
|
|
1418
|
+
* - Outputs: the next unconsumed request, or undefined while an earlier command validates.
|
|
1419
|
+
* - Throws / Errors: malformed command payloads are ignored.
|
|
1420
|
+
*/
|
|
1421
|
+
function nextWorkflowRequest(events) {
|
|
1422
|
+
const commands = /* @__PURE__ */ new Map();
|
|
1423
|
+
const requests = /* @__PURE__ */ new Map();
|
|
1424
|
+
for (const event of events) {
|
|
1425
|
+
if (event.type !== "command/run" && event.type !== "command/done") continue;
|
|
1426
|
+
const envelope = commandEnvelope.safeParse(event);
|
|
1427
|
+
if (!envelope.success) continue;
|
|
1428
|
+
const { type, data: command } = envelope.data;
|
|
1429
|
+
if (type === "command/done") {
|
|
1430
|
+
if (commands.has(command.commandId)) commands.set(command.commandId, command.kind);
|
|
1431
|
+
} else if (command.name === "wf") commands.set(command.commandId, "validating");
|
|
1432
|
+
else if (command.name === "wf-event" && command.args !== void 0) {
|
|
1433
|
+
let data;
|
|
1434
|
+
try {
|
|
1435
|
+
data = JSON.parse(command.args);
|
|
1436
|
+
} catch {
|
|
1437
|
+
continue;
|
|
1438
|
+
}
|
|
1439
|
+
const payload = requestPayload.safeParse(data);
|
|
1440
|
+
if (!payload.success) continue;
|
|
1441
|
+
if (payload.data.action === "request") requests.set(payload.data.runId, payload.data);
|
|
1442
|
+
else requests.delete(payload.data.runId);
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
for (const [runId, status] of commands) {
|
|
1446
|
+
if (status === "validating") return void 0;
|
|
1447
|
+
if (status === "error") continue;
|
|
1448
|
+
const request = requests.get(runId);
|
|
1449
|
+
if (request !== void 0) return request;
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
// src/rules.ts
|
|
1453
|
+
/**
|
|
1454
|
+
* PURPOSE: Pure workflow validation rules and composite validator.
|
|
1455
|
+
* ALLOWED: Pure computation, AST traversal, string analysis, schema enforcement.
|
|
1456
|
+
* FORBIDDEN: No I/O, no filesystem, no runtime state, no agent orchestration.
|
|
1457
|
+
*/
|
|
1458
|
+
const OUTPUT_REF_REGEX = /\{\{outputs\.([a-zA-Z0-9_-]+)\}\}/g;
|
|
1459
|
+
function extractDeclaredOutputs(steps) {
|
|
1460
|
+
const map = /* @__PURE__ */ new Map();
|
|
1461
|
+
for (let i = 0; i < steps.length; i++) {
|
|
1462
|
+
const step = steps[i];
|
|
1463
|
+
if (step.kind === "subagent" && step.output && !map.has(step.output)) {
|
|
1464
|
+
const outputType = step.foreach !== void 0 ? "list" : "string";
|
|
1465
|
+
map.set(step.output, {
|
|
1466
|
+
stepIndex: i,
|
|
1467
|
+
kind: step.kind,
|
|
1468
|
+
type: outputType
|
|
1469
|
+
});
|
|
1470
|
+
}
|
|
1471
|
+
if ((step.kind === "prompt" || step.kind === "subagent") && step.outputs) {
|
|
1472
|
+
for (const [name, def] of Object.entries(step.outputs)) if (!map.has(name)) {
|
|
1473
|
+
const outputType = step.kind === "subagent" && step.foreach !== void 0 ? "list" : def.type;
|
|
1474
|
+
map.set(name, {
|
|
1475
|
+
stepIndex: i,
|
|
1476
|
+
kind: step.kind,
|
|
1477
|
+
type: outputType
|
|
1478
|
+
});
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
return map;
|
|
1483
|
+
}
|
|
1484
|
+
function extractStepStrings(step, options = { includeForeach: true }) {
|
|
1485
|
+
const strings = [step.name];
|
|
1486
|
+
if (step.if) strings.push(step.if);
|
|
1487
|
+
if (step.kind === "prompt" || step.kind === "subagent") {
|
|
1488
|
+
strings.push(step.prompt);
|
|
1489
|
+
if (typeof step.gate === "string") strings.push(step.gate);
|
|
1490
|
+
if (step.kind === "subagent" && step.foreach && options.includeForeach !== false) strings.push(step.foreach);
|
|
1491
|
+
if (step.kind === "subagent") {
|
|
1492
|
+
if (step.rawSubagent) strings.push(step.rawSubagent);
|
|
1493
|
+
if (step.config.provider) strings.push(step.config.provider);
|
|
1494
|
+
if (step.config.llmProvider) strings.push(step.config.llmProvider);
|
|
1495
|
+
if (step.config.preset) strings.push(step.config.preset);
|
|
1496
|
+
if (step.config.model) strings.push(step.config.model);
|
|
1497
|
+
if (step.config.thinking) strings.push(step.config.thinking);
|
|
1498
|
+
}
|
|
1499
|
+
if (step.outputs) {
|
|
1500
|
+
for (const def of Object.values(step.outputs)) if (def.type === "file") strings.push(def.path);
|
|
1501
|
+
}
|
|
1502
|
+
} else strings.push(step.text);
|
|
1503
|
+
return strings;
|
|
1504
|
+
}
|
|
1505
|
+
/**
|
|
1506
|
+
* Purpose: Enforces that subagent steps do not declare direct 'list' outputs and foreach subagents only declare 'string' outputs.
|
|
1507
|
+
* Contract:
|
|
1508
|
+
* - Inputs: WorkflowValidationContext with doc.
|
|
1509
|
+
* - Outputs: readonly array of invalid subagent output type errors.
|
|
1510
|
+
*/
|
|
1511
|
+
const ruleSubagentOutputTypes = (context) => {
|
|
1512
|
+
const errors = [];
|
|
1513
|
+
for (let i = 0; i < context.doc.steps.length; i++) {
|
|
1514
|
+
const step = context.doc.steps[i];
|
|
1515
|
+
if (step.kind !== "subagent" || !step.outputs) continue;
|
|
1516
|
+
for (const [name, def] of Object.entries(step.outputs)) if (def.type === "list") errors.push({
|
|
1517
|
+
rule: "subagent-output-list-disallowed",
|
|
1518
|
+
category: "output",
|
|
1519
|
+
message: `Subagent step ${i + 1} ('${step.name}') output '${name}' cannot be of type 'list'. Subagents cannot produce list outputs directly.`,
|
|
1520
|
+
stepIndex: i
|
|
1521
|
+
});
|
|
1522
|
+
else if (step.foreach !== void 0 && def.type === "file") errors.push({
|
|
1523
|
+
rule: "foreach-subagent-output-file-disallowed",
|
|
1524
|
+
category: "output",
|
|
1525
|
+
message: `Subagent step ${i + 1} ('${step.name}') has foreach and cannot declare file output '${name}'. Foreach subagents only support string outputs.`,
|
|
1526
|
+
stepIndex: i
|
|
1527
|
+
});
|
|
1528
|
+
}
|
|
1529
|
+
return errors;
|
|
1530
|
+
};
|
|
1531
|
+
/**
|
|
1532
|
+
* Purpose: Enforces that all subagent steps declare at least one output via 'output' or 'outputs'.
|
|
1533
|
+
* Contract:
|
|
1534
|
+
* - Inputs: WorkflowValidationContext with doc.
|
|
1535
|
+
* - Outputs: readonly array of subagent output missing errors.
|
|
1536
|
+
*/
|
|
1537
|
+
const ruleSubagentOutputRequired = (context) => {
|
|
1538
|
+
const errors = [];
|
|
1539
|
+
for (let i = 0; i < context.doc.steps.length; i++) {
|
|
1540
|
+
const step = context.doc.steps[i];
|
|
1541
|
+
if (step.kind === "subagent") {
|
|
1542
|
+
if (!(Boolean(step.output?.trim()) || step.outputs !== void 0 && Object.keys(step.outputs).length > 0)) errors.push({
|
|
1543
|
+
rule: "subagent-output-required",
|
|
1544
|
+
category: "output",
|
|
1545
|
+
message: `Subagent step ${i + 1} ('${step.name}') must declare at least one output via 'output' or 'outputs'.`,
|
|
1546
|
+
stepIndex: i
|
|
1547
|
+
});
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
return errors;
|
|
1551
|
+
};
|
|
1552
|
+
/**
|
|
1553
|
+
* Purpose: Enforces that all output names across all steps in the document are globally unique.
|
|
1554
|
+
* Contract:
|
|
1555
|
+
* - Inputs: WorkflowValidationContext with doc.
|
|
1556
|
+
* - Outputs: readonly array of duplicate output name errors.
|
|
1557
|
+
*/
|
|
1558
|
+
const ruleDuplicateOutputNames = (context) => {
|
|
1559
|
+
const errors = [];
|
|
1560
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1561
|
+
for (let i = 0; i < context.doc.steps.length; i++) {
|
|
1562
|
+
const step = context.doc.steps[i];
|
|
1563
|
+
if (step.kind === "subagent" && step.output) {
|
|
1564
|
+
if (seen.has(step.output)) errors.push({
|
|
1565
|
+
rule: "duplicate-output-name",
|
|
1566
|
+
category: "output",
|
|
1567
|
+
message: `Duplicate output name '${step.output}' declared at step ${i + 1}. Output names must be globally unique.`,
|
|
1568
|
+
stepIndex: i
|
|
1569
|
+
});
|
|
1570
|
+
else seen.add(step.output);
|
|
1571
|
+
}
|
|
1572
|
+
if (step.kind === "prompt" || step.kind === "subagent") {
|
|
1573
|
+
if (step.outputs) for (const name of Object.keys(step.outputs)) if (seen.has(name)) errors.push({
|
|
1574
|
+
rule: "duplicate-output-name",
|
|
1575
|
+
category: "output",
|
|
1576
|
+
message: `Duplicate output name '${name}' declared at step ${i + 1}. Output names must be globally unique.`,
|
|
1577
|
+
stepIndex: i
|
|
1578
|
+
});
|
|
1579
|
+
else seen.add(name);
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
return errors;
|
|
1583
|
+
};
|
|
1584
|
+
/**
|
|
1585
|
+
* Purpose: Ensures workflow document name and title do not reference outputs before steps execute.
|
|
1586
|
+
* Contract:
|
|
1587
|
+
* - Inputs: WorkflowValidationContext with doc.
|
|
1588
|
+
* - Outputs: readonly array of workflow name and title output reference errors.
|
|
1589
|
+
*/
|
|
1590
|
+
const ruleWorkflowNameOutputReferences = (context) => {
|
|
1591
|
+
const errors = [];
|
|
1592
|
+
const seenRefs = /* @__PURE__ */ new Set();
|
|
1593
|
+
const checkOutputRefs = (text, field) => {
|
|
1594
|
+
const matches = text.matchAll(OUTPUT_REF_REGEX);
|
|
1595
|
+
for (const match of matches) {
|
|
1596
|
+
const refName = match[1];
|
|
1597
|
+
const key = `${field}:${refName}`;
|
|
1598
|
+
if (seenRefs.has(key)) continue;
|
|
1599
|
+
seenRefs.add(key);
|
|
1600
|
+
errors.push({
|
|
1601
|
+
rule: "workflow-name-output",
|
|
1602
|
+
category: "output",
|
|
1603
|
+
message: `Output '{{outputs.${refName}}}' referenced in workflow ${field} before any step execution.`
|
|
1604
|
+
});
|
|
1605
|
+
}
|
|
1606
|
+
};
|
|
1607
|
+
if (context.doc.name) checkOutputRefs(context.doc.name, "name");
|
|
1608
|
+
if (context.doc.title) checkOutputRefs(context.doc.title, "title");
|
|
1609
|
+
return errors;
|
|
1610
|
+
};
|
|
1611
|
+
/**
|
|
1612
|
+
* Purpose: Validates that step output references point to declared outputs and are not forward references.
|
|
1613
|
+
* Contract:
|
|
1614
|
+
* - Inputs: WorkflowValidationContext with doc.
|
|
1615
|
+
* - Outputs: readonly array of unknown and forward output reference errors.
|
|
1616
|
+
*/
|
|
1617
|
+
const ruleStepOutputReferences = (context) => {
|
|
1618
|
+
const errors = [];
|
|
1619
|
+
const declaredMap = extractDeclaredOutputs(context.doc.steps);
|
|
1620
|
+
for (let i = 0; i < context.doc.steps.length; i++) {
|
|
1621
|
+
const stringsToCheck = extractStepStrings(context.doc.steps[i], { includeForeach: false });
|
|
1622
|
+
const seenRefs = /* @__PURE__ */ new Set();
|
|
1623
|
+
for (const str of stringsToCheck) {
|
|
1624
|
+
const matches = str.matchAll(OUTPUT_REF_REGEX);
|
|
1625
|
+
for (const match of matches) {
|
|
1626
|
+
const refName = match[1];
|
|
1627
|
+
if (seenRefs.has(refName)) continue;
|
|
1628
|
+
seenRefs.add(refName);
|
|
1629
|
+
const declared = declaredMap.get(refName);
|
|
1630
|
+
if (declared === void 0) errors.push({
|
|
1631
|
+
rule: "unknown-output",
|
|
1632
|
+
category: "output",
|
|
1633
|
+
message: `Unknown output '{{outputs.${refName}}}' referenced at step ${i + 1}.`,
|
|
1634
|
+
stepIndex: i
|
|
1635
|
+
});
|
|
1636
|
+
else if (declared.stepIndex >= i) errors.push({
|
|
1637
|
+
rule: "forward-output-reference",
|
|
1638
|
+
category: "output",
|
|
1639
|
+
message: `Output '{{outputs.${refName}}}' referenced at step ${i + 1} before it is declared at step ${declared.stepIndex + 1}.`,
|
|
1640
|
+
stepIndex: i
|
|
1641
|
+
});
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
return errors;
|
|
1646
|
+
};
|
|
1647
|
+
/**
|
|
1648
|
+
* Purpose: Enforces that subagent steps do not depend on outputs produced by earlier subagent steps.
|
|
1649
|
+
* Contract:
|
|
1650
|
+
* - Inputs: WorkflowValidationContext with doc.
|
|
1651
|
+
* - Outputs: readonly array of subagent dependency errors.
|
|
1652
|
+
*/
|
|
1653
|
+
const ruleSubagentDependencies = (context) => {
|
|
1654
|
+
const errors = [];
|
|
1655
|
+
const declaredMap = extractDeclaredOutputs(context.doc.steps);
|
|
1656
|
+
for (let i = 0; i < context.doc.steps.length; i++) {
|
|
1657
|
+
const step = context.doc.steps[i];
|
|
1658
|
+
if (step.kind !== "subagent") continue;
|
|
1659
|
+
const stringsToCheck = extractStepStrings(step);
|
|
1660
|
+
const seenRefs = /* @__PURE__ */ new Set();
|
|
1661
|
+
for (const str of stringsToCheck) {
|
|
1662
|
+
const matches = str.matchAll(OUTPUT_REF_REGEX);
|
|
1663
|
+
for (const match of matches) {
|
|
1664
|
+
const refName = match[1];
|
|
1665
|
+
if (seenRefs.has(refName)) continue;
|
|
1666
|
+
seenRefs.add(refName);
|
|
1667
|
+
const declared = declaredMap.get(refName);
|
|
1668
|
+
if (declared && declared.stepIndex < i && declared.kind === "subagent") errors.push({
|
|
1669
|
+
rule: "subagent-dependency",
|
|
1670
|
+
category: "output",
|
|
1671
|
+
message: `Subagent step ${i + 1} ('${step.name}') cannot depend on output '{{outputs.${refName}}}' produced by subagent step ${declared.stepIndex + 1}. Subagents execute concurrently and cannot depend on each other.`,
|
|
1672
|
+
stepIndex: i
|
|
1673
|
+
});
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
return errors;
|
|
1678
|
+
};
|
|
1679
|
+
/**
|
|
1680
|
+
* Purpose: Ensures that every declared output is referenced at least once in subsequent workflow steps.
|
|
1681
|
+
* Contract:
|
|
1682
|
+
* - Inputs: WorkflowValidationContext with doc.
|
|
1683
|
+
* - Outputs: readonly array of unused output errors.
|
|
1684
|
+
*/
|
|
1685
|
+
const ruleUnusedOutputs = (context) => {
|
|
1686
|
+
const errors = [];
|
|
1687
|
+
const declaredMap = extractDeclaredOutputs(context.doc.steps);
|
|
1688
|
+
const usedOutputs = /* @__PURE__ */ new Set();
|
|
1689
|
+
for (let i = 0; i < context.doc.steps.length; i++) {
|
|
1690
|
+
const stringsToCheck = extractStepStrings(context.doc.steps[i]);
|
|
1691
|
+
for (const str of stringsToCheck) {
|
|
1692
|
+
const matches = str.matchAll(OUTPUT_REF_REGEX);
|
|
1693
|
+
for (const match of matches) usedOutputs.add(match[1]);
|
|
1694
|
+
}
|
|
1695
|
+
}
|
|
1696
|
+
for (const [name, { stepIndex }] of declaredMap) if (!usedOutputs.has(name)) errors.push({
|
|
1697
|
+
rule: "unused-output",
|
|
1698
|
+
category: "output",
|
|
1699
|
+
message: `Output '${name}' declared at step ${stepIndex + 1} is never used in the workflow. All outputs must be used at least once.`,
|
|
1700
|
+
stepIndex
|
|
1701
|
+
});
|
|
1702
|
+
return errors;
|
|
1703
|
+
};
|
|
1704
|
+
/**
|
|
1705
|
+
* Purpose: Validates that all {{args.<name>}} placeholders across doc name and steps can be resolved.
|
|
1706
|
+
* Contract:
|
|
1707
|
+
* - Inputs: WorkflowValidationContext with doc and optional resolved args.
|
|
1708
|
+
* - Outputs: readonly array of template argument interpolation or declaration errors.
|
|
1709
|
+
*/
|
|
1710
|
+
const ruleTemplateArgs = (context) => {
|
|
1711
|
+
const errors = [];
|
|
1712
|
+
const declaredAndDerivedArgs = new Set(Object.keys(context.doc.args));
|
|
1713
|
+
for (const def of Object.values(context.doc.args)) if (def.type === "choice") {
|
|
1714
|
+
const mapping = def.mapping ?? def.mappings;
|
|
1715
|
+
if (mapping && !isFlatChoiceMapping(mapping)) for (const derivedKey of Object.keys(mapping)) declaredAndDerivedArgs.add(derivedKey);
|
|
1716
|
+
}
|
|
1717
|
+
const seenMissing = /* @__PURE__ */ new Set();
|
|
1718
|
+
const check = (str, stepIndex) => {
|
|
1719
|
+
if (context.args !== void 0) try {
|
|
1720
|
+
interpolateTemplate(str, context.args);
|
|
1721
|
+
} catch (err) {
|
|
1722
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1723
|
+
errors.push({
|
|
1724
|
+
rule: "template-args",
|
|
1725
|
+
category: "template",
|
|
1726
|
+
message,
|
|
1727
|
+
...stepIndex !== void 0 ? { stepIndex } : {}
|
|
1728
|
+
});
|
|
1729
|
+
}
|
|
1730
|
+
else {
|
|
1731
|
+
const matches = str.matchAll(/\{\{args\.([a-zA-Z0-9_-]+)\}\}/g);
|
|
1732
|
+
for (const match of matches) {
|
|
1733
|
+
const argName = match[1];
|
|
1734
|
+
const key = `${stepIndex ?? "doc"}:${argName}`;
|
|
1735
|
+
if (!declaredAndDerivedArgs.has(argName) && !seenMissing.has(key)) {
|
|
1736
|
+
seenMissing.add(key);
|
|
1737
|
+
errors.push({
|
|
1738
|
+
rule: "template-args",
|
|
1739
|
+
category: "template",
|
|
1740
|
+
message: `Unresolved workflow argument: {{args.${argName}}} (not declared in workflow 'args')`,
|
|
1741
|
+
...stepIndex !== void 0 ? { stepIndex } : {}
|
|
1742
|
+
});
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
};
|
|
1747
|
+
if (context.doc.name) check(context.doc.name);
|
|
1748
|
+
if (context.doc.title) check(context.doc.title);
|
|
1749
|
+
for (let i = 0; i < context.doc.steps.length; i++) {
|
|
1750
|
+
const step = context.doc.steps[i];
|
|
1751
|
+
const uniqueStrings = new Set(extractStepStrings(step));
|
|
1752
|
+
for (const str of uniqueStrings) check(str, i);
|
|
1753
|
+
}
|
|
1754
|
+
return errors;
|
|
1755
|
+
};
|
|
1756
|
+
/**
|
|
1757
|
+
* Purpose: Enforces that 'foreach' on a subagent references a valid declared output of type 'list'.
|
|
1758
|
+
* Contract:
|
|
1759
|
+
* - Inputs: WorkflowValidationContext with doc.
|
|
1760
|
+
* - Outputs: readonly array of foreach validation errors.
|
|
1761
|
+
*/
|
|
1762
|
+
const ruleForeachOutputReferences = (context) => {
|
|
1763
|
+
const errors = [];
|
|
1764
|
+
const declaredMap = extractDeclaredOutputs(context.doc.steps);
|
|
1765
|
+
for (let i = 0; i < context.doc.steps.length; i++) {
|
|
1766
|
+
const step = context.doc.steps[i];
|
|
1767
|
+
if (step.kind !== "subagent" || !step.foreach) continue;
|
|
1768
|
+
const match = step.foreach.match(/^\{\{outputs\.([a-zA-Z0-9_-]+)\}\}$/);
|
|
1769
|
+
if (!match) {
|
|
1770
|
+
errors.push({
|
|
1771
|
+
rule: "foreach-invalid-expression",
|
|
1772
|
+
category: "output",
|
|
1773
|
+
message: `Subagent step ${i + 1} ('${step.name}') has invalid foreach expression '${step.foreach}'. Must be '{{outputs.<name>}}'.`,
|
|
1774
|
+
stepIndex: i
|
|
1775
|
+
});
|
|
1776
|
+
continue;
|
|
1777
|
+
}
|
|
1778
|
+
const refName = match[1];
|
|
1779
|
+
const declared = declaredMap.get(refName);
|
|
1780
|
+
if (declared === void 0) errors.push({
|
|
1781
|
+
rule: "unknown-output",
|
|
1782
|
+
category: "output",
|
|
1783
|
+
message: `Subagent step ${i + 1} ('${step.name}') foreach references unknown output '{{outputs.${refName}}}'.`,
|
|
1784
|
+
stepIndex: i
|
|
1785
|
+
});
|
|
1786
|
+
else if (declared.stepIndex >= i) errors.push({
|
|
1787
|
+
rule: "forward-output-reference",
|
|
1788
|
+
category: "output",
|
|
1789
|
+
message: `Subagent step ${i + 1} ('${step.name}') foreach references output '{{outputs.${refName}}}' before it is declared at step ${declared.stepIndex + 1}.`,
|
|
1790
|
+
stepIndex: i
|
|
1791
|
+
});
|
|
1792
|
+
else if (declared.type !== "list") errors.push({
|
|
1793
|
+
rule: "foreach-non-list-output",
|
|
1794
|
+
category: "output",
|
|
1795
|
+
message: `Subagent step ${i + 1} ('${step.name}') foreach references output '{{outputs.${refName}}}' which is of type '${declared.type}', expected 'list'.`,
|
|
1796
|
+
stepIndex: i
|
|
1797
|
+
});
|
|
1798
|
+
}
|
|
1799
|
+
return errors;
|
|
1800
|
+
};
|
|
1801
|
+
/**
|
|
1802
|
+
* Purpose: Validates exhaustiveness and unknown choice keys for a choice mapping entry.
|
|
1803
|
+
*/
|
|
1804
|
+
function validateChoiceMappingEntries(choices, choiceMap, argName, derivedKey) {
|
|
1805
|
+
const errors = [];
|
|
1806
|
+
const contextLabel = derivedKey ? `Argument '${argName}' mapping for '${derivedKey}'` : `Argument '${argName}' mapping`;
|
|
1807
|
+
for (const choice of choices) if (!Object.hasOwn(choiceMap, choice)) errors.push({
|
|
1808
|
+
rule: "choice-mapping-non-exhaustive",
|
|
1809
|
+
category: "template",
|
|
1810
|
+
message: `${contextLabel} is missing choice '${choice}'. All choices must be mapped.`
|
|
1811
|
+
});
|
|
1812
|
+
for (const mappedKey of Object.keys(choiceMap)) if (!choices.includes(mappedKey)) errors.push({
|
|
1813
|
+
rule: "choice-mapping-unknown-choice",
|
|
1814
|
+
category: "template",
|
|
1815
|
+
message: `${contextLabel} references unknown choice '${mappedKey}'. Allowed choices: ${choices.join(", ")}.`
|
|
1816
|
+
});
|
|
1817
|
+
return errors;
|
|
1818
|
+
}
|
|
1819
|
+
/**
|
|
1820
|
+
* Purpose: Enforces that choice argument mapping definitions are exhaustive, reference valid choices, and do not collide.
|
|
1821
|
+
* Contract:
|
|
1822
|
+
* - Inputs: WorkflowValidationContext with doc.
|
|
1823
|
+
* - Outputs: readonly array of choice mapping validation errors.
|
|
1824
|
+
*/
|
|
1825
|
+
const ruleChoiceMapping = (context) => {
|
|
1826
|
+
const errors = [];
|
|
1827
|
+
const seenDerived = /* @__PURE__ */ new Set();
|
|
1828
|
+
const topLevelArgNames = new Set(Object.keys(context.doc.args));
|
|
1829
|
+
for (const [argName, def] of Object.entries(context.doc.args)) {
|
|
1830
|
+
if (def.type !== "choice") continue;
|
|
1831
|
+
const mapping = def.mapping ?? def.mappings;
|
|
1832
|
+
if (!mapping) continue;
|
|
1833
|
+
if (Object.keys(mapping).length === 0) {
|
|
1834
|
+
errors.push({
|
|
1835
|
+
rule: "choice-mapping-empty",
|
|
1836
|
+
category: "template",
|
|
1837
|
+
message: `Argument '${argName}' mapping cannot be empty.`
|
|
1838
|
+
});
|
|
1839
|
+
continue;
|
|
1840
|
+
}
|
|
1841
|
+
if (isFlatChoiceMapping(mapping)) errors.push(...validateChoiceMappingEntries(def.choices, mapping, argName));
|
|
1842
|
+
else for (const [derivedKey, choiceMap] of Object.entries(mapping)) {
|
|
1843
|
+
if (topLevelArgNames.has(derivedKey)) errors.push({
|
|
1844
|
+
rule: "choice-mapping-collision",
|
|
1845
|
+
category: "template",
|
|
1846
|
+
message: `Derived argument '${derivedKey}' in argument '${argName}' mapping collides with top-level argument '${derivedKey}'.`
|
|
1847
|
+
});
|
|
1848
|
+
else if (seenDerived.has(derivedKey)) errors.push({
|
|
1849
|
+
rule: "choice-mapping-duplicate",
|
|
1850
|
+
category: "template",
|
|
1851
|
+
message: `Derived argument '${derivedKey}' in argument '${argName}' mapping is already defined in another choice mapping.`
|
|
1852
|
+
});
|
|
1853
|
+
else seenDerived.add(derivedKey);
|
|
1854
|
+
if (Object.keys(choiceMap).length === 0) {
|
|
1855
|
+
errors.push({
|
|
1856
|
+
rule: "choice-mapping-empty",
|
|
1857
|
+
category: "template",
|
|
1858
|
+
message: `Argument '${argName}' mapping for '${derivedKey}' cannot be empty.`
|
|
1859
|
+
});
|
|
1860
|
+
continue;
|
|
1861
|
+
}
|
|
1862
|
+
errors.push(...validateChoiceMappingEntries(def.choices, choiceMap, argName, derivedKey));
|
|
1863
|
+
}
|
|
1864
|
+
}
|
|
1865
|
+
return errors;
|
|
1866
|
+
};
|
|
1867
|
+
const WORKFLOW_RULES = [
|
|
1868
|
+
ruleSubagentOutputRequired,
|
|
1869
|
+
ruleSubagentOutputTypes,
|
|
1870
|
+
ruleDuplicateOutputNames,
|
|
1871
|
+
ruleWorkflowNameOutputReferences,
|
|
1872
|
+
ruleStepOutputReferences,
|
|
1873
|
+
ruleSubagentDependencies,
|
|
1874
|
+
ruleForeachOutputReferences,
|
|
1875
|
+
ruleUnusedOutputs,
|
|
1876
|
+
ruleTemplateArgs,
|
|
1877
|
+
ruleChoiceMapping
|
|
1878
|
+
];
|
|
1879
|
+
/**
|
|
1880
|
+
* Purpose: Executes a set of workflow validation rules against a document and arguments context.
|
|
1881
|
+
* Contract:
|
|
1882
|
+
* - Inputs: WorkflowValidationContext.
|
|
1883
|
+
* - Outputs: readonly array of all collected validation errors.
|
|
1884
|
+
*/
|
|
1885
|
+
function validateWorkflow(context) {
|
|
1886
|
+
return WORKFLOW_RULES.flatMap((rule) => rule(context));
|
|
1887
|
+
}
|
|
1888
|
+
/**
|
|
1889
|
+
* Purpose: Formats an array of validation errors into a human-readable diagnostic message.
|
|
1890
|
+
* Contract:
|
|
1891
|
+
* - Inputs: workflow target path and array of validation errors.
|
|
1892
|
+
* - Outputs: formatted error string.
|
|
1893
|
+
*/
|
|
1894
|
+
function formatValidationErrors(targetPath, errors) {
|
|
1895
|
+
if (errors.length === 0) return "";
|
|
1896
|
+
if (errors.length === 1) return `${errors[0].category === "template" ? "Template" : "Output"} validation error in workflow '${targetPath}': ${errors[0].message}`;
|
|
1897
|
+
return `Validation errors in workflow '${targetPath}':\n${errors.map((e) => `- ${e.message}`).join("\n")}`;
|
|
1898
|
+
}
|
|
1899
|
+
// src/transitions.ts
|
|
1900
|
+
/**
|
|
1901
|
+
* PURPOSE: Pure state machine transition functions for workflow execution.
|
|
1902
|
+
* ALLOWED: Pure computation, state progression, and declarative side-effect generation.
|
|
1903
|
+
* FORBIDDEN: No I/O, no filesystem, no timer/date manipulation, no agent side effects.
|
|
1904
|
+
*/
|
|
1905
|
+
function assertNever(value, label) {
|
|
1906
|
+
throw new TypeError(`Unhandled ${label}: ${JSON.stringify(value)}`);
|
|
1907
|
+
}
|
|
1908
|
+
/**
|
|
1909
|
+
* Computes the next state and declarative side effect for the workflow.
|
|
1910
|
+
* CONTRACT:
|
|
1911
|
+
* - Input: TransitionParams containing doc, invocation, state, and optional instructions.
|
|
1912
|
+
* - Output: TransitionResult containing immutable nextState and declarative effect.
|
|
1913
|
+
* - Invariant: Pure and deterministic. Does not mutate the input state.
|
|
1914
|
+
*/
|
|
1915
|
+
function computeStepTransition({ doc, invocation, state, instructions, outputs, resolvedOutputPaths = {} }) {
|
|
1916
|
+
if (state.stepIndex >= doc.steps.length) return {
|
|
1917
|
+
nextState: {
|
|
1918
|
+
...state,
|
|
1919
|
+
status: "completed"
|
|
1920
|
+
},
|
|
1921
|
+
effect: {
|
|
1922
|
+
type: "complete",
|
|
1923
|
+
totalSteps: doc.steps.length
|
|
1924
|
+
}
|
|
1925
|
+
};
|
|
1926
|
+
const effectiveOutputs = outputs ?? state.outputs;
|
|
1927
|
+
const hasOutputs = effectiveOutputs !== void 0 && Object.keys(effectiveOutputs).length > 0;
|
|
1928
|
+
const step = doc.steps[state.stepIndex];
|
|
1929
|
+
const resolvedArgs = invocation.resolvedArgs;
|
|
1930
|
+
const workflowName = doc.name ? interpolateTemplate(doc.name, resolvedArgs) : void 0;
|
|
1931
|
+
const stepName = interpolateTemplate(step.name, resolvedArgs, effectiveOutputs);
|
|
1932
|
+
const stepLabel = `Step ${state.stepIndex + 1} of ${doc.steps.length}: ${stepName}`;
|
|
1933
|
+
if (step.if && !evaluateStepCondition(step.if, resolvedArgs, effectiveOutputs)) return {
|
|
1934
|
+
nextState: {
|
|
1935
|
+
...state,
|
|
1936
|
+
stepIndex: state.stepIndex + 1,
|
|
1937
|
+
...hasOutputs ? { outputs: effectiveOutputs } : {}
|
|
1938
|
+
},
|
|
1939
|
+
effect: {
|
|
1940
|
+
type: "skip",
|
|
1941
|
+
stepIndex: state.stepIndex,
|
|
1942
|
+
stepLabel
|
|
1943
|
+
}
|
|
1944
|
+
};
|
|
1945
|
+
const isResumedStep = state.status === "aborted" || state.status === "paused" && state.pauseReason === "interrupted";
|
|
1946
|
+
switch (step.kind) {
|
|
1947
|
+
case "prompt": {
|
|
1948
|
+
const interpolatedPrompt = interpolateTemplate(step.prompt, resolvedArgs, effectiveOutputs);
|
|
1949
|
+
const interpolatedGate = resolveGate(step.gate, resolvedArgs, effectiveOutputs, stepName);
|
|
1950
|
+
if (step.isSoloGate && interpolatedGate === void 0) return {
|
|
1951
|
+
nextState: {
|
|
1952
|
+
...state,
|
|
1953
|
+
stepIndex: state.stepIndex + 1,
|
|
1954
|
+
status: "running",
|
|
1955
|
+
...hasOutputs ? { outputs: effectiveOutputs } : {}
|
|
1956
|
+
},
|
|
1957
|
+
effect: {
|
|
1958
|
+
type: "skip",
|
|
1959
|
+
stepIndex: state.stepIndex,
|
|
1960
|
+
stepLabel
|
|
1961
|
+
}
|
|
1962
|
+
};
|
|
1963
|
+
const outputRequirements = step.outputs ? Object.entries(step.outputs).map(([name, def]) => ({
|
|
1964
|
+
name,
|
|
1965
|
+
type: def.type,
|
|
1966
|
+
...def.type === "file" && resolvedOutputPaths?.[name] ? { resolvedPath: resolvedOutputPaths[name] } : {},
|
|
1967
|
+
...def.type !== "file" && def.description ? { description: def.description } : {},
|
|
1968
|
+
...def.type === "list" && def.min !== void 0 ? { min: def.min } : {},
|
|
1969
|
+
...def.type === "list" && def.max !== void 0 ? { max: def.max } : {}
|
|
1970
|
+
})) : void 0;
|
|
1971
|
+
return {
|
|
1972
|
+
nextState: {
|
|
1973
|
+
stepIndex: state.stepIndex + 1,
|
|
1974
|
+
status: "running",
|
|
1975
|
+
...hasOutputs ? { outputs: effectiveOutputs } : {}
|
|
1976
|
+
},
|
|
1977
|
+
effect: {
|
|
1978
|
+
type: "prompt",
|
|
1979
|
+
promptText: formatStepPrompt({
|
|
1980
|
+
stepIndex: state.stepIndex,
|
|
1981
|
+
totalSteps: doc.steps.length,
|
|
1982
|
+
stepName,
|
|
1983
|
+
workflowName,
|
|
1984
|
+
prompt: interpolatedPrompt,
|
|
1985
|
+
isResumedStep,
|
|
1986
|
+
instructions,
|
|
1987
|
+
outputRequirements
|
|
1988
|
+
}),
|
|
1989
|
+
stepLabel,
|
|
1990
|
+
gate: interpolatedGate,
|
|
1991
|
+
...step.outputs ? { outputs: step.outputs } : {}
|
|
1992
|
+
}
|
|
1993
|
+
};
|
|
1994
|
+
}
|
|
1995
|
+
case "subagent": {
|
|
1996
|
+
const interpolatedPrompt = interpolateTemplate(step.prompt, resolvedArgs, effectiveOutputs);
|
|
1997
|
+
const interpolatedGate = resolveGate(step.gate, resolvedArgs, effectiveOutputs, stepName);
|
|
1998
|
+
const hasStepOutputs = step.outputs !== void 0 && Object.keys(step.outputs).length > 0;
|
|
1999
|
+
const outputRequirements = hasStepOutputs ? Object.entries(step.outputs).map(([name, def]) => ({
|
|
2000
|
+
name,
|
|
2001
|
+
type: def.type,
|
|
2002
|
+
...def.type === "file" && resolvedOutputPaths?.[name] ? { resolvedPath: resolvedOutputPaths[name] } : {},
|
|
2003
|
+
...def.type === "string" && def.description ? { description: def.description } : {}
|
|
2004
|
+
})) : void 0;
|
|
2005
|
+
const outputSchema = hasStepOutputs ? buildSubagentOutputSchema(step.outputs, resolvedOutputPaths) : void 0;
|
|
2006
|
+
const promptText = formatSubagentPrompt({
|
|
2007
|
+
prompt: interpolatedPrompt,
|
|
2008
|
+
outputRequirements
|
|
2009
|
+
});
|
|
2010
|
+
const interpolatedConfig = interpolateSubagentConfig((() => {
|
|
2011
|
+
if (step.rawSubagent) return normalizeSubagentConfig(parseSubagentShorthand(interpolateTemplate(step.rawSubagent, resolvedArgs, effectiveOutputs)));
|
|
2012
|
+
return step.config;
|
|
2013
|
+
})(), resolvedArgs, effectiveOutputs);
|
|
2014
|
+
return {
|
|
2015
|
+
nextState: {
|
|
2016
|
+
stepIndex: state.stepIndex + 1,
|
|
2017
|
+
status: "running",
|
|
2018
|
+
...hasOutputs ? { outputs: effectiveOutputs } : {}
|
|
2019
|
+
},
|
|
2020
|
+
effect: {
|
|
2021
|
+
type: "subagent",
|
|
2022
|
+
promptText,
|
|
2023
|
+
stepLabel,
|
|
2024
|
+
config: interpolatedConfig,
|
|
2025
|
+
...step.foreach ? { foreach: step.foreach } : {},
|
|
2026
|
+
gate: interpolatedGate,
|
|
2027
|
+
...step.outputs ? { outputs: step.outputs } : {},
|
|
2028
|
+
...step.output ? { output: step.output } : {},
|
|
2029
|
+
...outputSchema ? { outputSchema } : {},
|
|
2030
|
+
...hasStepOutputs && resolvedOutputPaths ? { resolvedOutputPaths } : {}
|
|
2031
|
+
}
|
|
2032
|
+
};
|
|
2033
|
+
}
|
|
2034
|
+
case "print": {
|
|
2035
|
+
const interpolatedText = interpolateTemplate(step.text, resolvedArgs, effectiveOutputs);
|
|
2036
|
+
return {
|
|
2037
|
+
nextState: {
|
|
2038
|
+
stepIndex: state.stepIndex + 1,
|
|
2039
|
+
status: "running",
|
|
2040
|
+
...hasOutputs ? { outputs: effectiveOutputs } : {}
|
|
2041
|
+
},
|
|
2042
|
+
effect: {
|
|
2043
|
+
type: "print",
|
|
2044
|
+
text: interpolatedText,
|
|
2045
|
+
stepLabel
|
|
2046
|
+
}
|
|
2047
|
+
};
|
|
2048
|
+
}
|
|
2049
|
+
default: return assertNever(step, "workflow step");
|
|
2050
|
+
}
|
|
2051
|
+
}
|
|
2052
|
+
/**
|
|
2053
|
+
* Computes a state transition into the paused state at a gate checkpoint.
|
|
2054
|
+
* CONTRACT:
|
|
2055
|
+
* - Input: state, gate criteria description, stepLabel.
|
|
2056
|
+
* - Output: TransitionResult with status 'paused' and a 'gate_pause' effect.
|
|
2057
|
+
*/
|
|
2058
|
+
function applyGatePause(state, gate, stepLabel) {
|
|
2059
|
+
return {
|
|
2060
|
+
nextState: {
|
|
2061
|
+
...state,
|
|
2062
|
+
status: "paused",
|
|
2063
|
+
pauseReason: "gate"
|
|
2064
|
+
},
|
|
2065
|
+
effect: {
|
|
2066
|
+
type: "gate_pause",
|
|
2067
|
+
gate,
|
|
2068
|
+
stepLabel
|
|
2069
|
+
}
|
|
2070
|
+
};
|
|
2071
|
+
}
|
|
2072
|
+
/**
|
|
2073
|
+
* Computes a state transition into the paused state when a step is interrupted.
|
|
2074
|
+
* CONTRACT:
|
|
2075
|
+
* - Input: state, stepLabel.
|
|
2076
|
+
* - Output: TransitionResult with status 'paused', pauseReason 'interrupted', and a 'step_pause' effect.
|
|
2077
|
+
*/
|
|
2078
|
+
function applyStepPause(state, stepLabel) {
|
|
2079
|
+
return {
|
|
2080
|
+
nextState: {
|
|
2081
|
+
...state,
|
|
2082
|
+
status: "paused",
|
|
2083
|
+
pauseReason: "interrupted"
|
|
2084
|
+
},
|
|
2085
|
+
effect: {
|
|
2086
|
+
type: "step_pause",
|
|
2087
|
+
stepIndex: state.stepIndex,
|
|
2088
|
+
stepLabel
|
|
2089
|
+
}
|
|
2090
|
+
};
|
|
2091
|
+
}
|
|
2092
|
+
/**
|
|
2093
|
+
* Computes a state transition into the aborted state upon cancellation.
|
|
2094
|
+
* CONTRACT:
|
|
2095
|
+
* - Input: state, totalSteps, isAfter flag.
|
|
2096
|
+
* - Output: TransitionResult with status 'aborted' and an 'abort' effect.
|
|
2097
|
+
*/
|
|
2098
|
+
function applyAbort(state, totalSteps, isAfter) {
|
|
2099
|
+
return {
|
|
2100
|
+
nextState: {
|
|
2101
|
+
...state,
|
|
2102
|
+
status: "aborted"
|
|
2103
|
+
},
|
|
2104
|
+
effect: {
|
|
2105
|
+
type: "abort",
|
|
2106
|
+
stepIndex: state.stepIndex,
|
|
2107
|
+
totalSteps,
|
|
2108
|
+
isAfter
|
|
2109
|
+
}
|
|
2110
|
+
};
|
|
2111
|
+
}
|
|
2112
|
+
// src/runner.ts
|
|
2113
|
+
/**
|
|
2114
|
+
* PURPOSE: Stateless workflow execution loop and orchestrator.
|
|
2115
|
+
* ALLOWED: Interpreting pure transitions, coordinating steps via WorkflowEffectContext, abort handling.
|
|
2116
|
+
* FORBIDDEN: Direct command registration, direct filesystem access, Cordis runtime coupling.
|
|
2117
|
+
*/
|
|
2118
|
+
const executingSessions = /* @__PURE__ */ new Set();
|
|
2119
|
+
/**
|
|
2120
|
+
* Purpose: Validates and durably accepts a workflow command without retaining its YAML.
|
|
2121
|
+
* Contract:
|
|
2122
|
+
* - Inputs: command input, effects, and the originating /wf command ID.
|
|
2123
|
+
* - Outputs: immediate validation diagnostics or a queued acknowledgement.
|
|
2124
|
+
* - Throws / Errors: unexpected event-write failures propagate.
|
|
2125
|
+
*/
|
|
2126
|
+
async function requestWorkflow(rawInput, effects, runId) {
|
|
2127
|
+
const validated = await validateWorkflowInvocation(rawInput, effects, runId);
|
|
2128
|
+
if (validated.kind === "error") return validated;
|
|
2129
|
+
effects.emit({
|
|
2130
|
+
action: "request",
|
|
2131
|
+
rawInput,
|
|
2132
|
+
runId
|
|
2133
|
+
});
|
|
2134
|
+
return {
|
|
2135
|
+
kind: "success",
|
|
2136
|
+
text: "Workflow queued"
|
|
2137
|
+
};
|
|
2138
|
+
}
|
|
2139
|
+
/**
|
|
2140
|
+
* Purpose: Drains accepted requests after the preceding workflow finishes cleanup.
|
|
2141
|
+
* Contract:
|
|
2142
|
+
* - Inputs: effects for a live session whose command lifecycle is recorded.
|
|
2143
|
+
* - Outputs: requests execute FIFO; running or paused workflows keep requests pending.
|
|
2144
|
+
* - Throws / Errors: unexpected event-write failures propagate; validation failures are recorded.
|
|
2145
|
+
*/
|
|
2146
|
+
async function drainWorkflowRequests(effects) {
|
|
2147
|
+
if (executingSessions.has(effects.sessionId)) return;
|
|
2148
|
+
executingSessions.add(effects.sessionId);
|
|
2149
|
+
try {
|
|
2150
|
+
while (true) {
|
|
2151
|
+
const events = effects.snapshotEvents();
|
|
2152
|
+
const active = foldWorkflowState(events);
|
|
2153
|
+
if (active !== null && (active.state.status === "running" || active.state.status === "paused")) return;
|
|
2154
|
+
const request = nextWorkflowRequest(events);
|
|
2155
|
+
if (request === void 0) return;
|
|
2156
|
+
const startupAbortController = new AbortController();
|
|
2157
|
+
const cleanupStartupAbort = effects.watchAbort(startupAbortController);
|
|
2158
|
+
let validated;
|
|
2159
|
+
try {
|
|
2160
|
+
await effects.whenIdle();
|
|
2161
|
+
validated = await validateWorkflowInvocation(request.rawInput, effects, request.runId);
|
|
2162
|
+
} catch (error) {
|
|
2163
|
+
validated = {
|
|
2164
|
+
kind: "error",
|
|
2165
|
+
text: extractErrorMessage(error)
|
|
2166
|
+
};
|
|
2167
|
+
} finally {
|
|
2168
|
+
cleanupStartupAbort();
|
|
2169
|
+
}
|
|
2170
|
+
if (validated.kind === "error") {
|
|
2171
|
+
effects.emit({
|
|
2172
|
+
action: "request-failed",
|
|
2173
|
+
runId: request.runId
|
|
2174
|
+
});
|
|
2175
|
+
effects.emit({
|
|
2176
|
+
action: "step",
|
|
2177
|
+
id: `wf-request-${request.runId}-failed`,
|
|
2178
|
+
stepIndex: 0,
|
|
2179
|
+
label: `Queued workflow failed: ${validated.text}`,
|
|
2180
|
+
kind: "error",
|
|
2181
|
+
runId: request.runId
|
|
2182
|
+
});
|
|
2183
|
+
} else await executeValidatedWorkflowDirect(validated, effects, startupAbortController.signal);
|
|
2184
|
+
}
|
|
2185
|
+
} finally {
|
|
2186
|
+
executingSessions.delete(effects.sessionId);
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
/**
|
|
2190
|
+
* Purpose: Wakes pending workflows and reports unexpected background failures.
|
|
2191
|
+
* Contract:
|
|
2192
|
+
* - Inputs: effects for the session whose admission or execution just settled.
|
|
2193
|
+
* - Outputs: starts at most one drain; failures are logged.
|
|
2194
|
+
* - Throws / Errors: asynchronous errors are reported through logInfo.
|
|
2195
|
+
*/
|
|
2196
|
+
function startPendingWorkflows(effects) {
|
|
2197
|
+
drainWorkflowRequests(effects).catch((error) => {
|
|
2198
|
+
effects.logInfo(`Workflow queue failed: ${extractErrorMessage(error)}`);
|
|
2199
|
+
});
|
|
2200
|
+
}
|
|
2201
|
+
async function withWorkflowExecution(effects, execute) {
|
|
2202
|
+
if (executingSessions.has(effects.sessionId)) return {
|
|
2203
|
+
kind: "error",
|
|
2204
|
+
text: "A workflow is already executing in this session"
|
|
2205
|
+
};
|
|
2206
|
+
executingSessions.add(effects.sessionId);
|
|
2207
|
+
try {
|
|
2208
|
+
return await execute();
|
|
2209
|
+
} finally {
|
|
2210
|
+
executingSessions.delete(effects.sessionId);
|
|
2211
|
+
startPendingWorkflows(effects);
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
/**
|
|
2215
|
+
* Handles workflow abortion by computing aborted transition and emitting state.
|
|
2216
|
+
*/
|
|
2217
|
+
function handleAbort(effects, state, stepIndex, totalSteps, runId) {
|
|
2218
|
+
effects.emit({
|
|
2219
|
+
action: "state",
|
|
2220
|
+
...applyAbort(state, totalSteps, false).nextState,
|
|
2221
|
+
runId
|
|
2222
|
+
});
|
|
2223
|
+
return {
|
|
2224
|
+
kind: "error",
|
|
2225
|
+
text: `Workflow aborted at step ${stepIndex + 1}/${totalSteps}`
|
|
2226
|
+
};
|
|
2227
|
+
}
|
|
2228
|
+
/**
|
|
2229
|
+
* Checks whether an abort signal was triggered specifically to pause the workflow.
|
|
2230
|
+
*/
|
|
2231
|
+
function isPauseSignal(signal) {
|
|
2232
|
+
return signal.reason?.kind === "pause";
|
|
2233
|
+
}
|
|
2234
|
+
/**
|
|
2235
|
+
* Handles workflow pause (e.g. user interrupted via Stop Generating) by computing paused transition and emitting state.
|
|
2236
|
+
*/
|
|
2237
|
+
function handlePause(effects, state, stepIndex, stepLabel, totalSteps, runId) {
|
|
2238
|
+
const pauseTransition = applyStepPause(state, stepLabel);
|
|
2239
|
+
effects.emit({
|
|
2240
|
+
action: "state",
|
|
2241
|
+
...pauseTransition.nextState,
|
|
2242
|
+
runId
|
|
2243
|
+
});
|
|
2244
|
+
return {
|
|
2245
|
+
kind: "success",
|
|
2246
|
+
text: `Workflow paused at step ${stepIndex + 1}/${totalSteps}. Resume with /wf-resume`
|
|
2247
|
+
};
|
|
2248
|
+
}
|
|
2249
|
+
/**
|
|
2250
|
+
* Handles workflow termination (either pause on user stop or hard abort) by computing transition and emitting state.
|
|
2251
|
+
*/
|
|
2252
|
+
function handleTermination(signal, effects, state, stepIndex, stepLabel, totalSteps, runId) {
|
|
2253
|
+
if (isPauseSignal(signal)) return handlePause(effects, state, stepIndex, stepLabel, totalSteps, runId);
|
|
2254
|
+
return handleAbort(effects, state, stepIndex, totalSteps, runId);
|
|
2255
|
+
}
|
|
2256
|
+
/**
|
|
2257
|
+
* Emits completion state and returns success result.
|
|
2258
|
+
*/
|
|
2259
|
+
function completeWorkflow(effects, totalSteps, outputs, runId) {
|
|
2260
|
+
const hasOutputs = outputs !== void 0 && Object.keys(outputs).length > 0;
|
|
2261
|
+
effects.emit({
|
|
2262
|
+
action: "state",
|
|
2263
|
+
stepIndex: totalSteps,
|
|
2264
|
+
status: "completed",
|
|
2265
|
+
...hasOutputs ? { outputs } : {},
|
|
2266
|
+
runId
|
|
2267
|
+
});
|
|
2268
|
+
return {
|
|
2269
|
+
kind: "success",
|
|
2270
|
+
text: `Completed workflow (${totalSteps} steps)`
|
|
2271
|
+
};
|
|
2272
|
+
}
|
|
2273
|
+
/**
|
|
2274
|
+
* Safely extracts error message string from unknown error.
|
|
2275
|
+
*/
|
|
2276
|
+
function extractErrorMessage(err) {
|
|
2277
|
+
return (err instanceof Error ? err.message : String(err)) || "Unknown error";
|
|
2278
|
+
}
|
|
2279
|
+
/**
|
|
2280
|
+
* Emits aborted state, logs error, and returns CommandErrorResult on unhandled execution failure.
|
|
2281
|
+
*/
|
|
2282
|
+
function handleExecutionFailure(effects, state, action, err, totalSteps, runId) {
|
|
2283
|
+
const message = extractErrorMessage(err);
|
|
2284
|
+
const failedStepIndex = Math.min(state.stepIndex, totalSteps - 1);
|
|
2285
|
+
const displayStep = failedStepIndex + 1;
|
|
2286
|
+
const { pauseReason: _pauseReason, ...cleanState } = state;
|
|
2287
|
+
effects.emit({
|
|
2288
|
+
action: "state",
|
|
2289
|
+
...cleanState,
|
|
2290
|
+
stepIndex: failedStepIndex,
|
|
2291
|
+
status: "aborted",
|
|
2292
|
+
error: message,
|
|
2293
|
+
runId
|
|
2294
|
+
});
|
|
2295
|
+
effects.logInfo(`Workflow ${action} failed at step ${displayStep}/${totalSteps}: ${message}`);
|
|
2296
|
+
return {
|
|
2297
|
+
kind: "error",
|
|
2298
|
+
text: `Workflow ${action} failed at step ${displayStep}/${totalSteps}: ${message}`
|
|
2299
|
+
};
|
|
2300
|
+
}
|
|
2301
|
+
/**
|
|
2302
|
+
* Type predicate ensuring an unknown value is a non-null, non-array object.
|
|
2303
|
+
*/
|
|
2304
|
+
function isRecord(value) {
|
|
2305
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2306
|
+
}
|
|
2307
|
+
/**
|
|
2308
|
+
* Detects whether an error indicates Cordis context inactivation during fiber unload.
|
|
2309
|
+
*/
|
|
2310
|
+
function isInactiveContextError(err) {
|
|
2311
|
+
if (isRecord(err) && err.code === "INACTIVE_EFFECT") return true;
|
|
2312
|
+
return extractErrorMessage(err).includes("inactive context");
|
|
2313
|
+
}
|
|
2314
|
+
/**
|
|
2315
|
+
* Detects whether an error represents a tool, subagent, or user-initiated cancellation.
|
|
2316
|
+
*/
|
|
2317
|
+
function isAbortError(err) {
|
|
2318
|
+
if (!err) return false;
|
|
2319
|
+
if (err instanceof Error && err.name === "AbortError") return true;
|
|
2320
|
+
if (isRecord(err)) {
|
|
2321
|
+
const code = err.code;
|
|
2322
|
+
return code === "ABORTED" || code === "TOOL_ABORTED" || code === "TOOL_ABORTED_BEFORE_DISPATCH";
|
|
2323
|
+
}
|
|
2324
|
+
return false;
|
|
2325
|
+
}
|
|
2326
|
+
/**
|
|
2327
|
+
* Resolves declared file output paths against template arguments and workflow effect context.
|
|
2328
|
+
*/
|
|
2329
|
+
function resolveStepOutputFilePaths(outputsDef, args, currentOutputs, effects) {
|
|
2330
|
+
const resolved = {};
|
|
2331
|
+
if (!outputsDef) return resolved;
|
|
2332
|
+
for (const [name, def] of Object.entries(outputsDef)) if (def.type === "file") {
|
|
2333
|
+
const interpolatedPath = interpolateTemplate(def.path, args, currentOutputs);
|
|
2334
|
+
resolved[name] = effects.resolveOutputPath(interpolatedPath, def.base);
|
|
2335
|
+
}
|
|
2336
|
+
return resolved;
|
|
2337
|
+
}
|
|
2338
|
+
/**
|
|
2339
|
+
* Unifies error classification, pause handling, abort handling, and failure delegation during workflow execution.
|
|
2340
|
+
*/
|
|
2341
|
+
function handleWorkflowExecutionError({ effects, state, doc, signal, err, action, runId }) {
|
|
2342
|
+
const currentIdx = Math.min(state.stepIndex, doc.steps.length - 1);
|
|
2343
|
+
const stepName = doc.steps[currentIdx].name;
|
|
2344
|
+
if (signal.aborted || isAbortError(err)) return handleTermination(signal, effects, state, currentIdx, stepName, doc.steps.length, runId);
|
|
2345
|
+
if (isInactiveContextError(err)) return handlePause(effects, state, currentIdx, stepName, doc.steps.length, runId);
|
|
2346
|
+
return handleExecutionFailure(effects, state, action, err, doc.steps.length, runId);
|
|
2347
|
+
}
|
|
2348
|
+
/**
|
|
2349
|
+
* Validates session ID and awaits agent idle state before workflow resumption or discarding.
|
|
2350
|
+
*/
|
|
2351
|
+
async function ensureIdleSession(effects, action) {
|
|
2352
|
+
if (!effects.sessionId) return {
|
|
2353
|
+
kind: "error",
|
|
2354
|
+
text: `Workflow ${action} failed: agent session ID is required`
|
|
2355
|
+
};
|
|
2356
|
+
try {
|
|
2357
|
+
await effects.whenIdle();
|
|
2358
|
+
} catch (err) {
|
|
2359
|
+
const message = extractErrorMessage(err);
|
|
2360
|
+
effects.logInfo(`Workflow ${action} failed: ${message}`);
|
|
2361
|
+
return {
|
|
2362
|
+
kind: "error",
|
|
2363
|
+
text: `Workflow ${action} failed: ${message}`
|
|
2364
|
+
};
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
2367
|
+
/**
|
|
2368
|
+
* Runs a validation step and catches errors into a formatted CommandErrorResult.
|
|
2369
|
+
*/
|
|
2370
|
+
function runValidationStep(fn, prefix, targetPath) {
|
|
2371
|
+
try {
|
|
2372
|
+
return { result: fn() };
|
|
2373
|
+
} catch (err) {
|
|
2374
|
+
return {
|
|
2375
|
+
kind: "error",
|
|
2376
|
+
text: `${prefix} '${targetPath}': ${extractErrorMessage(err)}`
|
|
2377
|
+
};
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
/**
|
|
2381
|
+
* Drives sequential workflow step execution, interpreting pure state machine transitions.
|
|
2382
|
+
* CONTRACT:
|
|
2383
|
+
* - Input: effects, doc, invocation, initial state, optional signal, and instructions.
|
|
2384
|
+
* - Output: Promise resolving to CommandResult (success, gate pause, or abort error).
|
|
2385
|
+
*/
|
|
2386
|
+
async function runWorkflowSteps({ effects, doc, invocation, stateRef, signal, instructions }) {
|
|
2387
|
+
const steps = doc.steps;
|
|
2388
|
+
const runId = invocation.runId;
|
|
2389
|
+
const initialState = stateRef.current;
|
|
2390
|
+
let state = initialState;
|
|
2391
|
+
const outputs = { ...initialState.outputs };
|
|
2392
|
+
let pendingInstructions = instructions;
|
|
2393
|
+
if (steps.some((s) => (s.kind === "prompt" || s.kind === "subagent") && s.outputs !== void 0 && Object.values(s.outputs).some((o) => o.type === "file" && o.base === "scratch"))) await effects.ensureScratchDirectory();
|
|
2394
|
+
while (state.stepIndex < steps.length) {
|
|
2395
|
+
const currentStepIndex = state.stepIndex;
|
|
2396
|
+
if (signal.aborted) return handleTermination(signal, effects, stateRef.current, currentStepIndex, steps[currentStepIndex].name, steps.length, runId);
|
|
2397
|
+
const step = steps[currentStepIndex];
|
|
2398
|
+
if (step.kind === "subagent") {
|
|
2399
|
+
let waveEnd = currentStepIndex;
|
|
2400
|
+
while (waveEnd < steps.length) {
|
|
2401
|
+
const s = steps[waveEnd];
|
|
2402
|
+
if (s.kind !== "subagent") break;
|
|
2403
|
+
if (resolveGate(s.gate, invocation.resolvedArgs, outputs, s.name) !== void 0) {
|
|
2404
|
+
waveEnd++;
|
|
2405
|
+
break;
|
|
2406
|
+
}
|
|
2407
|
+
waveEnd++;
|
|
2408
|
+
}
|
|
2409
|
+
const activeWaveSteps = [];
|
|
2410
|
+
for (let idx = currentStepIndex; idx < waveEnd; idx++) {
|
|
2411
|
+
const waveStep = steps[idx];
|
|
2412
|
+
if (waveStep.foreach !== void 0) {
|
|
2413
|
+
const stepOutputPaths = resolveStepOutputFilePaths(waveStep.outputs, invocation.resolvedArgs, outputs, effects);
|
|
2414
|
+
const transition = computeStepTransition({
|
|
2415
|
+
doc,
|
|
2416
|
+
invocation,
|
|
2417
|
+
state: {
|
|
2418
|
+
...state,
|
|
2419
|
+
stepIndex: idx
|
|
2420
|
+
},
|
|
2421
|
+
instructions: pendingInstructions,
|
|
2422
|
+
outputs,
|
|
2423
|
+
resolvedOutputPaths: stepOutputPaths
|
|
2424
|
+
});
|
|
2425
|
+
if (transition.effect.type === "skip") continue;
|
|
2426
|
+
const listName = waveStep.foreach.slice(10, -2);
|
|
2427
|
+
const rawVal = outputs[listName];
|
|
2428
|
+
if (!Array.isArray(rawVal)) return handleExecutionFailure(effects, stateRef.current, "execution", /* @__PURE__ */ new Error(`Step ${idx + 1} foreach output '${listName}' is missing or not an array`), steps.length, runId);
|
|
2429
|
+
const listItems = rawVal;
|
|
2430
|
+
if (listItems.length === 0) {
|
|
2431
|
+
if (waveStep.output !== void 0) {
|
|
2432
|
+
effects.recordOutput(idx, waveStep.output, "[]", "list", void 0, runId);
|
|
2433
|
+
outputs[waveStep.output] = [];
|
|
2434
|
+
}
|
|
2435
|
+
if (waveStep.outputs !== void 0) for (const name of Object.keys(waveStep.outputs)) {
|
|
2436
|
+
effects.recordOutput(idx, name, "[]", "list", void 0, runId);
|
|
2437
|
+
outputs[name] = [];
|
|
2438
|
+
}
|
|
2439
|
+
continue;
|
|
2440
|
+
}
|
|
2441
|
+
const baseSubagentEffect = transition.effect;
|
|
2442
|
+
for (let itemIdx = 0; itemIdx < listItems.length; itemIdx++) {
|
|
2443
|
+
const itemVal = listItems[itemIdx];
|
|
2444
|
+
const itemPromptText = interpolateTemplate(baseSubagentEffect.promptText, invocation.resolvedArgs, outputs, { item: itemVal });
|
|
2445
|
+
const itemLabel = `Step ${idx + 1} (${itemIdx + 1}/${listItems.length}): ${waveStep.name} [${itemVal}]`;
|
|
2446
|
+
const subagentEffect = {
|
|
2447
|
+
...baseSubagentEffect,
|
|
2448
|
+
promptText: itemPromptText,
|
|
2449
|
+
stepLabel: itemLabel
|
|
2450
|
+
};
|
|
2451
|
+
activeWaveSteps.push({
|
|
2452
|
+
stepIndex: idx,
|
|
2453
|
+
itemIndex: itemIdx,
|
|
2454
|
+
totalItems: listItems.length,
|
|
2455
|
+
step: waveStep,
|
|
2456
|
+
effect: subagentEffect,
|
|
2457
|
+
resolvedOutputPaths: stepOutputPaths
|
|
2458
|
+
});
|
|
2459
|
+
}
|
|
2460
|
+
} else {
|
|
2461
|
+
const stepOutputPaths = resolveStepOutputFilePaths(waveStep.outputs, invocation.resolvedArgs, outputs, effects);
|
|
2462
|
+
const transition = computeStepTransition({
|
|
2463
|
+
doc,
|
|
2464
|
+
invocation,
|
|
2465
|
+
state: {
|
|
2466
|
+
...state,
|
|
2467
|
+
stepIndex: idx
|
|
2468
|
+
},
|
|
2469
|
+
instructions: pendingInstructions,
|
|
2470
|
+
outputs,
|
|
2471
|
+
resolvedOutputPaths: stepOutputPaths
|
|
2472
|
+
});
|
|
2473
|
+
if (transition.effect.type === "skip") continue;
|
|
2474
|
+
const subagentEffect = transition.effect;
|
|
2475
|
+
activeWaveSteps.push({
|
|
2476
|
+
stepIndex: idx,
|
|
2477
|
+
step: waveStep,
|
|
2478
|
+
effect: subagentEffect,
|
|
2479
|
+
resolvedOutputPaths: stepOutputPaths
|
|
2480
|
+
});
|
|
2481
|
+
}
|
|
2482
|
+
}
|
|
2483
|
+
if (activeWaveSteps.length === 0) {
|
|
2484
|
+
state = {
|
|
2485
|
+
...state,
|
|
2486
|
+
stepIndex: waveEnd,
|
|
2487
|
+
...Object.keys(outputs).length > 0 ? { outputs: { ...outputs } } : {}
|
|
2488
|
+
};
|
|
2489
|
+
stateRef.current = state;
|
|
2490
|
+
if (state.stepIndex < steps.length) effects.emit({
|
|
2491
|
+
action: "state",
|
|
2492
|
+
...state,
|
|
2493
|
+
runId
|
|
2494
|
+
});
|
|
2495
|
+
continue;
|
|
2496
|
+
}
|
|
2497
|
+
for (const item of activeWaveSteps) {
|
|
2498
|
+
const stepId = item.itemIndex !== void 0 ? `wf-step-${runId}-${item.stepIndex}-${item.itemIndex}` : `wf-step-${runId}-${item.stepIndex}`;
|
|
2499
|
+
effects.emit({
|
|
2500
|
+
action: "step",
|
|
2501
|
+
id: stepId,
|
|
2502
|
+
stepIndex: item.stepIndex,
|
|
2503
|
+
label: item.effect.stepLabel,
|
|
2504
|
+
kind: "success",
|
|
2505
|
+
runId
|
|
2506
|
+
});
|
|
2507
|
+
}
|
|
2508
|
+
const waveAbortController = new AbortController();
|
|
2509
|
+
const waveSignal = AbortSignal.any([signal, waveAbortController.signal]);
|
|
2510
|
+
let waveResults;
|
|
2511
|
+
let failingStepIndex = activeWaveSteps[0].stepIndex;
|
|
2512
|
+
try {
|
|
2513
|
+
waveResults = await Promise.all(activeWaveSteps.map(async (item) => {
|
|
2514
|
+
try {
|
|
2515
|
+
const subagentResult = await effects.dispatchSubagent(item.effect, waveSignal);
|
|
2516
|
+
return {
|
|
2517
|
+
...item,
|
|
2518
|
+
subagentResult
|
|
2519
|
+
};
|
|
2520
|
+
} catch (err) {
|
|
2521
|
+
if (!waveAbortController.signal.aborted) failingStepIndex = item.stepIndex;
|
|
2522
|
+
waveAbortController.abort({ kind: "error" });
|
|
2523
|
+
throw err;
|
|
2524
|
+
}
|
|
2525
|
+
}));
|
|
2526
|
+
} catch (err) {
|
|
2527
|
+
return handleWorkflowExecutionError({
|
|
2528
|
+
effects,
|
|
2529
|
+
state: {
|
|
2530
|
+
...stateRef.current,
|
|
2531
|
+
stepIndex: failingStepIndex
|
|
2532
|
+
},
|
|
2533
|
+
doc,
|
|
2534
|
+
signal,
|
|
2535
|
+
err,
|
|
2536
|
+
action: "execution",
|
|
2537
|
+
runId
|
|
2538
|
+
});
|
|
2539
|
+
}
|
|
2540
|
+
if (signal.aborted) {
|
|
2541
|
+
const firstActive = activeWaveSteps[0];
|
|
2542
|
+
return handleTermination(signal, effects, stateRef.current, firstActive.stepIndex, firstActive.step.name, steps.length, runId);
|
|
2543
|
+
}
|
|
2544
|
+
const processedStepIndices = /* @__PURE__ */ new Set();
|
|
2545
|
+
for (const item of activeWaveSteps) {
|
|
2546
|
+
if (processedStepIndices.has(item.stepIndex)) continue;
|
|
2547
|
+
processedStepIndices.add(item.stepIndex);
|
|
2548
|
+
const stepItems = waveResults.filter((r) => r.stepIndex === item.stepIndex);
|
|
2549
|
+
if (item.step.foreach !== void 0) {
|
|
2550
|
+
if (item.step.output) {
|
|
2551
|
+
const collected = stepItems.map((r) => r.subagentResult.outputText);
|
|
2552
|
+
effects.recordOutput(item.stepIndex, item.step.output, JSON.stringify(collected), "list", void 0, runId);
|
|
2553
|
+
outputs[item.step.output] = collected;
|
|
2554
|
+
} else if (item.step.outputs !== void 0) for (const name of Object.keys(item.step.outputs)) {
|
|
2555
|
+
const collectedValues = [];
|
|
2556
|
+
for (const r of stepItems) {
|
|
2557
|
+
if (!isRecord(r.subagentResult.structured)) return handleExecutionFailure(effects, {
|
|
2558
|
+
...stateRef.current,
|
|
2559
|
+
stepIndex: item.stepIndex
|
|
2560
|
+
}, "execution", /* @__PURE__ */ new Error(`Step ${item.stepIndex + 1} subagent failed to produce required structured outputs`), steps.length, runId);
|
|
2561
|
+
const val = r.subagentResult.structured[name];
|
|
2562
|
+
if (typeof val !== "string" || val.length === 0) return handleExecutionFailure(effects, {
|
|
2563
|
+
...stateRef.current,
|
|
2564
|
+
stepIndex: item.stepIndex
|
|
2565
|
+
}, "execution", /* @__PURE__ */ new Error(`Step ${item.stepIndex + 1} subagent structured output '${name}' is missing or empty`), steps.length, runId);
|
|
2566
|
+
collectedValues.push(val);
|
|
2567
|
+
}
|
|
2568
|
+
effects.recordOutput(item.stepIndex, name, JSON.stringify(collectedValues), "list", void 0, runId);
|
|
2569
|
+
outputs[name] = collectedValues;
|
|
2570
|
+
}
|
|
2571
|
+
stateRef.current = {
|
|
2572
|
+
...stateRef.current,
|
|
2573
|
+
outputs: { ...outputs }
|
|
2574
|
+
};
|
|
2575
|
+
} else {
|
|
2576
|
+
const subagentResult = stepItems[0].subagentResult;
|
|
2577
|
+
const outputText = subagentResult.outputText;
|
|
2578
|
+
if (item.step.outputs !== void 0 && Object.keys(item.step.outputs).length > 0) {
|
|
2579
|
+
if (!isRecord(subagentResult.structured)) return handleExecutionFailure(effects, {
|
|
2580
|
+
...stateRef.current,
|
|
2581
|
+
stepIndex: item.stepIndex
|
|
2582
|
+
}, "execution", /* @__PURE__ */ new Error(`Step ${item.stepIndex + 1} subagent failed to produce required structured outputs`), steps.length, runId);
|
|
2583
|
+
const structured = subagentResult.structured;
|
|
2584
|
+
const pendingStringOutputs = [];
|
|
2585
|
+
for (const [name, def] of Object.entries(item.step.outputs)) {
|
|
2586
|
+
const val = structured[name];
|
|
2587
|
+
if (typeof val !== "string" || val.length === 0) return handleExecutionFailure(effects, {
|
|
2588
|
+
...stateRef.current,
|
|
2589
|
+
stepIndex: item.stepIndex
|
|
2590
|
+
}, "execution", /* @__PURE__ */ new Error(`Step ${item.stepIndex + 1} subagent structured output '${name}' is missing or empty`), steps.length, runId);
|
|
2591
|
+
if (def.type === "string") pendingStringOutputs.push({
|
|
2592
|
+
name,
|
|
2593
|
+
val
|
|
2594
|
+
});
|
|
2595
|
+
else {
|
|
2596
|
+
const expectedResolved = item.resolvedOutputPaths[name];
|
|
2597
|
+
if (path.resolve(val) !== path.resolve(expectedResolved)) return handleExecutionFailure(effects, {
|
|
2598
|
+
...stateRef.current,
|
|
2599
|
+
stepIndex: item.stepIndex
|
|
2600
|
+
}, "execution", /* @__PURE__ */ new Error(`Step ${item.stepIndex + 1} subagent file output '${name}' returned path '${val}', expected '${expectedResolved}'`), steps.length, runId);
|
|
2601
|
+
}
|
|
2602
|
+
}
|
|
2603
|
+
for (const [name, def] of Object.entries(item.step.outputs)) if (def.type === "file") {
|
|
2604
|
+
const resolved = item.resolvedOutputPaths[name];
|
|
2605
|
+
if (!await effects.checkFileWritten(resolved)) return handleExecutionFailure(effects, {
|
|
2606
|
+
...stateRef.current,
|
|
2607
|
+
stepIndex: item.stepIndex
|
|
2608
|
+
}, "execution", /* @__PURE__ */ new Error(`Step ${item.stepIndex + 1} subagent output verification failed: declared outputs were missing or unwritten`), steps.length, runId);
|
|
2609
|
+
}
|
|
2610
|
+
for (const { name, val } of pendingStringOutputs) {
|
|
2611
|
+
effects.recordOutput(item.stepIndex, name, val, "string", void 0, runId);
|
|
2612
|
+
outputs[name] = val;
|
|
2613
|
+
}
|
|
2614
|
+
for (const [name, def] of Object.entries(item.step.outputs)) if (def.type === "file") {
|
|
2615
|
+
const resolved = item.resolvedOutputPaths[name];
|
|
2616
|
+
effects.recordOutput(item.stepIndex, name, resolved, def.type, def.base, runId);
|
|
2617
|
+
outputs[name] = resolved;
|
|
2618
|
+
}
|
|
2619
|
+
stateRef.current = {
|
|
2620
|
+
...stateRef.current,
|
|
2621
|
+
outputs: { ...outputs }
|
|
2622
|
+
};
|
|
2623
|
+
} else if (item.effect.output) {
|
|
2624
|
+
effects.recordOutput(item.stepIndex, item.effect.output, outputText, "string", void 0, runId);
|
|
2625
|
+
outputs[item.effect.output] = outputText;
|
|
2626
|
+
stateRef.current = {
|
|
2627
|
+
...stateRef.current,
|
|
2628
|
+
outputs: { ...outputs }
|
|
2629
|
+
};
|
|
2630
|
+
}
|
|
2631
|
+
}
|
|
2632
|
+
}
|
|
2633
|
+
const lastActive = activeWaveSteps[activeWaveSteps.length - 1];
|
|
2634
|
+
if (lastActive.effect.gate !== void 0) {
|
|
2635
|
+
state = {
|
|
2636
|
+
...applyGatePause(state, lastActive.effect.gate, lastActive.effect.stepLabel).nextState,
|
|
2637
|
+
stepIndex: lastActive.stepIndex,
|
|
2638
|
+
outputs: { ...outputs }
|
|
2639
|
+
};
|
|
2640
|
+
stateRef.current = state;
|
|
2641
|
+
effects.emit({
|
|
2642
|
+
action: "state",
|
|
2643
|
+
...state,
|
|
2644
|
+
runId
|
|
2645
|
+
});
|
|
2646
|
+
effects.emit({
|
|
2647
|
+
action: "step",
|
|
2648
|
+
id: `wf-step-${runId}-${lastActive.stepIndex}-gate`,
|
|
2649
|
+
stepIndex: lastActive.stepIndex,
|
|
2650
|
+
label: `Paused at gate: ${lastActive.effect.gate}`,
|
|
2651
|
+
kind: "success",
|
|
2652
|
+
runId
|
|
2653
|
+
});
|
|
2654
|
+
return {
|
|
2655
|
+
kind: "success",
|
|
2656
|
+
text: `Workflow paused at gate: "${lastActive.effect.gate}". Resume with /wf-resume`
|
|
2657
|
+
};
|
|
2658
|
+
}
|
|
2659
|
+
state = {
|
|
2660
|
+
...state,
|
|
2661
|
+
stepIndex: waveEnd,
|
|
2662
|
+
status: "running",
|
|
2663
|
+
outputs: { ...outputs }
|
|
2664
|
+
};
|
|
2665
|
+
stateRef.current = state;
|
|
2666
|
+
if (state.stepIndex < steps.length) effects.emit({
|
|
2667
|
+
action: "state",
|
|
2668
|
+
...state,
|
|
2669
|
+
runId
|
|
2670
|
+
});
|
|
2671
|
+
continue;
|
|
2672
|
+
}
|
|
2673
|
+
const resolvedOutputPaths = resolveStepOutputFilePaths(step.kind === "prompt" ? step.outputs : void 0, invocation.resolvedArgs, outputs, effects);
|
|
2674
|
+
const transition = computeStepTransition({
|
|
2675
|
+
doc,
|
|
2676
|
+
invocation,
|
|
2677
|
+
state,
|
|
2678
|
+
instructions: pendingInstructions,
|
|
2679
|
+
outputs,
|
|
2680
|
+
resolvedOutputPaths
|
|
2681
|
+
});
|
|
2682
|
+
if (transition.effect.type === "skip") {
|
|
2683
|
+
state = transition.nextState;
|
|
2684
|
+
stateRef.current = state;
|
|
2685
|
+
if (state.stepIndex < steps.length) effects.emit({
|
|
2686
|
+
action: "state",
|
|
2687
|
+
...state,
|
|
2688
|
+
runId
|
|
2689
|
+
});
|
|
2690
|
+
continue;
|
|
2691
|
+
}
|
|
2692
|
+
if (transition.effect.type === "prompt") {
|
|
2693
|
+
pendingInstructions = void 0;
|
|
2694
|
+
const { effect, nextState } = transition;
|
|
2695
|
+
effects.emit({
|
|
2696
|
+
action: "step",
|
|
2697
|
+
id: `wf-step-${runId}-${currentStepIndex}`,
|
|
2698
|
+
stepIndex: currentStepIndex,
|
|
2699
|
+
label: effect.stepLabel,
|
|
2700
|
+
kind: "success",
|
|
2701
|
+
runId
|
|
2702
|
+
});
|
|
2703
|
+
await effects.dispatchPrompt(effect);
|
|
2704
|
+
if (signal.aborted) return handleTermination(signal, effects, stateRef.current, currentStepIndex, effect.stepLabel, steps.length, runId);
|
|
2705
|
+
if (step.kind === "prompt" && step.outputs !== void 0 && Object.keys(step.outputs).length > 0) {
|
|
2706
|
+
const declaredOutputs = step.outputs;
|
|
2707
|
+
const verifiedValues = {};
|
|
2708
|
+
let allVerified = false;
|
|
2709
|
+
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
2710
|
+
const missing = [];
|
|
2711
|
+
for (const [name, def] of Object.entries(declaredOutputs)) {
|
|
2712
|
+
if (verifiedValues[name] !== void 0) continue;
|
|
2713
|
+
if (def.type === "file") {
|
|
2714
|
+
const resolved = resolvedOutputPaths[name];
|
|
2715
|
+
if (await effects.checkFileWritten(resolved)) verifiedValues[name] = resolved;
|
|
2716
|
+
else missing.push({
|
|
2717
|
+
name,
|
|
2718
|
+
type: "file",
|
|
2719
|
+
resolvedPath: resolved
|
|
2720
|
+
});
|
|
2721
|
+
} else if (def.type === "list") {
|
|
2722
|
+
const captured = effects.getCapturedOutput(currentStepIndex, name);
|
|
2723
|
+
if (captured !== void 0) {
|
|
2724
|
+
const parsed = parseListOutput(name, captured, def);
|
|
2725
|
+
if (parsed.kind === "success") verifiedValues[name] = parsed.value;
|
|
2726
|
+
else missing.push({
|
|
2727
|
+
name,
|
|
2728
|
+
type: "list"
|
|
2729
|
+
});
|
|
2730
|
+
} else missing.push({
|
|
2731
|
+
name,
|
|
2732
|
+
type: "list"
|
|
2733
|
+
});
|
|
2734
|
+
} else {
|
|
2735
|
+
const captured = effects.getCapturedOutput(currentStepIndex, name);
|
|
2736
|
+
if (captured !== void 0) verifiedValues[name] = captured;
|
|
2737
|
+
else missing.push({
|
|
2738
|
+
name,
|
|
2739
|
+
type: "string"
|
|
2740
|
+
});
|
|
2741
|
+
}
|
|
2742
|
+
}
|
|
2743
|
+
if (missing.length === 0) {
|
|
2744
|
+
allVerified = true;
|
|
2745
|
+
break;
|
|
2746
|
+
}
|
|
2747
|
+
if (attempt < 3) {
|
|
2748
|
+
const stepName = interpolateTemplate(step.name, invocation.resolvedArgs, outputs);
|
|
2749
|
+
const retryPromptText = formatOutputRetryPrompt({
|
|
2750
|
+
stepIndex: currentStepIndex,
|
|
2751
|
+
totalSteps: steps.length,
|
|
2752
|
+
stepName,
|
|
2753
|
+
missingOutputs: missing,
|
|
2754
|
+
attempt
|
|
2755
|
+
});
|
|
2756
|
+
await effects.dispatchPrompt({
|
|
2757
|
+
type: "prompt",
|
|
2758
|
+
promptText: retryPromptText,
|
|
2759
|
+
stepLabel: `${effect.stepLabel} (Output Retry ${attempt}/3)`
|
|
2760
|
+
});
|
|
2761
|
+
if (signal.aborted) return handleTermination(signal, effects, stateRef.current, currentStepIndex, effect.stepLabel, steps.length, runId);
|
|
2762
|
+
}
|
|
2763
|
+
}
|
|
2764
|
+
if (!allVerified) return handleExecutionFailure(effects, stateRef.current, "execution", /* @__PURE__ */ new Error(`Step ${currentStepIndex + 1} output verification failed after 3 attempts`), steps.length, runId);
|
|
2765
|
+
for (const [name, def] of Object.entries(declaredOutputs)) {
|
|
2766
|
+
const val = verifiedValues[name];
|
|
2767
|
+
if (def.type === "file") effects.recordOutput(currentStepIndex, name, val, def.type, def.base, runId);
|
|
2768
|
+
outputs[name] = val;
|
|
2769
|
+
}
|
|
2770
|
+
stateRef.current = {
|
|
2771
|
+
...stateRef.current,
|
|
2772
|
+
outputs: { ...outputs }
|
|
2773
|
+
};
|
|
2774
|
+
}
|
|
2775
|
+
const hasOutputs = Object.keys(outputs).length > 0;
|
|
2776
|
+
if (effect.gate !== void 0) {
|
|
2777
|
+
state = {
|
|
2778
|
+
...applyGatePause(state, effect.gate, effect.stepLabel).nextState,
|
|
2779
|
+
...hasOutputs ? { outputs } : {}
|
|
2780
|
+
};
|
|
2781
|
+
stateRef.current = state;
|
|
2782
|
+
effects.emit({
|
|
2783
|
+
action: "state",
|
|
2784
|
+
...state,
|
|
2785
|
+
runId
|
|
2786
|
+
});
|
|
2787
|
+
effects.emit({
|
|
2788
|
+
action: "step",
|
|
2789
|
+
id: `wf-step-${runId}-${currentStepIndex}-gate`,
|
|
2790
|
+
stepIndex: currentStepIndex,
|
|
2791
|
+
label: `Paused at gate: ${effect.gate}`,
|
|
2792
|
+
kind: "success",
|
|
2793
|
+
runId
|
|
2794
|
+
});
|
|
2795
|
+
return {
|
|
2796
|
+
kind: "success",
|
|
2797
|
+
text: `Workflow paused at gate: "${effect.gate}". Resume with /wf-resume`
|
|
2798
|
+
};
|
|
2799
|
+
}
|
|
2800
|
+
state = {
|
|
2801
|
+
...nextState,
|
|
2802
|
+
...hasOutputs ? { outputs } : {}
|
|
2803
|
+
};
|
|
2804
|
+
stateRef.current = state;
|
|
2805
|
+
} else {
|
|
2806
|
+
const effect = transition.effect;
|
|
2807
|
+
effects.emit({
|
|
2808
|
+
action: "print",
|
|
2809
|
+
id: `wf-print-${runId}-${currentStepIndex}`,
|
|
2810
|
+
text: effect.text,
|
|
2811
|
+
runId
|
|
2812
|
+
});
|
|
2813
|
+
if (signal.aborted) return handleTermination(signal, effects, stateRef.current, currentStepIndex, steps[currentStepIndex].name, steps.length, runId);
|
|
2814
|
+
const hasOutputs = Object.keys(outputs).length > 0;
|
|
2815
|
+
state = {
|
|
2816
|
+
...transition.nextState,
|
|
2817
|
+
...hasOutputs ? { outputs } : {}
|
|
2818
|
+
};
|
|
2819
|
+
stateRef.current = state;
|
|
2820
|
+
}
|
|
2821
|
+
if (state.stepIndex < steps.length) effects.emit({
|
|
2822
|
+
action: "state",
|
|
2823
|
+
...state,
|
|
2824
|
+
runId
|
|
2825
|
+
});
|
|
2826
|
+
}
|
|
2827
|
+
return completeWorkflow(effects, steps.length, outputs, runId);
|
|
2828
|
+
}
|
|
2829
|
+
/**
|
|
2830
|
+
* Loads and parses a workflow document from effects, returning the parsed document or an error CommandResult.
|
|
2831
|
+
*/
|
|
2832
|
+
async function loadAndParseWorkflow(targetPath, effects) {
|
|
2833
|
+
let content;
|
|
2834
|
+
try {
|
|
2835
|
+
content = await effects.readWorkflow(targetPath);
|
|
2836
|
+
} catch (err) {
|
|
2837
|
+
return {
|
|
2838
|
+
kind: "error",
|
|
2839
|
+
text: `Failed to load workflow '${targetPath}': ${err instanceof Error ? err.message : String(err)}`
|
|
2840
|
+
};
|
|
2841
|
+
}
|
|
2842
|
+
const docStep = runValidationStep(() => parseWorkflowDocument(content), "Failed to parse workflow", targetPath);
|
|
2843
|
+
if ("kind" in docStep) return docStep;
|
|
2844
|
+
return { doc: docStep.result };
|
|
2845
|
+
}
|
|
2846
|
+
/**
|
|
2847
|
+
* Validates subagent step configurations against the live environment.
|
|
2848
|
+
* CONTRACT:
|
|
2849
|
+
* - Inputs: WorkflowDocument, effects context, targetPath, optional arguments, optional AbortSignal.
|
|
2850
|
+
* - Outputs: Formatted error message string on failure, or undefined if valid.
|
|
2851
|
+
*/
|
|
2852
|
+
async function validateWorkflowSubagents(doc, effects, targetPath, args, signal) {
|
|
2853
|
+
const effectiveArgs = { ...args ?? {} };
|
|
2854
|
+
if (args === void 0) {
|
|
2855
|
+
for (const [key, def] of Object.entries(doc.args)) if (def.default !== void 0) effectiveArgs[key] = String(def.default);
|
|
2856
|
+
}
|
|
2857
|
+
for (let i = 0; i < doc.steps.length; i++) {
|
|
2858
|
+
const step = doc.steps[i];
|
|
2859
|
+
if (step.kind !== "subagent") continue;
|
|
2860
|
+
let configToValidate;
|
|
2861
|
+
try {
|
|
2862
|
+
if (step.rawSubagent) {
|
|
2863
|
+
const interpolated = interpolateTemplate(step.rawSubagent, effectiveArgs);
|
|
2864
|
+
if (interpolated.includes("{{")) continue;
|
|
2865
|
+
configToValidate = normalizeSubagentConfig(parseSubagentShorthand(interpolated));
|
|
2866
|
+
} else {
|
|
2867
|
+
const interpolatedConfig = interpolateSubagentConfig(step.config, effectiveArgs);
|
|
2868
|
+
if (Object.values(interpolatedConfig).some((v) => typeof v === "string" && v.includes("{{"))) continue;
|
|
2869
|
+
configToValidate = interpolatedConfig;
|
|
2870
|
+
}
|
|
2871
|
+
} catch (err) {
|
|
2872
|
+
if (args === void 0 && String(err).includes("Unresolved workflow argument")) continue;
|
|
2873
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2874
|
+
return `Validation error in workflow '${targetPath}': Subagent step ${i + 1} ('${step.name}'): ${message}`;
|
|
2875
|
+
}
|
|
2876
|
+
const routeResult = await effects.validateSubagentRoute(configToValidate, signal);
|
|
2877
|
+
if (!routeResult.valid) return `Validation error in workflow '${targetPath}': Subagent step ${i + 1} ('${step.name}'): ${routeResult.message}`;
|
|
2878
|
+
}
|
|
2879
|
+
}
|
|
2880
|
+
/**
|
|
2881
|
+
* Loads, parses, resolves arguments, runs pure AST rules, and validates subagent routes.
|
|
2882
|
+
* CONTRACT:
|
|
2883
|
+
* - Inputs: rawInput string, effects context, options (requireArgs, usageText, optional signal).
|
|
2884
|
+
* - Outputs: WorkflowValidationSuccess or CommandErrorResult.
|
|
2885
|
+
*/
|
|
2886
|
+
async function loadAndValidateWorkflowCore(rawInput, effects, options) {
|
|
2887
|
+
const parsed = parseInvocationInput(rawInput);
|
|
2888
|
+
if (!parsed.targetPath) return {
|
|
2889
|
+
kind: "error",
|
|
2890
|
+
text: options.usageText
|
|
2891
|
+
};
|
|
2892
|
+
const loaded = await loadAndParseWorkflow(parsed.targetPath, effects);
|
|
2893
|
+
if ("kind" in loaded) return loaded;
|
|
2894
|
+
const doc = loaded.doc;
|
|
2895
|
+
const hasExplicitArgs = Object.keys(parsed.explicitArgs).length > 0 || parsed.implicitInstructions.length > 0;
|
|
2896
|
+
let resolvedArgs;
|
|
2897
|
+
if (hasExplicitArgs || options.requireArgs) {
|
|
2898
|
+
const argsStep = runValidationStep(() => resolveWorkflowArgs({
|
|
2899
|
+
declarations: doc.args,
|
|
2900
|
+
explicitArgs: parsed.explicitArgs,
|
|
2901
|
+
implicitInstructions: parsed.implicitInstructions
|
|
2902
|
+
}), "Argument error in workflow", parsed.targetPath);
|
|
2903
|
+
if ("kind" in argsStep) return argsStep;
|
|
2904
|
+
resolvedArgs = argsStep.result;
|
|
2905
|
+
}
|
|
2906
|
+
const validationErrors = validateWorkflow({
|
|
2907
|
+
doc,
|
|
2908
|
+
args: resolvedArgs
|
|
2909
|
+
});
|
|
2910
|
+
if (validationErrors.length > 0) return {
|
|
2911
|
+
kind: "error",
|
|
2912
|
+
text: formatValidationErrors(parsed.targetPath, validationErrors)
|
|
2913
|
+
};
|
|
2914
|
+
const subagentError = await validateWorkflowSubagents(doc, effects, parsed.targetPath, resolvedArgs, options.signal);
|
|
2915
|
+
if (subagentError) return {
|
|
2916
|
+
kind: "error",
|
|
2917
|
+
text: subagentError
|
|
2918
|
+
};
|
|
2919
|
+
return {
|
|
2920
|
+
kind: "valid",
|
|
2921
|
+
doc,
|
|
2922
|
+
targetPath: parsed.targetPath,
|
|
2923
|
+
rawInput,
|
|
2924
|
+
resolvedArgs
|
|
2925
|
+
};
|
|
2926
|
+
}
|
|
2927
|
+
/**
|
|
2928
|
+
* Validates a workflow invocation input, reading and parsing the file and arguments.
|
|
2929
|
+
* CONTRACT:
|
|
2930
|
+
* - Input: targetPath string, effects context, optional runId, optional signal.
|
|
2931
|
+
* - Output: Promise resolving to ValidatedWorkflow or error CommandResult.
|
|
2932
|
+
* - Errors: returns error CommandResult if session ID missing, file not found, or syntax invalid.
|
|
2933
|
+
*/
|
|
2934
|
+
async function validateWorkflowInvocation(targetPath, effects, runId, signal) {
|
|
2935
|
+
if (!effects.sessionId) return {
|
|
2936
|
+
kind: "error",
|
|
2937
|
+
text: "Workflow execution failed: agent session ID is required"
|
|
2938
|
+
};
|
|
2939
|
+
const result = await loadAndValidateWorkflowCore(targetPath, effects, {
|
|
2940
|
+
requireArgs: true,
|
|
2941
|
+
usageText: "Usage: /wf <workflow.yaml>",
|
|
2942
|
+
signal
|
|
2943
|
+
});
|
|
2944
|
+
if (result.kind === "error") return result;
|
|
2945
|
+
const invocation = {
|
|
2946
|
+
targetPath: result.targetPath,
|
|
2947
|
+
rawInput: targetPath,
|
|
2948
|
+
resolvedArgs: result.resolvedArgs ?? {},
|
|
2949
|
+
runId: runId ?? crypto.randomUUID()
|
|
2950
|
+
};
|
|
2951
|
+
return {
|
|
2952
|
+
kind: "valid",
|
|
2953
|
+
doc: result.doc,
|
|
2954
|
+
invocation,
|
|
2955
|
+
state: {
|
|
2956
|
+
stepIndex: 0,
|
|
2957
|
+
status: "running"
|
|
2958
|
+
}
|
|
2959
|
+
};
|
|
2960
|
+
}
|
|
2961
|
+
/**
|
|
2962
|
+
* Validates a workflow file and optional invocation arguments without executing it.
|
|
2963
|
+
* CONTRACT:
|
|
2964
|
+
* - Input: rawInput string containing workflow target path and optional arguments, effects context.
|
|
2965
|
+
* - Output: Promise resolving to CommandResult (success with summary or error with diagnostics).
|
|
2966
|
+
* - Invariant: Zero state mutations, zero session events, does not require active session ID or idle workflow runner.
|
|
2967
|
+
*/
|
|
2968
|
+
async function validateWorkflowTarget(rawInput, effects) {
|
|
2969
|
+
const result = await loadAndValidateWorkflowCore(rawInput, effects, {
|
|
2970
|
+
requireArgs: false,
|
|
2971
|
+
usageText: "Usage: /wf-validate <workflow.yaml> [key=value ...]"
|
|
2972
|
+
});
|
|
2973
|
+
if (result.kind === "error") return result;
|
|
2974
|
+
return {
|
|
2975
|
+
kind: "success",
|
|
2976
|
+
text: formatValidationSummary(result.targetPath, result.doc, result.resolvedArgs)
|
|
2977
|
+
};
|
|
2978
|
+
}
|
|
2979
|
+
/**
|
|
2980
|
+
* Executes a pre-validated workflow, emitting initialization events and driving steps.
|
|
2981
|
+
* CONTRACT:
|
|
2982
|
+
* - Input: validated workflow descriptor, effects context, optional signal.
|
|
2983
|
+
* - Output: Promise resolving to CommandResult.
|
|
2984
|
+
*/
|
|
2985
|
+
async function executeValidatedWorkflow(validated, effects, signal) {
|
|
2986
|
+
const activeRun = foldWorkflowState(effects.snapshotEvents());
|
|
2987
|
+
if (activeRun !== null && activeRun.state.status === "running") return {
|
|
2988
|
+
kind: "error",
|
|
2989
|
+
text: `Cannot start workflow: '${activeRun.workflow.name ?? activeRun.invocation.targetPath}' is already running`
|
|
2990
|
+
};
|
|
2991
|
+
return withWorkflowExecution(effects, () => executeValidatedWorkflowDirect(validated, effects, signal));
|
|
2992
|
+
}
|
|
2993
|
+
async function executeValidatedWorkflowDirect(validated, effects, signal) {
|
|
2994
|
+
const { doc, invocation, state } = validated;
|
|
2995
|
+
const runId = invocation.runId;
|
|
2996
|
+
const workflowAbortController = new AbortController();
|
|
2997
|
+
const combinedSignal = signal ? AbortSignal.any([signal, workflowAbortController.signal]) : workflowAbortController.signal;
|
|
2998
|
+
const cleanupAbort = effects.watchAbort(workflowAbortController);
|
|
2999
|
+
const stateRef = { current: state };
|
|
3000
|
+
try {
|
|
3001
|
+
const rawTitle = doc.title ?? doc.name;
|
|
3002
|
+
if (rawTitle && !effects.hasTitle()) {
|
|
3003
|
+
const sessionTitle = interpolateTemplate(rawTitle, invocation.resolvedArgs);
|
|
3004
|
+
if (sessionTitle.trim().length > 0) effects.setTitle(sessionTitle);
|
|
3005
|
+
}
|
|
3006
|
+
effects.emit({
|
|
3007
|
+
action: "init",
|
|
3008
|
+
workflow: doc,
|
|
3009
|
+
invocation,
|
|
3010
|
+
runId
|
|
3011
|
+
});
|
|
3012
|
+
await effects.whenIdle();
|
|
3013
|
+
if (combinedSignal.aborted) return handleTermination(combinedSignal, effects, stateRef.current, stateRef.current.stepIndex, doc.steps[stateRef.current.stepIndex].name, doc.steps.length, runId);
|
|
3014
|
+
effects.setStatus("running");
|
|
3015
|
+
return await runWorkflowSteps({
|
|
3016
|
+
effects,
|
|
3017
|
+
doc,
|
|
3018
|
+
invocation,
|
|
3019
|
+
stateRef,
|
|
3020
|
+
signal: combinedSignal
|
|
3021
|
+
});
|
|
3022
|
+
} catch (err) {
|
|
3023
|
+
return handleWorkflowExecutionError({
|
|
3024
|
+
effects,
|
|
3025
|
+
state: stateRef.current,
|
|
3026
|
+
doc,
|
|
3027
|
+
signal: combinedSignal,
|
|
3028
|
+
err,
|
|
3029
|
+
action: "execution",
|
|
3030
|
+
runId
|
|
3031
|
+
});
|
|
3032
|
+
} finally {
|
|
3033
|
+
cleanupAbort();
|
|
3034
|
+
effects.setStatus("idle");
|
|
3035
|
+
}
|
|
3036
|
+
}
|
|
3037
|
+
/**
|
|
3038
|
+
* Loads and initiates a workflow YAML file, executing steps sequentially.
|
|
3039
|
+
* CONTRACT:
|
|
3040
|
+
* - Input: effects context, targetPath string, and optional signal.
|
|
3041
|
+
* - Output: Promise resolving to CommandResult (success, gate pause, or abort error).
|
|
3042
|
+
* - Errors: returns error CommandResult if session ID missing, file not found, or syntax invalid.
|
|
3043
|
+
*/
|
|
3044
|
+
async function executeWorkflow({ effects, targetPath, signal, runId }) {
|
|
3045
|
+
const validated = await validateWorkflowInvocation(targetPath, effects, runId, signal);
|
|
3046
|
+
if (validated.kind === "error") return validated;
|
|
3047
|
+
return executeValidatedWorkflow(validated, effects, signal);
|
|
3048
|
+
}
|
|
3049
|
+
/**
|
|
3050
|
+
* Resumes an interrupted or gate-paused workflow from session event log.
|
|
3051
|
+
* CONTRACT:
|
|
3052
|
+
* - Inputs: effects context, optional signal, and additional resumption instructions.
|
|
3053
|
+
* - Outputs: Promise resolving to CommandResult (success or error).
|
|
3054
|
+
* - Throws: None (errors returned as CommandResult error objects).
|
|
3055
|
+
*/
|
|
3056
|
+
function resumeWorkflow(options) {
|
|
3057
|
+
return withWorkflowExecution(options.effects, () => resumeWorkflowDirect(options));
|
|
3058
|
+
}
|
|
3059
|
+
/**
|
|
3060
|
+
* Purpose: Acknowledges a valid resume without retaining the submitting UI request.
|
|
3061
|
+
* Contract:
|
|
3062
|
+
* - Inputs: session effects, additional instructions, and the admission request signal.
|
|
3063
|
+
* - Outputs: validation errors or acknowledgement before resumed execution finishes.
|
|
3064
|
+
* - Throws / Errors: unexpected background failures are logged.
|
|
3065
|
+
*/
|
|
3066
|
+
async function requestWorkflowResume(effects, instructions, signal) {
|
|
3067
|
+
if (executingSessions.has(effects.sessionId)) return {
|
|
3068
|
+
kind: "error",
|
|
3069
|
+
text: "A workflow is already executing in this session"
|
|
3070
|
+
};
|
|
3071
|
+
const prepared = await prepareWorkflowResume(effects);
|
|
3072
|
+
if (prepared.kind === "error") return prepared;
|
|
3073
|
+
signal.throwIfAborted();
|
|
3074
|
+
if (executingSessions.has(effects.sessionId)) return {
|
|
3075
|
+
kind: "error",
|
|
3076
|
+
text: "A workflow is already executing in this session"
|
|
3077
|
+
};
|
|
3078
|
+
withWorkflowExecution(effects, () => executeWorkflowResume({
|
|
3079
|
+
effects,
|
|
3080
|
+
instructions,
|
|
3081
|
+
run: prepared.run
|
|
3082
|
+
})).catch((error) => {
|
|
3083
|
+
effects.logInfo(`Workflow resume failed: ${extractErrorMessage(error)}`);
|
|
3084
|
+
});
|
|
3085
|
+
return {
|
|
3086
|
+
kind: "success",
|
|
3087
|
+
text: "Workflow resume accepted"
|
|
3088
|
+
};
|
|
3089
|
+
}
|
|
3090
|
+
async function prepareWorkflowResume(effects) {
|
|
3091
|
+
const sessionError = await ensureIdleSession(effects, "resume");
|
|
3092
|
+
if (sessionError) return sessionError;
|
|
3093
|
+
const run = foldWorkflowState(effects.snapshotEvents());
|
|
3094
|
+
if (!run) return {
|
|
3095
|
+
kind: "error",
|
|
3096
|
+
text: "No interrupted workflow found to resume"
|
|
3097
|
+
};
|
|
3098
|
+
if (run.state.status === "completed") return {
|
|
3099
|
+
kind: "error",
|
|
3100
|
+
text: "Workflow has already completed"
|
|
3101
|
+
};
|
|
3102
|
+
return {
|
|
3103
|
+
kind: "ready",
|
|
3104
|
+
run
|
|
3105
|
+
};
|
|
3106
|
+
}
|
|
3107
|
+
async function resumeWorkflowDirect(options) {
|
|
3108
|
+
const prepared = await prepareWorkflowResume(options.effects);
|
|
3109
|
+
if (prepared.kind === "error") return prepared;
|
|
3110
|
+
return executeWorkflowResume({
|
|
3111
|
+
...options,
|
|
3112
|
+
run: prepared.run
|
|
3113
|
+
});
|
|
3114
|
+
}
|
|
3115
|
+
async function executeWorkflowResume({ effects, signal, instructions, run }) {
|
|
3116
|
+
const { workflow: doc, invocation, state } = run;
|
|
3117
|
+
const isInterruptedPause = state.status === "paused" && state.pauseReason === "interrupted";
|
|
3118
|
+
const nextStepIndex = state.status === "paused" && !isInterruptedPause ? state.stepIndex + 1 : state.stepIndex;
|
|
3119
|
+
const workflowAbortController = new AbortController();
|
|
3120
|
+
const combinedSignal = signal ? AbortSignal.any([signal, workflowAbortController.signal]) : workflowAbortController.signal;
|
|
3121
|
+
const cleanupAbort = effects.watchAbort(workflowAbortController);
|
|
3122
|
+
const { error: _error, ...cleanState } = state;
|
|
3123
|
+
const stateRef = { current: {
|
|
3124
|
+
...cleanState,
|
|
3125
|
+
stepIndex: nextStepIndex
|
|
3126
|
+
} };
|
|
3127
|
+
try {
|
|
3128
|
+
if (nextStepIndex >= doc.steps.length) return completeWorkflow(effects, doc.steps.length, state.outputs, invocation.runId);
|
|
3129
|
+
if (combinedSignal.aborted) return handleTermination(combinedSignal, effects, stateRef.current, nextStepIndex, doc.steps[nextStepIndex].name, doc.steps.length, invocation.runId);
|
|
3130
|
+
const { pauseReason: _pauseReason, ...runningState } = cleanState;
|
|
3131
|
+
effects.emit({
|
|
3132
|
+
action: "state",
|
|
3133
|
+
...runningState,
|
|
3134
|
+
stepIndex: nextStepIndex,
|
|
3135
|
+
status: "running",
|
|
3136
|
+
runId: invocation.runId
|
|
3137
|
+
});
|
|
3138
|
+
effects.logInfo(`Resuming workflow '${doc.name ?? invocation.targetPath}' at step ${nextStepIndex + 1}/${doc.steps.length}${instructions ? ` with instructions: ${instructions}` : ""}`);
|
|
3139
|
+
effects.setStatus("running");
|
|
3140
|
+
return await runWorkflowSteps({
|
|
3141
|
+
effects,
|
|
3142
|
+
doc,
|
|
3143
|
+
invocation,
|
|
3144
|
+
stateRef,
|
|
3145
|
+
signal: combinedSignal,
|
|
3146
|
+
instructions: instructions ? instructions.trim() : void 0
|
|
3147
|
+
});
|
|
3148
|
+
} catch (err) {
|
|
3149
|
+
return handleWorkflowExecutionError({
|
|
3150
|
+
effects,
|
|
3151
|
+
state: stateRef.current,
|
|
3152
|
+
doc,
|
|
3153
|
+
signal: combinedSignal,
|
|
3154
|
+
err,
|
|
3155
|
+
action: "resume",
|
|
3156
|
+
runId: invocation.runId
|
|
3157
|
+
});
|
|
3158
|
+
} finally {
|
|
3159
|
+
cleanupAbort();
|
|
3160
|
+
effects.setStatus("idle");
|
|
3161
|
+
}
|
|
3162
|
+
}
|
|
3163
|
+
/**
|
|
3164
|
+
* Purpose: Discards an active, paused, or interrupted workflow, marking it aborted.
|
|
3165
|
+
* Contract:
|
|
3166
|
+
* - Inputs: effects context for the target session.
|
|
3167
|
+
* - Outputs: Promise resolving to CommandResult (success or error).
|
|
3168
|
+
* - Throws: None.
|
|
3169
|
+
*/
|
|
3170
|
+
function discardWorkflow(options) {
|
|
3171
|
+
return withWorkflowExecution(options.effects, () => discardWorkflowDirect(options));
|
|
3172
|
+
}
|
|
3173
|
+
async function discardWorkflowDirect({ effects }) {
|
|
3174
|
+
const sessionError = await ensureIdleSession(effects, "discard");
|
|
3175
|
+
if (sessionError) return sessionError;
|
|
3176
|
+
const run = foldWorkflowState(effects.snapshotEvents());
|
|
3177
|
+
if (!run) return {
|
|
3178
|
+
kind: "error",
|
|
3179
|
+
text: "No active workflow to discard"
|
|
3180
|
+
};
|
|
3181
|
+
if (run.state.status === "running") return {
|
|
3182
|
+
kind: "error",
|
|
3183
|
+
text: "Cannot discard an actively running workflow; stop execution first"
|
|
3184
|
+
};
|
|
3185
|
+
if (run.state.status === "completed" || run.state.status === "aborted") return {
|
|
3186
|
+
kind: "error",
|
|
3187
|
+
text: "Workflow is not active or has already ended"
|
|
3188
|
+
};
|
|
3189
|
+
const { workflow: doc, state, invocation } = run;
|
|
3190
|
+
const runId = invocation.runId;
|
|
3191
|
+
const stepName = `: ${doc.steps[state.stepIndex].name}`;
|
|
3192
|
+
const transition = applyAbort(state, doc.steps.length, false);
|
|
3193
|
+
effects.emit({
|
|
3194
|
+
action: "state",
|
|
3195
|
+
...transition.nextState,
|
|
3196
|
+
runId
|
|
3197
|
+
});
|
|
3198
|
+
effects.emit({
|
|
3199
|
+
action: "step",
|
|
3200
|
+
id: `wf-step-${runId}-${state.stepIndex}-discarded`,
|
|
3201
|
+
stepIndex: state.stepIndex,
|
|
3202
|
+
label: `Workflow discarded at step ${state.stepIndex + 1} of ${doc.steps.length}${stepName}`,
|
|
3203
|
+
kind: "error",
|
|
3204
|
+
runId
|
|
3205
|
+
});
|
|
3206
|
+
effects.logInfo(`Workflow '${doc.name ?? run.invocation.targetPath}' discarded by user at step ${state.stepIndex + 1}/${doc.steps.length}`);
|
|
3207
|
+
return {
|
|
3208
|
+
kind: "success",
|
|
3209
|
+
text: `Workflow discarded at step ${state.stepIndex + 1}/${doc.steps.length}`
|
|
3210
|
+
};
|
|
3211
|
+
}
|
|
3212
|
+
/**
|
|
3213
|
+
* Purpose: Lists and summarizes available workflows in local and common directories.
|
|
3214
|
+
* Contract:
|
|
3215
|
+
* - Inputs: WorkflowEffectContext instance.
|
|
3216
|
+
* - Outputs: Promise resolving to CommandResult ({ kind: "success", text: string }).
|
|
3217
|
+
* - Throws: None (errors handled gracefully).
|
|
3218
|
+
*/
|
|
3219
|
+
async function listWorkflows(effects) {
|
|
3220
|
+
const [localFiles, commonFiles] = await Promise.all([effects.listWorkflowFiles("local"), effects.listWorkflowFiles("common")]);
|
|
3221
|
+
const parseSummaries = (files) => {
|
|
3222
|
+
const summaries = [];
|
|
3223
|
+
for (const file of files) {
|
|
3224
|
+
const summary = parseWorkflowSummary(file.target, file.content);
|
|
3225
|
+
if (summary) summaries.push(summary);
|
|
3226
|
+
}
|
|
3227
|
+
return summaries;
|
|
3228
|
+
};
|
|
3229
|
+
const localSummaries = parseSummaries(localFiles);
|
|
3230
|
+
const commonSummaries = parseSummaries(commonFiles);
|
|
3231
|
+
return {
|
|
3232
|
+
kind: "success",
|
|
3233
|
+
text: formatWorkflowList([{
|
|
3234
|
+
title: "Local Workflows (.agents/wf)",
|
|
3235
|
+
workflows: localSummaries
|
|
3236
|
+
}, {
|
|
3237
|
+
title: "Common Workflows (~/.agents/wf)",
|
|
3238
|
+
workflows: commonSummaries
|
|
3239
|
+
}])
|
|
3240
|
+
};
|
|
3241
|
+
}
|
|
3242
|
+
// src/index.ts
|
|
3243
|
+
const name = "dsh-workflow-runner";
|
|
3244
|
+
const inject = [
|
|
3245
|
+
"commands",
|
|
3246
|
+
"sessionProjections",
|
|
3247
|
+
"subagents",
|
|
3248
|
+
"tools",
|
|
3249
|
+
"skills"
|
|
3250
|
+
];
|
|
3251
|
+
/**
|
|
3252
|
+
* Registers /wf and /wf-resume slash commands with Cordis commands service.
|
|
3253
|
+
* CONTRACT:
|
|
3254
|
+
* - Input: Cordis Context instance with injected 'commands' service.
|
|
3255
|
+
* - Output: Promise<void> (registers projection, commands, and tools in context).
|
|
3256
|
+
*/
|
|
3257
|
+
async function apply(ctx) {
|
|
3258
|
+
const log = ctx.logger("dsh-workflow-runner");
|
|
3259
|
+
const sessionEffects = /* @__PURE__ */ new WeakMap();
|
|
3260
|
+
ctx.on("session/event", (session, event) => {
|
|
3261
|
+
if (event.type !== "command/done") return;
|
|
3262
|
+
const effects = sessionEffects.get(session);
|
|
3263
|
+
if (effects !== void 0) startPendingWorkflows(effects);
|
|
3264
|
+
});
|
|
3265
|
+
const projectionHandle = await ctx.sessionProjections.register({
|
|
3266
|
+
key: "workflow",
|
|
3267
|
+
stateSchema: workflowRunSummarySchema,
|
|
3268
|
+
init: () => initialWorkflowRunSummary(),
|
|
3269
|
+
apply: (state, event) => foldWorkflowEvent(state, event),
|
|
3270
|
+
wire: {
|
|
3271
|
+
viewSchema: workflowRunSummarySchema.nullable(),
|
|
3272
|
+
view: toWorkflowRunSummaryRecord
|
|
3273
|
+
},
|
|
3274
|
+
stateVersion: 1
|
|
3275
|
+
});
|
|
3276
|
+
ctx.effect(() => () => projectionHandle.dispose());
|
|
3277
|
+
ctx.effect(() => ctx.skills.register({
|
|
3278
|
+
name: WORKFLOW_SKILL_NAME,
|
|
3279
|
+
description: WORKFLOW_SKILL_DESCRIPTION,
|
|
3280
|
+
source: "runtime",
|
|
3281
|
+
content: WORKFLOW_SKILL_CONTENT
|
|
3282
|
+
}));
|
|
3283
|
+
ctx.tools.register(defineTool({
|
|
3284
|
+
name: "save_output",
|
|
3285
|
+
description: "Save a named workflow output value for the current workflow step.",
|
|
3286
|
+
parameters: {
|
|
3287
|
+
name: {
|
|
3288
|
+
type: "string",
|
|
3289
|
+
required: true,
|
|
3290
|
+
description: "The name of the output declared in the workflow step."
|
|
3291
|
+
},
|
|
3292
|
+
value: {
|
|
3293
|
+
type: "string",
|
|
3294
|
+
required: true,
|
|
3295
|
+
description: "The string value to save as the step output."
|
|
3296
|
+
}
|
|
3297
|
+
},
|
|
3298
|
+
output: {
|
|
3299
|
+
schema: {
|
|
3300
|
+
type: "object",
|
|
3301
|
+
properties: {
|
|
3302
|
+
success: {
|
|
3303
|
+
type: "boolean",
|
|
3304
|
+
required: true
|
|
3305
|
+
},
|
|
3306
|
+
message: {
|
|
3307
|
+
type: "string",
|
|
3308
|
+
required: true
|
|
3309
|
+
}
|
|
3310
|
+
},
|
|
3311
|
+
additionalProperties: false
|
|
3312
|
+
},
|
|
3313
|
+
render(_args, val) {
|
|
3314
|
+
return [{
|
|
3315
|
+
type: "text",
|
|
3316
|
+
text: val.message
|
|
3317
|
+
}];
|
|
3318
|
+
}
|
|
3319
|
+
},
|
|
3320
|
+
async execute(args, exec) {
|
|
3321
|
+
const agent = exec.agent;
|
|
3322
|
+
if (!agent) return {
|
|
3323
|
+
success: false,
|
|
3324
|
+
message: "No active agent session"
|
|
3325
|
+
};
|
|
3326
|
+
const run = foldWorkflowState(agent.session.snapshotEvents());
|
|
3327
|
+
if (!run) return {
|
|
3328
|
+
success: false,
|
|
3329
|
+
message: "No active workflow run found"
|
|
3330
|
+
};
|
|
3331
|
+
if (run.state.status !== "running") return {
|
|
3332
|
+
success: false,
|
|
3333
|
+
message: "Workflow is not currently running"
|
|
3334
|
+
};
|
|
3335
|
+
const currentStepIndex = run.state.stepIndex;
|
|
3336
|
+
const step = run.workflow.steps[currentStepIndex];
|
|
3337
|
+
if (!step || step.kind === "print" || !step.outputs) return {
|
|
3338
|
+
success: false,
|
|
3339
|
+
message: `Current step ${currentStepIndex + 1} does not declare any outputs`
|
|
3340
|
+
};
|
|
3341
|
+
const targetOutput = step.outputs[args.name];
|
|
3342
|
+
if (!targetOutput || targetOutput.type !== "string" && targetOutput.type !== "list") return {
|
|
3343
|
+
success: false,
|
|
3344
|
+
message: `Current step does not declare a string or list output named '${args.name}'`
|
|
3345
|
+
};
|
|
3346
|
+
let serializedValue = args.value;
|
|
3347
|
+
if (targetOutput.type === "list") {
|
|
3348
|
+
const parsed = parseListOutput(args.name, args.value, targetOutput);
|
|
3349
|
+
if (parsed.kind === "error") return {
|
|
3350
|
+
success: false,
|
|
3351
|
+
message: parsed.message
|
|
3352
|
+
};
|
|
3353
|
+
serializedValue = JSON.stringify(parsed.value);
|
|
3354
|
+
}
|
|
3355
|
+
new DshWorkflowEffectContext({
|
|
3356
|
+
ctx,
|
|
3357
|
+
agent,
|
|
3358
|
+
log
|
|
3359
|
+
}).recordOutput(currentStepIndex, args.name, serializedValue, targetOutput.type, void 0, run.invocation.runId);
|
|
3360
|
+
return {
|
|
3361
|
+
success: true,
|
|
3362
|
+
message: `Successfully saved output '${args.name}'`
|
|
3363
|
+
};
|
|
3364
|
+
}
|
|
3365
|
+
}), { when: ({ agent }) => projectionHandle.stateOf(agent.session).status === "running" });
|
|
3366
|
+
ctx.tools.register(defineTool({
|
|
3367
|
+
name: "wf_validate",
|
|
3368
|
+
description: "Validate a workflow YAML file and optional arguments without executing it.",
|
|
3369
|
+
parameters: {
|
|
3370
|
+
target: {
|
|
3371
|
+
type: "string",
|
|
3372
|
+
required: true,
|
|
3373
|
+
description: "Path or identifier of the workflow YAML file (e.g. 'deploy.yaml' or '.agents/wf/build.yaml')."
|
|
3374
|
+
},
|
|
3375
|
+
args: {
|
|
3376
|
+
type: "string",
|
|
3377
|
+
description: "Optional key=value arguments or trailing instructions (e.g. 'env=production version=1.0')."
|
|
3378
|
+
}
|
|
3379
|
+
},
|
|
3380
|
+
output: {
|
|
3381
|
+
schema: {
|
|
3382
|
+
type: "object",
|
|
3383
|
+
properties: {
|
|
3384
|
+
success: {
|
|
3385
|
+
type: "boolean",
|
|
3386
|
+
required: true
|
|
3387
|
+
},
|
|
3388
|
+
message: {
|
|
3389
|
+
type: "string",
|
|
3390
|
+
required: true
|
|
3391
|
+
}
|
|
3392
|
+
},
|
|
3393
|
+
additionalProperties: false
|
|
3394
|
+
},
|
|
3395
|
+
render(_args, val) {
|
|
3396
|
+
return [{
|
|
3397
|
+
type: "text",
|
|
3398
|
+
text: val.message
|
|
3399
|
+
}];
|
|
3400
|
+
}
|
|
3401
|
+
},
|
|
3402
|
+
async execute(args, exec) {
|
|
3403
|
+
const agent = exec.agent;
|
|
3404
|
+
if (!agent) return {
|
|
3405
|
+
success: false,
|
|
3406
|
+
message: "No active agent session"
|
|
3407
|
+
};
|
|
3408
|
+
const target = args.target.trim();
|
|
3409
|
+
if (target.length === 0) return {
|
|
3410
|
+
success: false,
|
|
3411
|
+
message: "Target workflow path is required"
|
|
3412
|
+
};
|
|
3413
|
+
const safeTarget = target.includes(" ") && !target.startsWith("\"") && !target.startsWith("'") ? `"${target}"` : target;
|
|
3414
|
+
const effects = new DshWorkflowEffectContext({
|
|
3415
|
+
ctx,
|
|
3416
|
+
agent,
|
|
3417
|
+
log
|
|
3418
|
+
});
|
|
3419
|
+
const result = await validateWorkflowTarget(typeof args.args === "string" && args.args.trim().length > 0 ? `${safeTarget} ${args.args}` : safeTarget, effects);
|
|
3420
|
+
if (result.kind === "error") return {
|
|
3421
|
+
success: false,
|
|
3422
|
+
message: result.text
|
|
3423
|
+
};
|
|
3424
|
+
return {
|
|
3425
|
+
success: true,
|
|
3426
|
+
message: result.text ?? ""
|
|
3427
|
+
};
|
|
3428
|
+
}
|
|
3429
|
+
}), { when: ({ agent }) => {
|
|
3430
|
+
const summary = projectionHandle.stateOf(agent.session);
|
|
3431
|
+
return summary.status !== "idle" || summary.skillInvoked;
|
|
3432
|
+
} });
|
|
3433
|
+
ctx.commands.register({
|
|
3434
|
+
name: "wf",
|
|
3435
|
+
description: "Execute prompt workflow from YAML",
|
|
3436
|
+
input: { hint: "<workflow.yaml>" },
|
|
3437
|
+
handler: async (invocation) => {
|
|
3438
|
+
const effects = new DshWorkflowEffectContext({
|
|
3439
|
+
ctx,
|
|
3440
|
+
agent: invocation.agent,
|
|
3441
|
+
log
|
|
3442
|
+
});
|
|
3443
|
+
sessionEffects.set(invocation.agent.session, effects);
|
|
3444
|
+
return requestWorkflow(invocation.rawInput, effects, invocation.commandId);
|
|
3445
|
+
}
|
|
3446
|
+
});
|
|
3447
|
+
ctx.commands.register({
|
|
3448
|
+
name: "wf-resume",
|
|
3449
|
+
description: "Resume an interrupted workflow",
|
|
3450
|
+
input: { hint: "[instructions]" },
|
|
3451
|
+
handler: (invocation) => {
|
|
3452
|
+
return requestWorkflowResume(new DshWorkflowEffectContext({
|
|
3453
|
+
ctx,
|
|
3454
|
+
agent: invocation.agent,
|
|
3455
|
+
log
|
|
3456
|
+
}), invocation.rawInput, invocation.signal);
|
|
3457
|
+
}
|
|
3458
|
+
});
|
|
3459
|
+
ctx.commands.register({
|
|
3460
|
+
name: "wf-abort",
|
|
3461
|
+
description: "Discard the active workflow",
|
|
3462
|
+
handler: (invocation) => {
|
|
3463
|
+
return discardWorkflow({ effects: new DshWorkflowEffectContext({
|
|
3464
|
+
ctx,
|
|
3465
|
+
agent: invocation.agent,
|
|
3466
|
+
log
|
|
3467
|
+
}) });
|
|
3468
|
+
}
|
|
3469
|
+
});
|
|
3470
|
+
ctx.commands.register({
|
|
3471
|
+
name: "wf-list",
|
|
3472
|
+
description: "List workflows in common and local directories",
|
|
3473
|
+
handler: (invocation) => {
|
|
3474
|
+
return listWorkflows(new DshWorkflowEffectContext({
|
|
3475
|
+
ctx,
|
|
3476
|
+
agent: invocation.agent,
|
|
3477
|
+
log
|
|
3478
|
+
}));
|
|
3479
|
+
}
|
|
3480
|
+
});
|
|
3481
|
+
ctx.commands.register({
|
|
3482
|
+
name: "wf-validate",
|
|
3483
|
+
description: "Validate workflow YAML and arguments without execution",
|
|
3484
|
+
input: { hint: "<workflow.yaml> [key=value ...]" },
|
|
3485
|
+
handler: (invocation) => {
|
|
3486
|
+
const effects = new DshWorkflowEffectContext({
|
|
3487
|
+
ctx,
|
|
3488
|
+
agent: invocation.agent,
|
|
3489
|
+
log
|
|
3490
|
+
});
|
|
3491
|
+
return validateWorkflowTarget(invocation.rawInput, effects);
|
|
3492
|
+
}
|
|
3493
|
+
});
|
|
3494
|
+
}
|
|
3495
|
+
export { FileOutputBaseSchema, StepOutputDefSchema, StepOutputsMapSchema, SubagentConfigSchema, WORKFLOW_EVENT_NAME, WORKFLOW_RULES, WORKFLOW_SKILL_CONTENT, WORKFLOW_SKILL_DESCRIPTION, WORKFLOW_SKILL_NAME, WorkflowArgSchema, WorkflowFileSchema, WorkflowFileStepSchema, WorkflowStateSchema, WorkflowStatusSchema, apply, applyAbort, applyGatePause, applyStepPause, computeStepTransition, discardWorkflow, executeValidatedWorkflow, executeWorkflow, foldWorkflowState, formatOutputRetryPrompt, formatStepPrompt, formatValidationErrors, formatValidationSummary, formatWorkflowList, formatWorkflowParamDescriptor, inject, interpolateTemplate, isFlatChoiceMapping, listWorkflows, name, parseBoolean, parseInvocationInput, parseSubagentShorthand, parseWorkflowDocument, parseWorkflowFile, parseWorkflowSummary, preprocessWorkflow, resolveGate, resolveWorkflowArgs, resumeWorkflow, ruleDuplicateOutputNames, ruleStepOutputReferences, ruleSubagentDependencies, ruleSubagentOutputRequired, ruleTemplateArgs, ruleUnusedOutputs, ruleWorkflowNameOutputReferences, validateWorkflow, validateWorkflowInvocation, validateWorkflowTarget };
|