@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/src/parser.ts
ADDED
|
@@ -0,0 +1,1146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PURPOSE: Pure parsing, argument resolution, templating, and prompt formatting utilities.
|
|
3
|
+
* ALLOWED: Pure computation, string manipulation, YAML parsing, schema validation.
|
|
4
|
+
* FORBIDDEN: No I/O, no filesystem, no runtime state, no agent orchestration.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { parse } from "yaml";
|
|
8
|
+
import { interpolateTemplate, parseBoolean } from "./boolean.ts";
|
|
9
|
+
|
|
10
|
+
export {
|
|
11
|
+
interpolateTemplate,
|
|
12
|
+
parseBoolean,
|
|
13
|
+
resolveGate,
|
|
14
|
+
} from "./boolean.ts";
|
|
15
|
+
|
|
16
|
+
import {
|
|
17
|
+
type ChoiceMapping,
|
|
18
|
+
type FormatStepPromptOptions,
|
|
19
|
+
type FormatStepPromptOutputRequirement,
|
|
20
|
+
type JsonSchemaNode,
|
|
21
|
+
type ObjectJsonSchema,
|
|
22
|
+
type ParsedInvocation,
|
|
23
|
+
type StepOutputDef,
|
|
24
|
+
type StepOutputsMap,
|
|
25
|
+
type SubagentConfig,
|
|
26
|
+
type WorkflowArg,
|
|
27
|
+
type WorkflowDocument,
|
|
28
|
+
type WorkflowFile,
|
|
29
|
+
WorkflowFileSchema,
|
|
30
|
+
type WorkflowGroup,
|
|
31
|
+
type WorkflowParamSummary,
|
|
32
|
+
type WorkflowStep,
|
|
33
|
+
type WorkflowStepOutputsMap,
|
|
34
|
+
type WorkflowSummary,
|
|
35
|
+
} from "./types.ts";
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Purpose: Parses raw YAML text into a validated WorkflowFile.
|
|
39
|
+
* CONTRACT:
|
|
40
|
+
* - Input: raw YAML string content.
|
|
41
|
+
* - Output: validated WorkflowFile representing valid file format.
|
|
42
|
+
* - Throws: Error when YAML parsing fails or file violates WorkflowFileSchema.
|
|
43
|
+
*/
|
|
44
|
+
export function parseWorkflowFile(content: string): WorkflowFile {
|
|
45
|
+
const raw = parse(content);
|
|
46
|
+
const result = WorkflowFileSchema.safeParse(raw);
|
|
47
|
+
if (!result.success) {
|
|
48
|
+
const reasons = result.error.issues
|
|
49
|
+
.map((issue) => `${issue.path.join(".") || "root"}: ${issue.message}`)
|
|
50
|
+
.join("; ");
|
|
51
|
+
throw new Error(`Invalid workflow schema: ${reasons}`);
|
|
52
|
+
}
|
|
53
|
+
return result.data;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Reserved model value: the child keeps the parent's provider and model. */
|
|
57
|
+
const INHERIT_MODEL = "inherit";
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Purpose: Parses concise model/subagent shorthand string [@preset/][llmProvider/]model[:thinking] or :thinking into SubagentConfig.
|
|
61
|
+
* Contract:
|
|
62
|
+
* - Inputs: Non-empty shorthand string.
|
|
63
|
+
* - Outputs: SubagentConfig with parsed preset, llmProvider, model, and thinking fields.
|
|
64
|
+
* - Throws: Error if format contains empty segments, runner prefixes, or invalid syntax.
|
|
65
|
+
*/
|
|
66
|
+
export function parseSubagentShorthand(shorthand: string): SubagentConfig {
|
|
67
|
+
const trimmed = shorthand.trim();
|
|
68
|
+
if (!trimmed) {
|
|
69
|
+
throw new Error("Subagent shorthand cannot be empty");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (trimmed.includes("+")) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
"Invalid thinking delimiter '+'; use ':thinking' instead (e.g. ':high' or 'model:high')",
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (
|
|
79
|
+
trimmed === "fork" ||
|
|
80
|
+
trimmed === "spawn" ||
|
|
81
|
+
trimmed.startsWith("fork:") ||
|
|
82
|
+
trimmed.startsWith("spawn:")
|
|
83
|
+
) {
|
|
84
|
+
throw new Error(
|
|
85
|
+
"Runner/provider is not supported in model shorthand; configure runner on step definition",
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (trimmed.includes("::")) {
|
|
90
|
+
throw new Error("Subagent shorthand cannot contain consecutive colons");
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (trimmed.includes("//")) {
|
|
94
|
+
throw new Error("Subagent shorthand cannot contain consecutive slashes");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const validateThinking = (thinking: string): void => {
|
|
98
|
+
if (!thinking) {
|
|
99
|
+
throw new Error("Subagent shorthand thinking after ':' cannot be empty");
|
|
100
|
+
}
|
|
101
|
+
if (
|
|
102
|
+
thinking.includes(":") ||
|
|
103
|
+
thinking.includes("/") ||
|
|
104
|
+
thinking.includes("@")
|
|
105
|
+
) {
|
|
106
|
+
throw new Error(
|
|
107
|
+
`Invalid thinking value '${thinking}': cannot contain ':', '/', or '@'`,
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
// Standalone thinking (:thinking)
|
|
113
|
+
if (trimmed.startsWith(":")) {
|
|
114
|
+
const thinking = trimmed.slice(1).trim();
|
|
115
|
+
validateThinking(thinking);
|
|
116
|
+
return { thinking };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
let remaining = trimmed;
|
|
120
|
+
let thinking: string | undefined;
|
|
121
|
+
|
|
122
|
+
const colonIdx = remaining.lastIndexOf(":");
|
|
123
|
+
if (colonIdx !== -1) {
|
|
124
|
+
thinking = remaining.slice(colonIdx + 1).trim();
|
|
125
|
+
validateThinking(thinking);
|
|
126
|
+
remaining = remaining.slice(0, colonIdx).trim();
|
|
127
|
+
if (remaining.includes(":")) {
|
|
128
|
+
throw new Error("Subagent shorthand cannot contain multiple colons");
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
let preset: string | undefined;
|
|
133
|
+
if (remaining.startsWith("@")) {
|
|
134
|
+
const firstSlashIdx = remaining.indexOf("/");
|
|
135
|
+
if (firstSlashIdx === -1) {
|
|
136
|
+
const presetName = remaining.slice(1).trim();
|
|
137
|
+
if (!presetName) {
|
|
138
|
+
throw new Error("Preset name after '@' cannot be empty");
|
|
139
|
+
}
|
|
140
|
+
throw new Error(
|
|
141
|
+
`Preset '@${presetName}' requires an explicit model (e.g. '@${presetName}/model')`,
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
preset = remaining.slice(1, firstSlashIdx).trim();
|
|
145
|
+
if (!preset) {
|
|
146
|
+
throw new Error("Preset name after '@' cannot be empty");
|
|
147
|
+
}
|
|
148
|
+
remaining = remaining.slice(firstSlashIdx + 1).trim();
|
|
149
|
+
if (!remaining) {
|
|
150
|
+
throw new Error(`Model name after preset '@${preset}/' cannot be empty`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
let llmProvider: string | undefined;
|
|
155
|
+
let model: string | undefined;
|
|
156
|
+
|
|
157
|
+
if (remaining.includes("/")) {
|
|
158
|
+
const slashIdx = remaining.indexOf("/");
|
|
159
|
+
llmProvider = remaining.slice(0, slashIdx).trim();
|
|
160
|
+
if (!llmProvider) {
|
|
161
|
+
throw new Error(
|
|
162
|
+
"Subagent shorthand LLM provider before '/' cannot be empty",
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
const rest = remaining.slice(slashIdx + 1).trim();
|
|
166
|
+
if (!rest) {
|
|
167
|
+
throw new Error("Model name after provider cannot be empty");
|
|
168
|
+
}
|
|
169
|
+
if (rest.includes("/")) {
|
|
170
|
+
throw new Error("Subagent shorthand model path has too many segments");
|
|
171
|
+
}
|
|
172
|
+
model = rest;
|
|
173
|
+
} else {
|
|
174
|
+
model = remaining;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (!model) {
|
|
178
|
+
throw new Error("Model name cannot be empty");
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return {
|
|
182
|
+
...(preset ? { preset } : {}),
|
|
183
|
+
...(llmProvider ? { llmProvider } : {}),
|
|
184
|
+
model,
|
|
185
|
+
...(thinking ? { thinking } : {}),
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Purpose: Normalizes a partial subagent configuration or shorthand result into a full SubagentConfig.
|
|
191
|
+
* CONTRACT:
|
|
192
|
+
* - Input: SubagentConfig | undefined
|
|
193
|
+
* - Output: SubagentConfig with guaranteed provider (defaulting to "spawn"); the `inherit` model sentinel resolves to no model
|
|
194
|
+
*/
|
|
195
|
+
export function normalizeSubagentConfig(
|
|
196
|
+
config: SubagentConfig | undefined,
|
|
197
|
+
): SubagentConfig {
|
|
198
|
+
const model = config?.model === INHERIT_MODEL ? undefined : config?.model;
|
|
199
|
+
return {
|
|
200
|
+
provider: config?.provider ?? "spawn",
|
|
201
|
+
...(config?.llmProvider ? { llmProvider: config.llmProvider } : {}),
|
|
202
|
+
...(config?.preset ? { preset: config.preset } : {}),
|
|
203
|
+
...(model ? { model } : {}),
|
|
204
|
+
...(config?.thinking ? { thinking: config.thinking } : {}),
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Purpose: Interpolates template variables in SubagentConfig fields.
|
|
210
|
+
* CONTRACT:
|
|
211
|
+
* - Inputs: SubagentConfig, optional args record, optional outputs map.
|
|
212
|
+
* - Outputs: New SubagentConfig with string fields interpolated; an interpolated `inherit` model sentinel resolves to no model.
|
|
213
|
+
*/
|
|
214
|
+
export function interpolateSubagentConfig(
|
|
215
|
+
config: SubagentConfig,
|
|
216
|
+
args?: Record<string, string>,
|
|
217
|
+
outputs?: Record<string, string | readonly string[]>,
|
|
218
|
+
): SubagentConfig {
|
|
219
|
+
const resolvedArgs = args ?? {};
|
|
220
|
+
const model = config.model
|
|
221
|
+
? interpolateTemplate(config.model, resolvedArgs, outputs)
|
|
222
|
+
: undefined;
|
|
223
|
+
return {
|
|
224
|
+
...(config.provider
|
|
225
|
+
? {
|
|
226
|
+
provider: interpolateTemplate(config.provider, resolvedArgs, outputs),
|
|
227
|
+
}
|
|
228
|
+
: {}),
|
|
229
|
+
...(config.llmProvider
|
|
230
|
+
? {
|
|
231
|
+
llmProvider: interpolateTemplate(
|
|
232
|
+
config.llmProvider,
|
|
233
|
+
resolvedArgs,
|
|
234
|
+
outputs,
|
|
235
|
+
),
|
|
236
|
+
}
|
|
237
|
+
: {}),
|
|
238
|
+
...(config.preset
|
|
239
|
+
? {
|
|
240
|
+
preset: interpolateTemplate(config.preset, resolvedArgs, outputs),
|
|
241
|
+
}
|
|
242
|
+
: {}),
|
|
243
|
+
...(model && model !== INHERIT_MODEL ? { model } : {}),
|
|
244
|
+
...(config.thinking
|
|
245
|
+
? {
|
|
246
|
+
thinking: interpolateTemplate(config.thinking, resolvedArgs, outputs),
|
|
247
|
+
}
|
|
248
|
+
: {}),
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function normalizeStepOutputs(
|
|
253
|
+
outputs: StepOutputsMap | undefined,
|
|
254
|
+
): WorkflowStepOutputsMap | undefined {
|
|
255
|
+
if (!outputs) return undefined;
|
|
256
|
+
return Object.fromEntries(
|
|
257
|
+
Object.entries(outputs).map(([name, def]) => [
|
|
258
|
+
name,
|
|
259
|
+
def.type === "file"
|
|
260
|
+
? { type: "file", path: def.path, base: def.base ?? "scratch" }
|
|
261
|
+
: def,
|
|
262
|
+
]),
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Purpose: Determines whether a ChoiceMapping is flat (direct choice-to-value) or nested (derived variable-to-choices).
|
|
268
|
+
* CONTRACT:
|
|
269
|
+
* - Inputs: ChoiceMapping object.
|
|
270
|
+
* - Outputs: boolean true if flat, false if nested.
|
|
271
|
+
*/
|
|
272
|
+
export function isFlatChoiceMapping(
|
|
273
|
+
mapping: ChoiceMapping,
|
|
274
|
+
): mapping is Record<string, string> {
|
|
275
|
+
// edge case: external YAML choice mapping is untagged; distinguished at boundary by inspecting value type
|
|
276
|
+
const values = Object.values(mapping);
|
|
277
|
+
if (values.length === 0) return false;
|
|
278
|
+
return typeof values[0] === "string";
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Purpose: Preprocesses a validated WorkflowFile into an internal runtime WorkflowDocument.
|
|
283
|
+
* CONTRACT:
|
|
284
|
+
* - Input: validated WorkflowFile.
|
|
285
|
+
* - Output: preprocessed WorkflowDocument where every step has a guaranteed name.
|
|
286
|
+
* - Invariant: Assigns "Step N" (1-indexed) to any step without an explicit name.
|
|
287
|
+
*/
|
|
288
|
+
export function preprocessWorkflow(file: WorkflowFile): WorkflowDocument {
|
|
289
|
+
const normalizedArgs: Record<string, WorkflowArg> = Object.fromEntries(
|
|
290
|
+
Object.entries(file.args ?? {}).map(([key, def]) => {
|
|
291
|
+
const normalizedDefault =
|
|
292
|
+
def.default !== undefined
|
|
293
|
+
? def.type === "bool"
|
|
294
|
+
? String(parseBoolean(def.default))
|
|
295
|
+
: String(def.default)
|
|
296
|
+
: undefined;
|
|
297
|
+
if (def.type === "choice") {
|
|
298
|
+
const { mappings, ...rest } = def;
|
|
299
|
+
const normalizedMapping = def.mapping ?? mappings;
|
|
300
|
+
return [
|
|
301
|
+
key,
|
|
302
|
+
// type-safe: rest retains choice variant properties and normalizedMapping preserves ChoiceMapping union
|
|
303
|
+
{
|
|
304
|
+
...rest,
|
|
305
|
+
...(normalizedMapping !== undefined
|
|
306
|
+
? { mapping: normalizedMapping }
|
|
307
|
+
: {}),
|
|
308
|
+
default: normalizedDefault,
|
|
309
|
+
required: def.required ?? def.default === undefined,
|
|
310
|
+
} as WorkflowArg,
|
|
311
|
+
];
|
|
312
|
+
}
|
|
313
|
+
return [
|
|
314
|
+
key,
|
|
315
|
+
// type-safe: object spread on validated def preserves discriminated union invariant
|
|
316
|
+
{
|
|
317
|
+
...def,
|
|
318
|
+
default: normalizedDefault,
|
|
319
|
+
required: def.required ?? def.default === undefined,
|
|
320
|
+
} as WorkflowArg,
|
|
321
|
+
];
|
|
322
|
+
}),
|
|
323
|
+
);
|
|
324
|
+
|
|
325
|
+
const steps: WorkflowStep[] = file.steps.map((raw, index) => {
|
|
326
|
+
const defaultName = `Step ${index + 1}`;
|
|
327
|
+
if (typeof raw === "string") {
|
|
328
|
+
return {
|
|
329
|
+
kind: "prompt",
|
|
330
|
+
name: defaultName,
|
|
331
|
+
prompt: raw,
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const record = raw as Record<string, unknown>;
|
|
336
|
+
const name =
|
|
337
|
+
typeof record.name === "string" && record.name.trim().length > 0
|
|
338
|
+
? record.name
|
|
339
|
+
: defaultName;
|
|
340
|
+
|
|
341
|
+
const ifCond =
|
|
342
|
+
typeof record.if === "string" && record.if.trim().length > 0
|
|
343
|
+
? record.if.trim()
|
|
344
|
+
: undefined;
|
|
345
|
+
|
|
346
|
+
const rawOutputs = record.outputs as StepOutputsMap | undefined;
|
|
347
|
+
const rawOutput =
|
|
348
|
+
typeof record.output === "string" && record.output.trim().length > 0
|
|
349
|
+
? record.output.trim()
|
|
350
|
+
: undefined;
|
|
351
|
+
const rawForeach =
|
|
352
|
+
typeof record.foreach === "string" && record.foreach.trim().length > 0
|
|
353
|
+
? record.foreach.trim()
|
|
354
|
+
: undefined;
|
|
355
|
+
|
|
356
|
+
if (rawOutput !== undefined && rawOutputs !== undefined) {
|
|
357
|
+
throw new Error(
|
|
358
|
+
`Step ${index + 1} cannot declare both 'output' and 'outputs'`,
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const isSubagent =
|
|
363
|
+
record.kind === "subagent" ||
|
|
364
|
+
(record.subagent !== undefined && record.subagent !== false);
|
|
365
|
+
|
|
366
|
+
if (rawOutput !== undefined && !isSubagent) {
|
|
367
|
+
throw new Error(
|
|
368
|
+
`Step ${index + 1} cannot declare 'output' without 'subagent: true'. 'output' is only supported on subagent steps.`,
|
|
369
|
+
);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const outputs = normalizeStepOutputs(rawOutputs);
|
|
373
|
+
|
|
374
|
+
const step: WorkflowStep = (() => {
|
|
375
|
+
if (record.kind === "print" || typeof record.print === "string") {
|
|
376
|
+
// type-safe: schema guarantees print step has either string text or string print property
|
|
377
|
+
const printText = (
|
|
378
|
+
typeof record.text === "string" ? record.text : record.print
|
|
379
|
+
) as string;
|
|
380
|
+
return {
|
|
381
|
+
kind: "print",
|
|
382
|
+
name,
|
|
383
|
+
text: printText,
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
const extractStepGate = (raw: unknown): string | boolean | undefined => {
|
|
388
|
+
if (typeof raw !== "string" && typeof raw !== "boolean") {
|
|
389
|
+
return undefined;
|
|
390
|
+
}
|
|
391
|
+
return parseBoolean(raw) === false ? undefined : raw;
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
if (record.kind === "subagent" && typeof record.prompt === "string") {
|
|
395
|
+
const gate = extractStepGate(record.gate);
|
|
396
|
+
return {
|
|
397
|
+
kind: "subagent",
|
|
398
|
+
name,
|
|
399
|
+
prompt: record.prompt,
|
|
400
|
+
// type-safe: schema guarantees preprocessed subagent step has valid SubagentConfig
|
|
401
|
+
config: record.config as SubagentConfig,
|
|
402
|
+
...(rawForeach ? { foreach: rawForeach } : {}),
|
|
403
|
+
...(gate !== undefined ? { gate } : {}),
|
|
404
|
+
...(outputs ? { outputs } : {}),
|
|
405
|
+
...(rawOutput ? { output: rawOutput } : {}),
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
if (typeof record.prompt === "string") {
|
|
410
|
+
const prompt = record.prompt;
|
|
411
|
+
const gate = extractStepGate(record.gate);
|
|
412
|
+
|
|
413
|
+
if (record.subagent !== undefined && record.subagent !== false) {
|
|
414
|
+
const rawSubagent =
|
|
415
|
+
typeof record.subagent === "string" &&
|
|
416
|
+
record.subagent.includes("{{")
|
|
417
|
+
? record.subagent
|
|
418
|
+
: undefined;
|
|
419
|
+
const parsedConfig =
|
|
420
|
+
typeof record.subagent === "string"
|
|
421
|
+
? parseSubagentShorthand(record.subagent)
|
|
422
|
+
: typeof record.subagent === "object" && record.subagent !== null
|
|
423
|
+
? // type-safe: schema validation guarantees valid SubagentConfig object
|
|
424
|
+
(record.subagent as SubagentConfig)
|
|
425
|
+
: undefined;
|
|
426
|
+
const subagentConfig = normalizeSubagentConfig(parsedConfig);
|
|
427
|
+
return {
|
|
428
|
+
kind: "subagent",
|
|
429
|
+
name,
|
|
430
|
+
prompt,
|
|
431
|
+
config: subagentConfig,
|
|
432
|
+
...(rawSubagent ? { rawSubagent } : {}),
|
|
433
|
+
...(rawForeach ? { foreach: rawForeach } : {}),
|
|
434
|
+
...(gate !== undefined ? { gate } : {}),
|
|
435
|
+
...(outputs ? { outputs } : {}),
|
|
436
|
+
...(rawOutput ? { output: rawOutput } : {}),
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
return {
|
|
441
|
+
kind: "prompt",
|
|
442
|
+
name,
|
|
443
|
+
prompt,
|
|
444
|
+
...(gate !== undefined ? { gate } : {}),
|
|
445
|
+
...(outputs ? { outputs } : {}),
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
if (typeof record.gate === "string" || typeof record.gate === "boolean") {
|
|
450
|
+
const gatePrompt = typeof record.gate === "string" ? record.gate : name;
|
|
451
|
+
const gate = extractStepGate(record.gate);
|
|
452
|
+
return {
|
|
453
|
+
kind: "prompt",
|
|
454
|
+
name,
|
|
455
|
+
prompt: gatePrompt,
|
|
456
|
+
isSoloGate: true,
|
|
457
|
+
...(gate !== undefined ? { gate } : {}),
|
|
458
|
+
...(outputs ? { outputs } : {}),
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
throw new Error(`Invalid step definition at step ${index + 1}`);
|
|
463
|
+
})();
|
|
464
|
+
|
|
465
|
+
return ifCond !== undefined ? { ...step, if: ifCond } : step;
|
|
466
|
+
});
|
|
467
|
+
|
|
468
|
+
return {
|
|
469
|
+
...(file.name !== undefined ? { name: file.name } : {}),
|
|
470
|
+
...(file.title !== undefined ? { title: file.title } : {}),
|
|
471
|
+
...(file.description !== undefined
|
|
472
|
+
? { description: file.description }
|
|
473
|
+
: {}),
|
|
474
|
+
args: normalizedArgs,
|
|
475
|
+
steps,
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* Parses raw YAML text into a validated and preprocessed WorkflowDocument.
|
|
481
|
+
* CONTRACT:
|
|
482
|
+
* - Input: raw YAML string content.
|
|
483
|
+
* - Output: fully validated and normalized WorkflowDocument.
|
|
484
|
+
* - Throws: Error when YAML parsing fails or document violates WorkflowFileSchema.
|
|
485
|
+
*/
|
|
486
|
+
export function parseWorkflowDocument(content: string): WorkflowDocument {
|
|
487
|
+
const file = parseWorkflowFile(content);
|
|
488
|
+
return preprocessWorkflow(file);
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Purpose: Parses a saved list output and enforces its declared bounds.
|
|
493
|
+
* Contract:
|
|
494
|
+
* - Inputs: Output name, serialized JSON value, and validated list definition.
|
|
495
|
+
* - Outputs: String array on success or a diagnostic for invalid JSON, items, or bounds.
|
|
496
|
+
* - Throws: Unexpected parsing errors propagate.
|
|
497
|
+
*/
|
|
498
|
+
export function parseListOutput(
|
|
499
|
+
name: string,
|
|
500
|
+
value: string,
|
|
501
|
+
definition: Extract<StepOutputDef, { type: "list" }>,
|
|
502
|
+
):
|
|
503
|
+
| { readonly kind: "success"; readonly value: readonly string[] }
|
|
504
|
+
| { readonly kind: "error"; readonly message: string } {
|
|
505
|
+
let parsed: unknown;
|
|
506
|
+
try {
|
|
507
|
+
parsed = JSON.parse(value);
|
|
508
|
+
} catch (err: unknown) {
|
|
509
|
+
if (!(err instanceof SyntaxError)) throw err;
|
|
510
|
+
return {
|
|
511
|
+
kind: "error",
|
|
512
|
+
message: `Output '${name}' is declared as type 'list', but could not parse value as JSON array.`,
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
if (!Array.isArray(parsed)) {
|
|
516
|
+
return {
|
|
517
|
+
kind: "error",
|
|
518
|
+
message: `Output '${name}' is declared as type 'list', but received non-array value. Expected JSON array string.`,
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
if (!parsed.every((item: unknown) => typeof item === "string")) {
|
|
522
|
+
return {
|
|
523
|
+
kind: "error",
|
|
524
|
+
message: `Output '${name}' is declared as type 'list', but contains non-string elements. Expected JSON array of strings.`,
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
if (definition.min !== undefined && parsed.length < definition.min) {
|
|
528
|
+
return {
|
|
529
|
+
kind: "error",
|
|
530
|
+
message: `Output '${name}' requires at least ${definition.min} items, but received ${parsed.length}.`,
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
if (definition.max !== undefined && parsed.length > definition.max) {
|
|
534
|
+
return {
|
|
535
|
+
kind: "error",
|
|
536
|
+
message: `Output '${name}' allows at most ${definition.max} items, but received ${parsed.length}.`,
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
return { kind: "success", value: parsed };
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Strips surrounding single or double quotes from a string.
|
|
544
|
+
*/
|
|
545
|
+
function unquote(text: string): string {
|
|
546
|
+
return text.replace(/^(['"])(.*)\1$/, "$2");
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Parses a CLI command invocation string into a target path, key-value args, and implicit instructions.
|
|
551
|
+
* CONTRACT:
|
|
552
|
+
* - Input: rawInput string (e.g., "build.yaml target=prod optimize=true please run tests").
|
|
553
|
+
* - Output: ParsedInvocation with targetPath, explicitArgs map, and implicitInstructions string.
|
|
554
|
+
* - Invariant: Leading '@' mentions are stripped; whitespace-only inputs return empty fields.
|
|
555
|
+
*/
|
|
556
|
+
export function parseInvocationInput(rawInput: string): ParsedInvocation {
|
|
557
|
+
// edge case: slash command chat mentions may prefix input with '@'
|
|
558
|
+
const trimmed = rawInput.trim().replace(/^@/, "");
|
|
559
|
+
if (!trimmed) {
|
|
560
|
+
return { targetPath: "", explicitArgs: {}, implicitInstructions: "" };
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
const tokenRegex =
|
|
564
|
+
/([a-zA-Z0-9_-]+)=(?:"([^"]*)"|'([^']*)'|([^\s]+))|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|[^\s]+/g;
|
|
565
|
+
|
|
566
|
+
const matches = trimmed.match(tokenRegex) as RegExpMatchArray;
|
|
567
|
+
|
|
568
|
+
let targetPath = "";
|
|
569
|
+
const explicitArgs: Record<string, string> = {};
|
|
570
|
+
const implicitTokens: string[] = [];
|
|
571
|
+
let pathConsumed = false;
|
|
572
|
+
|
|
573
|
+
for (const token of matches) {
|
|
574
|
+
const kvMatch = token.match(/^([a-zA-Z0-9_-]+)=(.*)$/);
|
|
575
|
+
if (kvMatch) {
|
|
576
|
+
const key = kvMatch[1];
|
|
577
|
+
explicitArgs[key] = unquote(kvMatch[2]);
|
|
578
|
+
} else if (!pathConsumed) {
|
|
579
|
+
targetPath = unquote(token);
|
|
580
|
+
pathConsumed = true;
|
|
581
|
+
} else {
|
|
582
|
+
implicitTokens.push(unquote(token));
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
return {
|
|
587
|
+
targetPath,
|
|
588
|
+
explicitArgs,
|
|
589
|
+
implicitInstructions: implicitTokens.join(" "),
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* Resolves workflow arguments against declarations, verifying required fields, choices, and defaults.
|
|
595
|
+
* CONTRACT:
|
|
596
|
+
* - Input: declarations map, explicit key-value arguments, and unflagged implicit instructions.
|
|
597
|
+
* - Output: complete map of resolved argument values.
|
|
598
|
+
* - Throws: Error if undeclared arguments are passed, required arguments are missing, or choices are violated.
|
|
599
|
+
*/
|
|
600
|
+
export function resolveWorkflowArgs({
|
|
601
|
+
declarations = {},
|
|
602
|
+
explicitArgs,
|
|
603
|
+
implicitInstructions,
|
|
604
|
+
}: {
|
|
605
|
+
declarations?: Record<string, WorkflowArg>;
|
|
606
|
+
explicitArgs: Record<string, string>;
|
|
607
|
+
implicitInstructions: string;
|
|
608
|
+
}): Record<string, string> {
|
|
609
|
+
const rawValues: Record<string, string> = { ...explicitArgs };
|
|
610
|
+
|
|
611
|
+
if (implicitInstructions.length > 0) {
|
|
612
|
+
if (!Object.hasOwn(declarations, "instructions")) {
|
|
613
|
+
throw new Error(
|
|
614
|
+
"Unexpected implicit instructions: workflow does not declare an 'instructions' argument in 'args'",
|
|
615
|
+
);
|
|
616
|
+
}
|
|
617
|
+
if (rawValues.instructions !== undefined) {
|
|
618
|
+
throw new Error(
|
|
619
|
+
"Cannot specify both explicit 'instructions' argument and implicit trailing instructions",
|
|
620
|
+
);
|
|
621
|
+
}
|
|
622
|
+
rawValues.instructions = implicitInstructions;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
for (const [argName, def] of Object.entries(declarations)) {
|
|
626
|
+
if (def.type === "choice") {
|
|
627
|
+
const mapping = def.mapping ?? def.mappings;
|
|
628
|
+
if (mapping && !isFlatChoiceMapping(mapping)) {
|
|
629
|
+
for (const derivedKey of Object.keys(mapping)) {
|
|
630
|
+
if (Object.hasOwn(explicitArgs, derivedKey)) {
|
|
631
|
+
throw new Error(
|
|
632
|
+
`Cannot pass explicit argument '${derivedKey}': '${derivedKey}' is derived from choice argument '${argName}'`,
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
for (const key of Object.keys(explicitArgs)) {
|
|
641
|
+
if (!Object.hasOwn(declarations, key)) {
|
|
642
|
+
const declaredKeys = Object.keys(declarations).join(", ");
|
|
643
|
+
throw new Error(
|
|
644
|
+
`Unknown argument '${key}'. Declared arguments: ${declaredKeys}`,
|
|
645
|
+
);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
const resolved: Record<string, string> = {};
|
|
650
|
+
|
|
651
|
+
for (const [name, def] of Object.entries(declarations)) {
|
|
652
|
+
const rawVal =
|
|
653
|
+
rawValues[name] ??
|
|
654
|
+
(def.default !== undefined ? String(def.default) : undefined);
|
|
655
|
+
if (rawVal === undefined) {
|
|
656
|
+
if (def.required !== false) {
|
|
657
|
+
throw new Error(`Missing required argument '${name}'`);
|
|
658
|
+
}
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
if (def.type === "choice") {
|
|
663
|
+
if (!def.choices.includes(rawVal)) {
|
|
664
|
+
throw new Error(
|
|
665
|
+
`Invalid value '${rawVal}' for argument '${name}'. Allowed choices: ${def.choices.join(", ")}`,
|
|
666
|
+
);
|
|
667
|
+
}
|
|
668
|
+
resolved[name] = rawVal;
|
|
669
|
+
} else if (def.type === "bool") {
|
|
670
|
+
const boolVal = parseBoolean(rawVal);
|
|
671
|
+
if (boolVal === undefined) {
|
|
672
|
+
throw new Error(
|
|
673
|
+
`Invalid value '${rawVal}' for bool argument '${name}'. Allowed values: true, false`,
|
|
674
|
+
);
|
|
675
|
+
}
|
|
676
|
+
resolved[name] = String(boolVal);
|
|
677
|
+
} else {
|
|
678
|
+
resolved[name] = rawVal;
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
for (const [argName, def] of Object.entries(declarations)) {
|
|
683
|
+
if (def.type === "choice") {
|
|
684
|
+
const mapping = def.mapping ?? def.mappings;
|
|
685
|
+
if (mapping) {
|
|
686
|
+
const choiceVal = resolved[argName];
|
|
687
|
+
if (choiceVal !== undefined) {
|
|
688
|
+
if (isFlatChoiceMapping(mapping)) {
|
|
689
|
+
if (!Object.hasOwn(mapping, choiceVal)) {
|
|
690
|
+
throw new Error(
|
|
691
|
+
`Choice '${choiceVal}' for argument '${argName}' is not defined in mapping.`,
|
|
692
|
+
);
|
|
693
|
+
}
|
|
694
|
+
resolved[argName] = mapping[choiceVal];
|
|
695
|
+
} else {
|
|
696
|
+
for (const [derivedKey, map] of Object.entries(mapping)) {
|
|
697
|
+
if (!Object.hasOwn(map, choiceVal)) {
|
|
698
|
+
throw new Error(
|
|
699
|
+
`Choice '${choiceVal}' for derived argument '${derivedKey}' in '${argName}' mapping is not defined.`,
|
|
700
|
+
);
|
|
701
|
+
}
|
|
702
|
+
resolved[derivedKey] = map[choiceVal];
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
return resolved;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* Purpose: Evaluates a step condition string against resolved arguments and outputs.
|
|
715
|
+
* CONTRACT:
|
|
716
|
+
* - Inputs: condition template string, resolved args dictionary, and optional outputs dictionary.
|
|
717
|
+
* - Outputs: boolean indicating whether the step condition is satisfied.
|
|
718
|
+
* - Supported patterns:
|
|
719
|
+
* - Equality / inequality comparison: `<left> == <right>` or `<left> != <right>`
|
|
720
|
+
* - Negated boolean: `!<expr>`
|
|
721
|
+
* - Direct boolean: `<expr>` (truthy strictly if "true")
|
|
722
|
+
*/
|
|
723
|
+
export function evaluateStepCondition(
|
|
724
|
+
condition: string,
|
|
725
|
+
args: Record<string, string>,
|
|
726
|
+
outputs?: Record<string, string | readonly string[]>,
|
|
727
|
+
): boolean {
|
|
728
|
+
const trimmed = condition.trim();
|
|
729
|
+
if (trimmed.length === 0) return false;
|
|
730
|
+
|
|
731
|
+
const cmpMatch = trimmed.match(/^(.*?)\s*(==|!=)\s*(.*?)$/);
|
|
732
|
+
if (cmpMatch) {
|
|
733
|
+
const left = unquote(
|
|
734
|
+
interpolateTemplate(cmpMatch[1].trim(), args, outputs).trim(),
|
|
735
|
+
);
|
|
736
|
+
const op = cmpMatch[2];
|
|
737
|
+
const right = unquote(
|
|
738
|
+
interpolateTemplate(cmpMatch[3].trim(), args, outputs).trim(),
|
|
739
|
+
);
|
|
740
|
+
return op === "==" ? left === right : left !== right;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
if (trimmed.startsWith("!")) {
|
|
744
|
+
const val = unquote(
|
|
745
|
+
interpolateTemplate(trimmed.slice(1).trim(), args, outputs).trim(),
|
|
746
|
+
);
|
|
747
|
+
return parseBoolean(val) !== true;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
const val = unquote(interpolateTemplate(trimmed, args, outputs).trim());
|
|
751
|
+
return parseBoolean(val) === true;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
/**
|
|
755
|
+
* Purpose: Formats the complete markdown/XML prompt for an individual workflow step.
|
|
756
|
+
* CONTRACT:
|
|
757
|
+
* - Input: FormatStepPromptOptions with step index, totals, prompt body, and flags.
|
|
758
|
+
* - Output: structured string with <workflow-info>, <step-instructions>, and <rules> blocks.
|
|
759
|
+
*/
|
|
760
|
+
export function formatStepPrompt(options: FormatStepPromptOptions): string {
|
|
761
|
+
const header = `[STEP ${options.stepIndex + 1} OF ${options.totalSteps}: ${options.stepName}]`;
|
|
762
|
+
|
|
763
|
+
const workflowInfoLines = ["<workflow-info>"];
|
|
764
|
+
if (options.workflowName) {
|
|
765
|
+
workflowInfoLines.push(`Workflow: "${options.workflowName}"`);
|
|
766
|
+
}
|
|
767
|
+
workflowInfoLines.push(
|
|
768
|
+
`Step: ${options.stepIndex + 1} of ${options.totalSteps}`,
|
|
769
|
+
);
|
|
770
|
+
workflowInfoLines.push("</workflow-info>");
|
|
771
|
+
const workflowInfo = workflowInfoLines.join("\n");
|
|
772
|
+
|
|
773
|
+
const sections = [header, workflowInfo];
|
|
774
|
+
|
|
775
|
+
if (options.isResumedStep) {
|
|
776
|
+
sections.push(
|
|
777
|
+
[
|
|
778
|
+
"<workflow-resume>",
|
|
779
|
+
`Workflow execution was resumed from an interrupted state at step ${options.stepIndex + 1} of ${options.totalSteps}.`,
|
|
780
|
+
"Prior steps have completed, and instructions in this step may already be partially or fully done.",
|
|
781
|
+
"Inspect current workspace and environment state before acting. Do not duplicate already completed operations.",
|
|
782
|
+
"</workflow-resume>",
|
|
783
|
+
].join("\n"),
|
|
784
|
+
);
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
if (options.instructions) {
|
|
788
|
+
sections.push(
|
|
789
|
+
`<user-instructions>\n${options.instructions}\n</user-instructions>`,
|
|
790
|
+
);
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
if (options.outputRequirements && options.outputRequirements.length > 0) {
|
|
794
|
+
const reqLines = [
|
|
795
|
+
"<output-requirements>",
|
|
796
|
+
"This step requires the following outputs to be produced:",
|
|
797
|
+
];
|
|
798
|
+
for (const req of options.outputRequirements) {
|
|
799
|
+
if (req.type === "file") {
|
|
800
|
+
reqLines.push(
|
|
801
|
+
`- File output '${req.name}': write to '${req.resolvedPath}'. Must exist and be non-empty.`,
|
|
802
|
+
);
|
|
803
|
+
} else if (req.type === "list") {
|
|
804
|
+
const desc = req.description ? ` (${req.description})` : "";
|
|
805
|
+
const bounds: string[] = [];
|
|
806
|
+
if (req.min !== undefined) bounds.push(`min items: ${req.min}`);
|
|
807
|
+
if (req.max !== undefined) bounds.push(`max items: ${req.max}`);
|
|
808
|
+
const boundsStr = bounds.length > 0 ? ` [${bounds.join(", ")}]` : "";
|
|
809
|
+
reqLines.push(
|
|
810
|
+
`- List output '${req.name}'${desc}${boundsStr}: call tool 'save_output' with name="${req.name}" and value as a JSON array string.`,
|
|
811
|
+
);
|
|
812
|
+
} else {
|
|
813
|
+
const desc = req.description ? ` (${req.description})` : "";
|
|
814
|
+
reqLines.push(
|
|
815
|
+
`- String output '${req.name}'${desc}: call tool 'save_output' with name="${req.name}" and value=<your_value>.`,
|
|
816
|
+
);
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
reqLines.push("</output-requirements>");
|
|
820
|
+
sections.push(reqLines.join("\n"));
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
sections.push(`<step-instructions>\n${options.prompt}\n</step-instructions>`);
|
|
824
|
+
|
|
825
|
+
const ruleLines = [
|
|
826
|
+
"<rules>",
|
|
827
|
+
"- Perform ONLY the instructions in <step-instructions>.",
|
|
828
|
+
"- Conclude when complete.",
|
|
829
|
+
"- Do NOT anticipate or execute any future steps.",
|
|
830
|
+
];
|
|
831
|
+
if (options.instructions) {
|
|
832
|
+
ruleLines.push(
|
|
833
|
+
"- Incorporate and follow the additional instructions in <user-instructions> while performing this step.",
|
|
834
|
+
);
|
|
835
|
+
}
|
|
836
|
+
if (options.outputRequirements && options.outputRequirements.length > 0) {
|
|
837
|
+
ruleLines.push(
|
|
838
|
+
"- Ensure all required outputs in <output-requirements> are produced before concluding.",
|
|
839
|
+
"- Do not present written outputs to the user as they are technical. Conclude with a brief acknowledgement message.",
|
|
840
|
+
);
|
|
841
|
+
}
|
|
842
|
+
if (options.isResumedStep) {
|
|
843
|
+
ruleLines.push(
|
|
844
|
+
"- Verify existing workspace state before executing to avoid repeating completed work.",
|
|
845
|
+
);
|
|
846
|
+
}
|
|
847
|
+
ruleLines.push("</rules>");
|
|
848
|
+
sections.push(ruleLines.join("\n"));
|
|
849
|
+
|
|
850
|
+
return sections.join("\n\n");
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
export interface OutputRetryMissingItem {
|
|
854
|
+
readonly name: string;
|
|
855
|
+
readonly type: "file" | "string" | "list";
|
|
856
|
+
readonly resolvedPath?: string;
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
/**
|
|
860
|
+
* Purpose: Formats an automated retry prompt when step output verification fails.
|
|
861
|
+
*/
|
|
862
|
+
export function formatOutputRetryPrompt({
|
|
863
|
+
stepIndex,
|
|
864
|
+
totalSteps,
|
|
865
|
+
stepName,
|
|
866
|
+
missingOutputs,
|
|
867
|
+
attempt,
|
|
868
|
+
}: {
|
|
869
|
+
stepIndex: number;
|
|
870
|
+
totalSteps: number;
|
|
871
|
+
stepName: string;
|
|
872
|
+
missingOutputs: readonly OutputRetryMissingItem[];
|
|
873
|
+
attempt: number;
|
|
874
|
+
}): string {
|
|
875
|
+
const header = `[STEP ${stepIndex + 1} OF ${totalSteps} OUTPUT VERIFICATION FAILED (Attempt ${attempt} of 3)]`;
|
|
876
|
+
const lines = [
|
|
877
|
+
header,
|
|
878
|
+
"<output-verification-failure>",
|
|
879
|
+
`Step '${stepName}' output verification failed. Missing outputs:`,
|
|
880
|
+
];
|
|
881
|
+
for (const missing of missingOutputs) {
|
|
882
|
+
if (missing.type === "file") {
|
|
883
|
+
lines.push(
|
|
884
|
+
`- File output '${missing.name}': expected non-empty file at '${missing.resolvedPath}'. Please create or write to this file.`,
|
|
885
|
+
);
|
|
886
|
+
} else if (missing.type === "list") {
|
|
887
|
+
lines.push(
|
|
888
|
+
`- List output '${missing.name}': tool 'save_output' was not called with name="${missing.name}" and a valid JSON array. Please call tool 'save_output'.`,
|
|
889
|
+
);
|
|
890
|
+
} else {
|
|
891
|
+
lines.push(
|
|
892
|
+
`- String output '${missing.name}': tool 'save_output' was not called with name="${missing.name}". Please call tool 'save_output'.`,
|
|
893
|
+
);
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
lines.push("</output-verification-failure>");
|
|
897
|
+
return lines.join("\n");
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
/**
|
|
901
|
+
* Purpose: Parses workflow YAML text and extracts a summary of metadata and parameters if valid.
|
|
902
|
+
* Contract:
|
|
903
|
+
* - Inputs: target path/identifier string and raw YAML string content.
|
|
904
|
+
* - Outputs: WorkflowSummary object if parsing and validation succeed; null otherwise.
|
|
905
|
+
* - Throws: None (errors caught and safely returned as null).
|
|
906
|
+
*/
|
|
907
|
+
export function parseWorkflowSummary(
|
|
908
|
+
target: string,
|
|
909
|
+
content: string,
|
|
910
|
+
): WorkflowSummary | null {
|
|
911
|
+
try {
|
|
912
|
+
const raw = parse(content);
|
|
913
|
+
const result = WorkflowFileSchema.safeParse(raw);
|
|
914
|
+
if (!result.success) return null;
|
|
915
|
+
const file = result.data;
|
|
916
|
+
const params: WorkflowParamSummary[] = Object.entries(file.args ?? {}).map(
|
|
917
|
+
([name, arg]) => ({
|
|
918
|
+
name,
|
|
919
|
+
description: arg.description,
|
|
920
|
+
type: arg.type,
|
|
921
|
+
required: arg.required ?? arg.default === undefined,
|
|
922
|
+
default: arg.default !== undefined ? String(arg.default) : undefined,
|
|
923
|
+
choices: arg.type === "choice" ? arg.choices : undefined,
|
|
924
|
+
}),
|
|
925
|
+
);
|
|
926
|
+
return {
|
|
927
|
+
target,
|
|
928
|
+
name: file.name,
|
|
929
|
+
description: file.description,
|
|
930
|
+
params,
|
|
931
|
+
};
|
|
932
|
+
} catch {
|
|
933
|
+
return null;
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
/**
|
|
938
|
+
* Purpose: Formats a parameter's metadata and description as a Markdown bullet line item.
|
|
939
|
+
* Contract:
|
|
940
|
+
* - Inputs: parameter name and metadata object with type, choices, default, required, and description.
|
|
941
|
+
* - Outputs: Formatted string (e.g. " - `env` (choice, choices: staging, production, default: \"staging\"): Target tier").
|
|
942
|
+
*/
|
|
943
|
+
export function formatWorkflowParamDescriptor(
|
|
944
|
+
name: string,
|
|
945
|
+
param: {
|
|
946
|
+
readonly type: string;
|
|
947
|
+
readonly choices?: readonly string[];
|
|
948
|
+
readonly default?: string | boolean;
|
|
949
|
+
readonly required?: boolean;
|
|
950
|
+
readonly description?: string;
|
|
951
|
+
},
|
|
952
|
+
): string {
|
|
953
|
+
const meta: string[] = [param.type];
|
|
954
|
+
if (param.choices && param.choices.length > 0) {
|
|
955
|
+
meta.push(`choices: ${param.choices.join(", ")}`);
|
|
956
|
+
}
|
|
957
|
+
if (param.default !== undefined) {
|
|
958
|
+
meta.push(`default: "${param.default}"`);
|
|
959
|
+
}
|
|
960
|
+
if (param.required) {
|
|
961
|
+
meta.push("required");
|
|
962
|
+
}
|
|
963
|
+
const metaStr = ` (${meta.join(", ")})`;
|
|
964
|
+
const desc = param.description ? `: ${param.description}` : "";
|
|
965
|
+
return ` - \`${name}\`${metaStr}${desc}`;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/**
|
|
969
|
+
* Purpose: Formats categorized workflow summaries into user-readable Markdown.
|
|
970
|
+
* Contract:
|
|
971
|
+
* - Inputs: Array of WorkflowGroup containing group title and WorkflowSummary items.
|
|
972
|
+
* - Outputs: Formatted Markdown text.
|
|
973
|
+
* - Throws: None.
|
|
974
|
+
*/
|
|
975
|
+
export function formatWorkflowList(groups: readonly WorkflowGroup[]): string {
|
|
976
|
+
const sections: string[] = [];
|
|
977
|
+
|
|
978
|
+
for (const group of groups) {
|
|
979
|
+
const lines: string[] = [`### ${group.title}`];
|
|
980
|
+
if (group.workflows.length === 0) {
|
|
981
|
+
lines.push("*(No workflows found)*");
|
|
982
|
+
} else {
|
|
983
|
+
for (const wf of group.workflows) {
|
|
984
|
+
const titlePart = wf.name
|
|
985
|
+
? `**${wf.name}** (\`${wf.target}\`)`
|
|
986
|
+
: `\`${wf.target}\``;
|
|
987
|
+
const descPart = wf.description ? `: ${wf.description}` : "";
|
|
988
|
+
lines.push(`- ${titlePart}${descPart}`);
|
|
989
|
+
if (wf.params.length > 0) {
|
|
990
|
+
for (const param of wf.params) {
|
|
991
|
+
lines.push(formatWorkflowParamDescriptor(param.name, param));
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
sections.push(lines.join("\n"));
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
return sections.join("\n\n");
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
/**
|
|
1003
|
+
* Purpose: Formats a diagnostic summary for a validated workflow document and optional resolved arguments.
|
|
1004
|
+
* Contract:
|
|
1005
|
+
* - Inputs: targetPath string, doc WorkflowDocument, optional resolvedArgs dictionary.
|
|
1006
|
+
* - Outputs: Markdown string detailing workflow status, steps, declared arguments, and resolved arguments.
|
|
1007
|
+
* - Throws: None.
|
|
1008
|
+
*/
|
|
1009
|
+
export function formatValidationSummary(
|
|
1010
|
+
targetPath: string,
|
|
1011
|
+
doc: WorkflowDocument,
|
|
1012
|
+
resolvedArgs?: Record<string, string>,
|
|
1013
|
+
): string {
|
|
1014
|
+
const lines: string[] = [
|
|
1015
|
+
`### Workflow Validation: \`${targetPath}\``,
|
|
1016
|
+
"- **Status:** Valid",
|
|
1017
|
+
];
|
|
1018
|
+
if (doc.name) {
|
|
1019
|
+
lines.push(`- **Name:** ${doc.name}`);
|
|
1020
|
+
}
|
|
1021
|
+
if (doc.title) {
|
|
1022
|
+
lines.push(`- **Title:** ${doc.title}`);
|
|
1023
|
+
}
|
|
1024
|
+
if (doc.description) {
|
|
1025
|
+
lines.push(`- **Description:** ${doc.description}`);
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
lines.push(`- **Steps:** ${doc.steps.length}`);
|
|
1029
|
+
for (let i = 0; i < doc.steps.length; i++) {
|
|
1030
|
+
const step = doc.steps[i];
|
|
1031
|
+
const isGateDeclared =
|
|
1032
|
+
(step.kind === "prompt" || step.kind === "subagent") &&
|
|
1033
|
+
step.gate !== undefined &&
|
|
1034
|
+
(typeof step.gate === "boolean"
|
|
1035
|
+
? step.gate
|
|
1036
|
+
: step.gate.trim() !== "" && parseBoolean(step.gate) !== false);
|
|
1037
|
+
const gateStr = isGateDeclared ? " [gate]" : "";
|
|
1038
|
+
lines.push(` ${i + 1}. [${step.kind}] ${step.name}${gateStr}`);
|
|
1039
|
+
if (step.kind === "subagent" && step.output) {
|
|
1040
|
+
lines.push(` - Output: \`${step.output}\``);
|
|
1041
|
+
}
|
|
1042
|
+
if ((step.kind === "prompt" || step.kind === "subagent") && step.outputs) {
|
|
1043
|
+
for (const [outName, outDef] of Object.entries(step.outputs)) {
|
|
1044
|
+
const extra =
|
|
1045
|
+
outDef.type === "file"
|
|
1046
|
+
? `: ${outDef.path}`
|
|
1047
|
+
: outDef.description
|
|
1048
|
+
? `: ${outDef.description}`
|
|
1049
|
+
: "";
|
|
1050
|
+
lines.push(` - Output: \`${outName}\` (${outDef.type})${extra}`);
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
const declaredArgs = Object.entries(doc.args);
|
|
1056
|
+
if (declaredArgs.length > 0) {
|
|
1057
|
+
lines.push("- **Declared Arguments:**");
|
|
1058
|
+
for (const [name, def] of declaredArgs) {
|
|
1059
|
+
lines.push(formatWorkflowParamDescriptor(name, def));
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
if (resolvedArgs !== undefined) {
|
|
1064
|
+
lines.push("- **Resolved Arguments:**");
|
|
1065
|
+
for (const [key, val] of Object.entries(resolvedArgs)) {
|
|
1066
|
+
lines.push(` - \`${key}\`: "${val}"`);
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
return lines.join("\n");
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
/**
|
|
1074
|
+
* Purpose: Constructs an ObjectJsonSchema enforcing structured JSON output for a subagent step.
|
|
1075
|
+
* Contract:
|
|
1076
|
+
* - Inputs: outputs map and resolvedOutputPaths dictionary mapping file output names to absolute paths.
|
|
1077
|
+
* - Outputs: ObjectJsonSchema with string properties and required keys matching all declared outputs.
|
|
1078
|
+
* - Invariant: File outputs become synthetic string parameters requiring the absolute file path.
|
|
1079
|
+
*/
|
|
1080
|
+
export function buildSubagentOutputSchema(
|
|
1081
|
+
outputs: WorkflowStepOutputsMap,
|
|
1082
|
+
resolvedOutputPaths: Record<string, string>,
|
|
1083
|
+
): ObjectJsonSchema {
|
|
1084
|
+
const properties: Record<string, JsonSchemaNode> = {};
|
|
1085
|
+
const required: string[] = [];
|
|
1086
|
+
|
|
1087
|
+
for (const [name, def] of Object.entries(outputs)) {
|
|
1088
|
+
required.push(name);
|
|
1089
|
+
if (def.type === "string") {
|
|
1090
|
+
properties[name] = {
|
|
1091
|
+
type: "string",
|
|
1092
|
+
description: def.description ?? `Output string value for '${name}'`,
|
|
1093
|
+
};
|
|
1094
|
+
} else {
|
|
1095
|
+
const resolvedPath = resolvedOutputPaths[name];
|
|
1096
|
+
properties[name] = {
|
|
1097
|
+
type: "string",
|
|
1098
|
+
description: `Absolute filesystem path of the written file for '${name}'. Must be written to: ${resolvedPath}`,
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
return {
|
|
1104
|
+
type: "object",
|
|
1105
|
+
properties,
|
|
1106
|
+
required,
|
|
1107
|
+
additionalProperties: false,
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
/**
|
|
1112
|
+
* Purpose: Formats instructions for a subagent step, including structured output requirements when declared.
|
|
1113
|
+
* Contract:
|
|
1114
|
+
* - Inputs: interpolated prompt string and optional output requirements array.
|
|
1115
|
+
* - Outputs: formatted prompt text. Returns raw prompt if no output requirements.
|
|
1116
|
+
*/
|
|
1117
|
+
export function formatSubagentPrompt({
|
|
1118
|
+
prompt,
|
|
1119
|
+
outputRequirements,
|
|
1120
|
+
}: {
|
|
1121
|
+
readonly prompt: string;
|
|
1122
|
+
readonly outputRequirements?: readonly FormatStepPromptOutputRequirement[];
|
|
1123
|
+
}): string {
|
|
1124
|
+
if (!outputRequirements || outputRequirements.length === 0) {
|
|
1125
|
+
return prompt;
|
|
1126
|
+
}
|
|
1127
|
+
const reqLines = [
|
|
1128
|
+
"<output-requirements>",
|
|
1129
|
+
"This step requires structured outputs adhering to the requested JSON schema:",
|
|
1130
|
+
];
|
|
1131
|
+
for (const req of outputRequirements) {
|
|
1132
|
+
if (req.type === "file") {
|
|
1133
|
+
reqLines.push(
|
|
1134
|
+
`- 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}'.`,
|
|
1135
|
+
);
|
|
1136
|
+
} else {
|
|
1137
|
+
const desc = req.description ? ` (${req.description})` : "";
|
|
1138
|
+
reqLines.push(
|
|
1139
|
+
`- String output '${req.name}'${desc}: in the returned JSON object, set property '${req.name}' to the output string value.`,
|
|
1140
|
+
);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
reqLines.push("</output-requirements>");
|
|
1144
|
+
|
|
1145
|
+
return `${prompt}\n\n${reqLines.join("\n")}`;
|
|
1146
|
+
}
|