@noetic-tools/core 5.20.0-next.1 → 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 (90) 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 +53 -8
  12. package/dist/builders/dynamic-workflow.js +53 -25
  13. package/dist/builders/mcp-url-pattern.d.ts +13 -0
  14. package/dist/builders/mcp-url-pattern.js +85 -0
  15. package/dist/builders/step-builders.d.ts +14 -6
  16. package/dist/builders/step-builders.js +25 -2
  17. package/dist/builders/workflow-acp-grants.d.ts +42 -0
  18. package/dist/builders/workflow-acp-grants.js +224 -0
  19. package/dist/builders/workflow-child-nodes.js +8 -0
  20. package/dist/builders/workflow-connection-nodes.d.ts +13 -3
  21. package/dist/builders/workflow-connection-nodes.js +129 -3
  22. package/dist/builders/workflow-connections.js +2 -1
  23. package/dist/builders/workflow-hydrator.d.ts +24 -1
  24. package/dist/builders/workflow-hydrator.js +8 -167
  25. package/dist/builders/workflow-mcp-servers.d.ts +44 -0
  26. package/dist/builders/workflow-mcp-servers.js +327 -0
  27. package/dist/builders/workflow-tool-entries.d.ts +84 -0
  28. package/dist/builders/workflow-tool-entries.js +216 -0
  29. package/dist/connections/durability.d.ts +11 -1
  30. package/dist/connections/durability.js +34 -0
  31. package/dist/connections/entries.d.ts +33 -0
  32. package/dist/connections/entries.js +118 -0
  33. package/dist/connections/errors.d.ts +6 -0
  34. package/dist/connections/errors.js +12 -0
  35. package/dist/connections/harness-wiring.d.ts +4 -4
  36. package/dist/connections/harness-wiring.js +1 -1
  37. package/dist/connections/in-memory-connection.d.ts +2 -0
  38. package/dist/connections/in-memory-connection.js +5 -0
  39. package/dist/connections/model-tools.d.ts +35 -12
  40. package/dist/connections/model-tools.js +348 -202
  41. package/dist/connections/registry-types.d.ts +7 -0
  42. package/dist/connections/registry.d.ts +35 -6
  43. package/dist/connections/registry.js +183 -39
  44. package/dist/connections/step-tools.d.ts +64 -0
  45. package/dist/connections/step-tools.js +154 -0
  46. package/dist/connections/views.d.ts +3 -2
  47. package/dist/connections/views.js +15 -6
  48. package/dist/harness/agent-harness.d.ts +11 -1
  49. package/dist/harness/agent-harness.js +69 -8
  50. package/dist/harness/connection-gate.d.ts +49 -8
  51. package/dist/harness/connection-gate.js +137 -26
  52. package/dist/harness/deps/interpreter.d.ts +3 -3
  53. package/dist/harness/deps/interpreter.js +3 -3
  54. package/dist/harness/harness-options.d.ts +4 -3
  55. package/dist/harness/model-request.js +3 -1
  56. package/dist/harness/model-schema.d.ts +1 -19
  57. package/dist/harness/model-schema.js +0 -28
  58. package/dist/harness/model-tool-round.js +2 -2
  59. package/dist/index.d.ts +5 -5
  60. package/dist/index.js +1 -1
  61. package/dist/interpreter/acp-events.d.ts +25 -1
  62. package/dist/interpreter/acp-events.js +53 -1
  63. package/dist/interpreter/acp-layers.d.ts +20 -0
  64. package/dist/interpreter/acp-layers.js +55 -0
  65. package/dist/interpreter/acp-tools.d.ts +108 -0
  66. package/dist/interpreter/acp-tools.js +462 -0
  67. package/dist/interpreter/collect-tools.d.ts +28 -0
  68. package/dist/interpreter/collect-tools.js +112 -15
  69. package/dist/interpreter/connection-steps.d.ts +0 -2
  70. package/dist/interpreter/connection-steps.js +30 -8
  71. package/dist/interpreter/execute-acp-agent.js +263 -72
  72. package/dist/interpreter/execute-action.d.ts +76 -1
  73. package/dist/interpreter/execute-action.js +35 -42
  74. package/dist/interpreter/execute.d.ts +2 -0
  75. package/dist/interpreter/execute.js +24 -1
  76. package/dist/interpreter/verify-host.js +2 -1
  77. package/dist/runtime/tool-call.d.ts +67 -0
  78. package/dist/runtime/tool-call.js +244 -0
  79. package/dist/runtime/tool-context.d.ts +1 -2
  80. package/dist/runtime/tool-context.js +6 -2
  81. package/dist/schemas/workflow.d.ts +1 -1
  82. package/dist/types/connection-entry.d.ts +22 -0
  83. package/dist/types/connection-entry.js +8 -0
  84. package/dist/util/harness-internals.d.ts +2 -0
  85. package/dist/util/root-context.d.ts +3 -0
  86. package/dist/util/root-context.js +8 -0
  87. package/dist/util/tool-name.d.ts +8 -0
  88. package/dist/util/tool-name.js +10 -0
  89. package/package.json +3 -3
  90. package/schema/noetic-workflow.schema.json +498 -128
@@ -8,10 +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
- import { checkConnectionAllowlist, checkDocumentConnections, globMatches, } from './workflow-connections.js';
14
+ import { acpBounds, acpPrompt, checkAcpAgents } from './workflow-acp-grants.js';
15
+ import { checkConnectionAllowlist, globMatches } from './workflow-connections.js';
14
16
  import { hydrateWorkflow } from './workflow-hydrator.js';
17
+ import { checkMcpServers, mcpPrompt } from './workflow-mcp-servers.js';
18
+ import { checkToolConnections } from './workflow-tool-entries.js';
15
19
  //#endregion
16
20
  //#region Constants
17
21
  const DEFAULT_MAX_DEPTH = 5;
@@ -26,7 +30,7 @@ The workflow document must be valid JSON with this structure:
26
30
  }
27
31
 
28
32
  A WorkflowNode is one of:
29
- - { "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)
30
34
  - { "kind": "invokeTool", "id": "<unique>", "toolName": "<name>", "args": { ... } } (call one tool directly, no LLM)
31
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)
32
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 }")
@@ -39,9 +43,9 @@ A WorkflowNode is one of:
39
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)
40
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)
41
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)
42
- - { "kind": "acp-agent", "id": "<unique>", "agent": "<registered agent id, e.g. claude-code>", "prompt": "<turn prompt>", "mode": "<optional session mode>", "model": "<optional>" }
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)
43
47
 
44
- 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.
45
49
 
46
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>" }.
47
51
 
@@ -69,6 +73,7 @@ Respond with ONLY the JSON document, no markdown fences or explanation.`;
69
73
  * @returns A `Step` that dynamically plans and executes.
70
74
  * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` (at execution) if `expressionLimits` holds a value that is not a positive integer or `Infinity`.
71
75
  * @throws `NoeticConfigError` with code `EXPRESSION_LIMIT_EXCEEDED` (at execution) if an expression in the generated workflow exceeds its limits.
76
+ * @throws `NoeticConfigError` with code `CONNECTION_NOT_ALLOWED` (at execution) if, on the last revision, the document asks for more than `connections`, `acp` or `mcp` grants.
72
77
  */
73
78
  export function dynamicWorkflow(opts) {
74
79
  const model = opts.model ?? DEFAULT_MODEL;
@@ -87,12 +92,17 @@ export function dynamicWorkflow(opts) {
87
92
  });
88
93
  }
89
94
  checkAllowlistNames(opts.connections, ctx);
95
+ // Read once: the planner is shown, the document checked against, and its
96
+ // acp-agent nodes run in this cwd, even if the harness's moves meanwhile.
97
+ const cwd = ctx.cwdState.cwd;
90
98
  const toolList = opts.tools.map((t) => `- ${t.name}: ${t.description}`).join('\n');
91
99
  const basePrompt = [
92
100
  opts.instructions,
93
101
  PLANNER_INSTRUCTIONS,
94
102
  `\nAvailable tools:\n${toolList}`,
95
103
  connectionsPrompt(opts.connections, plannerConnections(opts.connections, ctx)),
104
+ acpPrompt(opts.acpAgents, opts.acp, cwd),
105
+ mcpPrompt(opts.mcp),
96
106
  `\nTask: ${input}`,
97
107
  ]
98
108
  .filter(Boolean)
@@ -116,6 +126,10 @@ export function dynamicWorkflow(opts) {
116
126
  const parseResult = tryParseWorkflow(text, maxDepth, {
117
127
  allowlist: opts.connections ?? {},
118
128
  ranges: profileVersions(ctx),
129
+ acp: opts.acp,
130
+ cwd,
131
+ mcp: opts.mcp,
132
+ secrets: harnessInternal(harness, 'secrets'),
119
133
  });
120
134
  if (!parseResult.ok) {
121
135
  lastError = parseResult.error;
@@ -134,7 +148,11 @@ export function dynamicWorkflow(opts) {
134
148
  const hydrationCtx = {
135
149
  tools: toolMap,
136
150
  executeStep,
151
+ acpAgents: opts.acpAgents,
152
+ acpBounds: acpBounds(opts.acp, cwd),
137
153
  expressionLimits: opts.expressionLimits,
154
+ allowlist: opts.connections ?? {},
155
+ mcp: opts.mcp,
138
156
  };
139
157
  const hydrated = hydrateWorkflow(parseResult.doc, hydrationCtx);
140
158
  return frameworkCast(await executeStep(hydrated, input, ctx));
@@ -166,12 +184,19 @@ export function dynamicWorkflow(opts) {
166
184
  * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` if `expressionLimits` holds a value that is not a positive integer or `Infinity`.
167
185
  * @throws `NoeticConfigError` with code `EXPRESSION_LIMIT_EXCEEDED` if an expression exceeds its limits.
168
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.
169
- * @throws `NoeticConfigError` with code `CONNECTION_NOT_ALLOWED` if the document asks for more than `connections` 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.
188
+ * @throws `NoeticConfigError` with code `CONNECTION_INVALID` if an MCP server uses a `$secret` and the harness has no `environment.secrets`.
170
189
  */
171
190
  export async function parseAndRunWorkflow(opts) {
172
- checkAllowlistNames(opts.connections, opts.ctx);
191
+ const allowlist = opts.connections ?? {};
192
+ checkAllowlistNames(allowlist, opts.ctx);
193
+ const cwd = opts.ctx.cwdState.cwd;
173
194
  const parseResult = tryParseWorkflow(opts.json, opts.maxDepth ?? DEFAULT_MAX_DEPTH, {
174
- allowlist: opts.connections,
195
+ allowlist,
196
+ acp: opts.acp,
197
+ cwd,
198
+ mcp: opts.mcp,
199
+ secrets: harnessInternal(opts.harness, 'secrets'),
175
200
  });
176
201
  if (!parseResult.ok && parseResult.configError) {
177
202
  throw parseResult.configError;
@@ -189,8 +214,12 @@ export async function parseAndRunWorkflow(opts) {
189
214
  executeStep,
190
215
  layers: opts.layers,
191
216
  workflows: opts.workflows,
217
+ acpAgents: opts.acpAgents,
218
+ acpBounds: acpBounds(opts.acp, cwd),
192
219
  maxRecursionDepth: opts.maxRecursionDepth,
193
220
  expressionLimits: opts.expressionLimits,
221
+ allowlist,
222
+ mcp: opts.mcp,
194
223
  };
195
224
  const hydrated = hydrateWorkflow(parseResult.doc, hydrationCtx);
196
225
  const runSpan = beginWorkflowRunSpan(opts.harness, opts.ctx, parseResult.doc);
@@ -243,7 +272,7 @@ function buildToolMap(tools) {
243
272
  function coerceToString(value) {
244
273
  return outputText(value);
245
274
  }
246
- function tryParseWorkflow(raw, maxDepth, check = {}) {
275
+ function tryParseWorkflow(raw, maxDepth, check) {
247
276
  const json = typeof raw === 'string' ? safeParse(raw) : raw;
248
277
  if (json === null) {
249
278
  return {
@@ -294,15 +323,13 @@ function tryParseWorkflow(raw, maxDepth, check = {}) {
294
323
  doc: result.data,
295
324
  };
296
325
  }
297
- /** The connection error a document has, checked against its manifest and (when given) the host allowlist. */
326
+ /** The error a document has, checked against its manifest, the host connection allowlist, and what its `acp-agent` nodes may ask. */
298
327
  function connectionErrorOf(doc, check) {
299
328
  try {
300
- if (check.allowlist === undefined) {
301
- checkDocumentConnections(doc);
302
- }
303
- else {
304
- checkConnectionAllowlist(doc, check.allowlist);
305
- }
329
+ checkConnectionAllowlist(doc, check.allowlist);
330
+ checkToolConnections(doc, check.allowlist);
331
+ checkAcpAgents(doc, check.acp, check.cwd);
332
+ checkMcpServers(doc, check.mcp, check.secrets);
306
333
  return undefined;
307
334
  }
308
335
  catch (error) {
@@ -313,26 +340,25 @@ function connectionErrorOf(doc, check) {
313
340
  }
314
341
  }
315
342
  /**
316
- * Checks an allowlist names only connections the harness has, when the harness
317
- * 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.
318
345
  *
319
- * @throws `NoeticConfigError` `CONNECTION_UNKNOWN` for a name the harness does not have.
346
+ * @throws `NoeticConfigError` `CONNECTION_UNKNOWN` for a name neither has.
320
347
  */
321
348
  function checkAllowlistNames(allowlist, ctx) {
322
- // Structural: builders sit below the connection registry and must not import it.
323
- const registry = harnessInternal(ctx.harness, 'connectionRegistry');
349
+ const registry = registryOf(ctx);
324
350
  if (!allowlist || !registry) {
325
351
  return;
326
352
  }
327
- const known = new Set(registry.names());
353
+ const known = new Set(registry.visibleNames(rootOf(ctx).id));
328
354
  for (const name of Object.keys(allowlist)) {
329
355
  if (known.has(name)) {
330
356
  continue;
331
357
  }
332
358
  throw new NoeticConfigError({
333
359
  code: 'CONNECTION_UNKNOWN',
334
- message: `The connection allowlist names '${name}', which the harness does not have.`,
335
- hint: `Harness connections: ${[
360
+ message: `The connection allowlist names '${name}', which neither the harness nor the turn has.`,
361
+ hint: `Connections: ${[
336
362
  ...known,
337
363
  ].join(', ') || '(none)'}.`,
338
364
  });
@@ -356,6 +382,7 @@ function manifestErrorOf(issues) {
356
382
  hint: 'Each entry is { "profile": "<profile>@<range>", "extensions"?, "from"?, "fresh"?, "setup"? } or { "events": [...] }.',
357
383
  });
358
384
  }
385
+ /** Structural: builders sit below the connection registry and must not import it. */
359
386
  function registryOf(ctx) {
360
387
  return harnessInternal(ctx.harness, 'connectionRegistry');
361
388
  }
@@ -411,7 +438,7 @@ function plannerConnections(allowlist, ctx) {
411
438
  const registry = registryOf(ctx);
412
439
  const out = new Map();
413
440
  for (const [name, entry] of Object.entries(allowlist ?? {})) {
414
- const manifest = registry?.current?.(name)?.manifest;
441
+ const manifest = registry?.current?.(name, rootOf(ctx).id)?.manifest;
415
442
  if (!manifest) {
416
443
  continue;
417
444
  }
@@ -466,7 +493,8 @@ Connection nodes:
466
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>" })
467
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)
468
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)
469
- 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.`;
470
498
  }
471
499
  function safeParse(text) {
472
500
  try {
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The URL patterns of a host's `mcp` allowlist (spec 26 § MCP servers). A
3
+ * pattern is matched part by part — scheme, host, port, then path — so a `*`
4
+ * can never stand for a `/`, `?`, `#` or `@` that moves the URL to another
5
+ * host: `https://*.example.com/*` does not match
6
+ * `https://evil.com/.example.com/`.
7
+ */
8
+ /**
9
+ * Whether `url` matches the host's pattern.
10
+ *
11
+ * @throws `NoeticConfigError` `CONNECTION_INVALID` when the pattern is not `<scheme>://<host>[:<port>]<path>` with `*` only as a leading host label, the port, or in the path, or when a leading `*.` is followed by fewer than two labels (`*.com`).
12
+ */
13
+ export declare function urlPatternMatches(pattern: string, url: URL): boolean;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The URL patterns of a host's `mcp` allowlist (spec 26 § MCP servers). A
3
+ * pattern is matched part by part — scheme, host, port, then path — so a `*`
4
+ * can never stand for a `/`, `?`, `#` or `@` that moves the URL to another
5
+ * host: `https://*.example.com/*` does not match
6
+ * `https://evil.com/.example.com/`.
7
+ */
8
+ import { NoeticConfigError } from '@noetic-tools/types';
9
+ import { globMatches } from './workflow-connections.js';
10
+ //#endregion
11
+ //#region Public API
12
+ /**
13
+ * Whether `url` matches the host's pattern.
14
+ *
15
+ * @throws `NoeticConfigError` `CONNECTION_INVALID` when the pattern is not `<scheme>://<host>[:<port>]<path>` with `*` only as a leading host label, the port, or in the path, or when a leading `*.` is followed by fewer than two labels (`*.com`).
16
+ */
17
+ export function urlPatternMatches(pattern, url) {
18
+ const parts = parsePattern(pattern);
19
+ if (url.protocol !== parts.scheme) {
20
+ return false;
21
+ }
22
+ if (!hostMatches(parts, url.hostname)) {
23
+ return false;
24
+ }
25
+ if (parts.port !== '*' && url.port !== parts.port) {
26
+ return false;
27
+ }
28
+ return globMatches(parts.path, url.pathname);
29
+ }
30
+ //#endregion
31
+ //#region Parsing
32
+ const PATTERN = /^(https?):\/\/(\*\.)?(\[[0-9A-Fa-f:.]+\]|[^/:?#*@\\[\]]+)(?::(\d+|\*))?(\/[^?#]*)?$/;
33
+ function parsePattern(pattern) {
34
+ const match = PATTERN.exec(pattern);
35
+ const [, scheme, wildcard, host, port, path] = match ?? [];
36
+ if (!scheme || !host) {
37
+ throw invalid(pattern);
38
+ }
39
+ // Read the host and port back through `URL`, so the pattern is normalized
40
+ // exactly as the URLs it is matched against: lowercase, punycode, and the
41
+ // scheme's default port dropped.
42
+ const origin = `${scheme}://${host}${port && port !== '*' ? `:${port}` : ''}/`;
43
+ if (!URL.canParse(origin)) {
44
+ throw invalid(pattern);
45
+ }
46
+ const parsed = new URL(origin);
47
+ // `*.com` would grant every host under a top-level domain.
48
+ if (wildcard !== undefined && !hasTwoLabels(parsed.hostname)) {
49
+ throw invalid(pattern);
50
+ }
51
+ return {
52
+ scheme: parsed.protocol,
53
+ host: parsed.hostname,
54
+ subdomains: wildcard !== undefined,
55
+ port: port === '*' ? '*' : parsed.port,
56
+ path: new URL(path ?? '/', parsed).pathname,
57
+ };
58
+ }
59
+ function hostMatches(pattern, hostname) {
60
+ if (!pattern.subdomains) {
61
+ return hostname === pattern.host;
62
+ }
63
+ const suffix = `.${pattern.host}`;
64
+ if (!hostname.endsWith(suffix)) {
65
+ return false;
66
+ }
67
+ // `URL` reads `https://.example.com/` as host `.example.com`: an empty label.
68
+ const labels = hostname.slice(0, -suffix.length).split('.');
69
+ return labels.every((label) => label !== '');
70
+ }
71
+ function hasTwoLabels(host) {
72
+ if (host.startsWith('[')) {
73
+ return false;
74
+ }
75
+ const labels = host.split('.');
76
+ return labels.length >= 2 && labels.every((label) => label !== '');
77
+ }
78
+ function invalid(pattern) {
79
+ return new NoeticConfigError({
80
+ code: 'CONNECTION_INVALID',
81
+ message: `The host's mcp allowlist has URL pattern ${JSON.stringify(pattern)}, which is not <scheme>://<host>[:<port>]<path>.`,
82
+ hint: 'Use http or https, a host that may start with `*.` followed by at least two labels, a port number or `*`, and a path where `*` matches any run of characters, e.g. https://*.example.com/mcp/*.',
83
+ });
84
+ }
85
+ //#endregion
@@ -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,
@@ -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 {};