@noetic-tools/core 5.19.1 → 5.20.0-next.1

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
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Hydrators for the JSON workflow nodes that run their children as child
3
+ * executions: `inParallel` (static and fan-out paths), `spawn`, `withContext`,
4
+ * and `subflow` (a named or inline sub-document).
5
+ */
6
+ import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
7
+ import { inParallel } from './control-flow-builders.js';
8
+ import { outputText } from './output-text.js';
9
+ import { withContext } from './provide-builder.js';
10
+ import { spawn } from './spawn-builder.js';
11
+ import { runCode } from './step-builders.js';
12
+ import { checkManifestName } from './workflow-connection-nodes.js';
13
+ import { documentScope } from './workflow-custom-items.js';
14
+ import { hydrateNode } from './workflow-hydrator.js';
15
+ //#region Child-Execution Node Hydrators
16
+ export function hydrateInParallelNode(node, ctx) {
17
+ if (node.kind !== 'inParallel') {
18
+ return frameworkCast(undefined);
19
+ }
20
+ // Static inParallel: paths are known at hydration time and feed the optimizer.
21
+ // Dynamic inParallel (`each`): paths are produced per inParallel-input at runtime, one
22
+ // child per array item, so they cannot be pre-computed or optimized.
23
+ const dynamic = node.each !== undefined;
24
+ const eachTemplate = node.each;
25
+ if (Array.isArray(node.over)) {
26
+ for (const name of node.over) {
27
+ checkManifestName(name, `over of inParallel node '${node.id}'`, ctx);
28
+ }
29
+ }
30
+ const staticPaths = dynamic ? [] : (node.paths ?? []).map((p) => hydrateNode(p, ctx));
31
+ const pathsFactory = (input) => {
32
+ if (!dynamic || !eachTemplate) {
33
+ return staticPaths;
34
+ }
35
+ if (Array.isArray(node.over)) {
36
+ return node.over.map((name, i) => buildConnectionPathStep({
37
+ forkId: node.id,
38
+ eachTemplate,
39
+ name,
40
+ index: i,
41
+ ctx,
42
+ }));
43
+ }
44
+ const items = selectArray(input, node.over, node.id);
45
+ return items.map((item, i) => buildPerItemStep({
46
+ forkId: node.id,
47
+ eachTemplate,
48
+ item,
49
+ index: i,
50
+ ctx,
51
+ }));
52
+ };
53
+ const optimizable = dynamic ? undefined : frameworkCast(staticPaths);
54
+ if (node.mode === 'race') {
55
+ return inParallel({
56
+ id: node.id,
57
+ mode: 'race',
58
+ paths: pathsFactory,
59
+ concurrency: node.concurrency,
60
+ _optimizable: optimizable,
61
+ });
62
+ }
63
+ const mergeFn = buildMerge(node.merge ?? 'last');
64
+ if (node.mode === 'settle') {
65
+ return inParallel({
66
+ id: node.id,
67
+ mode: 'settle',
68
+ paths: pathsFactory,
69
+ merge: (results) => {
70
+ const values = results.filter((r) => r.status === 'fulfilled').map((r) => r.value ?? '');
71
+ return mergeFn(values);
72
+ },
73
+ concurrency: node.concurrency,
74
+ _optimizable: optimizable,
75
+ });
76
+ }
77
+ return inParallel({
78
+ id: node.id,
79
+ mode: 'all',
80
+ paths: pathsFactory,
81
+ merge: mergeFn,
82
+ concurrency: node.concurrency,
83
+ _optimizable: optimizable,
84
+ });
85
+ }
86
+ /** Paths may return objects (a `decide` node's answers): `concat` writes them as JSON, `first`/`last` pass them through. */
87
+ function buildMerge(strategy) {
88
+ if (strategy === 'first') {
89
+ return (r) => r[0] ?? '';
90
+ }
91
+ if (strategy === 'concat') {
92
+ return (r) => r.map(outputText).join('\n');
93
+ }
94
+ return (r) => r[r.length - 1] ?? '';
95
+ }
96
+ /**
97
+ * Parses the inParallel input (a JSON string) and locates the array to fan out over.
98
+ * When `over` is set, reads that property off the parsed object; otherwise the
99
+ * parsed value itself must be an array.
100
+ */
101
+ function selectArray(input, over, nodeId) {
102
+ let parsed;
103
+ try {
104
+ parsed = JSON.parse(input);
105
+ }
106
+ catch {
107
+ throw new NoeticConfigError({
108
+ code: 'INVALID_FORK_INPUT',
109
+ message: `Dynamic inParallel '${nodeId}' could not parse its input as JSON.`,
110
+ hint: 'A dynamic inParallel (with `each`) expects its input to be a JSON array (or a JSON object when `over` is set).',
111
+ });
112
+ }
113
+ const candidate = over === undefined ? parsed : frameworkCast(parsed)?.[over];
114
+ if (!Array.isArray(candidate)) {
115
+ throw new NoeticConfigError({
116
+ code: 'INVALID_FORK_INPUT',
117
+ message: `Dynamic inParallel '${nodeId}' did not resolve an array${over ? ` at key '${over}'` : ''}.`,
118
+ hint: over
119
+ ? `Ensure the input JSON object has an array at '${over}'.`
120
+ : 'Ensure the input is a JSON array, or set `over` to select an array property.',
121
+ });
122
+ }
123
+ return candidate;
124
+ }
125
+ /**
126
+ * Builds one inParallel path for a single dynamic fan-out item. The item is injected as
127
+ * the body's input (inParallel steps pass the same input to every path), and the
128
+ * template's node ids are suffixed with `-${i}` so each instantiation has
129
+ * unique ids for tracing and step-registry uniqueness.
130
+ */
131
+ function buildPerItemStep(opts) {
132
+ const { forkId, eachTemplate, item, index, ctx } = opts;
133
+ const hydratedEach = hydrateNode(suffixNodeIds(eachTemplate, `-${index}`), ctx);
134
+ return frameworkCast(runCode({
135
+ id: `${forkId}-item-${index}`,
136
+ execute: async (_input, execCtx) => {
137
+ const itemInput = JSON.stringify(item);
138
+ return outputText(await ctx.executeStep(hydratedEach, itemInput, execCtx));
139
+ },
140
+ }));
141
+ }
142
+ /**
143
+ * Builds one path of a connection fan-out (`over` a list of connection names):
144
+ * the template hydrates with `$item` bound to the name, ids suffixed `-<i>`, and
145
+ * runs on the fork's own input.
146
+ */
147
+ function buildConnectionPathStep(opts) {
148
+ const { forkId, eachTemplate, name, index, ctx } = opts;
149
+ const hydratedEach = hydrateNode(suffixNodeIds(eachTemplate, `-${index}`), {
150
+ ...ctx,
151
+ fanOutItem: name,
152
+ });
153
+ return frameworkCast(runCode({
154
+ id: `${forkId}-item-${index}`,
155
+ execute: async (input, execCtx) => outputText(await ctx.executeStep(hydratedEach, input, execCtx)),
156
+ }));
157
+ }
158
+ /** Keys whose values are opaque data bags, never child workflow nodes. */
159
+ const NON_NODE_KEYS = new Set([
160
+ 'args',
161
+ 'params',
162
+ 'parameters',
163
+ ]);
164
+ /**
165
+ * Deep-clones a workflow node template, appending `suffix` to the `id` of every
166
+ * nested node so a per-item instantiation has globally-unique step ids.
167
+ */
168
+ function suffixNodeIds(node, suffix) {
169
+ const clone = structuredClone(node);
170
+ const walk = (value) => {
171
+ if (!value || typeof value !== 'object') {
172
+ return;
173
+ }
174
+ if (Array.isArray(value)) {
175
+ for (const entry of value) {
176
+ walk(entry);
177
+ }
178
+ return;
179
+ }
180
+ const record = frameworkCast(value);
181
+ if (typeof record.kind === 'string' && typeof record.id === 'string') {
182
+ record.id = `${record.id}${suffix}`;
183
+ }
184
+ for (const [key, child] of Object.entries(record)) {
185
+ if (NON_NODE_KEYS.has(key)) {
186
+ continue;
187
+ }
188
+ walk(child);
189
+ }
190
+ };
191
+ walk(clone);
192
+ return clone;
193
+ }
194
+ /**
195
+ * Resolves layer names declared on a `withContext` / `spawn` node against the
196
+ * registry on `HydrationContext.layers`. Returns `[]` when no registry was
197
+ * supplied — the host runs with its harness-default layers in that case.
198
+ */
199
+ function resolveNamedLayers({ names, nodeKind, nodeId, ctx, }) {
200
+ if (!ctx.layers) {
201
+ return [];
202
+ }
203
+ return names.map((name) => {
204
+ const layer = ctx.layers?.get(name);
205
+ if (!layer) {
206
+ throw new NoeticConfigError({
207
+ code: 'UNKNOWN_LAYER_REFERENCE',
208
+ message: `Context layer '${name}' referenced in ${nodeKind} node '${nodeId}' is not registered.`,
209
+ hint: `Available layers: ${[
210
+ ...(ctx.layers?.keys() ?? []),
211
+ ].join(', ') || '(none)'}. Pass named layers via HydrationContext.layers.`,
212
+ });
213
+ }
214
+ return layer;
215
+ });
216
+ }
217
+ export function hydrateSpawnNode(node, ctx) {
218
+ if (node.kind !== 'spawn') {
219
+ return frameworkCast(undefined);
220
+ }
221
+ // `context` is left undefined when the node names no layers so the child
222
+ // inherits the parent's layers (spec 04). An explicit list replaces them.
223
+ const resolvedLayers = node.layers
224
+ ? resolveNamedLayers({
225
+ names: node.layers,
226
+ nodeKind: 'spawn',
227
+ nodeId: node.id,
228
+ ctx,
229
+ })
230
+ : undefined;
231
+ return spawn({
232
+ id: node.id,
233
+ child: hydrateNode(node.child, ctx),
234
+ timeout: node.timeout,
235
+ context: resolvedLayers,
236
+ steers: node.steers,
237
+ });
238
+ }
239
+ export function hydrateWithContextNode(node, ctx) {
240
+ if (node.kind !== 'withContext') {
241
+ return frameworkCast(undefined);
242
+ }
243
+ return withContext({
244
+ id: node.id,
245
+ child: hydrateNode(node.child, ctx),
246
+ context: resolveNamedLayers({
247
+ names: node.layers,
248
+ nodeKind: 'withContext',
249
+ nodeId: node.id,
250
+ ctx,
251
+ }),
252
+ });
253
+ }
254
+ /**
255
+ * Hydrates a `subflow` node lazily: the target document resolves and hydrates
256
+ * on first execution, memoized. Lazy because `HydrationContext.workflows` may
257
+ * be a live view that gains entries after hydration, and because a recursive
258
+ * ref must hydrate only the levels execution reaches — eager hydration of
259
+ * A→A would never end. Each level gets its own tree whose ids carry the
260
+ * calling node's (already suffixed) id, so levels never share step ids.
261
+ */
262
+ export function hydrateSubflowNode(node, ctx) {
263
+ if (node.kind !== 'subflow') {
264
+ return frameworkCast(undefined);
265
+ }
266
+ let cached;
267
+ const resolve = () => {
268
+ if (!cached) {
269
+ const { doc, childCtx } = resolveSubflowDocument(node, ctx);
270
+ cached = hydrateNode(suffixNodeIds(doc.root, `-${node.id}`), {
271
+ ...childCtx,
272
+ customItems: documentScope(doc, ctx.customItems),
273
+ });
274
+ }
275
+ return cached;
276
+ };
277
+ return frameworkCast(runCode({
278
+ id: node.id,
279
+ execute: async (input, execCtx) => {
280
+ const child = resolve();
281
+ return outputText(await ctx.executeStep(child, node.input ?? input, execCtx));
282
+ },
283
+ }));
284
+ }
285
+ function resolveSubflowDocument(node, ctx) {
286
+ if (node.document) {
287
+ // Inline documents are finite JSON trees — they cannot recurse, so they
288
+ // add nothing to the recursion depth.
289
+ return {
290
+ doc: node.document,
291
+ childCtx: ctx,
292
+ };
293
+ }
294
+ const ref = node.ref ?? '';
295
+ const depth = (ctx.recursionDepth ?? 0) + 1;
296
+ const limit = maxRecursionDepth(ctx);
297
+ if (depth > limit) {
298
+ throw new NoeticConfigError({
299
+ code: 'WORKFLOW_RECURSION_LIMIT',
300
+ message: `Sub-workflow '${ref}' referenced in subflow node '${node.id}' would resolve at recursion depth ${depth}, past the limit of ${limit}.`,
301
+ hint: 'Give the recursion a base case (e.g. a conditional that stops calling the subflow), or raise maxRecursionDepth.',
302
+ });
303
+ }
304
+ const doc = ctx.workflows?.get(ref);
305
+ if (!doc) {
306
+ throw new NoeticConfigError({
307
+ code: 'UNKNOWN_WORKFLOW_REFERENCE',
308
+ message: `Sub-workflow '${ref}' referenced in subflow node '${node.id}' is not registered.`,
309
+ hint: `Pass named workflows via HydrationContext.workflows. Available: ${[
310
+ ...(ctx.workflows?.keys() ?? []),
311
+ ].join(', ') || '(none)'}.`,
312
+ });
313
+ }
314
+ return {
315
+ doc,
316
+ childCtx: {
317
+ ...ctx,
318
+ recursionDepth: depth,
319
+ },
320
+ };
321
+ }
322
+ const DEFAULT_MAX_RECURSION_DEPTH = 100;
323
+ /** The context's recursion limit, defaulted; anything but a positive integer or `Infinity` throws. */
324
+ function maxRecursionDepth(ctx) {
325
+ const limit = ctx.maxRecursionDepth ?? DEFAULT_MAX_RECURSION_DEPTH;
326
+ if (limit === Number.POSITIVE_INFINITY || (Number.isInteger(limit) && limit >= 1)) {
327
+ return limit;
328
+ }
329
+ throw new NoeticConfigError({
330
+ code: 'INVALID_MAX_RECURSION_DEPTH',
331
+ message: `maxRecursionDepth must be a positive integer or Infinity, got ${limit}.`,
332
+ hint: 'Pass a positive integer such as 100 (the default), or Infinity to let named workflows recurse without a limit.',
333
+ });
334
+ }
335
+ //#endregion
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Hydrators for the connection nodes of a JSON workflow (spec 35): `call` and
3
+ * `wait`, plus resolving the connection a node runs on against the document's
4
+ * manifest.
5
+ */
6
+ import type { ContextData } from '@noetic-tools/context';
7
+ import type { Step } from '@noetic-tools/types';
8
+ import type { WorkflowNode } from '../schemas/workflow.js';
9
+ import type { HydrationContext } from './workflow-hydrator.js';
10
+ /**
11
+ * Checks a connection name against the document's manifest, when there is one.
12
+ *
13
+ * @throws `NoeticConfigError` `CONNECTION_UNKNOWN` for a name the manifest does not declare.
14
+ */
15
+ export declare function checkManifestName(name: string, where: string, ctx: HydrationContext): void;
16
+ export declare function hydrateCallNode(node: WorkflowNode, ctx: HydrationContext): Step<ContextData, string, string>;
17
+ export declare function hydrateWaitNode(node: WorkflowNode, ctx: HydrationContext): Step<ContextData, string, string>;
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Hydrators for the connection nodes of a JSON workflow (spec 35): `call` and
3
+ * `wait`, plus resolving the connection a node runs on against the document's
4
+ * manifest.
5
+ */
6
+ import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
7
+ import { compileExpression, compute, passes, readInput } from '../expression/jsonata.js';
8
+ import { getDefaultRegistrar } from '../types/step-registrar.js';
9
+ import { compileArgs, documentHandle, documentSecretsOf } from './workflow-connections.js';
10
+ import { bindingsFor, hydrateStepList } from './workflow-hydrator.js';
11
+ //#region Connection Node Hydrators
12
+ /**
13
+ * Checks a connection name against the document's manifest, when there is one.
14
+ *
15
+ * @throws `NoeticConfigError` `CONNECTION_UNKNOWN` for a name the manifest does not declare.
16
+ */
17
+ export function checkManifestName(name, where, ctx) {
18
+ if (!ctx.connections || Object.hasOwn(ctx.connections, name)) {
19
+ return;
20
+ }
21
+ const declared = Object.keys(ctx.connections);
22
+ throw new NoeticConfigError({
23
+ code: 'CONNECTION_UNKNOWN',
24
+ message: `${where} uses connection '${name}', which the document's connections do not declare.`,
25
+ hint: `Use one of ${declared.join(', ') || '(none)'}, or add '${name}' to the document's "connections".`,
26
+ });
27
+ }
28
+ /** The connection a document name binds to: a handle carrying its manifest entry, or the bare name without a manifest. */
29
+ function documentTarget(name, where, ctx) {
30
+ checkManifestName(name, where, ctx);
31
+ const entry = ctx.connections?.[name];
32
+ return entry ? documentHandle(name, entry, ctx.connectionUses?.get(name)) : name;
33
+ }
34
+ /**
35
+ * The connection a `call` or `wait` node runs on: its own, else the enclosing
36
+ * one, else the document's only connection. An expression is evaluated per run.
37
+ *
38
+ * @throws `NoeticConfigError` `CONNECTION_UNKNOWN` for an undeclared name, `CONNECTION_INVALID` when none is named or implied (or an expression gives no name).
39
+ */
40
+ function connectionTargetFor(ref, where, ctx) {
41
+ const effective = ref ?? ctx.enclosingConnection ?? onlyConnection(ctx);
42
+ if (effective === undefined) {
43
+ throw new NoeticConfigError({
44
+ code: 'CONNECTION_INVALID',
45
+ message: `${where} names no connection, and none is implied.`,
46
+ hint: 'Give the node a "connection", or run it inside a verify whose subject is the connection.',
47
+ });
48
+ }
49
+ if (typeof effective === 'string') {
50
+ return documentTarget(effective, where, ctx);
51
+ }
52
+ const compiled = compileExpression(effective.$expr, `connection of ${where}`, ctx.expressionLimits);
53
+ return async (input, execCtx) => {
54
+ const name = await compute(compiled, readInput(input), bindingsFor(execCtx, ctx));
55
+ if (typeof name !== 'string' || name.length === 0) {
56
+ throw new NoeticConfigError({
57
+ code: 'CONNECTION_INVALID',
58
+ message: `The connection expression of ${where} gave ${JSON.stringify(name)}, not a connection name.`,
59
+ hint: 'Write an expression that gives a declared connection name, e.g. { "$expr": "$item" } inside a fan-out.',
60
+ });
61
+ }
62
+ const target = documentTarget(name, where, ctx);
63
+ return typeof target === 'function' ? name : target;
64
+ };
65
+ }
66
+ /** The document's only connection, which a node without one runs on. */
67
+ function onlyConnection(ctx) {
68
+ const names = Object.keys(ctx.connections ?? {});
69
+ return names.length === 1 ? names[0] : undefined;
70
+ }
71
+ /** The operations the document uses on a node's connection (gate 1), when the name is static. */
72
+ function declaredOpsFor(ref, op, ctx) {
73
+ const name = typeof ref === 'string' ? ref : undefined;
74
+ const used = name === undefined ? undefined : ctx.connectionUses?.get(name)?.ops;
75
+ if (used && used.size > 0) {
76
+ return [
77
+ ...used,
78
+ ];
79
+ }
80
+ const all = new Set([
81
+ op,
82
+ ]);
83
+ for (const use of ctx.connectionUses?.values() ?? []) {
84
+ for (const usedOp of use.ops) {
85
+ all.add(usedOp);
86
+ }
87
+ }
88
+ return [
89
+ ...all,
90
+ ];
91
+ }
92
+ /** Registers a step built here as an object literal, like the builders do. */
93
+ function registered(built) {
94
+ getDefaultRegistrar().register(frameworkCast(built));
95
+ return built;
96
+ }
97
+ export function hydrateCallNode(node, ctx) {
98
+ if (node.kind !== 'call') {
99
+ return frameworkCast(undefined);
100
+ }
101
+ const where = `call node '${node.id}'`;
102
+ const connection = connectionTargetFor(node.connection, where, ctx);
103
+ const args = compileArgs(node.args, `args of ${where}`, ctx.expressionLimits);
104
+ const built = {
105
+ kind: 'call',
106
+ id: node.id,
107
+ connection,
108
+ op: node.op,
109
+ args: (input, execCtx) => args(readInput(input), bindingsFor(execCtx, ctx)),
110
+ _caller: 'document',
111
+ _declaredOps: declaredOpsFor(node.connection ?? ctx.enclosingConnection, node.op, ctx),
112
+ _documentSecrets: documentSecretsOf(node.args),
113
+ };
114
+ return registered(built);
115
+ }
116
+ /** A wait filter expression: a test against `{ event, input }`. */
117
+ function waitFilter(compiled, ctx) {
118
+ return (event, input, execCtx) => passes(compiled, {
119
+ event,
120
+ input: readInput(input),
121
+ }, bindingsFor(execCtx, ctx));
122
+ }
123
+ export function hydrateWaitNode(node, ctx) {
124
+ if (node.kind !== 'wait') {
125
+ return frameworkCast(undefined);
126
+ }
127
+ const where = `wait node '${node.id}'`;
128
+ const connectionRef = node.connection ?? ctx.enclosingConnection ?? onlyConnection(ctx);
129
+ const connection = connectionTargetFor(node.connection, where, ctx);
130
+ const filter = node.filter === undefined
131
+ ? undefined
132
+ : waitFilter(compileExpression(node.filter, `filter of ${where}`, ctx.expressionLimits), ctx);
133
+ const around = node.around === undefined
134
+ ? undefined
135
+ : hydrateStepList({
136
+ list: node.around,
137
+ parentId: node.id,
138
+ ctx,
139
+ enclosing: connectionRef,
140
+ });
141
+ const built = {
142
+ kind: 'wait',
143
+ id: node.id,
144
+ connection,
145
+ event: node.event,
146
+ timeoutMs: node.timeoutMs,
147
+ ...(filter
148
+ ? {
149
+ filter,
150
+ }
151
+ : {}),
152
+ ...(around
153
+ ? {
154
+ around,
155
+ }
156
+ : {}),
157
+ };
158
+ return registered(built);
159
+ }
160
+ //#endregion
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The connection side of JSON workflows (spec 35 § JSON workflows, § What a
3
+ * document may use): which connection each `call`, `wait` and `verify` node
4
+ * runs on, the operations and events a document uses per manifest entry, the
5
+ * requirement each entry negotiates, value wrappers, and the host allowlist.
6
+ */
7
+ import type { ConnectionAllowlist, ConnectionHandle, ConnectionRequirement } from '@noetic-tools/types';
8
+ import type { ExpressionBindings, ExpressionLimits } from '../expression/jsonata.js';
9
+ import type { WorkflowArgs, WorkflowConnectionRequirement, WorkflowDocument, WorkflowValue } from '../schemas/workflow.js';
10
+ /** The manifest a document declares, by the names its nodes use. */
11
+ export type ConnectionManifestEntries = Readonly<Record<string, WorkflowConnectionRequirement>>;
12
+ /** A secret a document uses: its name and the `op.field` it fills. */
13
+ export interface SecretUse {
14
+ name: string;
15
+ op: string;
16
+ field: string;
17
+ }
18
+ /** What a document uses of one manifest entry, worked out from its nodes. */
19
+ export interface ConnectionUse {
20
+ ops: Set<string>;
21
+ events: Set<string>;
22
+ secrets: SecretUse[];
23
+ }
24
+ /** Manifest name → what the document uses of it. */
25
+ export type ConnectionUses = Map<string, ConnectionUse>;
26
+ /** A compiled argument value: resolves against a node's input and bindings. */
27
+ export type ValueTemplate = (input: unknown, bindings: ExpressionBindings) => Promise<unknown>;
28
+ /**
29
+ * Compiles a connection argument value (spec 35 § JSON workflows, Values):
30
+ * `{ "$expr" }` evaluates against the node's input, `{ "$literal" }` passes its
31
+ * value through untouched, `{ "$secret" }`, `{ "$ref" }` and `{ "$blob" }` pass
32
+ * through for the registry to resolve, and arrays and objects compile field by field.
33
+ *
34
+ * @throws `NoeticConfigError` `WORKFLOW_VALIDATION_FAILED` when an expression does not parse.
35
+ */
36
+ export declare function compileValue(value: WorkflowValue, where: string, limits: ExpressionLimits | undefined): ValueTemplate;
37
+ /**
38
+ * Compiles a node's `args`: an object of values, or one `{ "$expr" }` computing
39
+ * them all (which must give a value).
40
+ */
41
+ export declare function compileArgs(args: WorkflowArgs | undefined, where: string, limits: ExpressionLimits | undefined): ValueTemplate;
42
+ /**
43
+ * The secrets a node's `args` write out, each with the dotted field it fills.
44
+ * The gates refuse any other secret a document call sends — one an expression
45
+ * produced at run time is never something the allowlist was checked against.
46
+ */
47
+ export declare function documentSecretsOf(args: WorkflowArgs | undefined): Array<{
48
+ name: string;
49
+ field: string;
50
+ }>;
51
+ /**
52
+ * Works out what a document uses of each manifest entry — the operations and
53
+ * events its nodes use and the secrets it passes — checking every connection a
54
+ * node names against the manifest. An inline subflow's nodes count against the
55
+ * enclosing document's manifest.
56
+ *
57
+ * @throws `NoeticConfigError` `CONNECTION_UNKNOWN` for a connection the manifest does not declare, `CONNECTION_INVALID` for a node whose connection is neither named nor implied.
58
+ */
59
+ export declare function documentConnectionUses(doc: WorkflowDocument): ConnectionUses;
60
+ /**
61
+ * Checks a document's connection nodes against its manifest: every name is
62
+ * declared, and a source entry (one declaring only `events`) is waited on only
63
+ * for the events it lists and never called.
64
+ *
65
+ * @throws `NoeticConfigError` `CONNECTION_UNKNOWN`, `CONNECTION_INVALID`, or `CONNECTION_UNSATISFIED`-shaped `CONNECTION_INVALID` for a source used beyond its events.
66
+ */
67
+ export declare function checkDocumentConnections(doc: WorkflowDocument): ConnectionUses;
68
+ /**
69
+ * The requirement a manifest entry negotiates: its profile and extension ranges,
70
+ * plus the operations and events the document uses of it.
71
+ */
72
+ export declare function manifestRequirement(entry: WorkflowConnectionRequirement, use: ConnectionUse | undefined): ConnectionRequirement;
73
+ /**
74
+ * A handle for a manifest entry, carrying the entry's requirement in place of a
75
+ * profile object (core never imports profile packages).
76
+ */
77
+ export declare function documentHandle(name: string, entry: WorkflowConnectionRequirement, use: ConnectionUse | undefined): ConnectionHandle;
78
+ /** The requirement a document handle carries, when it is one. */
79
+ export declare function documentRequirementOf(handle: ConnectionHandle): ConnectionRequirement | undefined;
80
+ /** `*` matches any run of characters; everything else literally. */
81
+ export declare function globMatches(pattern: string, value: string): boolean;
82
+ /**
83
+ * Checks a document against the host's allowlist (spec 35 § What a document may
84
+ * use). Each manifest entry binds to the harness connection `from ?? name`, which
85
+ * the allowlist must name; the operations, events, setup values and secrets the
86
+ * document uses of it must all be granted.
87
+ *
88
+ * @throws `NoeticConfigError` `CONNECTION_NOT_ALLOWED` when the document asks for more than the allowlist grants (or has connections and there is no allowlist); `CONNECTION_UNKNOWN` / `CONNECTION_INVALID` from `checkDocumentConnections`.
89
+ */
90
+ export declare function checkConnectionAllowlist(doc: WorkflowDocument, allowlist: ConnectionAllowlist | undefined): void;