@noetic-tools/core 5.19.3 → 5.20.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 (85) hide show
  1. package/dist/adapters/openrouter.d.ts +1 -48
  2. package/dist/adapters/openrouter.js +3 -204
  3. package/dist/builders/acp-agent-checks.d.ts +20 -0
  4. package/dist/builders/acp-agent-checks.js +68 -0
  5. package/dist/builders/acp-agent-tool.d.ts +4 -3
  6. package/dist/builders/acp-agent-tool.js +5 -2
  7. package/dist/builders/connection-ceiling.d.ts +13 -0
  8. package/dist/builders/connection-ceiling.js +17 -0
  9. package/dist/builders/document-entries.d.ts +13 -0
  10. package/dist/builders/document-entries.js +18 -0
  11. package/dist/builders/dynamic-workflow.d.ts +20 -12
  12. package/dist/builders/dynamic-workflow.js +28 -24
  13. package/dist/builders/step-builders.d.ts +14 -6
  14. package/dist/builders/step-builders.js +25 -2
  15. package/dist/builders/workflow-child-nodes.js +7 -0
  16. package/dist/builders/workflow-connection-nodes.d.ts +3 -1
  17. package/dist/builders/workflow-connection-nodes.js +94 -6
  18. package/dist/builders/workflow-connections.js +2 -1
  19. package/dist/builders/workflow-hydrator.d.ts +12 -1
  20. package/dist/builders/workflow-hydrator.js +7 -141
  21. package/dist/builders/workflow-mcp-servers.d.ts +34 -14
  22. package/dist/builders/workflow-mcp-servers.js +211 -104
  23. package/dist/builders/workflow-tool-entries.d.ts +84 -0
  24. package/dist/builders/workflow-tool-entries.js +216 -0
  25. package/dist/connections/durability.d.ts +11 -1
  26. package/dist/connections/durability.js +34 -0
  27. package/dist/connections/entries.d.ts +33 -0
  28. package/dist/connections/entries.js +118 -0
  29. package/dist/connections/errors.d.ts +6 -0
  30. package/dist/connections/errors.js +12 -0
  31. package/dist/connections/harness-wiring.d.ts +4 -4
  32. package/dist/connections/harness-wiring.js +1 -1
  33. package/dist/connections/in-memory-connection.d.ts +2 -0
  34. package/dist/connections/in-memory-connection.js +5 -0
  35. package/dist/connections/model-tools.d.ts +35 -12
  36. package/dist/connections/model-tools.js +348 -202
  37. package/dist/connections/registry-types.d.ts +7 -0
  38. package/dist/connections/registry.d.ts +35 -6
  39. package/dist/connections/registry.js +183 -39
  40. package/dist/connections/step-tools.d.ts +64 -0
  41. package/dist/connections/step-tools.js +154 -0
  42. package/dist/connections/views.d.ts +3 -2
  43. package/dist/connections/views.js +15 -6
  44. package/dist/harness/agent-harness.d.ts +11 -1
  45. package/dist/harness/agent-harness.js +69 -8
  46. package/dist/harness/connection-gate.d.ts +49 -8
  47. package/dist/harness/connection-gate.js +136 -26
  48. package/dist/harness/deps/interpreter.d.ts +3 -3
  49. package/dist/harness/deps/interpreter.js +3 -3
  50. package/dist/harness/harness-options.d.ts +4 -3
  51. package/dist/harness/model-request.js +3 -1
  52. package/dist/harness/model-schema.d.ts +1 -19
  53. package/dist/harness/model-schema.js +0 -28
  54. package/dist/harness/model-tool-round.js +2 -2
  55. package/dist/index.d.ts +5 -5
  56. package/dist/index.js +1 -1
  57. package/dist/interpreter/acp-events.d.ts +25 -1
  58. package/dist/interpreter/acp-events.js +53 -1
  59. package/dist/interpreter/acp-layers.d.ts +20 -0
  60. package/dist/interpreter/acp-layers.js +55 -0
  61. package/dist/interpreter/acp-tools.d.ts +108 -0
  62. package/dist/interpreter/acp-tools.js +462 -0
  63. package/dist/interpreter/collect-tools.d.ts +28 -0
  64. package/dist/interpreter/collect-tools.js +112 -15
  65. package/dist/interpreter/connection-steps.d.ts +0 -2
  66. package/dist/interpreter/connection-steps.js +30 -8
  67. package/dist/interpreter/execute-acp-agent.js +263 -72
  68. package/dist/interpreter/execute-action.d.ts +76 -1
  69. package/dist/interpreter/execute-action.js +35 -42
  70. package/dist/interpreter/execute.d.ts +2 -0
  71. package/dist/interpreter/execute.js +24 -1
  72. package/dist/interpreter/verify-host.js +2 -1
  73. package/dist/runtime/tool-call.d.ts +67 -0
  74. package/dist/runtime/tool-call.js +244 -0
  75. package/dist/runtime/tool-context.d.ts +1 -2
  76. package/dist/runtime/tool-context.js +6 -2
  77. package/dist/schemas/workflow.d.ts +1 -1
  78. package/dist/types/connection-entry.d.ts +22 -0
  79. package/dist/types/connection-entry.js +8 -0
  80. package/dist/util/root-context.d.ts +3 -0
  81. package/dist/util/root-context.js +8 -0
  82. package/dist/util/tool-name.d.ts +8 -0
  83. package/dist/util/tool-name.js +10 -0
  84. package/package.json +2 -2
  85. package/schema/noetic-workflow.schema.json +495 -176
@@ -8,12 +8,14 @@ import { expressionErrors } from '../expression/check.js';
8
8
  import { NoeticAttr } from '../observability/genai-attributes.js';
9
9
  import { WorkflowDocumentSchema, workflowDepth, workflowGraph } from '../schemas/workflow.js';
10
10
  import { harnessInternal } from '../util/harness-internals.js';
11
+ import { rootOf } from '../util/root-context.js';
11
12
  import { outputText } from './output-text.js';
12
13
  import { callModel, runCode } from './step-builders.js';
13
14
  import { acpBounds, acpPrompt, checkAcpAgents } from './workflow-acp-grants.js';
14
- import { checkConnectionAllowlist, checkDocumentConnections, globMatches, } from './workflow-connections.js';
15
+ import { checkConnectionAllowlist, globMatches } from './workflow-connections.js';
15
16
  import { hydrateWorkflow } from './workflow-hydrator.js';
16
17
  import { checkMcpServers, mcpPrompt } from './workflow-mcp-servers.js';
18
+ import { checkToolConnections } from './workflow-tool-entries.js';
17
19
  //#endregion
18
20
  //#region Constants
19
21
  const DEFAULT_MAX_DEPTH = 5;
@@ -28,7 +30,7 @@ The workflow document must be valid JSON with this structure:
28
30
  }
29
31
 
30
32
  A WorkflowNode is one of:
31
- - { "kind": "callModel", "id": "<unique>", "instructions": "<prompt>", "model": "<optional>", "tools": [{ "type": "<tool-name>" }, ...] } (one LLM call)
33
+ - { "kind": "callModel", "id": "<unique>", "instructions": "<prompt>", "model": "<optional>", "tools": [<tool entry>, ...] } (one LLM call)
32
34
  - { "kind": "invokeTool", "id": "<unique>", "toolName": "<name>", "args": { ... } } (call one tool directly, no LLM)
33
35
  - { "kind": "runCode", "id": "<unique>", "execute": "<source code>" } (runs the code in a subprocess with the step input on stdin; only emit if the task needs deterministic computation AND a subprocess adapter is available)
34
36
  - { "kind": "compute", "id": "<unique>", "expr": "<JSONata expression>" } (computes a value from the input, read as JSON, with no LLM; e.g. "{ 'n': n - 1, 'sum': sum + n }")
@@ -41,9 +43,9 @@ A WorkflowNode is one of:
41
43
  - { "kind": "schedule", "id": "<unique>", "step": <WorkflowNode>, "interval": <ms>, "onError": "continue"|"fail" } (re-runs the step forever on an interval and never returns — only emit for an explicitly daemon-style task)
42
44
  - { "kind": "routeSwitch", "id": "<unique>", "decide": { "kind": "decide", "id": "<unique>", "questions": { "<question-id>": { "type": "choice", "instructions": "<question>", "choices": ["<option>", ...] } } }, "on": "<question-id>", "cases": { "<option>": <WorkflowNode>, ... }, "uncertain": <WorkflowNode>, "minConfidence": <optional 0-1> } (a model decides, then the input goes to the matching case; a "boolean" question has cases "true" and "false"; a "score" question has "levels": ["<low>", ..., "<high>"] and routes by level; every outcome needs a case)
43
45
  - { "kind": "subflow", "id": "<unique>", "document": { "version": 1, "root": <WorkflowNode> } } (an inline sub-workflow run as one step; only emit the inline form — named refs require a registry this planner does not provide)
44
- - { "kind": "acp-agent", "id": "<unique>", "agent": "<an agent id listed below>", "prompt": "<turn prompt>", "mode": "<optional session mode>", "model": "<optional>", "mcpServers": [<optional; only servers listed below>], "cwd": "<optional absolute dir>", "permissions": { "default": "deny", "allow": [{ "kind": "<tool kind>", "title": "<substring>" }] }, "clientCapabilities": { "readTextFile": <bool>, "writeTextFile": <bool>, "terminal": <bool> }, "session": { "reuse": "<key>", "keepAlive": "step"|"run" } } (every field after "model" is optional and only within the agent's limits listed below)
46
+ - { "kind": "acp-agent", "id": "<unique>", "agent": "<an agent id listed below>", "prompt": "<turn prompt>", "mode": "<optional session mode>", "model": "<optional>", "tools": [<optional; connection and MCP server entries only>], "cwd": "<optional absolute dir>", "permissions": { "default": "deny", "allow": [{ "kind": "<tool kind>", "title": "<substring>" }] }, "clientCapabilities": { "readTextFile": <bool>, "writeTextFile": <bool>, "terminal": <bool> }, "session": { "reuse": "<key>", "keepAlive": "step"|"run" } } (every field after "model" is optional and only within the agent's limits listed below)
45
47
 
46
- Every entry of a callModel node's "tools" is an OBJECT, never a bare string. Use { "type": "<tool-name>" } to let the model call one of the tools listed below. Two provider-executed tools are also available without being listed: { "type": "openrouter:web_search" } and { "type": "openrouter:web_fetch" }, each accepting an optional "parameters" object.
48
+ Every entry of a node's "tools" is an OBJECT, never a bare string. Use { "type": "<tool-name>" } to let the model call one of the tools listed below. Two provider-executed tools are also available without being listed: { "type": "openrouter:web_search" } and { "type": "openrouter:web_fetch" }, each accepting an optional "parameters" object. { "connection": "<name>", "ops": ["<operation glob>", ...] } gives the model the tools of a connection listed below ("ops" optional), and { "mcp": { "name": "<name>", "type": "http", "url": "<url>" } } those of an MCP server listed below. The same { "mcp": … } entry under the document's "connections" (keyed by its name) attaches the server for the whole document.
47
49
 
48
50
  Any node may carry "emitItems": true to show its output to the user as an assistant message the moment it finishes, or "emitItems": { "onDone": "<JSONata expression on the output, e.g. 'Done ' & n & ' items'>" } to show computed text (no value shows nothing). Use it for progress inside loops: only the workflow's final output is shown otherwise. To stream a structured progress item, declare it in the document's root "customItems" map ({ "<name>": { "type": "<prefix>:<name>", "event": <JSON Schema>, "output": <JSON Schema of an object, without id or type> } }) and emit it with "emitItems": { "item": "<name>", "onStart": "<JSONata on the input: one event>", "onDone": "<JSONata on the output: the final fields>" }.
49
51
 
@@ -149,6 +151,8 @@ export function dynamicWorkflow(opts) {
149
151
  acpAgents: opts.acpAgents,
150
152
  acpBounds: acpBounds(opts.acp, cwd),
151
153
  expressionLimits: opts.expressionLimits,
154
+ allowlist: opts.connections ?? {},
155
+ mcp: opts.mcp,
152
156
  };
153
157
  const hydrated = hydrateWorkflow(parseResult.doc, hydrationCtx);
154
158
  return frameworkCast(await executeStep(hydrated, input, ctx));
@@ -180,14 +184,15 @@ export function dynamicWorkflow(opts) {
180
184
  * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` if `expressionLimits` holds a value that is not a positive integer or `Infinity`.
181
185
  * @throws `NoeticConfigError` with code `EXPRESSION_LIMIT_EXCEEDED` if an expression exceeds its limits.
182
186
  * @throws `NoeticConfigError` with code `CONNECTION_UNKNOWN` if a node uses a connection the document does not declare, or the allowlist names one the harness does not have.
183
- * @throws `NoeticConfigError` with code `CONNECTION_NOT_ALLOWED` if the document asks for more than `connections` grants, or an `acp-agent` node asks for more than `acp` or `mcp` grants.
187
+ * @throws `NoeticConfigError` with code `CONNECTION_NOT_ALLOWED` if the document asks for more than `connections` grants (none when absent), an `acp-agent` node asks for more than `acp` grants, or the document names an MCP server `mcp` does not grant.
184
188
  * @throws `NoeticConfigError` with code `CONNECTION_INVALID` if an MCP server uses a `$secret` and the harness has no `environment.secrets`.
185
189
  */
186
190
  export async function parseAndRunWorkflow(opts) {
187
- checkAllowlistNames(opts.connections, opts.ctx);
191
+ const allowlist = opts.connections ?? {};
192
+ checkAllowlistNames(allowlist, opts.ctx);
188
193
  const cwd = opts.ctx.cwdState.cwd;
189
194
  const parseResult = tryParseWorkflow(opts.json, opts.maxDepth ?? DEFAULT_MAX_DEPTH, {
190
- allowlist: opts.connections,
195
+ allowlist,
191
196
  acp: opts.acp,
192
197
  cwd,
193
198
  mcp: opts.mcp,
@@ -213,6 +218,8 @@ export async function parseAndRunWorkflow(opts) {
213
218
  acpBounds: acpBounds(opts.acp, cwd),
214
219
  maxRecursionDepth: opts.maxRecursionDepth,
215
220
  expressionLimits: opts.expressionLimits,
221
+ allowlist,
222
+ mcp: opts.mcp,
216
223
  };
217
224
  const hydrated = hydrateWorkflow(parseResult.doc, hydrationCtx);
218
225
  const runSpan = beginWorkflowRunSpan(opts.harness, opts.ctx, parseResult.doc);
@@ -316,15 +323,11 @@ function tryParseWorkflow(raw, maxDepth, check) {
316
323
  doc: result.data,
317
324
  };
318
325
  }
319
- /** The error a document has, checked against its manifest, (when given) the host connection allowlist, and what its `acp-agent` nodes may ask. */
326
+ /** The error a document has, checked against its manifest, the host connection allowlist, and what its `acp-agent` nodes may ask. */
320
327
  function connectionErrorOf(doc, check) {
321
328
  try {
322
- if (check.allowlist === undefined) {
323
- checkDocumentConnections(doc);
324
- }
325
- else {
326
- checkConnectionAllowlist(doc, check.allowlist);
327
- }
329
+ checkConnectionAllowlist(doc, check.allowlist);
330
+ checkToolConnections(doc, check.allowlist);
328
331
  checkAcpAgents(doc, check.acp, check.cwd);
329
332
  checkMcpServers(doc, check.mcp, check.secrets);
330
333
  return undefined;
@@ -337,26 +340,25 @@ function connectionErrorOf(doc, check) {
337
340
  }
338
341
  }
339
342
  /**
340
- * Checks an allowlist names only connections the harness has, when the harness
341
- * has a connection registry to ask.
343
+ * Checks an allowlist names only connections the harness or the turn has, when
344
+ * the harness has a connection registry to ask.
342
345
  *
343
- * @throws `NoeticConfigError` `CONNECTION_UNKNOWN` for a name the harness does not have.
346
+ * @throws `NoeticConfigError` `CONNECTION_UNKNOWN` for a name neither has.
344
347
  */
345
348
  function checkAllowlistNames(allowlist, ctx) {
346
- // Structural: builders sit below the connection registry and must not import it.
347
- const registry = harnessInternal(ctx.harness, 'connectionRegistry');
349
+ const registry = registryOf(ctx);
348
350
  if (!allowlist || !registry) {
349
351
  return;
350
352
  }
351
- const known = new Set(registry.names());
353
+ const known = new Set(registry.visibleNames(rootOf(ctx).id));
352
354
  for (const name of Object.keys(allowlist)) {
353
355
  if (known.has(name)) {
354
356
  continue;
355
357
  }
356
358
  throw new NoeticConfigError({
357
359
  code: 'CONNECTION_UNKNOWN',
358
- message: `The connection allowlist names '${name}', which the harness does not have.`,
359
- hint: `Harness connections: ${[
360
+ message: `The connection allowlist names '${name}', which neither the harness nor the turn has.`,
361
+ hint: `Connections: ${[
360
362
  ...known,
361
363
  ].join(', ') || '(none)'}.`,
362
364
  });
@@ -380,6 +382,7 @@ function manifestErrorOf(issues) {
380
382
  hint: 'Each entry is { "profile": "<profile>@<range>", "extensions"?, "from"?, "fresh"?, "setup"? } or { "events": [...] }.',
381
383
  });
382
384
  }
385
+ /** Structural: builders sit below the connection registry and must not import it. */
383
386
  function registryOf(ctx) {
384
387
  return harnessInternal(ctx.harness, 'connectionRegistry');
385
388
  }
@@ -435,7 +438,7 @@ function plannerConnections(allowlist, ctx) {
435
438
  const registry = registryOf(ctx);
436
439
  const out = new Map();
437
440
  for (const [name, entry] of Object.entries(allowlist ?? {})) {
438
- const manifest = registry?.current?.(name)?.manifest;
441
+ const manifest = registry?.current?.(name, rootOf(ctx).id)?.manifest;
439
442
  if (!manifest) {
440
443
  continue;
441
444
  }
@@ -490,7 +493,8 @@ Connection nodes:
490
493
  - { "kind": "call", "id": "<unique>", "connection": "<name>", "op": "<operation>", "args": { ... } } (run one operation; values may be { "$expr": "<JSONata on the input; $steps.<id> reads an earlier node's output>" }, { "$literal": ... }, or { "$secret": "<name>" })
491
494
  - { "kind": "wait", "id": "<unique>", "connection": "<name>", "event": "<event>", "filter": "<JSONata test on { event, input }>", "around": [<steps>], "timeoutMs": <ms> } (listen, run around, then wait for the event)
492
495
  - { "kind": "verify", "id": "<unique>", "subject": "<name>", "expect": [{ "<sense>": "<pattern>" }, ...], "never": [<matchers>], "act": [<steps>], "witnesses": ["<name>"], "close": { "until": "quiet"|"event"|"done"|"exit" } } (run act on the subject and check what was expected happened; act names operations by name)
493
- Inside "around", "act" or a sequence's "steps", { "<operation>": { ...args } } is a call on the enclosing connection.`;
496
+ Inside "around", "act" or a sequence's "steps", { "<operation>": { ...args } } is a call on the enclosing connection.
497
+ A callModel or acp-agent node may instead give the model a connection's tools with the "tools" entry { "connection": "<name>", "ops": [<optional; globs within the ops above>] }; this needs no "connections" map.`;
494
498
  }
495
499
  function safeParse(text) {
496
500
  try {
@@ -1,5 +1,5 @@
1
1
  import type { ContextData } from '@noetic-tools/context';
2
- import type { AcpAgent, AcpClientCapabilityConfig, AcpContentBlock, AcpMcpServer, AcpPermissionHandler, AcpPermissionPolicy, AcpSessionPolicy, AnyProfile, ConnectionEvent, ConnectionHandle, Context, CustomItemMap, CustomItemsBrand, Lazy, ModelParams, OperationInput, OperationName, OperationOutput, OutputCodec, RetryPolicy, RunCodeExecute, ServerToolSpec, StandardSchemaV1, Step, StepAcpAgent, StepCall, StepCallModel, StepEmitItems, StepInvokeTool, StepReplay, StepRunCode, StepWait, StepWaitOutput, SubprocessAdapter, Tool, ToolChoice } from '@noetic-tools/types';
2
+ import type { AcpAgent, AcpClientCapabilityConfig, AcpContentBlock, AcpPermissionHandler, AcpPermissionPolicy, AcpSessionPolicy, AnyProfile, ConnectionEvent, ConnectionHandle, Context, CustomItemMap, CustomItemsBrand, Lazy, ModelParams, OperationInput, OperationName, OperationOutput, OutputCodec, RetryPolicy, RunCodeExecute, StandardSchemaV1, Step, StepAcpAgent, StepCall, StepCallModel, StepEmitItems, StepInvokeTool, StepReplay, StepRunCode, StepToolEntry, StepWait, StepWaitOutput, SubprocessAdapter, Tool, ToolChoice } from '@noetic-tools/types';
3
3
  import { verify } from './verify-builder.js';
4
4
  export interface RunCodeOpts<TContext, I, O, M extends CustomItemMap = CustomItemMap> extends StepReplay<TContext, I>, StepEmitItems<TContext, I, O, M> {
5
5
  id: string;
@@ -21,10 +21,11 @@ export interface CallModelOpts<TContext, O, I = unknown> extends StepReplay<TCon
21
21
  instructions?: Lazy<string | undefined, TContext>;
22
22
  /**
23
23
  * Optional tools; eager array or `(ctx) => (...)[] | undefined` getter. Each
24
- * entry is either a client `Tool` or an inline `ServerToolSpec` (an OpenRouter
25
- * server tool the provider executes, e.g. web search/fetch).
24
+ * entry is a client `Tool`, an inline `ServerToolSpec` (an OpenRouter server
25
+ * tool the provider executes, e.g. web search/fetch), a connection entry
26
+ * (`mcp({ name, … })`), or a `ConnectionPick` (`connectionTools(…)`).
26
27
  */
27
- tools?: Lazy<(Tool | ServerToolSpec)[] | undefined, TContext>;
28
+ tools?: Lazy<ReadonlyArray<StepToolEntry> | undefined, TContext>;
28
29
  /**
29
30
  * How the model may use its tools: `'auto'` (default), `'required'`,
30
31
  * `'none'`, or `{ tool: name }` to force one client tool from `tools`.
@@ -57,8 +58,15 @@ export interface StepAcpAgentOpts<TContext, O, I = unknown> extends StepReplay<T
57
58
  * did not advertise the matching prompt capability.
58
59
  */
59
60
  content?: Lazy<ReadonlyArray<AcpContentBlock> | undefined, TContext>;
60
- /** MCP servers to expose to the agent for this session. */
61
- mcpServers?: Lazy<ReadonlyArray<AcpMcpServer> | undefined, TContext>;
61
+ /**
62
+ * What to give the agent: `tool()` definitions, connection entries
63
+ * (`mcp({ name, … })`) and picks (`connectionTools(…)`), as a `callModel`
64
+ * step takes them. Served to the agent through noetic's tool bridge; every
65
+ * call runs the same steering, validation, approval, and execution path.
66
+ * The agent's own permission request for one of these is allowed, since
67
+ * that path gates it.
68
+ */
69
+ tools?: Lazy<ReadonlyArray<StepToolEntry> | undefined, TContext>;
62
70
  /** Working directory for the session. Defaults to `ctx.cwdState.cwd`. */
63
71
  cwd?: Lazy<string | undefined, TContext>;
64
72
  /** Session mode to switch to before prompting (e.g. `'plan'`). */
@@ -1,5 +1,6 @@
1
- import { frameworkCast, isServerToolSpec, NoeticConfigError } from '@noetic-tools/types';
1
+ import { frameworkCast, isConnectionEntry, isConnectionPick, isServerToolSpec, NoeticConfigError, } from '@noetic-tools/types';
2
2
  import { getDefaultRegistrar } from '../types/step-registrar.js';
3
+ import { assertAgentTakesTools, checkedAcpTools } from './acp-agent-checks.js';
3
4
  import { checkEmitItems, isGeneratorFunction } from './custom-item.js';
4
5
  import { verify } from './verify-builder.js';
5
6
  //#endregion
@@ -80,6 +81,22 @@ function validateAcpAgentOpts(opts) {
80
81
  hint: 'Pass `prompt` for plain text, or `content` for image/audio/resource blocks.',
81
82
  });
82
83
  }
84
+ validateAcpAgentTools(opts);
85
+ }
86
+ /**
87
+ * Reject tools the agent cannot take while the step is built. Only an eager
88
+ * `tools` array and an eager agent can be checked here; getters are checked
89
+ * when the step runs.
90
+ */
91
+ function validateAcpAgentTools(opts) {
92
+ const tools = Array.isArray(opts.tools) ? opts.tools : [];
93
+ if (tools.length === 0) {
94
+ return;
95
+ }
96
+ if (typeof opts.agent === 'object') {
97
+ assertAgentTakesTools(opts.id, opts.agent);
98
+ }
99
+ checkedAcpTools(opts.id, tools.filter((entry) => !isConnectionPick(entry) && !isConnectionEntry(entry)));
83
100
  }
84
101
  /**
85
102
  * A forced tool must be one the step offers. Only an eager `tools` array can be
@@ -90,7 +107,13 @@ function validateToolChoice(opts) {
90
107
  if (typeof choice !== 'object' || !Array.isArray(opts.tools)) {
91
108
  return;
92
109
  }
93
- const names = opts.tools.flatMap((entry) => isServerToolSpec(entry)
110
+ const tools = opts.tools;
111
+ // A connection's tool names come from its server, so they are checked when
112
+ // the turn's tool set is built.
113
+ if (tools.some((entry) => isConnectionPick(entry) || isConnectionEntry(entry))) {
114
+ return;
115
+ }
116
+ const names = tools.flatMap((entry) => isServerToolSpec(entry) || isConnectionPick(entry) || isConnectionEntry(entry)
94
117
  ? []
95
118
  : [
96
119
  entry.name,
@@ -311,6 +311,13 @@ function resolveSubflowDocument(node, ctx) {
311
311
  ].join(', ') || '(none)'}.`,
312
312
  });
313
313
  }
314
+ if (Object.keys(doc.connections ?? {}).length > 0) {
315
+ throw new NoeticConfigError({
316
+ code: 'CONNECTION_INVALID',
317
+ message: `Sub-workflow '${ref}' referenced in subflow node '${node.id}' declares connections, which a subflow cannot: its nodes use the root document's.`,
318
+ hint: `Move the connections of '${ref}' to the root document's "connections".`,
319
+ });
320
+ }
314
321
  return {
315
322
  doc,
316
323
  childCtx: {
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Hydrators for the JSON workflow nodes that reach outside the workflow:
3
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).
4
+ * the document's manifest; `acp-agent` with its tools (spec 27); and `runCode`,
5
+ * which runs its code through a subprocess adapter.
5
6
  */
6
7
  import type { ContextData } from '@noetic-tools/context';
7
8
  import type { Step } from '@noetic-tools/types';
@@ -23,3 +24,4 @@ export declare function hydrateWaitNode(node: WorkflowNode, ctx: HydrationContex
23
24
  * @throws `NoeticConfigError` `UNKNOWN_ACP_AGENT_REFERENCE` when `ctx.acpAgents` has no adapter for the node's agent.
24
25
  */
25
26
  export declare function hydrateAcpAgentNode(node: WorkflowNode, ctx: HydrationContext): Step<ContextData, string, string>;
27
+ export declare function hydrateRunCodeNode(node: WorkflowNode, ctx: HydrationContext): Step<ContextData, string, string>;
@@ -1,16 +1,19 @@
1
1
  /**
2
2
  * Hydrators for the JSON workflow nodes that reach outside the workflow:
3
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).
4
+ * the document's manifest; `acp-agent` with its tools (spec 27); and `runCode`,
5
+ * which runs its code through a subprocess adapter.
5
6
  */
6
7
  import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
7
8
  import { compileExpression, compute, passes, readInput } from '../expression/jsonata.js';
8
9
  import { getDefaultRegistrar } from '../types/step-registrar.js';
9
- import { step } from './step-builders.js';
10
+ import { DetachedHandleImpl } from '../util/detached-handle.js';
11
+ import { outputText } from './output-text.js';
12
+ import { runCode, step } from './step-builders.js';
10
13
  import { boundedAcpSettings } from './workflow-acp-grants.js';
11
14
  import { compileArgs, documentHandle, documentSecretsOf } from './workflow-connections.js';
12
15
  import { bindingsFor, hydrateStepList } from './workflow-hydrator.js';
13
- import { stepMcpServers } from './workflow-mcp-servers.js';
16
+ import { nodeTools, withCeiling } from './workflow-tool-entries.js';
14
17
  //#region Connection Node Hydrators
15
18
  /**
16
19
  * Checks a connection name against the document's manifest, when there is one.
@@ -161,7 +164,7 @@ export function hydrateWaitNode(node, ctx) {
161
164
  return registered(built);
162
165
  }
163
166
  //#endregion
164
- //#region ACP Agent Node Hydrator
167
+ //#region Agent and Code Node Hydrators
165
168
  /**
166
169
  * Hydrates an `acp-agent` node into `step.acpAgent`. Under `ctx.acpBounds` the
167
170
  * node's cwd, client capabilities and session key are held to its agent's
@@ -182,17 +185,102 @@ export function hydrateAcpAgentNode(node, ctx) {
182
185
  });
183
186
  }
184
187
  const bounded = ctx.acpBounds ? boundedAcpSettings(node, ctx.acpBounds) : node;
185
- return step.acpAgent({
188
+ const built = step.acpAgent({
186
189
  id: node.id,
187
190
  agent,
188
191
  prompt: node.prompt,
189
192
  cwd: bounded.cwd,
190
193
  mode: node.mode,
191
194
  model: node.model,
192
- mcpServers: stepMcpServers(node.mcpServers),
195
+ tools: nodeTools(node, {
196
+ ...ctx,
197
+ spawn: agent.spawn,
198
+ }),
193
199
  permissions: node.permissions,
194
200
  clientCapabilities: bounded.clientCapabilities,
195
201
  session: bounded.session,
196
202
  });
203
+ return withCeiling(built, node, ctx);
204
+ }
205
+ export function hydrateRunCodeNode(node, ctx) {
206
+ if (node.kind !== 'runCode') {
207
+ return frameworkCast(undefined);
208
+ }
209
+ const code = node.execute;
210
+ const subprocessRef = node.subprocess;
211
+ return frameworkCast(runCode({
212
+ id: node.id,
213
+ retry: node.retry,
214
+ execute: async (input, execCtx) => {
215
+ const adapter = resolveSubprocessAdapter({
216
+ ref: subprocessRef,
217
+ hydrationCtx: ctx,
218
+ execCtx,
219
+ nodeId: node.id,
220
+ });
221
+ return runCodeViaSubprocess({
222
+ adapter,
223
+ nodeId: node.id,
224
+ code,
225
+ input: outputText(input),
226
+ });
227
+ },
228
+ }));
229
+ }
230
+ //#endregion
231
+ //#region Run Node Helpers
232
+ /**
233
+ * Resolves the subprocess adapter for a `runCode` node. When the node names an
234
+ * adapter ref, the host must supply a `resolveSubprocess` resolver; otherwise
235
+ * the step falls back to the harness adapter on the execution context.
236
+ */
237
+ function resolveSubprocessAdapter(opts) {
238
+ const { ref, hydrationCtx, execCtx, nodeId } = opts;
239
+ if (ref === undefined) {
240
+ return execCtx.subprocess;
241
+ }
242
+ const resolved = hydrationCtx.resolveSubprocess?.(ref);
243
+ if (!resolved) {
244
+ throw new NoeticConfigError({
245
+ code: 'UNKNOWN_SUBPROCESS_REFERENCE',
246
+ message: `Subprocess adapter '${ref}' referenced in run node '${nodeId}' could not be resolved.`,
247
+ hint: 'Pass a `resolveSubprocess(ref)` mapping in the HydrationContext, or omit `subprocess` to use the harness default (ctx.subprocess).',
248
+ });
249
+ }
250
+ return resolved;
251
+ }
252
+ /**
253
+ * Dispatches a `runCode` node's code string through a subprocess adapter: ships the
254
+ * code plus the JSON-stringified input as a process request (input on stdin),
255
+ * waits for the handle to settle, and returns the captured stdout as the step
256
+ * output. A non-zero exit / failed handle surfaces as a thrown error.
257
+ *
258
+ * The code is never eval'd in-process (Cloudflare Workers forbid eval). The
259
+ * adapter owns running the code and capturing stdout into `handle.metadata.result`.
260
+ */
261
+ async function runCodeViaSubprocess(opts) {
262
+ const { adapter, nodeId, code, input } = opts;
263
+ const request = {
264
+ kind: 'process',
265
+ command: 'node',
266
+ args: [
267
+ '-e',
268
+ code,
269
+ ],
270
+ stdin: input,
271
+ metadata: {
272
+ noeticRun: true,
273
+ stepId: nodeId,
274
+ code,
275
+ input,
276
+ },
277
+ };
278
+ const handle = new DetachedHandleImpl({
279
+ id: `run-${nodeId}`,
280
+ stepId: nodeId,
281
+ spawned: adapter.spawn(request),
282
+ });
283
+ const result = await handle.await();
284
+ return outputText(result);
197
285
  }
198
286
  //#endregion
@@ -533,7 +533,8 @@ function checkUse(name, use, allowed) {
533
533
  * @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`.
534
534
  */
535
535
  export function checkConnectionAllowlist(doc, allowlist) {
536
- const manifest = doc.connections ?? {};
536
+ // A document's own `{ "mcp" }` connections answer to the `mcp` allowlist instead.
537
+ const manifest = Object.fromEntries(Object.entries(doc.connections ?? {}).filter(([, entry]) => entry.mcp === undefined));
537
538
  const uses = checkDocumentConnections(doc);
538
539
  const names = Object.keys(manifest);
539
540
  if (names.length === 0) {
@@ -6,7 +6,7 @@
6
6
  * ones — they register in the step registry, carry retry policies, etc.
7
7
  */
8
8
  import type { ContextData, ContextLayer } from '@noetic-tools/context';
9
- import type { AcpAgent, AcpAllowlist, Context, CustomItemMap, ExecuteStepFn, OutputCodec, Step, SubprocessAdapter, Tool } from '@noetic-tools/types';
9
+ import type { AcpAgent, AcpAllowlist, ConnectionAllowlist, Context, CustomItemMap, ExecuteStepFn, McpAllowlist, OutputCodec, Step, SubprocessAdapter, Tool } from '@noetic-tools/types';
10
10
  import type { ExpressionBindings, ExpressionLimits } from '../expression/jsonata.js';
11
11
  import type { WorkflowConnectionRef, WorkflowDocument, WorkflowNode, WorkflowStepList } from '../schemas/workflow.js';
12
12
  import type { ConnectionManifestEntries, ConnectionUses } from './workflow-connections.js';
@@ -91,6 +91,17 @@ export interface HydrationContext {
91
91
  enclosingConnection?: WorkflowConnectionRef;
92
92
  /** The connection name `$item` holds on a fan-out path (an `inParallel` whose `over` lists connections). */
93
93
  fanOutItem?: string;
94
+ /**
95
+ * What the document may use of each connection. A `{ "connection" }` tool
96
+ * entry is narrowed to the operations it grants. Absent allows every
97
+ * connection the harness or the turn holds.
98
+ */
99
+ allowlist?: ConnectionAllowlist;
100
+ /**
101
+ * The MCP servers the document may name (spec 26 § MCP servers): its
102
+ * `{ "mcp" }` entries, in `tools` or `connections`. Absent grants none.
103
+ */
104
+ mcp?: McpAllowlist;
94
105
  }
95
106
  /** The `$steps` scope of the document `ctx` is hydrating. */
96
107
  export declare function documentScopeOf(ctx: HydrationContext): object;
@@ -5,61 +5,35 @@
5
5
  * `loop`, etc.) so hydrated steps are indistinguishable from programmatic
6
6
  * ones — they register in the step registry, carry retry policies, etc.
7
7
  */
8
- import { frameworkCast, isServerToolSpec, NoeticConfigError } from '@noetic-tools/types';
8
+ import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
9
9
  import { compileExpression, compute, readInput } from '../expression/jsonata.js';
10
10
  import { markRecorded, stepOutputsOf } from '../expression/step-outputs.js';
11
11
  import { shorthandStepId, stepEntryToNode, stepListEntries } from '../schemas/workflow.js';
12
- import { DetachedHandleImpl } from '../util/detached-handle.js';
13
12
  import { outputText } from './output-text.js';
14
13
  import { callModel, runCode } from './step-builders.js';
15
14
  import { hydrateInParallelNode, hydrateSpawnNode, hydrateSubflowNode, hydrateWithContextNode, } from './workflow-child-nodes.js';
16
- import { hydrateAcpAgentNode, hydrateCallNode, hydrateWaitNode } from './workflow-connection-nodes.js';
15
+ import { hydrateAcpAgentNode, hydrateCallNode, hydrateRunCodeNode, hydrateWaitNode, } from './workflow-connection-nodes.js';
17
16
  import { checkDocumentConnections } from './workflow-connections.js';
18
17
  import { hydrateConditionalNode, hydrateDecideNode, hydrateLoopNode, hydrateRouteSwitchNode, hydrateScheduleNode, } from './workflow-control-nodes.js';
19
18
  import { documentScope, everyDocumentItem, hydrateEmitItems, nodeScope, } from './workflow-custom-items.js';
20
19
  import { workflowReplayKey } from './workflow-replay-key.js';
20
+ import { nodeTools, recordDocumentConnections, registeredSentence, withCeiling, } from './workflow-tool-entries.js';
21
21
  import { hydrateVerifyNode } from './workflow-verify.js';
22
22
  //#endregion
23
23
  //#region Node Hydrators
24
- /**
25
- * Resolve an llm node's `tools` entries into a combined client+server list.
26
- *
27
- * Every entry is `{ type, parameters? }`. A reserved `openrouter:*` literal is
28
- * a SERVER tool (flows through unchanged); any other `type` is a CLIENT tool
29
- * whose `type` is the registered tool NAME (resolved from the registry). Both
30
- * kinds combine into one `tools` array; the interpreter partitions them again
31
- * at execution.
32
- */
33
- function resolveCallModelTools(entries, registry) {
34
- const toolNames = [];
35
- const serverSpecs = [];
36
- for (const entry of entries ?? []) {
37
- if (isServerToolSpec(entry)) {
38
- serverSpecs.push(entry);
39
- }
40
- else {
41
- toolNames.push(entry.type);
42
- }
43
- }
44
- return [
45
- ...resolveTools(toolNames, registry),
46
- ...serverSpecs,
47
- ];
48
- }
49
24
  function hydrateCallModelNode(node, ctx) {
50
25
  if (node.kind !== 'callModel') {
51
26
  return frameworkCast(undefined);
52
27
  }
53
- const combined = resolveCallModelTools(node.tools, ctx.tools);
54
- return callModel({
28
+ return withCeiling(callModel({
55
29
  id: node.id,
56
30
  model: node.model ?? 'openai/gpt-4o',
57
31
  instructions: node.instructions,
58
- tools: combined.length > 0 ? combined : undefined,
32
+ tools: nodeTools(node, ctx),
59
33
  toolChoice: node.toolChoice,
60
34
  params: node.params,
61
35
  output: resolveOutputCodec(node.output, node.id, ctx),
62
- });
36
+ }), node, ctx);
63
37
  }
64
38
  /**
65
39
  * Resolve a `callModel` node's `output` codec reference to a live `OutputCodec`.
@@ -69,16 +43,6 @@ function hydrateCallModelNode(node, ctx) {
69
43
  * runtime still returns the codec's real value. This is the same erasure the
70
44
  * rest of the hydrator applies via `frameworkCast`.
71
45
  */
72
- /** A complete sentence naming what is registered, for a hint. */
73
- function registeredSentence(noun, names) {
74
- const list = [
75
- ...names,
76
- ];
77
- if (list.length === 0) {
78
- return `No ${noun} are registered.`;
79
- }
80
- return `Registered ${noun}: ${list.join(', ')}.`;
81
- }
82
46
  function resolveOutputCodec(ref, nodeId, ctx) {
83
47
  if (!ref) {
84
48
  return undefined;
@@ -137,31 +101,6 @@ function hydrateInvokeToolNode(node, ctx) {
137
101
  },
138
102
  }));
139
103
  }
140
- function hydrateRunCodeNode(node, ctx) {
141
- if (node.kind !== 'runCode') {
142
- return frameworkCast(undefined);
143
- }
144
- const code = node.execute;
145
- const subprocessRef = node.subprocess;
146
- return frameworkCast(runCode({
147
- id: node.id,
148
- retry: node.retry,
149
- execute: async (input, execCtx) => {
150
- const adapter = resolveSubprocessAdapter({
151
- ref: subprocessRef,
152
- hydrationCtx: ctx,
153
- execCtx,
154
- nodeId: node.id,
155
- });
156
- return runCodeViaSubprocess({
157
- adapter,
158
- nodeId: node.id,
159
- code,
160
- input: outputText(input),
161
- });
162
- },
163
- }));
164
- }
165
104
  function hydrateComputeNode(node, ctx) {
166
105
  if (node.kind !== 'compute') {
167
106
  return frameworkCast(undefined);
@@ -249,80 +188,6 @@ const NODE_HYDRATORS = {
249
188
  verify: hydrateVerifyNode,
250
189
  };
251
190
  //#endregion
252
- //#region Helpers
253
- function resolveTools(toolNames, registry) {
254
- if (!toolNames || toolNames.length === 0) {
255
- return [];
256
- }
257
- return toolNames.map((name) => {
258
- const resolved = registry.get(name);
259
- if (!resolved) {
260
- throw new NoeticConfigError({
261
- code: 'UNKNOWN_TOOL_REFERENCE',
262
- message: `Tool '${name}' referenced in workflow is not registered.`,
263
- hint: `Register '${name}' in HydrationContext.tools before hydrating. ${registeredSentence('tools', registry.keys())}`,
264
- });
265
- }
266
- return resolved;
267
- });
268
- }
269
- //#endregion
270
- //#region Run Node Helpers
271
- /**
272
- * Resolves the subprocess adapter for a `runCode` node. When the node names an
273
- * adapter ref, the host must supply a `resolveSubprocess` resolver; otherwise
274
- * the step falls back to the harness adapter on the execution context.
275
- */
276
- function resolveSubprocessAdapter(opts) {
277
- const { ref, hydrationCtx, execCtx, nodeId } = opts;
278
- if (ref === undefined) {
279
- return execCtx.subprocess;
280
- }
281
- const resolved = hydrationCtx.resolveSubprocess?.(ref);
282
- if (!resolved) {
283
- throw new NoeticConfigError({
284
- code: 'UNKNOWN_SUBPROCESS_REFERENCE',
285
- message: `Subprocess adapter '${ref}' referenced in run node '${nodeId}' could not be resolved.`,
286
- hint: 'Pass a `resolveSubprocess(ref)` mapping in the HydrationContext, or omit `subprocess` to use the harness default (ctx.subprocess).',
287
- });
288
- }
289
- return resolved;
290
- }
291
- /**
292
- * Dispatches a `runCode` node's code string through a subprocess adapter: ships the
293
- * code plus the JSON-stringified input as a process request (input on stdin),
294
- * waits for the handle to settle, and returns the captured stdout as the step
295
- * output. A non-zero exit / failed handle surfaces as a thrown error.
296
- *
297
- * The code is never eval'd in-process (Cloudflare Workers forbid eval). The
298
- * adapter owns running the code and capturing stdout into `handle.metadata.result`.
299
- */
300
- async function runCodeViaSubprocess(opts) {
301
- const { adapter, nodeId, code, input } = opts;
302
- const request = {
303
- kind: 'process',
304
- command: 'node',
305
- args: [
306
- '-e',
307
- code,
308
- ],
309
- stdin: input,
310
- metadata: {
311
- noeticRun: true,
312
- stepId: nodeId,
313
- code,
314
- input,
315
- },
316
- };
317
- const handle = new DetachedHandleImpl({
318
- id: `run-${nodeId}`,
319
- stepId: nodeId,
320
- spawned: adapter.spawn(request),
321
- });
322
- const result = await handle.await();
323
- return outputText(result);
324
- }
325
- //#endregion
326
191
  //#region Public API
327
192
  /**
328
193
  * Hydrates a single `WorkflowNode` into a live `Step`.
@@ -401,6 +266,7 @@ export function hydrateWorkflow(doc, ctx, customItems) {
401
266
  ...everyDocumentItem(doc),
402
267
  ...root.customItems,
403
268
  };
269
+ recordDocumentConnections(frameworkCast(root), doc, ctx.mcp);
404
270
  return root;
405
271
  }
406
272
  //#endregion