@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
@@ -0,0 +1,42 @@
1
+ /**
2
+ * What a document's `acp-agent` nodes may ask of an agent. A node's
3
+ * `permissions`, `mode`, `cwd`, `clientCapabilities` and `session` decide what
4
+ * the agent can do on the host — `terminal` alone hands it a shell, and a mode
5
+ * such as `bypassPermissions` lifts its prompts — so a document
6
+ * a host did not write may ask only for what the host's `acp` allowlist grants
7
+ * that agent (spec 26 § ACP agents).
8
+ */
9
+ import type { AcpAgent, AcpAllowlist, AcpCapabilityGrant, AcpSessionPolicy, WorkflowDocument, WorkflowNode } from '@noetic-tools/types';
10
+ import type { HydrationContext } from './workflow-hydrator.js';
11
+ type AcpAgentNode = Extract<WorkflowNode, {
12
+ kind: 'acp-agent';
13
+ }>;
14
+ type AcpBounds = NonNullable<HydrationContext['acpBounds']>;
15
+ /**
16
+ * Checks every `acp-agent` node against the grant for its agent. Inline
17
+ * subflows count; named refs resolve from the host's own registry and are not
18
+ * checked.
19
+ *
20
+ * @throws `NoeticConfigError` `CONNECTION_NOT_ALLOWED` for a permission, mode, model, `cwd`, client capability or session setting the grant does not allow.
21
+ */
22
+ export declare function checkAcpAgents(doc: WorkflowDocument, grants: AcpAllowlist | undefined, harnessCwd: string): void;
23
+ /**
24
+ * A new namespace for one run of a document's sessions, with the harness's
25
+ * working directory as it was when the document was checked.
26
+ */
27
+ export declare function acpBounds(grants: AcpAllowlist | undefined, harnessCwd: string): AcpBounds;
28
+ /**
29
+ * The node's settings as its step runs them. An omitted `cwd` takes the
30
+ * grant's, else the harness's as it was when the document was checked — never
31
+ * the harness's at run time, which may since have left the grant. An omitted
32
+ * capability takes the grant's value rather than the protocol client's default
33
+ * of on, and a `session.reuse` key moves into the document's namespace.
34
+ */
35
+ export declare function boundedAcpSettings(node: AcpAgentNode, bounds: AcpBounds): {
36
+ cwd: string;
37
+ clientCapabilities: Required<AcpCapabilityGrant>;
38
+ session: AcpSessionPolicy | undefined;
39
+ };
40
+ /** The planner's view of the agents it may run and the most it may ask of each. */
41
+ export declare function acpPrompt(agents: ReadonlyMap<string, AcpAgent> | undefined, grants: AcpAllowlist | undefined, harnessCwd: string): string;
42
+ export {};
@@ -0,0 +1,224 @@
1
+ /**
2
+ * What a document's `acp-agent` nodes may ask of an agent. A node's
3
+ * `permissions`, `mode`, `cwd`, `clientCapabilities` and `session` decide what
4
+ * the agent can do on the host — `terminal` alone hands it a shell, and a mode
5
+ * such as `bypassPermissions` lifts its prompts — so a document
6
+ * a host did not write may ask only for what the host's `acp` allowlist grants
7
+ * that agent (spec 26 § ACP agents).
8
+ */
9
+ import { NoeticConfigError, walkWorkflow } from '@noetic-tools/types';
10
+ //#endregion
11
+ //#region Public API
12
+ /**
13
+ * Checks every `acp-agent` node against the grant for its agent. Inline
14
+ * subflows count; named refs resolve from the host's own registry and are not
15
+ * checked.
16
+ *
17
+ * @throws `NoeticConfigError` `CONNECTION_NOT_ALLOWED` for a permission, mode, model, `cwd`, client capability or session setting the grant does not allow.
18
+ */
19
+ export function checkAcpAgents(doc, grants, harnessCwd) {
20
+ for (const node of walkWorkflow(doc.root)) {
21
+ if (node.kind !== 'acp-agent') {
22
+ continue;
23
+ }
24
+ const grant = grantFor(grants, node.agent);
25
+ checkPermissions(node, grant.permissions);
26
+ checkChoice(node, 'mode', grant.modes ?? []);
27
+ checkChoice(node, 'model', grant.models);
28
+ checkCwd(node, grant.cwd ?? harnessCwd);
29
+ checkCapabilities(node, capabilityCeiling(grant));
30
+ checkSession(node, grant);
31
+ }
32
+ }
33
+ /**
34
+ * A new namespace for one run of a document's sessions, with the harness's
35
+ * working directory as it was when the document was checked.
36
+ */
37
+ export function acpBounds(grants, harnessCwd) {
38
+ return {
39
+ grants: grants ?? {},
40
+ sessionScope: `document-${crypto.randomUUID()}`,
41
+ cwd: harnessCwd,
42
+ };
43
+ }
44
+ /**
45
+ * The node's settings as its step runs them. An omitted `cwd` takes the
46
+ * grant's, else the harness's as it was when the document was checked — never
47
+ * the harness's at run time, which may since have left the grant. An omitted
48
+ * capability takes the grant's value rather than the protocol client's default
49
+ * of on, and a `session.reuse` key moves into the document's namespace.
50
+ */
51
+ export function boundedAcpSettings(node, bounds) {
52
+ const grant = grantFor(bounds.grants, node.agent);
53
+ const ceiling = capabilityCeiling(grant);
54
+ const capability = (name) => node.clientCapabilities?.[name] ?? ceiling[name] === true;
55
+ const reuse = node.session?.reuse;
56
+ return {
57
+ cwd: node.cwd ?? grant.cwd ?? bounds.cwd,
58
+ clientCapabilities: {
59
+ readTextFile: capability('readTextFile'),
60
+ writeTextFile: capability('writeTextFile'),
61
+ terminal: capability('terminal'),
62
+ },
63
+ session: reuse
64
+ ? {
65
+ ...node.session,
66
+ reuse: `${bounds.sessionScope}/${reuse}`,
67
+ }
68
+ : node.session,
69
+ };
70
+ }
71
+ /** The planner's view of the agents it may run and the most it may ask of each. */
72
+ export function acpPrompt(agents, grants, harnessCwd) {
73
+ const ids = [
74
+ ...(agents?.keys() ?? []),
75
+ ];
76
+ if (ids.length === 0) {
77
+ return '\nNo ACP agents are available: do not emit acp-agent nodes.';
78
+ }
79
+ const lines = ids.map((id) => agentLine(id, grantFor(grants, id), harnessCwd));
80
+ return `\nACP agents an acp-agent node may run (no others), and the most a node may ask of each:
81
+ ${lines.join('\n')}`;
82
+ }
83
+ //#endregion
84
+ //#region Checks
85
+ const NO_GRANT = {};
86
+ const DEFAULT_CAPABILITIES = {
87
+ readTextFile: true,
88
+ };
89
+ const CAPABILITIES = [
90
+ 'readTextFile',
91
+ 'writeTextFile',
92
+ 'terminal',
93
+ ];
94
+ const KEEP_ALIVE_ORDER = {
95
+ step: 0,
96
+ run: 1,
97
+ harness: 2,
98
+ };
99
+ /** A document's session namespace dies with its run, so no session outlives the run. */
100
+ const LONGEST_KEEP_ALIVE = 'run';
101
+ function grantFor(grants, agent) {
102
+ return grants && Object.hasOwn(grants, agent) ? (grants[agent] ?? NO_GRANT) : NO_GRANT;
103
+ }
104
+ function capabilityCeiling(grant) {
105
+ return grant.clientCapabilities ?? DEFAULT_CAPABILITIES;
106
+ }
107
+ function checkPermissions(node, grant) {
108
+ const policy = node.permissions;
109
+ if (!policy) {
110
+ return;
111
+ }
112
+ if (policy.default === 'allow' && grant?.default !== 'allow') {
113
+ throw notAllowed(node, 'permissions.default "allow"', 'Leave `default` out, which denies.');
114
+ }
115
+ if (policy.persist && !grant?.persist) {
116
+ throw notAllowed(node, 'permissions.persist', 'Leave `persist` out.');
117
+ }
118
+ for (const rule of policy.allow ?? []) {
119
+ if (!(grant?.allow ?? []).some((ceiling) => covers(ceiling, rule))) {
120
+ throw notAllowed(node, `the permissions.allow rule ${JSON.stringify(rule)}`, `Allow only within ${JSON.stringify(grant?.allow ?? [])}.`);
121
+ }
122
+ }
123
+ }
124
+ /**
125
+ * Whether every tool call `rule` matches, `ceiling` matches too. Titles match
126
+ * as case-insensitive substrings, so a title containing the ceiling's title
127
+ * matches only calls the ceiling's title matches.
128
+ */
129
+ function covers(ceiling, rule) {
130
+ if (ceiling.kind !== undefined && ceiling.kind !== rule.kind) {
131
+ return false;
132
+ }
133
+ if (ceiling.title === undefined) {
134
+ return true;
135
+ }
136
+ return rule.title?.toLowerCase().includes(ceiling.title.toLowerCase()) === true;
137
+ }
138
+ /** Refuses a node's `field` not in `granted`. Undefined `granted` allows any value; an empty one, none. */
139
+ function checkChoice(node, field, granted) {
140
+ const value = node[field];
141
+ if (value === undefined || granted === undefined || granted.includes(value)) {
142
+ return;
143
+ }
144
+ throw notAllowed(node, `${field} ${JSON.stringify(value)}`, granted.length > 0
145
+ ? `Set \`${field}\` to one of ${JSON.stringify(granted)}, or leave it out.`
146
+ : `Leave \`${field}\` out.`);
147
+ }
148
+ function checkCwd(node, root) {
149
+ if (node.cwd === undefined || isUnder(node.cwd, root)) {
150
+ return;
151
+ }
152
+ throw notAllowed(node, `cwd ${JSON.stringify(node.cwd)}`, `Use ${root} or an absolute directory under it, written without '.', '..' or repeated '/'.`);
153
+ }
154
+ /**
155
+ * Lexical, with no `node:path`, so core stays runtime-neutral: `path` must
156
+ * already be absolute and plain, so no `..` can walk it back out of `root`.
157
+ */
158
+ function isUnder(path, root) {
159
+ if (!path.startsWith('/') || path.includes('\\')) {
160
+ return false;
161
+ }
162
+ const segments = path === '/' ? [] : path.slice(1).split('/');
163
+ if (segments.some((s) => s === '' || s === '.' || s === '..')) {
164
+ return false;
165
+ }
166
+ const base = root.length > 1 && root.endsWith('/') ? root.slice(0, -1) : root;
167
+ return path === base || path.startsWith(base === '/' ? '/' : `${base}/`);
168
+ }
169
+ function checkCapabilities(node, ceiling) {
170
+ for (const name of CAPABILITIES) {
171
+ if (node.clientCapabilities?.[name] === true && ceiling[name] !== true) {
172
+ throw notAllowed(node, `clientCapabilities.${name}`, `Leave \`${name}\` out or set it to false.`);
173
+ }
174
+ }
175
+ }
176
+ function checkSession(node, grant) {
177
+ const longest = longestKeepAlive(grant);
178
+ const keepAlive = node.session?.keepAlive ?? 'step';
179
+ if (KEEP_ALIVE_ORDER[keepAlive] > KEEP_ALIVE_ORDER[longest]) {
180
+ throw notAllowed(node, `session.keepAlive "${keepAlive}"`, `Keep the session alive no longer than "${longest}".`);
181
+ }
182
+ if (node.session?.load !== undefined && !grant.session?.load) {
183
+ throw notAllowed(node, 'session.load', 'Leave `load` out to start a new session.');
184
+ }
185
+ }
186
+ /** The grant's `keepAlive`, capped at `'run'` for a grant from untyped code that says `'harness'`. */
187
+ function longestKeepAlive(grant) {
188
+ const granted = grant.session?.keepAlive ?? LONGEST_KEEP_ALIVE;
189
+ return KEEP_ALIVE_ORDER[granted] > KEEP_ALIVE_ORDER[LONGEST_KEEP_ALIVE]
190
+ ? LONGEST_KEEP_ALIVE
191
+ : granted;
192
+ }
193
+ function notAllowed(node, what, hint) {
194
+ return new NoeticConfigError({
195
+ code: 'CONNECTION_NOT_ALLOWED',
196
+ message: `Node '${node.id}' asks agent '${node.agent}' for ${what}, which the host does not allow.`,
197
+ hint,
198
+ });
199
+ }
200
+ //#endregion
201
+ //#region Prompt
202
+ function agentLine(id, grant, harnessCwd) {
203
+ const permissions = grant.permissions;
204
+ const ceiling = capabilityCeiling(grant);
205
+ const on = CAPABILITIES.filter((name) => ceiling[name] === true);
206
+ return [
207
+ `- ${JSON.stringify(id)}:`,
208
+ `permissions default ${permissions?.default === 'allow' ? '"allow" or "deny"' : '"deny" only'},`,
209
+ `"allow" rules only within ${JSON.stringify(permissions?.allow ?? [])},`,
210
+ `${permissions?.persist ? '' : 'no '}"persist";`,
211
+ `${choiceLine('mode', grant.modes ?? [])};`,
212
+ `${choiceLine('model', grant.models)};`,
213
+ `cwd ${JSON.stringify(grant.cwd ?? harnessCwd)} or a directory under it;`,
214
+ `clientCapabilities ${on.length > 0 ? on.join(', ') : 'none'} (any other off);`,
215
+ `session keepAlive up to ${JSON.stringify(longestKeepAlive(grant))}, ${grant.session?.load ? '"load" allowed' : 'no "load"'}`,
216
+ ].join(' ');
217
+ }
218
+ function choiceLine(field, granted) {
219
+ if (granted === undefined) {
220
+ return `any ${field}`;
221
+ }
222
+ return granted.length > 0 ? `${field} one of ${JSON.stringify(granted)}` : `no ${field}`;
223
+ }
224
+ //#endregion
@@ -0,0 +1,21 @@
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 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
+ export declare function hydrateInParallelNode(node: WorkflowNode, ctx: HydrationContext): Step<ContextData, string, string>;
11
+ export declare function hydrateSpawnNode(node: WorkflowNode, ctx: HydrationContext): Step<ContextData, string, string>;
12
+ export declare function hydrateWithContextNode(node: WorkflowNode, ctx: HydrationContext): Step<ContextData, string, string>;
13
+ /**
14
+ * Hydrates a `subflow` node lazily: the target document resolves and hydrates
15
+ * on first execution, memoized. Lazy because `HydrationContext.workflows` may
16
+ * be a live view that gains entries after hydration, and because a recursive
17
+ * ref must hydrate only the levels execution reaches — eager hydration of
18
+ * A→A would never end. Each level gets its own tree whose ids carry the
19
+ * calling node's (already suffixed) id, so levels never share step ids.
20
+ */
21
+ export declare function hydrateSubflowNode(node: WorkflowNode, ctx: HydrationContext): Step<ContextData, string, string>;
@@ -0,0 +1,336 @@
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
+ acpBounds: undefined,
320
+ },
321
+ };
322
+ }
323
+ const DEFAULT_MAX_RECURSION_DEPTH = 100;
324
+ /** The context's recursion limit, defaulted; anything but a positive integer or `Infinity` throws. */
325
+ function maxRecursionDepth(ctx) {
326
+ const limit = ctx.maxRecursionDepth ?? DEFAULT_MAX_RECURSION_DEPTH;
327
+ if (limit === Number.POSITIVE_INFINITY || (Number.isInteger(limit) && limit >= 1)) {
328
+ return limit;
329
+ }
330
+ throw new NoeticConfigError({
331
+ code: 'INVALID_MAX_RECURSION_DEPTH',
332
+ message: `maxRecursionDepth must be a positive integer or Infinity, got ${limit}.`,
333
+ hint: 'Pass a positive integer such as 100 (the default), or Infinity to let named workflows recurse without a limit.',
334
+ });
335
+ }
336
+ //#endregion
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Hydrators for the JSON workflow nodes that reach outside the workflow:
3
+ * `call` and `wait` (spec 35), resolving the connection a node runs on against
4
+ * the document's manifest, and `acp-agent` with its MCP servers (spec 27).
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>;
18
+ /**
19
+ * Hydrates an `acp-agent` node into `step.acpAgent`. Under `ctx.acpBounds` the
20
+ * node's cwd, client capabilities and session key are held to its agent's
21
+ * grant (see `boundedAcpSettings`).
22
+ *
23
+ * @throws `NoeticConfigError` `UNKNOWN_ACP_AGENT_REFERENCE` when `ctx.acpAgents` has no adapter for the node's agent.
24
+ */
25
+ export declare function hydrateAcpAgentNode(node: WorkflowNode, ctx: HydrationContext): Step<ContextData, string, string>;