@nones/agentflow-strategy-workflow 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts ADDED
@@ -0,0 +1,36 @@
1
+ export { workflowStrategy } from "./strategy";
2
+ export {
3
+ canonicalJson,
4
+ expandWorkflow,
5
+ expansionToRunPlan,
6
+ sha256Digest,
7
+ WORKFLOW_EXPANSION_VERSION,
8
+ } from "./expansion";
9
+ export type {
10
+ WorkflowExpansion,
11
+ WorkflowPhase,
12
+ WorkflowRound,
13
+ WorkflowRoundMode,
14
+ WorkflowStep,
15
+ WorkflowStepDependency,
16
+ WorkflowStepKind,
17
+ WorkflowStepProvenance,
18
+ } from "./expansion";
19
+ export {
20
+ createWorkflowTemplateRegistry,
21
+ interpolateTemplateParameters,
22
+ parseWorkflowTemplate,
23
+ parseWorkflowTemplateJson,
24
+ previewWorkflowTemplate,
25
+ readWorkflowTemplateFile,
26
+ validateTemplateParameters,
27
+ workflowTemplateDigest,
28
+ WORKFLOW_TEMPLATE_VERSION,
29
+ WorkflowTemplateError,
30
+ } from "./templates";
31
+ export type {
32
+ ParsedWorkflowTemplate,
33
+ WorkflowTemplate,
34
+ WorkflowTemplatePreview,
35
+ WorkflowTemplateRegistry,
36
+ } from "./templates";
@@ -0,0 +1,343 @@
1
+ import type {
2
+ AgentSpec,
3
+ ArtifactDeclaration,
4
+ RunPlan,
5
+ WaveSpec,
6
+ } from "@nones/agentflow-core";
7
+
8
+ const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
9
+
10
+ /**
11
+ * Stable logical key: `<phase>/<round>/<step>`. This is the inspection and
12
+ * dependency namespace and is never an engine ID.
13
+ */
14
+ const STEP_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
15
+
16
+ const PLAN_FIELDS = [
17
+ "waves",
18
+ "profile",
19
+ "artifacts",
20
+ "sealed",
21
+ "scripts",
22
+ "gates",
23
+ "metadata",
24
+ ] as const;
25
+ const WAVE_FIELDS = ["id", "agents"] as const;
26
+ const AGENT_FIELDS = [
27
+ "id",
28
+ "prompt",
29
+ "cwd",
30
+ "profile",
31
+ "model",
32
+ "preset",
33
+ "settings",
34
+ "strategy",
35
+ "strategyInput",
36
+ ] as const;
37
+ const ARTIFACT_FIELDS = ["id", "type", "required", "schema"] as const;
38
+
39
+ export function isRecord(value: unknown): value is Record<string, unknown> {
40
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
41
+ return false;
42
+ }
43
+ const prototype = Object.getPrototypeOf(value);
44
+ return prototype === Object.prototype || prototype === null;
45
+ }
46
+
47
+ export function fail(path: string, message: string): never {
48
+ throw new TypeError(`${path}: ${message}`);
49
+ }
50
+
51
+ export function expectRecord(
52
+ value: unknown,
53
+ path: string,
54
+ ): Record<string, unknown> {
55
+ if (!isRecord(value)) {
56
+ fail(path, "must be a plain object");
57
+ }
58
+ return value;
59
+ }
60
+
61
+ export function assertOnlyKeys(
62
+ record: Record<string, unknown>,
63
+ allowed: readonly string[],
64
+ path: string,
65
+ ): void {
66
+ const allowedKeys = new Set(allowed);
67
+ for (const key of Object.keys(record)) {
68
+ if (!allowedKeys.has(key)) {
69
+ fail(`${path}.${key}`, "is not a recognized field");
70
+ }
71
+ }
72
+ }
73
+
74
+ export function expectString(value: unknown, path: string): string {
75
+ if (typeof value !== "string") {
76
+ fail(path, "must be a string");
77
+ }
78
+ if (value.trim().length === 0) {
79
+ fail(path, "must not be empty");
80
+ }
81
+ return value;
82
+ }
83
+
84
+ export function expectOptionalString(
85
+ value: unknown,
86
+ path: string,
87
+ ): string | undefined {
88
+ if (value === undefined) {
89
+ return undefined;
90
+ }
91
+ return expectString(value, path);
92
+ }
93
+
94
+ export function expectId(value: unknown, path: string): string {
95
+ const id = expectString(value, path);
96
+ if (!ID_PATTERN.test(id)) {
97
+ fail(
98
+ path,
99
+ "must start with an alphanumeric character and contain only letters, digits, '.', '_', ':' or '-'",
100
+ );
101
+ }
102
+ return id;
103
+ }
104
+
105
+ /**
106
+ * Engine-facing ID: accepted by core `assertId`, so `/` (wave `phase/round`)
107
+ * and `@` (foreach `item`) are allowed. Control characters and the 256-char
108
+ * cap still apply.
109
+ */
110
+ export function expectEngineId(value: unknown, path: string): string {
111
+ const id = expectString(value, path);
112
+ if (id.length > 256) {
113
+ fail(path, "must be at most 256 characters");
114
+ }
115
+ if (/[\u0000-\u001f\u007f]/.test(id)) {
116
+ fail(path, "must not contain control characters");
117
+ }
118
+ return id;
119
+ }
120
+
121
+ export function assertJsonValue(
122
+ value: unknown,
123
+ path: string,
124
+ seen: Set<object> = new Set<object>(),
125
+ ): void {
126
+ if (value === null) {
127
+ return;
128
+ }
129
+ switch (typeof value) {
130
+ case "string":
131
+ case "boolean":
132
+ return;
133
+ case "number":
134
+ if (!Number.isFinite(value)) {
135
+ fail(path, "must be a finite number");
136
+ }
137
+ return;
138
+ case "object": {
139
+ if (seen.has(value)) {
140
+ fail(path, "must not contain circular references");
141
+ }
142
+ if (Object.getOwnPropertySymbols(value).length > 0) {
143
+ fail(path, "must not contain symbol keys");
144
+ }
145
+ seen.add(value);
146
+ if (Array.isArray(value)) {
147
+ value.forEach((item, index) =>
148
+ assertJsonValue(item, `${path}[${index}]`, seen),
149
+ );
150
+ } else if (isRecord(value)) {
151
+ for (const [key, item] of Object.entries(value)) {
152
+ assertJsonValue(item, `${path}.${key}`, seen);
153
+ }
154
+ } else {
155
+ fail(path, "must be JSON-serializable");
156
+ }
157
+ seen.delete(value);
158
+ return;
159
+ }
160
+ default:
161
+ fail(path, `must be JSON-serializable (got ${typeof value})`);
162
+ }
163
+ }
164
+
165
+ export function cloneJson<T>(value: unknown, path: string): T {
166
+ assertJsonValue(value, path);
167
+ return JSON.parse(JSON.stringify(value)) as T;
168
+ }
169
+
170
+ export function normalizeAgent(value: unknown, path: string): AgentSpec {
171
+ const record = expectRecord(value, path);
172
+ assertOnlyKeys(record, AGENT_FIELDS, path);
173
+
174
+ const id = expectEngineId(record.id, `${path}.id`);
175
+ const prompt = expectString(record.prompt, `${path}.prompt`);
176
+ const cwd = expectString(record.cwd, `${path}.cwd`);
177
+
178
+ const spec: AgentSpec = { id, prompt, cwd };
179
+
180
+ const profile = expectOptionalString(record.profile, `${path}.profile`);
181
+ if (profile !== undefined) {
182
+ spec.profile = profile;
183
+ }
184
+
185
+ const model = expectOptionalString(record.model, `${path}.model`);
186
+ if (model !== undefined) {
187
+ spec.model = model;
188
+ }
189
+ const preset = expectOptionalString(record.preset, `${path}.preset`);
190
+ if (preset !== undefined) {
191
+ spec.preset = preset;
192
+ }
193
+
194
+ if (record.settings !== undefined) {
195
+ const settings = expectRecord(record.settings, `${path}.settings`);
196
+ spec.settings = cloneJson<Record<string, unknown>>(
197
+ settings,
198
+ `${path}.settings`,
199
+ );
200
+ }
201
+
202
+ const strategy = expectOptionalString(record.strategy, `${path}.strategy`);
203
+ if (strategy !== undefined) {
204
+ spec.strategy = strategy;
205
+ }
206
+
207
+ if (record.strategyInput !== undefined) {
208
+ spec.strategyInput = cloneJson<unknown>(
209
+ record.strategyInput,
210
+ `${path}.strategyInput`,
211
+ );
212
+ }
213
+
214
+ return spec;
215
+ }
216
+
217
+ export function normalizeArtifacts(
218
+ value: unknown,
219
+ path: string,
220
+ ): ArtifactDeclaration[] {
221
+ if (!Array.isArray(value)) {
222
+ fail(path, "must be an array");
223
+ }
224
+
225
+ const ids = new Set<string>();
226
+
227
+ return value.map((item, index) => {
228
+ const itemPath = `${path}[${index}]`;
229
+ const record = expectRecord(item, itemPath);
230
+ assertOnlyKeys(record, ARTIFACT_FIELDS, itemPath);
231
+
232
+ const id = expectId(record.id, `${itemPath}.id`);
233
+ if (ids.has(id)) {
234
+ fail(`${itemPath}.id`, `duplicate artifact id "${id}"`);
235
+ }
236
+ ids.add(id);
237
+
238
+ const type = record.type;
239
+ if (type !== "json" && type !== "text" && type !== "file") {
240
+ fail(`${itemPath}.type`, 'must be "json", "text" or "file"');
241
+ }
242
+
243
+ const artifact: ArtifactDeclaration = { id, type };
244
+
245
+ if (record.required !== undefined) {
246
+ if (typeof record.required !== "boolean") {
247
+ fail(`${itemPath}.required`, "must be a boolean");
248
+ }
249
+ artifact.required = record.required;
250
+ }
251
+
252
+ if (record.schema !== undefined) {
253
+ const schema = expectRecord(record.schema, `${itemPath}.schema`);
254
+ artifact.schema = cloneJson<Record<string, unknown>>(
255
+ schema,
256
+ `${itemPath}.schema`,
257
+ );
258
+ }
259
+
260
+ return artifact;
261
+ });
262
+ }
263
+
264
+ /**
265
+ * Validate and clone an untrusted RunPlan-shaped value. Wave IDs and agent IDs
266
+ * must be unique across the whole plan because core addresses agents by ID.
267
+ */
268
+ export function normalizeRunPlan(
269
+ value: unknown,
270
+ path = "workflow input",
271
+ ): RunPlan {
272
+ const record = expectRecord(value, path);
273
+ assertOnlyKeys(record, PLAN_FIELDS, path);
274
+
275
+ if (record.waves === undefined) {
276
+ fail(`${path}.waves`, "is required");
277
+ }
278
+ if (!Array.isArray(record.waves)) {
279
+ fail(`${path}.waves`, "must be an array");
280
+ }
281
+
282
+ const waveIds = new Set<string>();
283
+ const agentIds = new Set<string>();
284
+
285
+ const waves: WaveSpec[] = record.waves.map((waveValue, waveIndex) => {
286
+ const wavePath = `${path}.waves[${waveIndex}]`;
287
+ const waveRecord = expectRecord(waveValue, wavePath);
288
+ assertOnlyKeys(waveRecord, WAVE_FIELDS, wavePath);
289
+
290
+ const id = expectEngineId(waveRecord.id, `${wavePath}.id`);
291
+ if (waveIds.has(id)) {
292
+ fail(`${wavePath}.id`, `duplicate wave id "${id}"`);
293
+ }
294
+ waveIds.add(id);
295
+
296
+ if (waveRecord.agents === undefined) {
297
+ fail(`${wavePath}.agents`, "is required");
298
+ }
299
+ if (!Array.isArray(waveRecord.agents)) {
300
+ fail(`${wavePath}.agents`, "must be an array");
301
+ }
302
+ if (waveRecord.agents.length === 0) {
303
+ fail(`${wavePath}.agents`, "must contain at least one agent");
304
+ }
305
+
306
+ const agents = waveRecord.agents.map((agentValue, agentIndex) => {
307
+ const agentPath = `${wavePath}.agents[${agentIndex}]`;
308
+ const spec = normalizeAgent(agentValue, agentPath);
309
+ if (agentIds.has(spec.id)) {
310
+ fail(`${agentPath}.id`, `duplicate agent id "${spec.id}" across waves`);
311
+ }
312
+ agentIds.add(spec.id);
313
+ return spec;
314
+ });
315
+
316
+ return { id, agents };
317
+ });
318
+
319
+ const plan: RunPlan = { waves };
320
+
321
+ const profile = expectOptionalString(record.profile, `${path}.profile`);
322
+ if (profile !== undefined) {
323
+ plan.profile = profile;
324
+ }
325
+
326
+ if (record.artifacts !== undefined) {
327
+ plan.artifacts = normalizeArtifacts(record.artifacts, `${path}.artifacts`);
328
+ }
329
+
330
+ if (record.sealed !== undefined) {
331
+ if (typeof record.sealed !== "boolean") {
332
+ fail(`${path}.sealed`, "must be a boolean");
333
+ }
334
+ plan.sealed = record.sealed;
335
+ }
336
+
337
+ for (const key of ["scripts", "gates", "metadata"] as const) {
338
+ if (record[key] !== undefined) {
339
+ Object.assign(plan, { [key]: cloneJson(record[key], `${path}.${key}`) });
340
+ }
341
+ }
342
+ return plan;
343
+ }
@@ -0,0 +1,28 @@
1
+ import type { RunPlan, Strategy } from "@nones/agentflow-core";
2
+ import { fail, isRecord, normalizeRunPlan } from "./internal";
3
+
4
+ /**
5
+ * Workflow strategy. Its input is already a RunPlan; compilation validates and
6
+ * clones the value. `singleAdapter` is true because a workflow run must use one
7
+ * adapter ID across every agent and every append operation.
8
+ */
9
+ export const workflowStrategy: Strategy = {
10
+ id: "workflow",
11
+ singleAdapter: true,
12
+ compile(input: unknown): RunPlan {
13
+ const plan = normalizeRunPlan(input);
14
+ const payload = plan.metadata?.envelope?.payload;
15
+ if (
16
+ isRecord(payload) &&
17
+ Array.isArray(payload.unsupported) &&
18
+ payload.unsupported.length > 0
19
+ ) {
20
+ fail(
21
+ "plan",
22
+ "contains steps the scheduler cannot admit: " +
23
+ payload.unsupported.join(", "),
24
+ );
25
+ }
26
+ return plan;
27
+ },
28
+ };