@noetic-tools/core 5.19.1 → 5.19.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.
Files changed (152) 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 +54 -2
  6. package/dist/builders/dynamic-workflow.js +247 -12
  7. package/dist/builders/every.d.ts +3 -3
  8. package/dist/builders/every.js +2 -1
  9. package/dist/builders/mcp-url-pattern.d.ts +13 -0
  10. package/dist/builders/mcp-url-pattern.js +85 -0
  11. package/dist/builders/provide-builder.d.ts +3 -2
  12. package/dist/builders/provide-builder.js +2 -1
  13. package/dist/builders/sequence.d.ts +14 -0
  14. package/dist/builders/sequence.js +103 -0
  15. package/dist/builders/spawn-builder.d.ts +3 -2
  16. package/dist/builders/spawn-builder.js +3 -2
  17. package/dist/builders/step-builders.d.ts +80 -1
  18. package/dist/builders/step-builders.js +115 -1
  19. package/dist/builders/verify-builder.d.ts +79 -0
  20. package/dist/builders/verify-builder.js +69 -0
  21. package/dist/builders/workflow-acp-grants.d.ts +42 -0
  22. package/dist/builders/workflow-acp-grants.js +224 -0
  23. package/dist/builders/workflow-child-nodes.d.ts +21 -0
  24. package/dist/builders/workflow-child-nodes.js +336 -0
  25. package/dist/builders/workflow-connection-nodes.d.ts +25 -0
  26. package/dist/builders/workflow-connection-nodes.js +198 -0
  27. package/dist/builders/workflow-connections.d.ts +90 -0
  28. package/dist/builders/workflow-connections.js +560 -0
  29. package/dist/builders/workflow-control-nodes.d.ts +13 -0
  30. package/dist/builders/workflow-control-nodes.js +213 -0
  31. package/dist/builders/workflow-hydrator.d.ts +56 -3
  32. package/dist/builders/workflow-hydrator.js +53 -520
  33. package/dist/builders/workflow-mcp-servers.d.ts +24 -0
  34. package/dist/builders/workflow-mcp-servers.js +220 -0
  35. package/dist/builders/workflow-verify.d.ts +19 -0
  36. package/dist/builders/workflow-verify.js +194 -0
  37. package/dist/conditions/conditions.d.ts +7 -5
  38. package/dist/conditions/conditions.js +7 -4
  39. package/dist/connections/blobs.d.ts +33 -0
  40. package/dist/connections/blobs.js +77 -0
  41. package/dist/connections/cron-schedule.d.ts +32 -0
  42. package/dist/connections/cron-schedule.js +213 -0
  43. package/dist/connections/durability.d.ts +65 -0
  44. package/dist/connections/durability.js +54 -0
  45. package/dist/connections/errors.d.ts +30 -0
  46. package/dist/connections/errors.js +100 -0
  47. package/dist/connections/event-stream.d.ts +24 -0
  48. package/dist/connections/event-stream.js +176 -0
  49. package/dist/connections/gates.d.ts +94 -0
  50. package/dist/connections/gates.js +271 -0
  51. package/dist/connections/glob.d.ts +10 -0
  52. package/dist/connections/glob.js +46 -0
  53. package/dist/connections/handle.d.ts +22 -0
  54. package/dist/connections/handle.js +84 -0
  55. package/dist/connections/harness-wiring.d.ts +52 -0
  56. package/dist/connections/harness-wiring.js +143 -0
  57. package/dist/connections/in-memory-connection.d.ts +147 -0
  58. package/dist/connections/in-memory-connection.js +593 -0
  59. package/dist/connections/index.d.ts +34 -0
  60. package/dist/connections/index.js +23 -0
  61. package/dist/connections/json-schema.d.ts +28 -0
  62. package/dist/connections/json-schema.js +338 -0
  63. package/dist/connections/model-tools.d.ts +46 -0
  64. package/dist/connections/model-tools.js +466 -0
  65. package/dist/connections/negotiation.d.ts +30 -0
  66. package/dist/connections/negotiation.js +159 -0
  67. package/dist/connections/policy.d.ts +21 -0
  68. package/dist/connections/policy.js +34 -0
  69. package/dist/connections/pool.d.ts +111 -0
  70. package/dist/connections/pool.js +339 -0
  71. package/dist/connections/refs.d.ts +74 -0
  72. package/dist/connections/refs.js +316 -0
  73. package/dist/connections/registry-types.d.ts +141 -0
  74. package/dist/connections/registry-types.js +14 -0
  75. package/dist/connections/registry.d.ts +125 -0
  76. package/dist/connections/registry.js +775 -0
  77. package/dist/connections/secrets.d.ts +59 -0
  78. package/dist/connections/secrets.js +153 -0
  79. package/dist/connections/settle.d.ts +9 -0
  80. package/dist/connections/settle.js +26 -0
  81. package/dist/connections/sources.d.ts +27 -0
  82. package/dist/connections/sources.js +300 -0
  83. package/dist/connections/triggers.d.ts +78 -0
  84. package/dist/connections/triggers.js +310 -0
  85. package/dist/connections/values.d.ts +26 -0
  86. package/dist/connections/values.js +93 -0
  87. package/dist/connections/views.d.ts +31 -0
  88. package/dist/connections/views.js +176 -0
  89. package/dist/expression/check.js +80 -1
  90. package/dist/expression/jsonata.d.ts +14 -4
  91. package/dist/expression/jsonata.js +27 -9
  92. package/dist/expression/step-outputs.d.ts +25 -0
  93. package/dist/expression/step-outputs.js +78 -0
  94. package/dist/harness/agent-harness.d.ts +69 -166
  95. package/dist/harness/agent-harness.js +170 -262
  96. package/dist/harness/call-span-collector.d.ts +33 -0
  97. package/dist/harness/call-span-collector.js +83 -0
  98. package/dist/harness/connection-gate.d.ts +78 -0
  99. package/dist/harness/connection-gate.js +170 -0
  100. package/dist/harness/deps/interpreter.d.ts +1 -0
  101. package/dist/harness/deps/interpreter.js +1 -0
  102. package/dist/harness/deps/runtime.d.ts +1 -1
  103. package/dist/harness/deps/types.d.ts +1 -1
  104. package/dist/harness/harness-options.d.ts +153 -0
  105. package/dist/harness/harness-options.js +36 -0
  106. package/dist/harness/harness-tracing.d.ts +16 -0
  107. package/dist/harness/harness-tracing.js +35 -0
  108. package/dist/harness/llm-client.d.ts +71 -0
  109. package/dist/harness/llm-client.js +218 -0
  110. package/dist/harness/model-call.d.ts +2 -7
  111. package/dist/harness/model-call.js +21 -549
  112. package/dist/harness/model-request.d.ts +42 -0
  113. package/dist/harness/model-request.js +159 -0
  114. package/dist/harness/model-stream.d.ts +39 -0
  115. package/dist/harness/model-stream.js +131 -0
  116. package/dist/harness/model-tool-round.d.ts +37 -0
  117. package/dist/harness/model-tool-round.js +197 -0
  118. package/dist/harness/spend.d.ts +2 -0
  119. package/dist/harness/spend.js +5 -1
  120. package/dist/index.d.ts +33 -8
  121. package/dist/index.js +18 -1
  122. package/dist/interpreter/connection-steps.d.ts +194 -0
  123. package/dist/interpreter/connection-steps.js +537 -0
  124. package/dist/interpreter/execute-action.d.ts +2 -8
  125. package/dist/interpreter/execute-action.js +3 -178
  126. package/dist/interpreter/execute-call.d.ts +19 -0
  127. package/dist/interpreter/execute-call.js +99 -0
  128. package/dist/interpreter/execute-control.d.ts +6 -1
  129. package/dist/interpreter/execute-control.js +14 -0
  130. package/dist/interpreter/execute-invoke-tool.d.ts +11 -0
  131. package/dist/interpreter/execute-invoke-tool.js +183 -0
  132. package/dist/interpreter/execute-verify.d.ts +21 -0
  133. package/dist/interpreter/execute-verify.js +391 -0
  134. package/dist/interpreter/execute-wait.d.ts +21 -0
  135. package/dist/interpreter/execute-wait.js +233 -0
  136. package/dist/interpreter/execute.js +24 -133
  137. package/dist/interpreter/step-kind-dispatch.d.ts +24 -0
  138. package/dist/interpreter/step-kind-dispatch.js +157 -0
  139. package/dist/interpreter/step-walk.d.ts +2 -0
  140. package/dist/interpreter/step-walk.js +24 -0
  141. package/dist/interpreter/verify-host.d.ts +40 -0
  142. package/dist/interpreter/verify-host.js +245 -0
  143. package/dist/runtime/durable/step-ledger.d.ts +31 -1
  144. package/dist/runtime/durable/step-ledger.js +87 -1
  145. package/dist/runtime/in-memory-artifact-store.d.ts +24 -0
  146. package/dist/runtime/in-memory-artifact-store.js +240 -0
  147. package/dist/schemas/workflow.d.ts +2 -2
  148. package/dist/schemas/workflow.js +1 -1
  149. package/dist/util/harness-internals.d.ts +25 -0
  150. package/dist/util/harness-internals.js +35 -0
  151. package/package.json +3 -3
  152. package/schema/noetic-workflow.schema.json +1309 -180
@@ -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
- import { callModel, runCode, step } from './step-builders.js';
14
+ import { callModel, runCode } from './step-builders.js';
15
+ import { hydrateInParallelNode, hydrateSpawnNode, hydrateSubflowNode, hydrateWithContextNode, } from './workflow-child-nodes.js';
16
+ import { hydrateAcpAgentNode, 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),
172
+ execute: async (input, execCtx) => outputText(await compute(expr, readInput(input), bindingsFor(execCtx, ctx))),
244
173
  }));
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),
307
- }));
308
- }
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
174
  }
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,109 +189,41 @@ 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
- function hydrateAcpAgentNode(node, ctx) {
467
- if (node.kind !== 'acp-agent') {
468
- return frameworkCast(undefined);
469
- }
470
- const agent = ctx.acpAgents?.get(node.agent);
471
- if (!agent) {
472
- throw new NoeticConfigError({
473
- code: 'UNKNOWN_ACP_AGENT_REFERENCE',
474
- message: `ACP agent '${node.agent}' referenced in workflow node '${node.id}' is not registered.`,
475
- hint: 'Pass agent adapters via HydrationContext.acpAgents, e.g. createAcpAgentRegistry(claudeCode()) from @noetic-tools/acp.',
476
- });
477
- }
478
- return step.acpAgent({
479
- id: node.id,
480
- agent,
481
- prompt: node.prompt,
482
- cwd: node.cwd,
483
- mode: node.mode,
484
- model: node.model,
485
- mcpServers: node.mcpServers,
486
- permissions: node.permissions,
487
- clientCapabilities: node.clientCapabilities,
488
- session: node.session,
489
- });
192
+ //#endregion
193
+ //#region Document Scope
194
+ /** Nodes hydrated outside any `hydrateWorkflow` (a bare `hydrateNode`) share one scope. */
195
+ const BARE_DOCUMENT_SCOPE = {};
196
+ /** The `$steps` scope of the document `ctx` is hydrating. */
197
+ export function documentScopeOf(ctx) {
198
+ return ctx.documentScope ?? BARE_DOCUMENT_SCOPE;
199
+ }
200
+ /** The bindings an expression evaluated in `execCtx` sees: `$steps`, and `$item` on a fan-out path. */
201
+ export function bindingsFor(execCtx, ctx) {
202
+ return {
203
+ steps: stepOutputsOf(execCtx, documentScopeOf(ctx)),
204
+ ...(ctx.fanOutItem === undefined
205
+ ? {}
206
+ : {
207
+ item: ctx.fanOutItem,
208
+ }),
209
+ };
490
210
  }
491
211
  /**
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.
212
+ * Hydrates a step list (`around`, `act`, a sequence's steps): each entry a node,
213
+ * or an operation written by name that becomes a `call` with id `<parentId>[i]`
214
+ * on `enclosing` (when given).
215
+ *
216
+ * @public
498
217
  */
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;
513
- };
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
- }
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: {
218
+ export function hydrateStepList(opts) {
219
+ const { list, parentId, ctx, enclosing } = opts;
220
+ const childCtx = enclosing === undefined
221
+ ? ctx
222
+ : {
554
223
  ...ctx,
555
- recursionDepth: depth,
556
- },
557
- };
224
+ enclosingConnection: enclosing,
225
+ };
226
+ return stepListEntries(list).map((entry, i) => frameworkCast(hydrateNode(stepEntryToNode(entry, shorthandStepId(parentId, i)), childCtx)));
558
227
  }
559
228
  //#endregion
560
229
  //#region Handler Registry
@@ -574,21 +243,13 @@ const NODE_HYDRATORS = {
574
243
  schedule: hydrateScheduleNode,
575
244
  subflow: hydrateSubflowNode,
576
245
  'acp-agent': hydrateAcpAgentNode,
246
+ call: hydrateCallNode,
247
+ wait: hydrateWaitNode,
248
+ // Owned by the verification slice (spec 37); it hydrates `act` through `hydrateStepList`.
249
+ verify: hydrateVerifyNode,
577
250
  };
578
251
  //#endregion
579
252
  //#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
253
  function resolveTools(toolNames, registry) {
593
254
  if (!toolNames || toolNames.length === 0) {
594
255
  return [];
@@ -605,141 +266,6 @@ function resolveTools(toolNames, registry) {
605
266
  return resolved;
606
267
  });
607
268
  }
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
269
  //#endregion
744
270
  //#region Run Node Helpers
745
271
  /**
@@ -826,6 +352,8 @@ export function hydrateNode(node, ctx) {
826
352
  });
827
353
  }
828
354
  const hydrated = hydrator(node, ctx);
355
+ // Its output becomes `$steps.<id>` for later expressions of its document once it completes.
356
+ markRecorded(hydrated, documentScopeOf(ctx));
829
357
  // Set in place rather than copied: builders register the step object itself.
830
358
  if (node.durable !== undefined) {
831
359
  hydrated.durable = node.durable;
@@ -856,11 +384,16 @@ export function hydrateNode(node, ctx) {
856
384
  * @param customItems - TypeScript declarations of the document's root custom items (spec 34).
857
385
  * @returns The root `Step` of the hydrated workflow.
858
386
  * @throws `NoeticConfigError` with code `CUSTOM_ITEM_MISMATCH` when `customItems` and the document give one name different types.
387
+ * @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
388
  */
860
389
  export function hydrateWorkflow(doc, ctx, customItems) {
390
+ const connectionUses = checkDocumentConnections(doc);
861
391
  const root = hydrateNode(doc.root, {
862
392
  ...ctx,
393
+ documentScope: {},
863
394
  customItems: documentScope(doc, ctx.customItems, customItems),
395
+ connections: doc.connections ?? {},
396
+ connectionUses,
864
397
  });
865
398
  // The root's dispatch accepts every item the document declares before anything
866
399
  // runs or replays; keyed by type, they cannot shadow the root's own names.
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The MCP servers a document's `acp-agent` nodes hand to an agent. A stdio
3
+ * server is a command the agent launches, and a header or environment value
4
+ * reaches the agent process, so a document a host did not write may name only
5
+ * the servers the host's `mcp` allowlist grants (spec 26 § MCP servers).
6
+ */
7
+ import type { AcpMcpServer, Lazy, McpAllowlist, SecretResolver, WorkflowDocument, WorkflowMcpServer } from '@noetic-tools/types';
8
+ /**
9
+ * Checks every MCP server a document's `acp-agent` nodes name against the
10
+ * host's allowlist. No allowlist grants nothing. Inline subflows count; named
11
+ * refs resolve from the host's own registry and are not checked.
12
+ *
13
+ * @throws `NoeticConfigError` `CONNECTION_NOT_ALLOWED` for a server, header or environment value the allowlist does not grant, or a header or environment variable named twice.
14
+ * @throws `NoeticConfigError` `CONNECTION_INVALID` for a value that is a `$secret` when the harness has no `secrets` resolver, or an allowlist URL pattern that does not parse.
15
+ */
16
+ export declare function checkMcpServers(doc: WorkflowDocument, allowlist: McpAllowlist | undefined, secrets: SecretResolver | undefined): void;
17
+ /**
18
+ * The servers an `acp-agent` step gets: as written, or — when a value is a
19
+ * `$secret` — resolved through the harness's `environment.secrets` when the
20
+ * session starts.
21
+ */
22
+ export declare function stepMcpServers(servers: ReadonlyArray<WorkflowMcpServer> | undefined): Lazy<ReadonlyArray<AcpMcpServer> | undefined>;
23
+ /** The planner's view of the servers it may give an `acp-agent` node. */
24
+ export declare function mcpPrompt(allowlist: McpAllowlist | undefined): string;