@noetic-tools/core 5.11.0 → 5.13.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.
Files changed (36) hide show
  1. package/dist/adapters/in-memory-subprocess/step-completion.d.ts +2 -2
  2. package/dist/adapters/in-memory-subprocess/step-completion.js +48 -52
  3. package/dist/adapters/in-memory-subprocess/types.d.ts +3 -6
  4. package/dist/adapters/in-memory-subprocess-adapter.js +30 -48
  5. package/dist/adapters/live-handles.d.ts +26 -0
  6. package/dist/adapters/live-handles.js +50 -0
  7. package/dist/builders/dynamic-workflow.d.ts +19 -0
  8. package/dist/builders/dynamic-workflow.js +24 -3
  9. package/dist/builders/loop-builder.d.ts +4 -2
  10. package/dist/builders/loop-builder.js +7 -2
  11. package/dist/builders/workflow-hydrator.d.ts +17 -4
  12. package/dist/builders/workflow-hydrator.js +93 -32
  13. package/dist/builders/workflow-step.d.ts +10 -3
  14. package/dist/builders/workflow-step.js +8 -8
  15. package/dist/expression/check.d.ts +11 -0
  16. package/dist/expression/check.js +66 -0
  17. package/dist/expression/jsonata.d.ts +63 -0
  18. package/dist/expression/jsonata.js +258 -0
  19. package/dist/index.d.ts +15 -4
  20. package/dist/index.js +6 -3
  21. package/dist/interpreter/execute-control.js +50 -15
  22. package/dist/interpreter/execute-decide.d.ts +3 -1
  23. package/dist/interpreter/execute-decide.js +10 -0
  24. package/dist/interpreter/execute.js +1 -3
  25. package/dist/interpreter/step-dispatcher.d.ts +2 -2
  26. package/dist/interpreter/step-dispatcher.js +3 -5
  27. package/dist/interpreter/step-walk.js +8 -1
  28. package/dist/schemas/workflow.d.ts +1 -1
  29. package/dist/until/combinators.d.ts +12 -5
  30. package/dist/until/combinators.js +17 -8
  31. package/dist/until/decider.d.ts +11 -0
  32. package/dist/until/decider.js +63 -0
  33. package/dist/util/detached-handle.d.ts +9 -20
  34. package/dist/util/detached-handle.js +7 -108
  35. package/package.json +4 -3
  36. package/schema/noetic-workflow.schema.json +291 -4
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import type { ContextData, ContextLayer } from '@noetic-tools/context';
9
9
  import type { AcpAgent, ExecuteStepFn, OutputCodec, Step, SubprocessAdapter, Tool } from '@noetic-tools/types';
10
+ import type { ExpressionLimits } from '../expression/jsonata.js';
10
11
  import type { WorkflowDocument, WorkflowNode } from '../schemas/workflow.js';
11
12
  /** @public Context required to hydrate a JSON workflow into live steps. */
12
13
  export interface HydrationContext {
@@ -39,10 +40,17 @@ export interface HydrationContext {
39
40
  */
40
41
  workflows?: ReadonlyMap<string, WorkflowDocument>;
41
42
  /**
42
- * Ancestor ref chain for cycle detection on named sub-workflow references.
43
- * Threaded internally by the subflow hydrator — callers never set it.
43
+ * Deepest allowed chain of named-ref resolutions on one execution path.
44
+ * Positive integer or `Infinity`. Default: 100.
44
45
  */
45
- subflowAncestry?: ReadonlySet<string>;
46
+ maxRecursionDepth?: number;
47
+ /**
48
+ * Named-ref resolutions above the node being hydrated. Threaded internally
49
+ * by the subflow hydrator — callers never set it.
50
+ */
51
+ recursionDepth?: number;
52
+ /** Bounds on each expression evaluation; unset fields use `DEFAULT_EXPRESSION_LIMITS`. */
53
+ expressionLimits?: ExpressionLimits;
46
54
  }
47
55
  /**
48
56
  * Hydrates a single `WorkflowNode` into a live `Step`.
@@ -54,8 +62,13 @@ export interface HydrationContext {
54
62
  * @throws `NoeticConfigError` with code `UNKNOWN_NODE_KIND` if the node kind is unrecognised.
55
63
  * @throws `NoeticConfigError` with code `UNKNOWN_TOOL_REFERENCE` if a tool name cannot be resolved.
56
64
  * @throws `NoeticConfigError` with code `UNKNOWN_UNTIL_PREDICATE` if an until predicate kind is unrecognised.
65
+ * @throws `NoeticConfigError` with code `INVALID_UNTIL_DECIDER` if a decide until predicate does not ask exactly one boolean question.
57
66
  * @throws `NoeticConfigError` with code `UNKNOWN_WORKFLOW_REFERENCE` (at execution time) if a subflow ref names no registered workflow.
58
- * @throws `NoeticConfigError` with code `WORKFLOW_CYCLE` (at execution time) if named sub-workflow refs form a cycle.
67
+ * @throws `NoeticConfigError` with code `WORKFLOW_RECURSION_LIMIT` (at execution time) if named sub-workflow refs nest deeper than `maxRecursionDepth`.
68
+ * @throws `NoeticConfigError` with code `INVALID_MAX_RECURSION_DEPTH` (at execution time) when a named ref resolves under a `maxRecursionDepth` that is not a positive integer or `Infinity`.
69
+ * @throws `NoeticConfigError` with code `WORKFLOW_VALIDATION_FAILED` if a `compute` expression, a conditional route's `expr`, or an `expr` until predicate does not parse.
70
+ * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` if an expression compiles under `expressionLimits` holding a value that is not a positive integer or `Infinity`.
71
+ * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED` (at execution time) if an expression fails or exceeds its limits.
59
72
  */
60
73
  export declare function hydrateNode(node: WorkflowNode, ctx: HydrationContext): Step<ContextData, string, string>;
61
74
  /**
@@ -6,6 +6,7 @@
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';
9
10
  import { all, any } from '../until/combinators.js';
10
11
  import { until } from '../until/predicates.js';
11
12
  import { DetachedHandleImpl } from '../util/detached-handle.js';
@@ -18,8 +19,16 @@ import { spawn } from './spawn-builder.js';
18
19
  import { callModel, runCode, step } from './step-builders.js';
19
20
  import { workflowReplayKey } from './workflow-replay-key.js';
20
21
  //#endregion
22
+ //#region Constants
23
+ const DEFAULT_MAX_RECURSION_DEPTH = 100;
24
+ //#endregion
21
25
  //#region Until Predicate Hydration
22
- function hydrateUntilPredicate(pred) {
26
+ /**
27
+ * A `decide` predicate hydrates to the decide step itself; the loop runs it as
28
+ * the decider. `where` names the loop in errors from its `expr` predicates.
29
+ */
30
+ function hydrateUntilPredicate(pred, ctx, where) {
31
+ const hydrate = (p) => hydrateUntilPredicate(p, ctx, where);
23
32
  switch (pred.kind) {
24
33
  case 'maxSteps':
25
34
  return until.maxSteps(pred.n);
@@ -39,18 +48,37 @@ function hydrateUntilPredicate(pred) {
39
48
  return until.converged({
40
49
  threshold: pred.threshold,
41
50
  });
51
+ case 'expr':
52
+ return untilExpr(pred.expr, where, ctx.expressionLimits);
42
53
  case 'any':
43
- return any(...pred.predicates.map(hydrateUntilPredicate));
54
+ return any(...pred.predicates.map(hydrate));
44
55
  case 'all':
45
- return all(...pred.predicates.map(hydrateUntilPredicate));
56
+ return all(...pred.predicates.map(hydrate));
57
+ case 'decide':
58
+ return frameworkCast(hydrateNode(pred, ctx));
46
59
  default:
47
60
  throw new NoeticConfigError({
48
61
  code: 'UNKNOWN_UNTIL_PREDICATE',
49
62
  message: `Unknown until predicate kind: '${frameworkCast(pred).kind}'.`,
50
- hint: 'Supported kinds: maxSteps, maxCost, maxDuration, noToolCalls, never, outputContains, outputEquals, converged, any, all.',
63
+ hint: 'Supported kinds: maxSteps, maxCost, maxDuration, noToolCalls, never, outputContains, outputEquals, converged, expr, any, all, decide.',
51
64
  });
52
65
  }
53
66
  }
67
+ /**
68
+ * Stops when `expr` gives `true` against the loop's last output, read as an
69
+ * expression input. A failing expression throws `NoeticConfigError`, which
70
+ * fails the loop instead of stopping it (spec 05, Error Behavior).
71
+ */
72
+ function untilExpr(expr, where, limits) {
73
+ const compiled = compileExpression(expr, where, limits);
74
+ return async (snap) => {
75
+ const stop = await passes(compiled, readInput(snap.lastOutput));
76
+ return {
77
+ stop,
78
+ reason: stop ? `expr gave true: ${expr}` : undefined,
79
+ };
80
+ };
81
+ }
54
82
  //#endregion
55
83
  //#region Node Hydrators
56
84
  /**
@@ -194,12 +222,22 @@ function hydrateRunCodeNode(node, ctx) {
194
222
  },
195
223
  }));
196
224
  }
225
+ function hydrateComputeNode(node, ctx) {
226
+ if (node.kind !== 'compute') {
227
+ return frameworkCast(undefined);
228
+ }
229
+ const expr = compileExpression(node.expr, `compute node '${node.id}'`, ctx.expressionLimits);
230
+ return frameworkCast(runCode({
231
+ id: node.id,
232
+ execute: async (input) => stringifyResult(await compute(expr, readInput(input))),
233
+ }));
234
+ }
197
235
  function hydrateConditionalNode(node, ctx) {
198
236
  if (node.kind !== 'conditional') {
199
237
  return frameworkCast(undefined);
200
238
  }
201
- const hydratedRoutes = node.routes.map((r) => ({
202
- match: r.match,
239
+ const hydratedRoutes = node.routes.map((r, i) => ({
240
+ passes: routeTest(r, `route ${i} of conditional node '${node.id}'`, ctx.expressionLimits),
203
241
  target: hydrateNode(r.target, ctx),
204
242
  }));
205
243
  const defaultTarget = node.default ? hydrateNode(node.default, ctx) : null;
@@ -209,10 +247,13 @@ function hydrateConditionalNode(node, ctx) {
209
247
  }
210
248
  return conditional({
211
249
  id: node.id,
212
- route: (input) => {
213
- const trimmed = routeText(input).trim().toLowerCase();
250
+ route: async (input) => {
251
+ const view = {
252
+ text: routeText(input).trim().toLowerCase(),
253
+ value: readInput(input),
254
+ };
214
255
  for (const r of hydratedRoutes) {
215
- if (trimmed.includes(r.match.toLowerCase())) {
256
+ if (await r.passes(view)) {
216
257
  return r.target;
217
258
  }
218
259
  }
@@ -221,6 +262,14 @@ function hydrateConditionalNode(node, ctx) {
221
262
  _optimizable: frameworkCast(allTargets),
222
263
  });
223
264
  }
265
+ function routeTest(route, where, limits) {
266
+ if (route.expr !== undefined) {
267
+ const compiled = compileExpression(route.expr, where, limits);
268
+ return (input) => passes(compiled, input.value);
269
+ }
270
+ const needle = (route.match ?? '').toLowerCase();
271
+ return (input) => input.text.includes(needle);
272
+ }
224
273
  function hydrateDecideNode(node, _ctx) {
225
274
  if (node.kind !== 'decide') {
226
275
  return frameworkCast(undefined);
@@ -379,8 +428,8 @@ function hydrateLoopNode(node, ctx) {
379
428
  steps: [
380
429
  hydrateNode(node.body, ctx),
381
430
  ],
382
- until: hydrateUntilPredicate(node.until),
383
- maxIterations: node.maxIterations,
431
+ until: hydrateUntilPredicate(node.until, ctx, `until of loop node '${node.id}'`),
432
+ maxIterations: node.maxIterations === 'infinity' ? Number.POSITIVE_INFINITY : node.maxIterations,
384
433
  });
385
434
  }
386
435
  function hydrateSequenceNode(node, ctx) {
@@ -439,9 +488,10 @@ function hydrateAcpAgentNode(node, ctx) {
439
488
  /**
440
489
  * Hydrates a `subflow` node lazily: the target document resolves and hydrates
441
490
  * on first execution, memoized. Lazy because `HydrationContext.workflows` may
442
- * be a live view that gains entries after hydration, and because it keeps
443
- * cycle detection path-scoped — each ref chain threads its own ancestry set,
444
- * so diamond reuse of a named workflow is legal while A→B→A throws.
491
+ * be a live view that gains entries after hydration, and because a recursive
492
+ * ref must hydrate only the levels execution reaches — eager hydration of
493
+ * A→A would never end. Each level gets its own tree whose ids carry the
494
+ * calling node's (already suffixed) id, so levels never share step ids.
445
495
  */
446
496
  function hydrateSubflowNode(node, ctx) {
447
497
  if (node.kind !== 'subflow') {
@@ -465,23 +515,21 @@ function hydrateSubflowNode(node, ctx) {
465
515
  }
466
516
  function resolveSubflowDocument(node, ctx) {
467
517
  if (node.document) {
468
- // Inline documents are finite JSON trees — they cannot cycle, so they
469
- // add nothing to the ancestry chain.
518
+ // Inline documents are finite JSON trees — they cannot recurse, so they
519
+ // add nothing to the recursion depth.
470
520
  return {
471
521
  doc: node.document,
472
522
  childCtx: ctx,
473
523
  };
474
524
  }
475
525
  const ref = node.ref ?? '';
476
- const ancestry = ctx.subflowAncestry ?? new Set();
477
- if (ancestry.has(ref)) {
526
+ const depth = (ctx.recursionDepth ?? 0) + 1;
527
+ const limit = maxRecursionDepth(ctx);
528
+ if (depth > limit) {
478
529
  throw new NoeticConfigError({
479
- code: 'WORKFLOW_CYCLE',
480
- message: `Sub-workflow '${ref}' referenced in subflow node '${node.id}' forms a reference cycle (${[
481
- ...ancestry,
482
- ref,
483
- ].join(' -> ')}).`,
484
- hint: 'A named sub-workflow may not reference itself, directly or transitively. Break the cycle or inline the document.',
530
+ code: 'WORKFLOW_RECURSION_LIMIT',
531
+ message: `Sub-workflow '${ref}' referenced in subflow node '${node.id}' would resolve at recursion depth ${depth}, past the limit of ${limit}.`,
532
+ hint: 'Give the recursion a base case (e.g. a conditional that stops calling the subflow), or raise maxRecursionDepth.',
485
533
  });
486
534
  }
487
535
  const doc = ctx.workflows?.get(ref);
@@ -498,10 +546,7 @@ function resolveSubflowDocument(node, ctx) {
498
546
  doc,
499
547
  childCtx: {
500
548
  ...ctx,
501
- subflowAncestry: new Set([
502
- ...ancestry,
503
- ref,
504
- ]),
549
+ recursionDepth: depth,
505
550
  },
506
551
  };
507
552
  }
@@ -511,6 +556,7 @@ const NODE_HYDRATORS = {
511
556
  callModel: hydrateCallModelNode,
512
557
  invokeTool: hydrateInvokeToolNode,
513
558
  runCode: hydrateRunCodeNode,
559
+ compute: hydrateComputeNode,
514
560
  conditional: hydrateConditionalNode,
515
561
  decide: hydrateDecideNode,
516
562
  routeSwitch: hydrateRouteSwitchNode,
@@ -525,6 +571,18 @@ const NODE_HYDRATORS = {
525
571
  };
526
572
  //#endregion
527
573
  //#region Helpers
574
+ /** The context's recursion limit, defaulted; anything but a positive integer or `Infinity` throws. */
575
+ function maxRecursionDepth(ctx) {
576
+ const limit = ctx.maxRecursionDepth ?? DEFAULT_MAX_RECURSION_DEPTH;
577
+ if (limit === Number.POSITIVE_INFINITY || (Number.isInteger(limit) && limit >= 1)) {
578
+ return limit;
579
+ }
580
+ throw new NoeticConfigError({
581
+ code: 'INVALID_MAX_RECURSION_DEPTH',
582
+ message: `maxRecursionDepth must be a positive integer or Infinity, got ${limit}.`,
583
+ hint: 'Pass a positive integer such as 100 (the default), or Infinity to let named workflows recurse without a limit.',
584
+ });
585
+ }
528
586
  function resolveTools(toolNames, registry) {
529
587
  if (!toolNames || toolNames.length === 0) {
530
588
  return [];
@@ -733,12 +791,10 @@ async function runCodeViaSubprocess(opts) {
733
791
  input,
734
792
  },
735
793
  };
736
- const spawnPromise = adapter.spawn(request);
737
794
  const handle = new DetachedHandleImpl({
738
795
  id: `run-${nodeId}`,
739
796
  stepId: nodeId,
740
- adapter,
741
- spawnPromise,
797
+ spawned: adapter.spawn(request),
742
798
  });
743
799
  const result = await handle.await();
744
800
  return stringifyResult(result);
@@ -755,8 +811,13 @@ async function runCodeViaSubprocess(opts) {
755
811
  * @throws `NoeticConfigError` with code `UNKNOWN_NODE_KIND` if the node kind is unrecognised.
756
812
  * @throws `NoeticConfigError` with code `UNKNOWN_TOOL_REFERENCE` if a tool name cannot be resolved.
757
813
  * @throws `NoeticConfigError` with code `UNKNOWN_UNTIL_PREDICATE` if an until predicate kind is unrecognised.
814
+ * @throws `NoeticConfigError` with code `INVALID_UNTIL_DECIDER` if a decide until predicate does not ask exactly one boolean question.
758
815
  * @throws `NoeticConfigError` with code `UNKNOWN_WORKFLOW_REFERENCE` (at execution time) if a subflow ref names no registered workflow.
759
- * @throws `NoeticConfigError` with code `WORKFLOW_CYCLE` (at execution time) if named sub-workflow refs form a cycle.
816
+ * @throws `NoeticConfigError` with code `WORKFLOW_RECURSION_LIMIT` (at execution time) if named sub-workflow refs nest deeper than `maxRecursionDepth`.
817
+ * @throws `NoeticConfigError` with code `INVALID_MAX_RECURSION_DEPTH` (at execution time) when a named ref resolves under a `maxRecursionDepth` that is not a positive integer or `Infinity`.
818
+ * @throws `NoeticConfigError` with code `WORKFLOW_VALIDATION_FAILED` if a `compute` expression, a conditional route's `expr`, or an `expr` until predicate does not parse.
819
+ * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` if an expression compiles under `expressionLimits` holding a value that is not a positive integer or `Infinity`.
820
+ * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED` (at execution time) if an expression fails or exceeds its limits.
760
821
  */
761
822
  export function hydrateNode(node, ctx) {
762
823
  const hydrator = NODE_HYDRATORS[node.kind];
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import type { ContextData, ContextLayer } from '@noetic-tools/context';
9
9
  import type { AcpAgent, OutputCodec, StepRunCode, SubprocessAdapter, Tool, WorkflowDocument } from '@noetic-tools/types';
10
+ import type { ExpressionLimits } from '../expression/jsonata.js';
10
11
  /** @public Options for `workflow`. */
11
12
  export interface WorkflowOpts {
12
13
  id: string;
@@ -20,6 +21,10 @@ export interface WorkflowOpts {
20
21
  layers?: ReadonlyMap<string, ContextLayer>;
21
22
  /** Named sub-workflows for `subflow` nodes — and for resolving `ref` itself. */
22
23
  workflows?: ReadonlyMap<string, WorkflowDocument>;
24
+ /** Deepest allowed chain of named-ref resolutions (`ref` itself included). Positive integer or `Infinity`. Default: 100. */
25
+ maxRecursionDepth?: number;
26
+ /** Bounds on each expression evaluation; unset fields use `DEFAULT_EXPRESSION_LIMITS`. */
27
+ expressionLimits?: ExpressionLimits;
23
28
  /** ACP agent adapters, keyed by `agentId`, for `acp-agent` nodes. */
24
29
  acpAgents?: ReadonlyMap<string, AcpAgent>;
25
30
  /** Output codecs for `callModel` nodes' `output` codec references. */
@@ -34,9 +39,9 @@ export interface WorkflowOpts {
34
39
  *
35
40
  * The document resolves lazily on first execution (so a `ref` may target a
36
41
  * workflow registered after the step is built) and the hydrated tree is
37
- * memoized across executions. When the step itself is built from a `ref`,
38
- * that name seeds the subflow ancestry chain, so a self-referencing named
39
- * workflow fails with `WORKFLOW_CYCLE` instead of recursing forever.
42
+ * memoized across executions. Named workflows may recurse; when the step
43
+ * itself is built from a `ref`, that ref counts as the first resolution
44
+ * toward `maxRecursionDepth`.
40
45
  *
41
46
  * @public
42
47
  * @param opts - See `WorkflowOpts`.
@@ -45,5 +50,7 @@ export interface WorkflowOpts {
45
50
  * @throws `NoeticConfigError` with code `INVALID_WORKFLOW_SOURCE` unless exactly one of `document`/`ref` is set.
46
51
  * @throws `NoeticConfigError` with code `MISSING_HARNESS_CONTEXT` (at execution) without `ctx.harness`.
47
52
  * @throws `NoeticConfigError` with code `UNKNOWN_WORKFLOW_REFERENCE` (at execution) if `ref` names no registered workflow.
53
+ * @throws `NoeticConfigError` with code `WORKFLOW_RECURSION_LIMIT` (at execution) if named refs nest deeper than `maxRecursionDepth`.
54
+ * @throws `NoeticConfigError` with code `INVALID_MAX_RECURSION_DEPTH` (at execution) if a nested ref resolves under an invalid `maxRecursionDepth`.
48
55
  */
49
56
  export declare function workflow(opts: WorkflowOpts): StepRunCode<ContextData, string, string>;
@@ -16,9 +16,9 @@ import { hydrateWorkflow } from './workflow-hydrator.js';
16
16
  *
17
17
  * The document resolves lazily on first execution (so a `ref` may target a
18
18
  * workflow registered after the step is built) and the hydrated tree is
19
- * memoized across executions. When the step itself is built from a `ref`,
20
- * that name seeds the subflow ancestry chain, so a self-referencing named
21
- * workflow fails with `WORKFLOW_CYCLE` instead of recursing forever.
19
+ * memoized across executions. Named workflows may recurse; when the step
20
+ * itself is built from a `ref`, that ref counts as the first resolution
21
+ * toward `maxRecursionDepth`.
22
22
  *
23
23
  * @public
24
24
  * @param opts - See `WorkflowOpts`.
@@ -27,6 +27,8 @@ import { hydrateWorkflow } from './workflow-hydrator.js';
27
27
  * @throws `NoeticConfigError` with code `INVALID_WORKFLOW_SOURCE` unless exactly one of `document`/`ref` is set.
28
28
  * @throws `NoeticConfigError` with code `MISSING_HARNESS_CONTEXT` (at execution) without `ctx.harness`.
29
29
  * @throws `NoeticConfigError` with code `UNKNOWN_WORKFLOW_REFERENCE` (at execution) if `ref` names no registered workflow.
30
+ * @throws `NoeticConfigError` with code `WORKFLOW_RECURSION_LIMIT` (at execution) if named refs nest deeper than `maxRecursionDepth`.
31
+ * @throws `NoeticConfigError` with code `INVALID_MAX_RECURSION_DEPTH` (at execution) if a nested ref resolves under an invalid `maxRecursionDepth`.
30
32
  */
31
33
  export function workflow(opts) {
32
34
  if (!opts.id || opts.id.trim() === '') {
@@ -94,11 +96,9 @@ function hydrate(opts, executeStep) {
94
96
  acpAgents: opts.acpAgents,
95
97
  uiLibraries: opts.uiLibraries,
96
98
  resolveSubprocess: opts.resolveSubprocess,
97
- subflowAncestry: opts.ref
98
- ? new Set([
99
- opts.ref,
100
- ])
101
- : undefined,
99
+ maxRecursionDepth: opts.maxRecursionDepth,
100
+ expressionLimits: opts.expressionLimits,
101
+ recursionDepth: opts.ref ? 1 : undefined,
102
102
  };
103
103
  const hydrated = hydrateWorkflow(doc, hydrationCtx);
104
104
  if (opts.isolation !== 'spawn') {
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Finds expressions in a workflow tree that do not parse, so a document's
3
+ * JSONata syntax errors fail validation instead of surfacing mid-run.
4
+ */
5
+ import type { WorkflowNode } from '@noetic-tools/types';
6
+ /**
7
+ * Lists a message for every expression in the tree under `root` that fails
8
+ * to parse. Empty when all parse. Named `subflow` refs are not followed; their
9
+ * expressions compile when the referenced document hydrates.
10
+ */
11
+ export declare function expressionErrors(root: WorkflowNode): string[];
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Finds expressions in a workflow tree that do not parse, so a document's
3
+ * JSONata syntax errors fail validation instead of surfacing mid-run.
4
+ */
5
+ import { walkWorkflow } from '@noetic-tools/types';
6
+ import { syntaxError } from './jsonata.js';
7
+ //#endregion
8
+ //#region Public API
9
+ /**
10
+ * Lists a message for every expression in the tree under `root` that fails
11
+ * to parse. Empty when all parse. Named `subflow` refs are not followed; their
12
+ * expressions compile when the referenced document hydrates.
13
+ */
14
+ export function expressionErrors(root) {
15
+ const errors = [];
16
+ for (const node of walkWorkflow(root)) {
17
+ for (const found of expressionsOf(node)) {
18
+ const error = syntaxError(found.source);
19
+ if (error !== undefined) {
20
+ errors.push(`Expression in ${found.where} does not parse: ${error}`);
21
+ }
22
+ }
23
+ }
24
+ return errors;
25
+ }
26
+ //#endregion
27
+ //#region Helpers
28
+ function expressionsOf(node) {
29
+ if (node.kind === 'compute') {
30
+ return [
31
+ {
32
+ where: `compute node '${node.id}'`,
33
+ source: node.expr,
34
+ },
35
+ ];
36
+ }
37
+ if (node.kind === 'conditional') {
38
+ return node.routes.flatMap((route, i) => route.expr === undefined
39
+ ? []
40
+ : [
41
+ {
42
+ where: `route ${i} of conditional node '${node.id}'`,
43
+ source: route.expr,
44
+ },
45
+ ]);
46
+ }
47
+ if (node.kind === 'loop') {
48
+ return untilTests(node.until, `until of loop node '${node.id}'`);
49
+ }
50
+ return [];
51
+ }
52
+ function untilTests(pred, where) {
53
+ if (pred.kind === 'expr') {
54
+ return [
55
+ {
56
+ where,
57
+ source: pred.expr,
58
+ },
59
+ ];
60
+ }
61
+ if (pred.kind === 'any' || pred.kind === 'all') {
62
+ return pred.predicates.flatMap((child) => untilTests(child, where));
63
+ }
64
+ return [];
65
+ }
66
+ //#endregion
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The one adapter between Noetic and JSONata (spec 33). It compiles
3
+ * expressions with evaluation limits, reads node input, and turns JSONata's
4
+ * thrown error objects into `NoeticConfigError`s, so no other module touches
5
+ * the library or its error shapes.
6
+ */
7
+ /**
8
+ * @public Bounds on one expression evaluation. Each field is a positive
9
+ * integer or `Infinity` (no bound) and falls back to `DEFAULT_EXPRESSION_LIMITS`.
10
+ */
11
+ export interface ExpressionLimits {
12
+ /**
13
+ * Wall-clock milliseconds one evaluation may run. Checked only as each
14
+ * sub-expression starts, so one long built-in call runs to its end. Workers
15
+ * freeze `Date.now()` during pure CPU work, so there `steps` is the bound that holds.
16
+ */
17
+ timeout?: number;
18
+ /** How deep evaluation may nest, counting each sub-expression and function call. Tail calls do not nest. */
19
+ depth?: number;
20
+ /** The most items one sequence (JSONata's result list) or range may hold. */
21
+ length?: number;
22
+ /** How many sub-expressions one evaluation may evaluate, counting each repeat. Independent of the clock. */
23
+ steps?: number;
24
+ }
25
+ /** A compiled expression, ready to run against node input. */
26
+ export interface CompiledExpression {
27
+ /** Names the expression's owner in error messages, e.g. `compute node 'step'`. */
28
+ where: string;
29
+ /** Evaluates against `input`, already read by `readInput`. Resolves to JSONata's raw result. */
30
+ run(input: unknown): Promise<unknown>;
31
+ }
32
+ /** @public The limits an expression runs under unless the host sets its own. */
33
+ export declare const DEFAULT_EXPRESSION_LIMITS: Readonly<Required<ExpressionLimits>>;
34
+ /**
35
+ * Compiles `source` under `limits`. Every `run` gets fresh budgets: the clock,
36
+ * depth, and step count start over per evaluation.
37
+ *
38
+ * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` when a limit is not a positive integer or `Infinity`.
39
+ * @throws `NoeticConfigError` with code `WORKFLOW_VALIDATION_FAILED` when `source` does not parse.
40
+ */
41
+ export declare function compileExpression(source: string, where: string, limits?: ExpressionLimits): CompiledExpression;
42
+ /** The parse error in `source`, or `undefined` when it compiles. */
43
+ export declare function syntaxError(source: string): string | undefined;
44
+ /**
45
+ * Evaluates a `compute` expression. JSONata's "no value" (`undefined`) and a
46
+ * result holding a function, at any depth, have no JSON form, so both fail
47
+ * rather than turn silently into empty or garbled output.
48
+ *
49
+ * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
50
+ */
51
+ export declare function compute(expr: CompiledExpression, input: unknown): Promise<unknown>;
52
+ /**
53
+ * Evaluates an `expr` test. `true` passes; `false` and JSONata's "no value"
54
+ * (`undefined`, e.g. a path that matched nothing) do not; anything else fails.
55
+ *
56
+ * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
57
+ */
58
+ export declare function passes(expr: CompiledExpression, input: unknown): Promise<boolean>;
59
+ /**
60
+ * Reads a node's input as an expression sees it: a string is parsed as JSON
61
+ * when it parses, else kept as the raw string; any other value is used as is.
62
+ */
63
+ export declare function readInput(value: unknown): unknown;