@noetic-tools/core 5.19.1 → 5.19.2

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.
Files changed (146) hide show
  1. package/dist/adapters/openrouter.js +5 -0
  2. package/dist/builders/control-flow-builders.d.ts +15 -6
  3. package/dist/builders/control-flow-builders.js +8 -0
  4. package/dist/builders/decide-builders.d.ts +2 -5
  5. package/dist/builders/dynamic-workflow.d.ts +16 -1
  6. package/dist/builders/dynamic-workflow.js +222 -11
  7. package/dist/builders/every.d.ts +3 -3
  8. package/dist/builders/every.js +2 -1
  9. package/dist/builders/provide-builder.d.ts +3 -2
  10. package/dist/builders/provide-builder.js +2 -1
  11. package/dist/builders/sequence.d.ts +14 -0
  12. package/dist/builders/sequence.js +103 -0
  13. package/dist/builders/spawn-builder.d.ts +3 -2
  14. package/dist/builders/spawn-builder.js +3 -2
  15. package/dist/builders/step-builders.d.ts +80 -1
  16. package/dist/builders/step-builders.js +115 -1
  17. package/dist/builders/verify-builder.d.ts +79 -0
  18. package/dist/builders/verify-builder.js +69 -0
  19. package/dist/builders/workflow-child-nodes.d.ts +21 -0
  20. package/dist/builders/workflow-child-nodes.js +335 -0
  21. package/dist/builders/workflow-connection-nodes.d.ts +17 -0
  22. package/dist/builders/workflow-connection-nodes.js +160 -0
  23. package/dist/builders/workflow-connections.d.ts +90 -0
  24. package/dist/builders/workflow-connections.js +560 -0
  25. package/dist/builders/workflow-control-nodes.d.ts +13 -0
  26. package/dist/builders/workflow-control-nodes.js +213 -0
  27. package/dist/builders/workflow-hydrator.d.ts +44 -3
  28. package/dist/builders/workflow-hydrator.js +53 -495
  29. package/dist/builders/workflow-verify.d.ts +19 -0
  30. package/dist/builders/workflow-verify.js +194 -0
  31. package/dist/conditions/conditions.d.ts +7 -5
  32. package/dist/conditions/conditions.js +7 -4
  33. package/dist/connections/blobs.d.ts +33 -0
  34. package/dist/connections/blobs.js +77 -0
  35. package/dist/connections/cron-schedule.d.ts +32 -0
  36. package/dist/connections/cron-schedule.js +213 -0
  37. package/dist/connections/durability.d.ts +65 -0
  38. package/dist/connections/durability.js +54 -0
  39. package/dist/connections/errors.d.ts +30 -0
  40. package/dist/connections/errors.js +100 -0
  41. package/dist/connections/event-stream.d.ts +24 -0
  42. package/dist/connections/event-stream.js +176 -0
  43. package/dist/connections/gates.d.ts +94 -0
  44. package/dist/connections/gates.js +271 -0
  45. package/dist/connections/glob.d.ts +10 -0
  46. package/dist/connections/glob.js +46 -0
  47. package/dist/connections/handle.d.ts +22 -0
  48. package/dist/connections/handle.js +84 -0
  49. package/dist/connections/harness-wiring.d.ts +52 -0
  50. package/dist/connections/harness-wiring.js +143 -0
  51. package/dist/connections/in-memory-connection.d.ts +147 -0
  52. package/dist/connections/in-memory-connection.js +593 -0
  53. package/dist/connections/index.d.ts +34 -0
  54. package/dist/connections/index.js +23 -0
  55. package/dist/connections/json-schema.d.ts +28 -0
  56. package/dist/connections/json-schema.js +338 -0
  57. package/dist/connections/model-tools.d.ts +46 -0
  58. package/dist/connections/model-tools.js +466 -0
  59. package/dist/connections/negotiation.d.ts +30 -0
  60. package/dist/connections/negotiation.js +159 -0
  61. package/dist/connections/policy.d.ts +21 -0
  62. package/dist/connections/policy.js +34 -0
  63. package/dist/connections/pool.d.ts +111 -0
  64. package/dist/connections/pool.js +339 -0
  65. package/dist/connections/refs.d.ts +74 -0
  66. package/dist/connections/refs.js +316 -0
  67. package/dist/connections/registry-types.d.ts +141 -0
  68. package/dist/connections/registry-types.js +14 -0
  69. package/dist/connections/registry.d.ts +125 -0
  70. package/dist/connections/registry.js +775 -0
  71. package/dist/connections/secrets.d.ts +59 -0
  72. package/dist/connections/secrets.js +153 -0
  73. package/dist/connections/settle.d.ts +9 -0
  74. package/dist/connections/settle.js +26 -0
  75. package/dist/connections/sources.d.ts +27 -0
  76. package/dist/connections/sources.js +300 -0
  77. package/dist/connections/triggers.d.ts +78 -0
  78. package/dist/connections/triggers.js +310 -0
  79. package/dist/connections/values.d.ts +26 -0
  80. package/dist/connections/values.js +93 -0
  81. package/dist/connections/views.d.ts +31 -0
  82. package/dist/connections/views.js +176 -0
  83. package/dist/expression/check.js +80 -1
  84. package/dist/expression/jsonata.d.ts +14 -4
  85. package/dist/expression/jsonata.js +27 -9
  86. package/dist/expression/step-outputs.d.ts +25 -0
  87. package/dist/expression/step-outputs.js +78 -0
  88. package/dist/harness/agent-harness.d.ts +69 -166
  89. package/dist/harness/agent-harness.js +170 -262
  90. package/dist/harness/call-span-collector.d.ts +33 -0
  91. package/dist/harness/call-span-collector.js +83 -0
  92. package/dist/harness/connection-gate.d.ts +78 -0
  93. package/dist/harness/connection-gate.js +169 -0
  94. package/dist/harness/deps/interpreter.d.ts +1 -0
  95. package/dist/harness/deps/interpreter.js +1 -0
  96. package/dist/harness/deps/runtime.d.ts +1 -1
  97. package/dist/harness/deps/types.d.ts +1 -1
  98. package/dist/harness/harness-options.d.ts +153 -0
  99. package/dist/harness/harness-options.js +36 -0
  100. package/dist/harness/harness-tracing.d.ts +16 -0
  101. package/dist/harness/harness-tracing.js +35 -0
  102. package/dist/harness/llm-client.d.ts +71 -0
  103. package/dist/harness/llm-client.js +218 -0
  104. package/dist/harness/model-call.d.ts +2 -7
  105. package/dist/harness/model-call.js +21 -549
  106. package/dist/harness/model-request.d.ts +42 -0
  107. package/dist/harness/model-request.js +159 -0
  108. package/dist/harness/model-stream.d.ts +39 -0
  109. package/dist/harness/model-stream.js +131 -0
  110. package/dist/harness/model-tool-round.d.ts +37 -0
  111. package/dist/harness/model-tool-round.js +197 -0
  112. package/dist/harness/spend.d.ts +2 -0
  113. package/dist/harness/spend.js +5 -1
  114. package/dist/index.d.ts +31 -6
  115. package/dist/index.js +18 -1
  116. package/dist/interpreter/connection-steps.d.ts +194 -0
  117. package/dist/interpreter/connection-steps.js +537 -0
  118. package/dist/interpreter/execute-action.d.ts +2 -8
  119. package/dist/interpreter/execute-action.js +3 -178
  120. package/dist/interpreter/execute-call.d.ts +19 -0
  121. package/dist/interpreter/execute-call.js +99 -0
  122. package/dist/interpreter/execute-control.d.ts +6 -1
  123. package/dist/interpreter/execute-control.js +14 -0
  124. package/dist/interpreter/execute-invoke-tool.d.ts +11 -0
  125. package/dist/interpreter/execute-invoke-tool.js +183 -0
  126. package/dist/interpreter/execute-verify.d.ts +21 -0
  127. package/dist/interpreter/execute-verify.js +391 -0
  128. package/dist/interpreter/execute-wait.d.ts +21 -0
  129. package/dist/interpreter/execute-wait.js +233 -0
  130. package/dist/interpreter/execute.js +24 -133
  131. package/dist/interpreter/step-kind-dispatch.d.ts +24 -0
  132. package/dist/interpreter/step-kind-dispatch.js +157 -0
  133. package/dist/interpreter/step-walk.d.ts +2 -0
  134. package/dist/interpreter/step-walk.js +24 -0
  135. package/dist/interpreter/verify-host.d.ts +40 -0
  136. package/dist/interpreter/verify-host.js +245 -0
  137. package/dist/runtime/durable/step-ledger.d.ts +31 -1
  138. package/dist/runtime/durable/step-ledger.js +87 -1
  139. package/dist/runtime/in-memory-artifact-store.d.ts +24 -0
  140. package/dist/runtime/in-memory-artifact-store.js +240 -0
  141. package/dist/schemas/workflow.d.ts +2 -2
  142. package/dist/schemas/workflow.js +1 -1
  143. package/dist/util/harness-internals.d.ts +23 -0
  144. package/dist/util/harness-internals.js +35 -0
  145. package/package.json +3 -3
  146. package/schema/noetic-workflow.schema.json +1170 -92
@@ -6,81 +6,19 @@
6
6
  * ones — they register in the step registry, carry retry policies, etc.
7
7
  */
8
8
  import { frameworkCast, isServerToolSpec, NoeticConfigError } from '@noetic-tools/types';
9
- import { compileExpression, compute, passes, readInput } from '../expression/jsonata.js';
10
- import { all, any } from '../until/combinators.js';
11
- import { until } from '../until/predicates.js';
9
+ import { compileExpression, compute, readInput } from '../expression/jsonata.js';
10
+ import { markRecorded, stepOutputsOf } from '../expression/step-outputs.js';
11
+ import { shorthandStepId, stepEntryToNode, stepListEntries } from '../schemas/workflow.js';
12
12
  import { DetachedHandleImpl } from '../util/detached-handle.js';
13
- import { conditional, inParallel } from './control-flow-builders.js';
14
- import { decide, routeSwitch } from './decide-builders.js';
15
- import { schedule } from './every.js';
16
- import { loop } from './loop-builder.js';
17
13
  import { outputText } from './output-text.js';
18
- import { withContext } from './provide-builder.js';
19
- import { spawn } from './spawn-builder.js';
20
14
  import { callModel, runCode, step } from './step-builders.js';
15
+ import { hydrateInParallelNode, hydrateSpawnNode, hydrateSubflowNode, hydrateWithContextNode, } from './workflow-child-nodes.js';
16
+ import { hydrateCallNode, hydrateWaitNode } from './workflow-connection-nodes.js';
17
+ import { checkDocumentConnections } from './workflow-connections.js';
18
+ import { hydrateConditionalNode, hydrateDecideNode, hydrateLoopNode, hydrateRouteSwitchNode, hydrateScheduleNode, } from './workflow-control-nodes.js';
21
19
  import { documentScope, everyDocumentItem, hydrateEmitItems, nodeScope, } from './workflow-custom-items.js';
22
20
  import { workflowReplayKey } from './workflow-replay-key.js';
23
- //#endregion
24
- //#region Constants
25
- const DEFAULT_MAX_RECURSION_DEPTH = 100;
26
- //#endregion
27
- //#region Until Predicate Hydration
28
- /**
29
- * A `decide` predicate hydrates to the decide step itself; the loop runs it as
30
- * the decider. `where` names the loop in errors from its `expr` predicates.
31
- */
32
- function hydrateUntilPredicate(pred, ctx, where) {
33
- const hydrate = (p) => hydrateUntilPredicate(p, ctx, where);
34
- switch (pred.kind) {
35
- case 'maxSteps':
36
- return until.maxSteps(pred.n);
37
- case 'maxCost':
38
- return until.maxCost(pred.usd);
39
- case 'maxDuration':
40
- return until.maxDuration(pred.duration);
41
- case 'noToolCalls':
42
- return until.noToolCalls();
43
- case 'never':
44
- return until.never();
45
- case 'outputContains':
46
- return until.outputContains(pred.marker);
47
- case 'outputEquals':
48
- return until.outputEquals(pred.sentinel);
49
- case 'converged':
50
- return until.converged({
51
- threshold: pred.threshold,
52
- });
53
- case 'expr':
54
- return untilExpr(pred.expr, where, ctx.expressionLimits);
55
- case 'any':
56
- return any(...pred.predicates.map(hydrate));
57
- case 'all':
58
- return all(...pred.predicates.map(hydrate));
59
- case 'decide':
60
- return frameworkCast(hydrateNode(pred, ctx));
61
- default:
62
- throw new NoeticConfigError({
63
- code: 'UNKNOWN_UNTIL_PREDICATE',
64
- message: `Unknown until predicate kind: '${frameworkCast(pred).kind}'.`,
65
- hint: 'Supported kinds: maxSteps, maxCost, maxDuration, noToolCalls, never, outputContains, outputEquals, converged, expr, any, all, decide.',
66
- });
67
- }
68
- }
69
- /**
70
- * Stops when `expr` gives `true` against the loop's last output, read as an
71
- * expression input. A failing expression throws `NoeticConfigError`, which
72
- * fails the loop instead of stopping it (spec 05, Error Behavior).
73
- */
74
- function untilExpr(expr, where, limits) {
75
- const compiled = compileExpression(expr, where, limits);
76
- return async (snap) => {
77
- const stop = await passes(compiled, readInput(snap.lastOutput));
78
- return {
79
- stop,
80
- reason: stop ? `expr gave true: ${expr}` : undefined,
81
- };
82
- };
83
- }
21
+ import { hydrateVerifyNode } from './workflow-verify.js';
84
22
  //#endregion
85
23
  //#region Node Hydrators
86
24
  /**
@@ -231,215 +169,14 @@ function hydrateComputeNode(node, ctx) {
231
169
  const expr = compileExpression(node.expr, `compute node '${node.id}'`, ctx.expressionLimits);
232
170
  return frameworkCast(runCode({
233
171
  id: node.id,
234
- execute: async (input) => outputText(await compute(expr, readInput(input))),
235
- }));
236
- }
237
- function hydrateConditionalNode(node, ctx) {
238
- if (node.kind !== 'conditional') {
239
- return frameworkCast(undefined);
240
- }
241
- const hydratedRoutes = node.routes.map((r, i) => ({
242
- passes: routeTest(r, `route ${i} of conditional node '${node.id}'`, ctx.expressionLimits),
243
- target: hydrateNode(r.target, ctx),
244
- }));
245
- const defaultTarget = node.default ? hydrateNode(node.default, ctx) : null;
246
- const allTargets = hydratedRoutes.map((r) => r.target);
247
- if (defaultTarget) {
248
- allTargets.push(defaultTarget);
249
- }
250
- return conditional({
251
- id: node.id,
252
- route: async (input) => {
253
- const view = {
254
- text: routeText(input).trim().toLowerCase(),
255
- value: readInput(input),
256
- };
257
- for (const r of hydratedRoutes) {
258
- if (await r.passes(view)) {
259
- return r.target;
260
- }
261
- }
262
- return defaultTarget;
263
- },
264
- _optimizable: frameworkCast(allTargets),
265
- });
266
- }
267
- function routeTest(route, where, limits) {
268
- if (route.expr !== undefined) {
269
- const compiled = compileExpression(route.expr, where, limits);
270
- return (input) => passes(compiled, input.value);
271
- }
272
- const needle = (route.match ?? '').toLowerCase();
273
- return (input) => input.text.includes(needle);
274
- }
275
- function hydrateDecideNode(node, _ctx) {
276
- if (node.kind !== 'decide') {
277
- return frameworkCast(undefined);
278
- }
279
- return frameworkCast(decideFromNode(node));
280
- }
281
- function decideFromNode(node) {
282
- return decide({
283
- id: node.id,
284
- model: node.model,
285
- instructions: node.instructions,
286
- questions: node.questions,
287
- view: node.view,
288
- samples: node.samples,
289
- });
290
- }
291
- function hydrateRouteSwitchNode(node, ctx) {
292
- if (node.kind !== 'routeSwitch') {
293
- return frameworkCast(undefined);
294
- }
295
- const cases = {};
296
- for (const [key, target] of Object.entries(node.cases)) {
297
- cases[key] = hydrateNode(target, ctx);
298
- }
299
- // A JSON node's outcomes are only known at runtime; the builder checks them.
300
- return frameworkCast(routeSwitch({
301
- id: node.id,
302
- decide: decideFromNode(node.decide),
303
- on: node.on,
304
- cases: frameworkCast(cases),
305
- minConfidence: node.minConfidence,
306
- uncertain: hydrateNode(node.uncertain, ctx),
172
+ execute: async (input, execCtx) => outputText(await compute(expr, readInput(input), bindingsFor(execCtx, ctx))),
307
173
  }));
308
174
  }
309
- function hydrateInParallelNode(node, ctx) {
310
- if (node.kind !== 'inParallel') {
311
- return frameworkCast(undefined);
312
- }
313
- // Static inParallel: paths are known at hydration time and feed the optimizer.
314
- // Dynamic inParallel (`each`): paths are produced per inParallel-input at runtime, one
315
- // child per array item, so they cannot be pre-computed or optimized.
316
- const dynamic = node.each !== undefined;
317
- const eachTemplate = node.each;
318
- const staticPaths = dynamic ? [] : (node.paths ?? []).map((p) => hydrateNode(p, ctx));
319
- const pathsFactory = (input) => {
320
- if (!dynamic || !eachTemplate) {
321
- return staticPaths;
322
- }
323
- const items = selectArray(input, node.over, node.id);
324
- return items.map((item, i) => buildPerItemStep({
325
- forkId: node.id,
326
- eachTemplate,
327
- item,
328
- index: i,
329
- ctx,
330
- }));
331
- };
332
- const optimizable = dynamic ? undefined : frameworkCast(staticPaths);
333
- if (node.mode === 'race') {
334
- return inParallel({
335
- id: node.id,
336
- mode: 'race',
337
- paths: pathsFactory,
338
- concurrency: node.concurrency,
339
- _optimizable: optimizable,
340
- });
341
- }
342
- const mergeFn = buildMerge(node.merge ?? 'last');
343
- if (node.mode === 'settle') {
344
- return inParallel({
345
- id: node.id,
346
- mode: 'settle',
347
- paths: pathsFactory,
348
- merge: (results) => {
349
- const values = results.filter((r) => r.status === 'fulfilled').map((r) => r.value ?? '');
350
- return mergeFn(values);
351
- },
352
- concurrency: node.concurrency,
353
- _optimizable: optimizable,
354
- });
355
- }
356
- return inParallel({
357
- id: node.id,
358
- mode: 'all',
359
- paths: pathsFactory,
360
- merge: mergeFn,
361
- concurrency: node.concurrency,
362
- _optimizable: optimizable,
363
- });
364
- }
365
- /**
366
- * Resolves layer names declared on a `withContext` / `spawn` node against the
367
- * registry on `HydrationContext.layers`. Returns `[]` when no registry was
368
- * supplied — the host runs with its harness-default layers in that case.
369
- */
370
- function resolveNamedLayers({ names, nodeKind, nodeId, ctx, }) {
371
- if (!ctx.layers) {
372
- return [];
373
- }
374
- return names.map((name) => {
375
- const layer = ctx.layers?.get(name);
376
- if (!layer) {
377
- throw new NoeticConfigError({
378
- code: 'UNKNOWN_LAYER_REFERENCE',
379
- message: `Context layer '${name}' referenced in ${nodeKind} node '${nodeId}' is not registered.`,
380
- hint: `Available layers: ${[
381
- ...(ctx.layers?.keys() ?? []),
382
- ].join(', ') || '(none)'}. Pass named layers via HydrationContext.layers.`,
383
- });
384
- }
385
- return layer;
386
- });
387
- }
388
- function hydrateSpawnNode(node, ctx) {
389
- if (node.kind !== 'spawn') {
390
- return frameworkCast(undefined);
391
- }
392
- // `context` is left undefined when the node names no layers so the child
393
- // inherits the parent's layers (spec 04). An explicit list replaces them.
394
- const resolvedLayers = node.layers
395
- ? resolveNamedLayers({
396
- names: node.layers,
397
- nodeKind: 'spawn',
398
- nodeId: node.id,
399
- ctx,
400
- })
401
- : undefined;
402
- return spawn({
403
- id: node.id,
404
- child: hydrateNode(node.child, ctx),
405
- timeout: node.timeout,
406
- context: resolvedLayers,
407
- steers: node.steers,
408
- });
409
- }
410
- function hydrateWithContextNode(node, ctx) {
411
- if (node.kind !== 'withContext') {
412
- return frameworkCast(undefined);
413
- }
414
- return withContext({
415
- id: node.id,
416
- child: hydrateNode(node.child, ctx),
417
- context: resolveNamedLayers({
418
- names: node.layers,
419
- nodeKind: 'withContext',
420
- nodeId: node.id,
421
- ctx,
422
- }),
423
- });
424
- }
425
- function hydrateLoopNode(node, ctx) {
426
- if (node.kind !== 'loop') {
427
- return frameworkCast(undefined);
428
- }
429
- return loop({
430
- id: node.id,
431
- steps: [
432
- hydrateNode(node.body, ctx),
433
- ],
434
- until: hydrateUntilPredicate(node.until, ctx, `until of loop node '${node.id}'`),
435
- maxIterations: node.maxIterations === 'infinity' ? Number.POSITIVE_INFINITY : node.maxIterations,
436
- });
437
- }
438
175
  function hydrateSequenceNode(node, ctx) {
439
176
  if (node.kind !== 'sequence') {
440
177
  return frameworkCast(undefined);
441
178
  }
442
- const children = node.steps.map((s) => hydrateNode(s, ctx));
179
+ const children = node.steps.map((s, i) => hydrateNode(stepEntryToNode(s, shorthandStepId(node.id, i)), ctx));
443
180
  return frameworkCast(runCode({
444
181
  id: node.id,
445
182
  execute: async (input, execCtx) => {
@@ -452,17 +189,6 @@ function hydrateSequenceNode(node, ctx) {
452
189
  },
453
190
  }));
454
191
  }
455
- function hydrateScheduleNode(node, ctx) {
456
- if (node.kind !== 'schedule') {
457
- return frameworkCast(undefined);
458
- }
459
- return schedule({
460
- id: node.id,
461
- step: hydrateNode(node.step, ctx),
462
- interval: node.interval,
463
- onError: node.onError,
464
- });
465
- }
466
192
  function hydrateAcpAgentNode(node, ctx) {
467
193
  if (node.kind !== 'acp-agent') {
468
194
  return frameworkCast(undefined);
@@ -488,73 +214,41 @@ function hydrateAcpAgentNode(node, ctx) {
488
214
  session: node.session,
489
215
  });
490
216
  }
491
- /**
492
- * Hydrates a `subflow` node lazily: the target document resolves and hydrates
493
- * on first execution, memoized. Lazy because `HydrationContext.workflows` may
494
- * be a live view that gains entries after hydration, and because a recursive
495
- * ref must hydrate only the levels execution reaches — eager hydration of
496
- * A→A would never end. Each level gets its own tree whose ids carry the
497
- * calling node's (already suffixed) id, so levels never share step ids.
498
- */
499
- function hydrateSubflowNode(node, ctx) {
500
- if (node.kind !== 'subflow') {
501
- return frameworkCast(undefined);
502
- }
503
- let cached;
504
- const resolve = () => {
505
- if (!cached) {
506
- const { doc, childCtx } = resolveSubflowDocument(node, ctx);
507
- cached = hydrateNode(suffixNodeIds(doc.root, `-${node.id}`), {
508
- ...childCtx,
509
- customItems: documentScope(doc, ctx.customItems),
510
- });
511
- }
512
- return cached;
217
+ //#endregion
218
+ //#region Document Scope
219
+ /** Nodes hydrated outside any `hydrateWorkflow` (a bare `hydrateNode`) share one scope. */
220
+ const BARE_DOCUMENT_SCOPE = {};
221
+ /** The `$steps` scope of the document `ctx` is hydrating. */
222
+ export function documentScopeOf(ctx) {
223
+ return ctx.documentScope ?? BARE_DOCUMENT_SCOPE;
224
+ }
225
+ /** The bindings an expression evaluated in `execCtx` sees: `$steps`, and `$item` on a fan-out path. */
226
+ export function bindingsFor(execCtx, ctx) {
227
+ return {
228
+ steps: stepOutputsOf(execCtx, documentScopeOf(ctx)),
229
+ ...(ctx.fanOutItem === undefined
230
+ ? {}
231
+ : {
232
+ item: ctx.fanOutItem,
233
+ }),
513
234
  };
514
- return frameworkCast(runCode({
515
- id: node.id,
516
- execute: async (input, execCtx) => {
517
- const child = resolve();
518
- return outputText(await ctx.executeStep(child, node.input ?? input, execCtx));
519
- },
520
- }));
521
235
  }
522
- function resolveSubflowDocument(node, ctx) {
523
- if (node.document) {
524
- // Inline documents are finite JSON trees — they cannot recurse, so they
525
- // add nothing to the recursion depth.
526
- return {
527
- doc: node.document,
528
- childCtx: ctx,
529
- };
530
- }
531
- const ref = node.ref ?? '';
532
- const depth = (ctx.recursionDepth ?? 0) + 1;
533
- const limit = maxRecursionDepth(ctx);
534
- if (depth > limit) {
535
- throw new NoeticConfigError({
536
- code: 'WORKFLOW_RECURSION_LIMIT',
537
- message: `Sub-workflow '${ref}' referenced in subflow node '${node.id}' would resolve at recursion depth ${depth}, past the limit of ${limit}.`,
538
- hint: 'Give the recursion a base case (e.g. a conditional that stops calling the subflow), or raise maxRecursionDepth.',
539
- });
540
- }
541
- const doc = ctx.workflows?.get(ref);
542
- if (!doc) {
543
- throw new NoeticConfigError({
544
- code: 'UNKNOWN_WORKFLOW_REFERENCE',
545
- message: `Sub-workflow '${ref}' referenced in subflow node '${node.id}' is not registered.`,
546
- hint: `Pass named workflows via HydrationContext.workflows. Available: ${[
547
- ...(ctx.workflows?.keys() ?? []),
548
- ].join(', ') || '(none)'}.`,
549
- });
550
- }
551
- return {
552
- doc,
553
- childCtx: {
236
+ /**
237
+ * Hydrates a step list (`around`, `act`, a sequence's steps): each entry a node,
238
+ * or an operation written by name that becomes a `call` with id `<parentId>[i]`
239
+ * on `enclosing` (when given).
240
+ *
241
+ * @public
242
+ */
243
+ export function hydrateStepList(opts) {
244
+ const { list, parentId, ctx, enclosing } = opts;
245
+ const childCtx = enclosing === undefined
246
+ ? ctx
247
+ : {
554
248
  ...ctx,
555
- recursionDepth: depth,
556
- },
557
- };
249
+ enclosingConnection: enclosing,
250
+ };
251
+ return stepListEntries(list).map((entry, i) => frameworkCast(hydrateNode(stepEntryToNode(entry, shorthandStepId(parentId, i)), childCtx)));
558
252
  }
559
253
  //#endregion
560
254
  //#region Handler Registry
@@ -574,21 +268,13 @@ const NODE_HYDRATORS = {
574
268
  schedule: hydrateScheduleNode,
575
269
  subflow: hydrateSubflowNode,
576
270
  'acp-agent': hydrateAcpAgentNode,
271
+ call: hydrateCallNode,
272
+ wait: hydrateWaitNode,
273
+ // Owned by the verification slice (spec 37); it hydrates `act` through `hydrateStepList`.
274
+ verify: hydrateVerifyNode,
577
275
  };
578
276
  //#endregion
579
277
  //#region Helpers
580
- /** The context's recursion limit, defaulted; anything but a positive integer or `Infinity` throws. */
581
- function maxRecursionDepth(ctx) {
582
- const limit = ctx.maxRecursionDepth ?? DEFAULT_MAX_RECURSION_DEPTH;
583
- if (limit === Number.POSITIVE_INFINITY || (Number.isInteger(limit) && limit >= 1)) {
584
- return limit;
585
- }
586
- throw new NoeticConfigError({
587
- code: 'INVALID_MAX_RECURSION_DEPTH',
588
- message: `maxRecursionDepth must be a positive integer or Infinity, got ${limit}.`,
589
- hint: 'Pass a positive integer such as 100 (the default), or Infinity to let named workflows recurse without a limit.',
590
- });
591
- }
592
278
  function resolveTools(toolNames, registry) {
593
279
  if (!toolNames || toolNames.length === 0) {
594
280
  return [];
@@ -605,141 +291,6 @@ function resolveTools(toolNames, registry) {
605
291
  return resolved;
606
292
  });
607
293
  }
608
- /** Paths may return objects (a `decide` node's answers): `concat` writes them as JSON, `first`/`last` pass them through. */
609
- function buildMerge(strategy) {
610
- if (strategy === 'first') {
611
- return (r) => r[0] ?? '';
612
- }
613
- if (strategy === 'concat') {
614
- return (r) => r.map(outputText).join('\n');
615
- }
616
- return (r) => r[r.length - 1] ?? '';
617
- }
618
- /**
619
- * The text a branch matches against. An object input — a `decide` node's
620
- * answers, or their JSON once a sequence has stringified them — matches on its
621
- * string values only: its keys and probability maps name every choice, so
622
- * matching the JSON would hit every route.
623
- */
624
- function routeText(input) {
625
- const value = typeof input === 'string' ? parseJsonObject(input) : input;
626
- if (typeof value === 'string') {
627
- return value;
628
- }
629
- const values = [];
630
- const walk = (value) => {
631
- if (typeof value === 'string') {
632
- values.push(value);
633
- return;
634
- }
635
- if (typeof value !== 'object' || value === null) {
636
- return;
637
- }
638
- for (const child of Object.values(value)) {
639
- walk(child);
640
- }
641
- };
642
- walk(value);
643
- return values.join('\n');
644
- }
645
- /** The parsed object or array when `text` is one in JSON, else `text` itself. */
646
- function parseJsonObject(text) {
647
- const trimmed = text.trim();
648
- if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {
649
- return text;
650
- }
651
- try {
652
- const parsed = JSON.parse(trimmed);
653
- return typeof parsed === 'object' && parsed !== null ? parsed : text;
654
- }
655
- catch {
656
- return text;
657
- }
658
- }
659
- //#endregion
660
- //#region Dynamic Fork Helpers
661
- /**
662
- * Parses the inParallel input (a JSON string) and locates the array to fan out over.
663
- * When `over` is set, reads that property off the parsed object; otherwise the
664
- * parsed value itself must be an array.
665
- */
666
- function selectArray(input, over, nodeId) {
667
- let parsed;
668
- try {
669
- parsed = JSON.parse(input);
670
- }
671
- catch {
672
- throw new NoeticConfigError({
673
- code: 'INVALID_FORK_INPUT',
674
- message: `Dynamic inParallel '${nodeId}' could not parse its input as JSON.`,
675
- hint: 'A dynamic inParallel (with `each`) expects its input to be a JSON array (or a JSON object when `over` is set).',
676
- });
677
- }
678
- const candidate = over === undefined ? parsed : frameworkCast(parsed)?.[over];
679
- if (!Array.isArray(candidate)) {
680
- throw new NoeticConfigError({
681
- code: 'INVALID_FORK_INPUT',
682
- message: `Dynamic inParallel '${nodeId}' did not resolve an array${over ? ` at key '${over}'` : ''}.`,
683
- hint: over
684
- ? `Ensure the input JSON object has an array at '${over}'.`
685
- : 'Ensure the input is a JSON array, or set `over` to select an array property.',
686
- });
687
- }
688
- return candidate;
689
- }
690
- /**
691
- * Builds one inParallel path for a single dynamic fan-out item. The item is injected as
692
- * the body's input (inParallel steps pass the same input to every path), and the
693
- * template's node ids are suffixed with `-${i}` so each instantiation has
694
- * unique ids for tracing and step-registry uniqueness.
695
- */
696
- function buildPerItemStep(opts) {
697
- const { forkId, eachTemplate, item, index, ctx } = opts;
698
- const hydratedEach = hydrateNode(suffixNodeIds(eachTemplate, `-${index}`), ctx);
699
- return frameworkCast(runCode({
700
- id: `${forkId}-item-${index}`,
701
- execute: async (_input, execCtx) => {
702
- const itemInput = JSON.stringify(item);
703
- return outputText(await ctx.executeStep(hydratedEach, itemInput, execCtx));
704
- },
705
- }));
706
- }
707
- /** Keys whose values are opaque data bags, never child workflow nodes. */
708
- const NON_NODE_KEYS = new Set([
709
- 'args',
710
- 'params',
711
- 'parameters',
712
- ]);
713
- /**
714
- * Deep-clones a workflow node template, appending `suffix` to the `id` of every
715
- * nested node so a per-item instantiation has globally-unique step ids.
716
- */
717
- function suffixNodeIds(node, suffix) {
718
- const clone = structuredClone(node);
719
- const walk = (value) => {
720
- if (!value || typeof value !== 'object') {
721
- return;
722
- }
723
- if (Array.isArray(value)) {
724
- for (const entry of value) {
725
- walk(entry);
726
- }
727
- return;
728
- }
729
- const record = frameworkCast(value);
730
- if (typeof record.kind === 'string' && typeof record.id === 'string') {
731
- record.id = `${record.id}${suffix}`;
732
- }
733
- for (const [key, child] of Object.entries(record)) {
734
- if (NON_NODE_KEYS.has(key)) {
735
- continue;
736
- }
737
- walk(child);
738
- }
739
- };
740
- walk(clone);
741
- return clone;
742
- }
743
294
  //#endregion
744
295
  //#region Run Node Helpers
745
296
  /**
@@ -826,6 +377,8 @@ export function hydrateNode(node, ctx) {
826
377
  });
827
378
  }
828
379
  const hydrated = hydrator(node, ctx);
380
+ // Its output becomes `$steps.<id>` for later expressions of its document once it completes.
381
+ markRecorded(hydrated, documentScopeOf(ctx));
829
382
  // Set in place rather than copied: builders register the step object itself.
830
383
  if (node.durable !== undefined) {
831
384
  hydrated.durable = node.durable;
@@ -856,11 +409,16 @@ export function hydrateNode(node, ctx) {
856
409
  * @param customItems - TypeScript declarations of the document's root custom items (spec 34).
857
410
  * @returns The root `Step` of the hydrated workflow.
858
411
  * @throws `NoeticConfigError` with code `CUSTOM_ITEM_MISMATCH` when `customItems` and the document give one name different types.
412
+ * @throws `NoeticConfigError` with code `CONNECTION_UNKNOWN` when a node uses a connection the document's `connections` do not declare, or `CONNECTION_INVALID` when a node's connection is neither named nor implied, or a source entry is used beyond its events.
859
413
  */
860
414
  export function hydrateWorkflow(doc, ctx, customItems) {
415
+ const connectionUses = checkDocumentConnections(doc);
861
416
  const root = hydrateNode(doc.root, {
862
417
  ...ctx,
418
+ documentScope: {},
863
419
  customItems: documentScope(doc, ctx.customItems, customItems),
420
+ connections: doc.connections ?? {},
421
+ connectionUses,
864
422
  });
865
423
  // The root's dispatch accepts every item the document declares before anything
866
424
  // runs or replays; keyed by type, they cannot shadow the root's own names.
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Hydrates the JSON `verify` node (spec 37 § In JSON, spec 26) into a
3
+ * `StepVerify`. Operations written by name in `act` — and `call`/`wait` nodes
4
+ * without a `connection` — run on the subject. A list subject hydrates one
5
+ * verify per connection (ids `<id>.<name>`, each with `act` on its own
6
+ * subject), run in parallel under the node's id with the worst outcome.
7
+ */
8
+ import type { ContextData } from '@noetic-tools/context';
9
+ import type { Step } from '@noetic-tools/types';
10
+ import type { WorkflowNode } from '../schemas/workflow.js';
11
+ import type { HydrationContext } from './workflow-hydrator.js';
12
+ /**
13
+ * Hydrates a JSON `verify` node.
14
+ *
15
+ * @public
16
+ * @throws `NoeticConfigError` `VERIFY_INVALID` for a matcher that names no sense or event;
17
+ * `CONNECTION_UNKNOWN` for a subject or witness the document's connections do not declare.
18
+ */
19
+ export declare function hydrateVerifyNode(node: WorkflowNode, ctx: HydrationContext): Step<ContextData, string, string>;