@nones/agentflow-core 0.1.0 → 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/validation.ts CHANGED
@@ -1,12 +1,17 @@
1
1
  import { AgentFlowError } from "./errors";
2
2
  import { assertSerializable, isPlainObject } from "./json";
3
3
  import type {
4
+ AgentDefaults,
4
5
  AgentSpec,
5
6
  ArtifactDeclaration,
6
7
  ArtifactType,
8
+ PlanHandler,
9
+ PlanHandlerStep,
10
+ PlanStepRef,
7
11
  Profile,
8
12
  ProviderAdapter,
9
13
  RunPlan,
14
+ RunPlanMetadata,
10
15
  Strategy,
11
16
  WaveSpec,
12
17
  } from "./types";
@@ -18,8 +23,22 @@ export interface ValidatedPlan {
18
23
  artifacts: ArtifactDeclaration[];
19
24
  sealed: boolean;
20
25
  profile?: string;
26
+ /** Trusted non-agent steps, in declaration order. */
27
+ scripts: PlanHandlerStep[];
28
+ metadata?: RunPlanMetadata;
29
+ gates: PlanHandlerStep[];
21
30
  }
22
31
 
32
+ /** Step coordinates: `waveId` plus the step's ID inside that wave. */
33
+ const STEP_REF_KEYS: ReadonlySet<string> = new Set(["waveId", "id"]);
34
+
35
+ /**
36
+ * A step's `id`, `handler` and `dependsOn` may also carry executable-looking
37
+ * text from a template source. Only a safe handler name is accepted, so an
38
+ * unregistered snippet can never reach a runtime.
39
+ */
40
+ const HANDLER_NAME_SHAPE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/u;
41
+
23
42
  function fail(path: string, message: string): never {
24
43
  throw new AgentFlowError("validation", `${path}: ${message}`);
25
44
  }
@@ -88,7 +107,132 @@ export function validateRunPlan(input: unknown): ValidatedPlan {
88
107
  const profile = optionalString(input.profile, "plan.profile");
89
108
  const sealed = optionalBoolean(input.sealed, "plan.sealed") ?? false;
90
109
 
91
- return { waves, artifacts, sealed, profile };
110
+ const scripts = validateHandlerSteps(
111
+ input.scripts,
112
+ "script",
113
+ "plan.scripts",
114
+ waves,
115
+ );
116
+ const gates = validateHandlerSteps(input.gates, "gate", "plan.gates", waves);
117
+
118
+ if (input.metadata !== undefined && !isPlainObject(input.metadata)) {
119
+ fail("plan.metadata", "must be an object");
120
+ }
121
+ return {
122
+ waves,
123
+ artifacts,
124
+ sealed,
125
+ profile,
126
+ scripts,
127
+ gates,
128
+ ...(input.metadata === undefined
129
+ ? {}
130
+ : { metadata: input.metadata as unknown as RunPlanMetadata }),
131
+ };
132
+ }
133
+
134
+ function parseStepRef(value: unknown, path: string): PlanStepRef {
135
+ if (!isPlainObject(value)) fail(path, "must be an object");
136
+ for (const key of Object.keys(value)) {
137
+ if (!STEP_REF_KEYS.has(key)) {
138
+ fail(`${path}.${key}`, "is not a supported step reference field");
139
+ }
140
+ }
141
+ const waveId = assertId(value.waveId, `${path}.waveId`);
142
+ const id = assertId(value.id, `${path}.id`);
143
+ return { waveId, id };
144
+ }
145
+
146
+ function validateHandlerSteps(
147
+ input: unknown,
148
+ kind: "script" | "gate",
149
+ path: string,
150
+ waves: WaveSpec[],
151
+ ): PlanHandlerStep[] {
152
+ if (input === undefined) return [];
153
+ if (!Array.isArray(input)) fail(path, "must be an array");
154
+ const waveIds = new Set(waves.map((wave) => wave.id));
155
+ const seen = new Set<string>();
156
+ return input.map((raw, index) => {
157
+ const stepPath = `${path}[${index}]`;
158
+ if (!isPlainObject(raw)) fail(stepPath, "must be an object");
159
+ const stepId = assertId(raw.id, `${stepPath}.id`);
160
+ if (seen.has(stepId)) {
161
+ fail(`${stepPath}.id`, `duplicate ${kind} step id ${stepId}`);
162
+ }
163
+ seen.add(stepId);
164
+ for (const key of Object.keys(raw)) {
165
+ if (
166
+ key !== "id" &&
167
+ key !== "kind" &&
168
+ key !== "handler" &&
169
+ key !== "handlerVersion" &&
170
+ key !== "waveId" &&
171
+ key !== "dependsOn" &&
172
+ key !== "description" &&
173
+ key !== "cwd"
174
+ ) {
175
+ fail(
176
+ `${stepPath}.${key}`,
177
+ "is not a supported step field; a plan step declares only a trusted handler",
178
+ );
179
+ }
180
+ }
181
+ if (raw.kind !== undefined && raw.kind !== kind) {
182
+ fail(`${stepPath}.kind`, `must be ${kind}`);
183
+ }
184
+ const handler = assertId(raw.handler, `${stepPath}.handler`);
185
+ if (!HANDLER_NAME_SHAPE.test(handler)) {
186
+ fail(
187
+ `${stepPath}.handler`,
188
+ "must be a registered handler name, not executable text",
189
+ );
190
+ }
191
+ const handlerVersion = optionalString(
192
+ raw.handlerVersion,
193
+ `${stepPath}.handlerVersion`,
194
+ );
195
+ if (handlerVersion !== undefined && handlerVersion.trim() === "") {
196
+ fail(`${stepPath}.handlerVersion`, "must be a non-empty string");
197
+ }
198
+ const waveId =
199
+ optionalString(raw.waveId, `${stepPath}.waveId`) ??
200
+ (waves.length === 1 ? waves[0]?.id : undefined);
201
+ if (waveId === undefined) {
202
+ fail(`${stepPath}.waveId`, "must identify a wave in the plan");
203
+ }
204
+ if (!waveIds.has(waveId)) {
205
+ fail(`${stepPath}.waveId`, `unknown wave ${waveId}`);
206
+ }
207
+ const cwd = optionalString(raw.cwd, `${stepPath}.cwd`);
208
+ if (cwd !== undefined && cwd === "") {
209
+ fail(`${stepPath}.cwd`, "must be a non-empty string");
210
+ }
211
+ const description = optionalString(
212
+ raw.description,
213
+ `${stepPath}.description`,
214
+ );
215
+ const dependsRaw = raw.dependsOn;
216
+ let dependsOn: PlanStepRef[] | undefined;
217
+ if (dependsRaw !== undefined) {
218
+ if (!Array.isArray(dependsRaw)) {
219
+ fail(`${stepPath}.dependsOn`, "must be an array of step references");
220
+ }
221
+ dependsOn = dependsRaw.map((ref, refIndex) =>
222
+ parseStepRef(ref, `${stepPath}.dependsOn[${refIndex}]`),
223
+ );
224
+ }
225
+ return {
226
+ id: stepId,
227
+ kind,
228
+ handler,
229
+ ...(handlerVersion === undefined ? {} : { handlerVersion }),
230
+ ...(dependsOn === undefined ? {} : { dependsOn }),
231
+ ...(description === undefined ? {} : { description }),
232
+ waveId,
233
+ ...(cwd === undefined ? {} : { cwd }),
234
+ };
235
+ });
92
236
  }
93
237
 
94
238
  function validateWave(
@@ -133,6 +277,10 @@ function validateAgent(
133
277
 
134
278
  const profile = optionalString(input.profile, `${path}.profile`);
135
279
  const model = optionalString(input.model, `${path}.model`);
280
+ const preset = optionalString(input.preset, `${path}.preset`);
281
+ if (preset !== undefined && preset.trim() === "") {
282
+ fail(`${path}.preset`, "must be a non-empty preset name");
283
+ }
136
284
  const strategy = optionalString(input.strategy, `${path}.strategy`);
137
285
  const settings = optionalSettings(input.settings, `${path}.settings`);
138
286
  let strategyInput: unknown;
@@ -152,11 +300,282 @@ function validateAgent(
152
300
  ...(profile === undefined ? {} : { profile }),
153
301
  ...(model === undefined ? {} : { model }),
154
302
  ...(settings === undefined ? {} : { settings }),
303
+ ...(preset === undefined ? {} : { preset }),
155
304
  ...(strategy === undefined ? {} : { strategy }),
156
305
  ...(strategyInput === undefined ? {} : { strategyInput }),
157
306
  };
158
307
  }
159
308
 
309
+ const DEFAULT_PATH_KEYS = ["skillDirectories", "contextFiles"] as const;
310
+
311
+ /**
312
+ * Validate one `AgentDefaults` value. Unknown fields are rejected: this shape
313
+ * only carries the three documented defaults, so a typo cannot silently do
314
+ * nothing on the server.
315
+ */
316
+ export function validateAgentDefaults(
317
+ value: unknown,
318
+ path: string,
319
+ ): AgentDefaults | undefined {
320
+ if (value === undefined) return undefined;
321
+ if (!isPlainObject(value)) fail(path, "must be a plain object");
322
+ for (const key of Object.keys(value)) {
323
+ if (key !== "profile" && key !== "model" && key !== "settings") {
324
+ fail(`${path}.${key}`, "is not a supported agent default field");
325
+ }
326
+ }
327
+ const profile = optionalString(value.profile, `${path}.profile`);
328
+ if (profile !== undefined && profile.trim() === "") {
329
+ fail(`${path}.profile`, "must be a non-empty profile ID");
330
+ }
331
+ const model = optionalString(value.model, `${path}.model`);
332
+ if (model !== undefined && model.trim() === "") {
333
+ fail(`${path}.model`, "must be a non-empty model ID");
334
+ }
335
+ const settings = optionalSettings(value.settings, `${path}.settings`);
336
+ if (settings !== undefined) {
337
+ for (const key of DEFAULT_PATH_KEYS) {
338
+ const paths = settings[key];
339
+ if (
340
+ paths !== undefined &&
341
+ (!Array.isArray(paths) ||
342
+ paths.some(
343
+ (entry) => typeof entry !== "string" || entry.trim() === "",
344
+ ))
345
+ ) {
346
+ fail(`${path}.settings.${key}`, "must contain paths");
347
+ }
348
+ }
349
+ }
350
+ return {
351
+ ...(profile === undefined ? {} : { profile }),
352
+ ...(model === undefined ? {} : { model }),
353
+ ...(settings === undefined ? {} : { settings }),
354
+ };
355
+ }
356
+
357
+ /** Validate a named preset map (`subagents`). */
358
+ export function validateAgentDefaultsMap(
359
+ value: unknown,
360
+ path: string,
361
+ ): Record<string, AgentDefaults> {
362
+ if (value === undefined) return {};
363
+ if (!isPlainObject(value)) {
364
+ fail(path, "must be an object keyed by preset name");
365
+ }
366
+ const result: Record<string, AgentDefaults> = {};
367
+ for (const [name, raw] of Object.entries(value)) {
368
+ if (name.trim() === "") {
369
+ fail(path, "preset names must be non-empty");
370
+ }
371
+ if (name === "__proto__") {
372
+ fail(`${path}.${name}`, "is not a valid preset name");
373
+ }
374
+ const defaults = validateAgentDefaults(raw, `${path}.${name}`);
375
+ if (defaults !== undefined) result[name] = defaults;
376
+ }
377
+ return result;
378
+ }
379
+
380
+ export interface ResolveAgentDefaultsOptions {
381
+ agentDefaults?: AgentDefaults;
382
+ subagents?: Record<string, AgentDefaults>;
383
+ profiles: ReadonlyMap<string, Profile>;
384
+ /** Profile selected for the run; the fallback when nothing names one. */
385
+ runProfile: Profile;
386
+ }
387
+
388
+ /**
389
+ * Resolve the effective spec for one agent without persisting anything.
390
+ *
391
+ * Precedence is explicit agent script fields, then the explicitly selected
392
+ * named preset, then `agentDefaults`. The model keeps that order, then prefers
393
+ * the configured profile model over a generic `agentDefaults` fallback. A
394
+ * profile model is left for the provider to resolve instead of being copied
395
+ * into the spec. An unknown preset or profile fails here, before admission.
396
+ */
397
+ export function applyAgentDefaults(
398
+ spec: AgentSpec,
399
+ options: ResolveAgentDefaultsOptions,
400
+ ): AgentSpec {
401
+ const preset =
402
+ spec.preset === undefined
403
+ ? undefined
404
+ : presetByName(options.subagents, spec.preset);
405
+ if (spec.preset !== undefined && preset === undefined) {
406
+ const names = Object.keys(options.subagents ?? {}).sort();
407
+ fail(
408
+ `agent ${spec.id}`,
409
+ `preset "${spec.preset}" is not configured` +
410
+ (names.length === 0
411
+ ? "; no subagent presets are configured"
412
+ : `; configured presets: ${names.join(", ")}`),
413
+ );
414
+ }
415
+
416
+ const defaults = options.agentDefaults;
417
+ const profileId = spec.profile ?? preset?.profile ?? defaults?.profile;
418
+ const profile =
419
+ profileId === undefined
420
+ ? options.runProfile
421
+ : options.profiles.get(profileId);
422
+ if (profile === undefined) {
423
+ fail(`agent ${spec.id}`, `profile "${profileId}" is not configured`);
424
+ }
425
+
426
+ // Model priority: explicit agent (direct, then settings) > named preset >
427
+ // configured profile > generic agentDefaults. A profile model is not copied
428
+ // into the spec: the provider already resolves it, and object-form
429
+ // `settings.model` values must survive untouched.
430
+ const specModel = modelChoice(spec);
431
+ const presetModel = modelChoice(preset);
432
+ const profileModel = modelChoice(profile);
433
+ const defaultsModel = modelChoice(defaults);
434
+ let model: string | undefined;
435
+ let modelLayer: "spec" | "preset" | "profile" | "defaults" | "none";
436
+ if (specModel.present) {
437
+ modelLayer = "spec";
438
+ } else if (presetModel.present) {
439
+ modelLayer = "preset";
440
+ model = presetModel.value;
441
+ } else if (profileModel.present) {
442
+ modelLayer = "profile";
443
+ } else if (defaultsModel.present) {
444
+ modelLayer = "defaults";
445
+ model = defaultsModel.value;
446
+ } else {
447
+ modelLayer = "none";
448
+ }
449
+
450
+ // Keep each layer's `model` out of the settings merge, then attach only the
451
+ // winning settings form. Otherwise a generic `agentDefaults.settings.model`
452
+ // would look like an explicit agent setting and beat `profile.model` inside
453
+ // the provider.
454
+ const baseSettings = mergeSettings(
455
+ withoutSettingsModel(defaults?.settings),
456
+ withoutSettingsModel(preset?.settings),
457
+ withoutSettingsModel(spec?.settings),
458
+ );
459
+ const settingsModel = settingsModelEntry(spec.settings);
460
+ const winningSettingsModel = settingsModel.present
461
+ ? settingsModel
462
+ : modelLayer === "preset"
463
+ ? settingsModelEntry(preset?.settings)
464
+ : modelLayer === "defaults"
465
+ ? settingsModelEntry(defaults?.settings)
466
+ : { present: false as const };
467
+ const settings = winningSettingsModel.present
468
+ ? {
469
+ ...(baseSettings ?? {}),
470
+ model: winningSettingsModel.value,
471
+ }
472
+ : baseSettings;
473
+
474
+ return {
475
+ ...spec,
476
+ ...(profileId === undefined ? {} : { profile: profileId }),
477
+ ...(model === undefined ? {} : { model }),
478
+ ...(settings === undefined ||
479
+ (Object.keys(settings).length === 0 && spec.settings === undefined)
480
+ ? {}
481
+ : { settings }),
482
+ };
483
+ }
484
+
485
+ function withoutSettingsModel(
486
+ settings: Record<string, unknown> | undefined,
487
+ ): Record<string, unknown> | undefined {
488
+ if (settings === undefined || !Object.hasOwn(settings, "model")) {
489
+ return settings;
490
+ }
491
+ const { model: _model, ...rest } = settings;
492
+ return rest;
493
+ }
494
+
495
+ function settingsModelEntry(settings: Record<string, unknown> | undefined): {
496
+ present: boolean;
497
+ value?: unknown;
498
+ } {
499
+ if (
500
+ settings === undefined ||
501
+ !Object.hasOwn(settings, "model") ||
502
+ settings.model === undefined
503
+ ) {
504
+ return { present: false };
505
+ }
506
+ return { present: true, value: settings.model };
507
+ }
508
+
509
+ function presetByName(
510
+ subagents: Record<string, AgentDefaults> | undefined,
511
+ name: string,
512
+ ): AgentDefaults | undefined {
513
+ if (subagents === undefined || !Object.hasOwn(subagents, name)) {
514
+ return undefined;
515
+ }
516
+ const value = subagents[name];
517
+ return isPlainObject(value) ? (value as AgentDefaults) : undefined;
518
+ }
519
+
520
+ interface ModelChoice {
521
+ /** True when this layer configures a model, even as an object reference. */
522
+ present: boolean;
523
+ /** The string form to copy, when this layer uses one. */
524
+ value?: string;
525
+ }
526
+
527
+ function modelChoice(
528
+ layer: { model?: unknown; settings?: Record<string, unknown> } | undefined,
529
+ ): ModelChoice {
530
+ if (layer === undefined) return { present: false };
531
+ const direct = modelValue(layer.model);
532
+ if (direct.present) return direct;
533
+ return modelValue(layer.settings?.model);
534
+ }
535
+
536
+ function modelValue(value: unknown): ModelChoice {
537
+ if (value === undefined || value === null || value === "") {
538
+ return { present: false };
539
+ }
540
+ if (typeof value === "string") {
541
+ return value.trim() === "" ? { present: false } : { present: true, value };
542
+ }
543
+ // Object-form references (for example OpenCode's providerID + model id) are
544
+ // valid; keep them in place instead of overriding them with a fallback.
545
+ return { present: true };
546
+ }
547
+
548
+ function mergeSettings(
549
+ ...layers: Array<Record<string, unknown> | undefined>
550
+ ): Record<string, unknown> | undefined {
551
+ let merged: Record<string, unknown> | undefined;
552
+ for (const layer of layers) {
553
+ if (layer === undefined) continue;
554
+ merged =
555
+ merged === undefined ? { ...layer } : mergePlainObjects(merged, layer);
556
+ }
557
+ return merged;
558
+ }
559
+
560
+ function mergePlainObjects(
561
+ base: Record<string, unknown>,
562
+ incoming: Record<string, unknown>,
563
+ ): Record<string, unknown> {
564
+ const result: Record<string, unknown> = { ...base };
565
+ for (const [key, value] of Object.entries(incoming)) {
566
+ // Never let a data key mutate the merged object's prototype.
567
+ if (key === "__proto__") continue;
568
+ const current = result[key];
569
+ // A model reference is a single value. Merge it one level only so an
570
+ // object-form model is replaced whole rather than mixed field by field.
571
+ result[key] =
572
+ key !== "model" && isPlainObject(current) && isPlainObject(value)
573
+ ? mergePlainObjects(current, value)
574
+ : value;
575
+ }
576
+ return result;
577
+ }
578
+
160
579
  function validateArtifact(
161
580
  input: unknown,
162
581
  index: number,
@@ -309,3 +728,41 @@ export function validateStrategies(strategies: unknown): Strategy[] {
309
728
  return candidate;
310
729
  });
311
730
  }
731
+
732
+ /** `name@version` registry key used for handler lookup. */
733
+ export function handlerKey(name: string, version: string): string {
734
+ return `${name}@${version}`;
735
+ }
736
+
737
+ /**
738
+ * Validate the trusted handler registry. An empty or omitted registry is valid
739
+ * and simply means the daemon executes no script or gate step; a plan that
740
+ * references one is then rejected before admission.
741
+ */
742
+ export function validateHandlers(handlers: unknown): PlanHandler[] {
743
+ if (handlers === undefined) return [];
744
+ if (!Array.isArray(handlers)) fail("handlers", "must be an array");
745
+ const keys = new Set<string>();
746
+ return handlers.map((handler, index) => {
747
+ const path = `handlers[${index}]`;
748
+ if (handler === null || typeof handler !== "object") {
749
+ fail(path, "must be an object");
750
+ }
751
+ const candidate = handler as PlanHandler;
752
+ const name = assertId(candidate.name, `${path}.name`);
753
+ if (!HANDLER_NAME_SHAPE.test(name)) {
754
+ fail(`${path}.name`, "must be a plain handler name");
755
+ }
756
+ const version = assertId(candidate.version, `${path}.version`);
757
+ const key = handlerKey(name, version);
758
+ if (keys.has(key)) fail(`${path}.version`, `duplicate handler ${key}`);
759
+ keys.add(key);
760
+ if (candidate.kind !== "script" && candidate.kind !== "gate") {
761
+ fail(`${path}.kind`, "must be script or gate");
762
+ }
763
+ if (typeof candidate.run !== "function") {
764
+ fail(`${path}.run`, "must be a function");
765
+ }
766
+ return candidate;
767
+ });
768
+ }