@noetic-tools/core 5.19.2 → 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.
@@ -3,7 +3,7 @@
3
3
  * then hydrates and runs it within the same harness session.
4
4
  */
5
5
  import type { ContextData, ContextLayer } from '@noetic-tools/context';
6
- import type { AgentHarnessContract, ConnectionAllowlist, Context, Step, Tool } from '@noetic-tools/types';
6
+ import type { AcpAgent, AcpAllowlist, AgentHarnessContract, ConnectionAllowlist, Context, McpAllowlist, Step, Tool } from '@noetic-tools/types';
7
7
  import type { ExpressionLimits } from '../expression/jsonata.js';
8
8
  import type { WorkflowDocument } from '../schemas/workflow.js';
9
9
  /** @public Options for creating a dynamic workflow step. */
@@ -22,6 +22,21 @@ export interface DynamicWorkflowOpts {
22
22
  * `CONNECTION_NOT_ALLOWED`. The planner is shown only these connections.
23
23
  */
24
24
  connections?: ConnectionAllowlist;
25
+ /** ACP agent adapters, keyed by `agentId`, that the document's `acp-agent` nodes may run. Default: none. */
26
+ acpAgents?: ReadonlyMap<string, AcpAgent>;
27
+ /**
28
+ * The most a generated `acp-agent` node may ask of each agent: permissions,
29
+ * `cwd`, client capabilities and sessions (spec 26 § ACP agents). An agent
30
+ * without an entry gets the narrowest defaults; a node asking for more fails
31
+ * validation with `CONNECTION_NOT_ALLOWED`. The planner is shown these limits.
32
+ */
33
+ acp?: AcpAllowlist;
34
+ /**
35
+ * The MCP servers a generated `acp-agent` node may hand its agent (spec 26 §
36
+ * MCP servers). Without it, a node naming any server fails validation with
37
+ * `CONNECTION_NOT_ALLOWED`. The planner is shown only these servers.
38
+ */
39
+ mcp?: McpAllowlist;
25
40
  }
26
41
  /**
27
42
  * Creates a step that uses an LLM to generate a workflow as JSON, then
@@ -38,6 +53,7 @@ export interface DynamicWorkflowOpts {
38
53
  * @returns A `Step` that dynamically plans and executes.
39
54
  * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` (at execution) if `expressionLimits` holds a value that is not a positive integer or `Infinity`.
40
55
  * @throws `NoeticConfigError` with code `EXPRESSION_LIMIT_EXCEEDED` (at execution) if an expression in the generated workflow exceeds its limits.
56
+ * @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.
41
57
  */
42
58
  export declare function dynamicWorkflow(opts: DynamicWorkflowOpts): Step<ContextData, string, string>;
43
59
  /** @public Options for `parseAndRunWorkflow`. */
@@ -54,7 +70,12 @@ export interface ParseAndRunWorkflowOpts {
54
70
  * host that runs layer-bearing workflows must pass its layers here.
55
71
  */
56
72
  layers?: ReadonlyMap<string, ContextLayer>;
57
- /** Named sub-workflows the document's `subflow` nodes may reference via `ref`. */
73
+ /**
74
+ * Named sub-workflows the document's `subflow` nodes may reference via `ref`.
75
+ * A named workflow runs as the host wrote it, not held to `connections`,
76
+ * `acp` or `mcp`: register only workflows you would let any document run
77
+ * with their own settings.
78
+ */
58
79
  workflows?: ReadonlyMap<string, WorkflowDocument>;
59
80
  /**
60
81
  * Deepest allowed chain of named-ref resolutions on one execution path —
@@ -70,6 +91,21 @@ export interface ParseAndRunWorkflowOpts {
70
91
  * `CONNECTION_NOT_ALLOWED`.
71
92
  */
72
93
  connections?: ConnectionAllowlist;
94
+ /** ACP agent adapters, keyed by `agentId`, that the document's `acp-agent` nodes may run. Default: none. */
95
+ acpAgents?: ReadonlyMap<string, AcpAgent>;
96
+ /**
97
+ * The most the document's `acp-agent` nodes may ask of each agent:
98
+ * permissions, `cwd`, client capabilities and sessions (spec 26 § ACP
99
+ * agents). An agent without an entry gets the narrowest defaults; a node
100
+ * asking for more fails validation with `CONNECTION_NOT_ALLOWED`.
101
+ */
102
+ acp?: AcpAllowlist;
103
+ /**
104
+ * The MCP servers the document's `acp-agent` nodes may hand their agent
105
+ * (spec 26 § MCP servers). Unlike `connections`, absence grants nothing: a
106
+ * node naming any server fails validation with `CONNECTION_NOT_ALLOWED`.
107
+ */
108
+ mcp?: McpAllowlist;
73
109
  }
74
110
  /**
75
111
  * Parses raw JSON into a `WorkflowDocument`, hydrates it into a live step
@@ -90,6 +126,7 @@ export interface ParseAndRunWorkflowOpts {
90
126
  * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` if `expressionLimits` holds a value that is not a positive integer or `Infinity`.
91
127
  * @throws `NoeticConfigError` with code `EXPRESSION_LIMIT_EXCEEDED` if an expression exceeds its limits.
92
128
  * @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.
93
- * @throws `NoeticConfigError` with code `CONNECTION_NOT_ALLOWED` if the document asks for more than `connections` grants.
129
+ * @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.
130
+ * @throws `NoeticConfigError` with code `CONNECTION_INVALID` if an MCP server uses a `$secret` and the harness has no `environment.secrets`.
94
131
  */
95
132
  export declare function parseAndRunWorkflow(opts: ParseAndRunWorkflowOpts): Promise<string>;
@@ -10,8 +10,10 @@ import { WorkflowDocumentSchema, workflowDepth, workflowGraph } from '../schemas
10
10
  import { harnessInternal } from '../util/harness-internals.js';
11
11
  import { outputText } from './output-text.js';
12
12
  import { callModel, runCode } from './step-builders.js';
13
+ import { acpBounds, acpPrompt, checkAcpAgents } from './workflow-acp-grants.js';
13
14
  import { checkConnectionAllowlist, checkDocumentConnections, globMatches, } from './workflow-connections.js';
14
15
  import { hydrateWorkflow } from './workflow-hydrator.js';
16
+ import { checkMcpServers, mcpPrompt } from './workflow-mcp-servers.js';
15
17
  //#endregion
16
18
  //#region Constants
17
19
  const DEFAULT_MAX_DEPTH = 5;
@@ -39,7 +41,7 @@ A WorkflowNode is one of:
39
41
  - { "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
42
  - { "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
43
  - { "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>" }
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)
43
45
 
44
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.
45
47
 
@@ -69,6 +71,7 @@ Respond with ONLY the JSON document, no markdown fences or explanation.`;
69
71
  * @returns A `Step` that dynamically plans and executes.
70
72
  * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` (at execution) if `expressionLimits` holds a value that is not a positive integer or `Infinity`.
71
73
  * @throws `NoeticConfigError` with code `EXPRESSION_LIMIT_EXCEEDED` (at execution) if an expression in the generated workflow exceeds its limits.
74
+ * @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
75
  */
73
76
  export function dynamicWorkflow(opts) {
74
77
  const model = opts.model ?? DEFAULT_MODEL;
@@ -87,12 +90,17 @@ export function dynamicWorkflow(opts) {
87
90
  });
88
91
  }
89
92
  checkAllowlistNames(opts.connections, ctx);
93
+ // Read once: the planner is shown, the document checked against, and its
94
+ // acp-agent nodes run in this cwd, even if the harness's moves meanwhile.
95
+ const cwd = ctx.cwdState.cwd;
90
96
  const toolList = opts.tools.map((t) => `- ${t.name}: ${t.description}`).join('\n');
91
97
  const basePrompt = [
92
98
  opts.instructions,
93
99
  PLANNER_INSTRUCTIONS,
94
100
  `\nAvailable tools:\n${toolList}`,
95
101
  connectionsPrompt(opts.connections, plannerConnections(opts.connections, ctx)),
102
+ acpPrompt(opts.acpAgents, opts.acp, cwd),
103
+ mcpPrompt(opts.mcp),
96
104
  `\nTask: ${input}`,
97
105
  ]
98
106
  .filter(Boolean)
@@ -116,6 +124,10 @@ export function dynamicWorkflow(opts) {
116
124
  const parseResult = tryParseWorkflow(text, maxDepth, {
117
125
  allowlist: opts.connections ?? {},
118
126
  ranges: profileVersions(ctx),
127
+ acp: opts.acp,
128
+ cwd,
129
+ mcp: opts.mcp,
130
+ secrets: harnessInternal(harness, 'secrets'),
119
131
  });
120
132
  if (!parseResult.ok) {
121
133
  lastError = parseResult.error;
@@ -134,6 +146,8 @@ export function dynamicWorkflow(opts) {
134
146
  const hydrationCtx = {
135
147
  tools: toolMap,
136
148
  executeStep,
149
+ acpAgents: opts.acpAgents,
150
+ acpBounds: acpBounds(opts.acp, cwd),
137
151
  expressionLimits: opts.expressionLimits,
138
152
  };
139
153
  const hydrated = hydrateWorkflow(parseResult.doc, hydrationCtx);
@@ -166,12 +180,18 @@ export function dynamicWorkflow(opts) {
166
180
  * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` if `expressionLimits` holds a value that is not a positive integer or `Infinity`.
167
181
  * @throws `NoeticConfigError` with code `EXPRESSION_LIMIT_EXCEEDED` if an expression exceeds its limits.
168
182
  * @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.
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.
184
+ * @throws `NoeticConfigError` with code `CONNECTION_INVALID` if an MCP server uses a `$secret` and the harness has no `environment.secrets`.
170
185
  */
171
186
  export async function parseAndRunWorkflow(opts) {
172
187
  checkAllowlistNames(opts.connections, opts.ctx);
188
+ const cwd = opts.ctx.cwdState.cwd;
173
189
  const parseResult = tryParseWorkflow(opts.json, opts.maxDepth ?? DEFAULT_MAX_DEPTH, {
174
190
  allowlist: opts.connections,
191
+ acp: opts.acp,
192
+ cwd,
193
+ mcp: opts.mcp,
194
+ secrets: harnessInternal(opts.harness, 'secrets'),
175
195
  });
176
196
  if (!parseResult.ok && parseResult.configError) {
177
197
  throw parseResult.configError;
@@ -189,6 +209,8 @@ export async function parseAndRunWorkflow(opts) {
189
209
  executeStep,
190
210
  layers: opts.layers,
191
211
  workflows: opts.workflows,
212
+ acpAgents: opts.acpAgents,
213
+ acpBounds: acpBounds(opts.acp, cwd),
192
214
  maxRecursionDepth: opts.maxRecursionDepth,
193
215
  expressionLimits: opts.expressionLimits,
194
216
  };
@@ -243,7 +265,7 @@ function buildToolMap(tools) {
243
265
  function coerceToString(value) {
244
266
  return outputText(value);
245
267
  }
246
- function tryParseWorkflow(raw, maxDepth, check = {}) {
268
+ function tryParseWorkflow(raw, maxDepth, check) {
247
269
  const json = typeof raw === 'string' ? safeParse(raw) : raw;
248
270
  if (json === null) {
249
271
  return {
@@ -294,7 +316,7 @@ function tryParseWorkflow(raw, maxDepth, check = {}) {
294
316
  doc: result.data,
295
317
  };
296
318
  }
297
- /** The connection error a document has, checked against its manifest and (when given) the host allowlist. */
319
+ /** The error a document has, checked against its manifest, (when given) the host connection allowlist, and what its `acp-agent` nodes may ask. */
298
320
  function connectionErrorOf(doc, check) {
299
321
  try {
300
322
  if (check.allowlist === undefined) {
@@ -303,6 +325,8 @@ function connectionErrorOf(doc, check) {
303
325
  else {
304
326
  checkConnectionAllowlist(doc, check.allowlist);
305
327
  }
328
+ checkAcpAgents(doc, check.acp, check.cwd);
329
+ checkMcpServers(doc, check.mcp, check.secrets);
306
330
  return undefined;
307
331
  }
308
332
  catch (error) {
@@ -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
@@ -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
@@ -316,6 +316,7 @@ function resolveSubflowDocument(node, ctx) {
316
316
  childCtx: {
317
317
  ...ctx,
318
318
  recursionDepth: depth,
319
+ acpBounds: undefined,
319
320
  },
320
321
  };
321
322
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
- * Hydrators for the connection nodes of a JSON workflow (spec 35): `call` and
3
- * `wait`, plus resolving the connection a node runs on against the document's
4
- * manifest.
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
5
  */
6
6
  import type { ContextData } from '@noetic-tools/context';
7
7
  import type { Step } from '@noetic-tools/types';
@@ -15,3 +15,11 @@ import type { HydrationContext } from './workflow-hydrator.js';
15
15
  export declare function checkManifestName(name: string, where: string, ctx: HydrationContext): void;
16
16
  export declare function hydrateCallNode(node: WorkflowNode, ctx: HydrationContext): Step<ContextData, string, string>;
17
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>;
@@ -1,13 +1,16 @@
1
1
  /**
2
- * Hydrators for the connection nodes of a JSON workflow (spec 35): `call` and
3
- * `wait`, plus resolving the connection a node runs on against the document's
4
- * manifest.
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
5
  */
6
6
  import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
7
7
  import { compileExpression, compute, passes, readInput } from '../expression/jsonata.js';
8
8
  import { getDefaultRegistrar } from '../types/step-registrar.js';
9
+ import { step } from './step-builders.js';
10
+ import { boundedAcpSettings } from './workflow-acp-grants.js';
9
11
  import { compileArgs, documentHandle, documentSecretsOf } from './workflow-connections.js';
10
12
  import { bindingsFor, hydrateStepList } from './workflow-hydrator.js';
13
+ import { stepMcpServers } from './workflow-mcp-servers.js';
11
14
  //#region Connection Node Hydrators
12
15
  /**
13
16
  * Checks a connection name against the document's manifest, when there is one.
@@ -158,3 +161,38 @@ export function hydrateWaitNode(node, ctx) {
158
161
  return registered(built);
159
162
  }
160
163
  //#endregion
164
+ //#region ACP Agent Node Hydrator
165
+ /**
166
+ * Hydrates an `acp-agent` node into `step.acpAgent`. Under `ctx.acpBounds` the
167
+ * node's cwd, client capabilities and session key are held to its agent's
168
+ * grant (see `boundedAcpSettings`).
169
+ *
170
+ * @throws `NoeticConfigError` `UNKNOWN_ACP_AGENT_REFERENCE` when `ctx.acpAgents` has no adapter for the node's agent.
171
+ */
172
+ export function hydrateAcpAgentNode(node, ctx) {
173
+ if (node.kind !== 'acp-agent') {
174
+ return frameworkCast(undefined);
175
+ }
176
+ const agent = ctx.acpAgents?.get(node.agent);
177
+ if (!agent) {
178
+ throw new NoeticConfigError({
179
+ code: 'UNKNOWN_ACP_AGENT_REFERENCE',
180
+ message: `ACP agent '${node.agent}' referenced in workflow node '${node.id}' is not registered.`,
181
+ hint: 'Pass agent adapters via HydrationContext.acpAgents, e.g. createAcpAgentRegistry(claudeCode()) from @noetic-tools/acp.',
182
+ });
183
+ }
184
+ const bounded = ctx.acpBounds ? boundedAcpSettings(node, ctx.acpBounds) : node;
185
+ return step.acpAgent({
186
+ id: node.id,
187
+ agent,
188
+ prompt: node.prompt,
189
+ cwd: bounded.cwd,
190
+ mode: node.mode,
191
+ model: node.model,
192
+ mcpServers: stepMcpServers(node.mcpServers),
193
+ permissions: node.permissions,
194
+ clientCapabilities: bounded.clientCapabilities,
195
+ session: bounded.session,
196
+ });
197
+ }
198
+ //#endregion
@@ -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, Context, CustomItemMap, ExecuteStepFn, OutputCodec, Step, SubprocessAdapter, Tool } from '@noetic-tools/types';
9
+ import type { AcpAgent, AcpAllowlist, Context, CustomItemMap, ExecuteStepFn, 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';
@@ -52,6 +52,18 @@ export interface HydrationContext {
52
52
  recursionDepth?: number;
53
53
  /** Bounds on each expression evaluation; unset fields use `DEFAULT_EXPRESSION_LIMITS`. */
54
54
  expressionLimits?: ExpressionLimits;
55
+ /**
56
+ * What `acp-agent` nodes are held to when the host did not write the
57
+ * document: set by `parseAndRunWorkflow` and `dynamicWorkflow`, dropped for
58
+ * named subflow refs, which the host wrote. Callers never set it.
59
+ */
60
+ acpBounds?: {
61
+ readonly grants: AcpAllowlist;
62
+ /** Prefixes every `session.reuse` key, so the document's sessions never meet the host's. */
63
+ readonly sessionScope: string;
64
+ /** The harness's working directory when the document was checked: a node's `cwd` when neither it nor its grant sets one. */
65
+ readonly cwd: string;
66
+ };
55
67
  /**
56
68
  * The hydrated document's identity for `$steps`: each `hydrateWorkflow` call
57
69
  * makes a new one, so two documents in one run never read each other's node
@@ -11,9 +11,9 @@ import { markRecorded, stepOutputsOf } from '../expression/step-outputs.js';
11
11
  import { shorthandStepId, stepEntryToNode, stepListEntries } from '../schemas/workflow.js';
12
12
  import { DetachedHandleImpl } from '../util/detached-handle.js';
13
13
  import { outputText } from './output-text.js';
14
- import { callModel, runCode, step } from './step-builders.js';
14
+ import { callModel, runCode } from './step-builders.js';
15
15
  import { hydrateInParallelNode, hydrateSpawnNode, hydrateSubflowNode, hydrateWithContextNode, } from './workflow-child-nodes.js';
16
- import { hydrateCallNode, hydrateWaitNode } from './workflow-connection-nodes.js';
16
+ import { hydrateAcpAgentNode, hydrateCallNode, hydrateWaitNode } from './workflow-connection-nodes.js';
17
17
  import { checkDocumentConnections } from './workflow-connections.js';
18
18
  import { hydrateConditionalNode, hydrateDecideNode, hydrateLoopNode, hydrateRouteSwitchNode, hydrateScheduleNode, } from './workflow-control-nodes.js';
19
19
  import { documentScope, everyDocumentItem, hydrateEmitItems, nodeScope, } from './workflow-custom-items.js';
@@ -189,31 +189,6 @@ function hydrateSequenceNode(node, ctx) {
189
189
  },
190
190
  }));
191
191
  }
192
- function hydrateAcpAgentNode(node, ctx) {
193
- if (node.kind !== 'acp-agent') {
194
- return frameworkCast(undefined);
195
- }
196
- const agent = ctx.acpAgents?.get(node.agent);
197
- if (!agent) {
198
- throw new NoeticConfigError({
199
- code: 'UNKNOWN_ACP_AGENT_REFERENCE',
200
- message: `ACP agent '${node.agent}' referenced in workflow node '${node.id}' is not registered.`,
201
- hint: 'Pass agent adapters via HydrationContext.acpAgents, e.g. createAcpAgentRegistry(claudeCode()) from @noetic-tools/acp.',
202
- });
203
- }
204
- return step.acpAgent({
205
- id: node.id,
206
- agent,
207
- prompt: node.prompt,
208
- cwd: node.cwd,
209
- mode: node.mode,
210
- model: node.model,
211
- mcpServers: node.mcpServers,
212
- permissions: node.permissions,
213
- clientCapabilities: node.clientCapabilities,
214
- session: node.session,
215
- });
216
- }
217
192
  //#endregion
218
193
  //#region Document Scope
219
194
  /** Nodes hydrated outside any `hydrateWorkflow` (a bare `hydrateNode`) share one scope. */
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The MCP servers a document's `acp-agent` nodes hand to an agent. A stdio
3
+ * server is a command the agent launches, and a header or environment value
4
+ * reaches the agent process, so a document a host did not write may name only
5
+ * the servers the host's `mcp` allowlist grants (spec 26 § MCP servers).
6
+ */
7
+ import type { AcpMcpServer, Lazy, McpAllowlist, SecretResolver, WorkflowDocument, WorkflowMcpServer } from '@noetic-tools/types';
8
+ /**
9
+ * Checks every MCP server a document's `acp-agent` nodes name against the
10
+ * host's allowlist. No allowlist grants nothing. Inline subflows count; named
11
+ * refs resolve from the host's own registry and are not checked.
12
+ *
13
+ * @throws `NoeticConfigError` `CONNECTION_NOT_ALLOWED` for a server, header or environment value the allowlist does not grant, or a header or environment variable named twice.
14
+ * @throws `NoeticConfigError` `CONNECTION_INVALID` for a value that is a `$secret` when the harness has no `secrets` resolver, or an allowlist URL pattern that does not parse.
15
+ */
16
+ export declare function checkMcpServers(doc: WorkflowDocument, allowlist: McpAllowlist | undefined, secrets: SecretResolver | undefined): void;
17
+ /**
18
+ * The servers an `acp-agent` step gets: as written, or — when a value is a
19
+ * `$secret` — resolved through the harness's `environment.secrets` when the
20
+ * session starts.
21
+ */
22
+ export declare function stepMcpServers(servers: ReadonlyArray<WorkflowMcpServer> | undefined): Lazy<ReadonlyArray<AcpMcpServer> | undefined>;
23
+ /** The planner's view of the servers it may give an `acp-agent` node. */
24
+ export declare function mcpPrompt(allowlist: McpAllowlist | undefined): string;
@@ -0,0 +1,220 @@
1
+ /**
2
+ * The MCP servers a document's `acp-agent` nodes hand to an agent. A stdio
3
+ * server is a command the agent launches, and a header or environment value
4
+ * reaches the agent process, so a document a host did not write may name only
5
+ * the servers the host's `mcp` allowlist grants (spec 26 § MCP servers).
6
+ */
7
+ import { NoeticConfigError, walkWorkflow } from '@noetic-tools/types';
8
+ import { harnessInternal } from '../util/harness-internals.js';
9
+ import { urlPatternMatches } from './mcp-url-pattern.js';
10
+ //#endregion
11
+ //#region Public API
12
+ /**
13
+ * Checks every MCP server a document's `acp-agent` nodes name against the
14
+ * host's allowlist. No allowlist grants nothing. Inline subflows count; named
15
+ * refs resolve from the host's own registry and are not checked.
16
+ *
17
+ * @throws `NoeticConfigError` `CONNECTION_NOT_ALLOWED` for a server, header or environment value the allowlist does not grant, or a header or environment variable named twice.
18
+ * @throws `NoeticConfigError` `CONNECTION_INVALID` for a value that is a `$secret` when the harness has no `secrets` resolver, or an allowlist URL pattern that does not parse.
19
+ */
20
+ export function checkMcpServers(doc, allowlist, secrets) {
21
+ for (const node of walkWorkflow(doc.root)) {
22
+ for (const server of serversOf(node)) {
23
+ checkServer(node.id, server, allowlist ?? {});
24
+ if (!secrets && !isLiteral(server)) {
25
+ throw noResolver();
26
+ }
27
+ }
28
+ }
29
+ }
30
+ /**
31
+ * The servers an `acp-agent` step gets: as written, or — when a value is a
32
+ * `$secret` — resolved through the harness's `environment.secrets` when the
33
+ * session starts.
34
+ */
35
+ export function stepMcpServers(servers) {
36
+ if (!servers || servers.every(isLiteral)) {
37
+ return servers;
38
+ }
39
+ return (ctx) => resolveServers(servers, ctx);
40
+ }
41
+ /** The planner's view of the servers it may give an `acp-agent` node. */
42
+ export function mcpPrompt(allowlist) {
43
+ const lines = [
44
+ ...(allowlist?.urls ?? []).map(urlLine),
45
+ ...(allowlist?.commands ?? []).map(commandLine),
46
+ ];
47
+ if (lines.length === 0) {
48
+ return '\nNo MCP servers are available: do not give acp-agent nodes "mcpServers".';
49
+ }
50
+ return `\nMCP servers an acp-agent node may list in "mcpServers" (no others; header and env values only as the { "$secret": "<name>" } shown; write each URL as \`new URL(url).href\` gives it back, e.g. "https://host/" with a lowercase host and a path):
51
+ ${lines.join('\n')}`;
52
+ }
53
+ //#endregion
54
+ //#region Checks
55
+ function serversOf(node) {
56
+ return node.kind === 'acp-agent' ? (node.mcpServers ?? []) : [];
57
+ }
58
+ function checkServer(nodeId, server, allowlist) {
59
+ if ('url' in server) {
60
+ checkUrlServer(nodeId, server, allowlist.urls ?? []);
61
+ return;
62
+ }
63
+ checkStdioServer(nodeId, server, allowlist.commands ?? []);
64
+ }
65
+ function checkUrlServer(nodeId, server, grants) {
66
+ const url = plainUrl(nodeId, server);
67
+ const matching = grants.filter((g) => urlPatternMatches(g.url, url));
68
+ if (matching.length === 0) {
69
+ throw notAllowed(`Node '${nodeId}' gives the agent MCP server '${server.name}' at ${server.url}, which the host does not allow.`, `Allowed MCP server URLs: ${grants.map((g) => g.url).join(', ') || '(none)'}.`);
70
+ }
71
+ checkValues(server.headers, matching, {
72
+ nodeId,
73
+ server: server.name,
74
+ what: 'header',
75
+ });
76
+ }
77
+ function checkStdioServer(nodeId, server, grants) {
78
+ const matching = grants.filter((g) => g.command === server.command && sameArgs(g.args ?? [], server.args));
79
+ if (matching.length === 0) {
80
+ throw notAllowed(`Node '${nodeId}' gives the agent stdio MCP server '${server.name}' (${commandText(server.command, server.args)}), which the host does not allow.`, `Allowed MCP server commands: ${grants.map((g) => commandText(g.command, g.args ?? [])).join('; ') || '(none)'}.`);
81
+ }
82
+ checkValues(server.env, matching, {
83
+ nodeId,
84
+ server: server.name,
85
+ what: 'environment variable',
86
+ });
87
+ }
88
+ /**
89
+ * Every header or environment value must be a `$secret` that one grant matching
90
+ * the server binds to that name — the same grant for all of them, so a looser
91
+ * grant listed first cannot hide a tighter one that allows the values. Each
92
+ * name appears once: which of two `Authorization` headers the agent sends is
93
+ * up to the agent.
94
+ */
95
+ function checkValues(values, grants, where) {
96
+ const twice = values.find((entry, i) => values.slice(0, i).some((earlier) => sameName(earlier.name, entry.name, where.what)));
97
+ if (twice) {
98
+ throw notAllowed(`Node '${where.nodeId}' sets ${where.what} '${twice.name}' on MCP server '${where.server}' more than once.`, `Name each ${where.what} once.`);
99
+ }
100
+ if (grants.some((g) => values.every((entry) => binds(g, entry, where.what)))) {
101
+ return;
102
+ }
103
+ const { nodeId, server, what } = where;
104
+ const entry = values.find((e) => !grants.some((g) => binds(g, e, what)));
105
+ if (!entry) {
106
+ throw notAllowed(`Node '${nodeId}' sets ${what}s ${values.map((e) => `'${e.name}'`).join(', ')} on MCP server '${server}', which no one grant allows together.`, `Name only the ${what}s one grant binds.`);
107
+ }
108
+ const granted = grants.flatMap((g) => Object.entries(g.secrets ?? {})
109
+ .filter(([, name]) => sameName(name, entry.name, what))
110
+ .map(([secret]) => `{ "$secret": "${secret}" }`));
111
+ throw notAllowed(`Node '${nodeId}' sets ${what} '${entry.name}' on MCP server '${server}' to a value the host does not allow.`, granted.length > 0
112
+ ? `'${entry.name}' takes only ${granted.join(' or ')}.`
113
+ : `The host binds no secret to ${what} '${entry.name}'.`);
114
+ }
115
+ function binds(grant, entry, what) {
116
+ if (!isSecret(entry.value) ||
117
+ !grant.secrets ||
118
+ !Object.hasOwn(grant.secrets, entry.value.$secret)) {
119
+ return false;
120
+ }
121
+ return sameName(grant.secrets[entry.value.$secret] ?? '', entry.name, what);
122
+ }
123
+ /** HTTP header names are case-insensitive; environment variable names are not. */
124
+ function sameName(granted, written, what) {
125
+ return what === 'header' ? granted.toLowerCase() === written.toLowerCase() : granted === written;
126
+ }
127
+ /**
128
+ * The server's URL, when it is http(s), carries no user or password
129
+ * (`http://localhost:1@evil.example/` would otherwise match
130
+ * `http://localhost:*`), and is written exactly as `URL` reads it back. The
131
+ * agent gets the URL as written, so a URL whose reading differs — a backslash,
132
+ * a tab, an uppercase host — is refused rather than checked in one form and
133
+ * used in another.
134
+ */
135
+ function plainUrl(nodeId, server) {
136
+ const parsed = URL.canParse(server.url) ? new URL(server.url) : undefined;
137
+ if (!parsed ||
138
+ (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') ||
139
+ parsed.username !== '' ||
140
+ parsed.password !== '') {
141
+ throw notAllowed(`Node '${nodeId}' gives the agent MCP server '${server.name}' at ${JSON.stringify(server.url)}, which is not an http: or https: URL without a user or password.`, 'Give an http: or https: URL with no user or password.');
142
+ }
143
+ if (parsed.href !== server.url) {
144
+ throw notAllowed(`Node '${nodeId}' gives the agent MCP server '${server.name}' at ${JSON.stringify(server.url)}, which reads as ${parsed.href}.`, `Write the URL as ${parsed.href}.`);
145
+ }
146
+ return parsed;
147
+ }
148
+ function sameArgs(a, b) {
149
+ return a.length === b.length && a.every((arg, i) => arg === b[i]);
150
+ }
151
+ function commandText(command, args) {
152
+ return JSON.stringify([
153
+ command,
154
+ ...args,
155
+ ]);
156
+ }
157
+ function notAllowed(message, hint) {
158
+ return new NoeticConfigError({
159
+ code: 'CONNECTION_NOT_ALLOWED',
160
+ message,
161
+ hint,
162
+ });
163
+ }
164
+ function noResolver() {
165
+ return new NoeticConfigError({
166
+ code: 'CONNECTION_INVALID',
167
+ message: 'An MCP server uses a $secret but the harness has no secret resolver.',
168
+ hint: 'Set `environment.secrets` on the AgentHarness to resolve secret names.',
169
+ });
170
+ }
171
+ //#endregion
172
+ //#region Secrets
173
+ async function resolveServers(servers, ctx) {
174
+ const resolver = harnessInternal(ctx.harness, 'secrets');
175
+ if (!resolver) {
176
+ throw noResolver();
177
+ }
178
+ const signal = ctx.aborted ? AbortSignal.abort(ctx.abortReason) : new AbortController().signal;
179
+ const resolve = async (entry) => ({
180
+ name: entry.name,
181
+ value: isSecret(entry.value)
182
+ ? await resolver.resolve(entry.value.$secret, {
183
+ signal,
184
+ })
185
+ : entry.value,
186
+ });
187
+ return Promise.all(servers.map(async (server) => withValues(server, await Promise.all(valuesOf(server).map(resolve)))));
188
+ }
189
+ function valuesOf(server) {
190
+ return 'url' in server ? server.headers : server.env;
191
+ }
192
+ function withValues(server, values) {
193
+ return 'url' in server
194
+ ? {
195
+ ...server,
196
+ headers: values,
197
+ }
198
+ : {
199
+ ...server,
200
+ env: values,
201
+ };
202
+ }
203
+ /** Whether no header or environment value is a `$secret`, so the server is already an ACP one. */
204
+ function isLiteral(server) {
205
+ return valuesOf(server).every((entry) => !isSecret(entry.value));
206
+ }
207
+ function isSecret(value) {
208
+ return typeof value !== 'string';
209
+ }
210
+ //#endregion
211
+ //#region Prompt
212
+ function urlLine(grant) {
213
+ const headers = Object.entries(grant.secrets ?? {}).map(([secret, header]) => `{ "name": "${header}", "value": { "$secret": "${secret}" } }`);
214
+ return `- { "type": "http" or "sse", "name": "<name>", "url": "<URL matching ${grant.url}>", "headers": [${headers.join(', ')}] } (headers optional)`;
215
+ }
216
+ function commandLine(grant) {
217
+ const env = Object.entries(grant.secrets ?? {}).map(([secret, variable]) => `{ "name": "${variable}", "value": { "$secret": "${secret}" } }`);
218
+ return `- { "name": "<name>", "command": ${JSON.stringify(grant.command)}, "args": ${JSON.stringify(grant.args ?? [])}, "env": [${env.join(', ')}] } (env optional)`;
219
+ }
220
+ //#endregion
@@ -31,6 +31,7 @@ export class ConnectionGate {
31
31
  setHarnessInternals(options.harness, {
32
32
  connectionRegistry: this.#connections?.registry,
33
33
  verifier: options.verifier,
34
+ secrets: options.secrets,
34
35
  });
35
36
  }
36
37
  /** The connection registry, absent on a harness without connections or triggers. */
package/dist/index.d.ts CHANGED
@@ -127,7 +127,7 @@ export type { Expression } from '@noetic-tools/types';
127
127
  /** @public */
128
128
  export { defaultItemSchemaRegistry, ExpressionSchema, ItemSchema, ItemSchemaRegistry, } from '@noetic-tools/types';
129
129
  /** @public */
130
- export type { AcpAgentWorkflowNode, CallModelWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, MergeStrategy, RouteSwitchWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, WithContextWorkflowNode, WorkflowCustomItem, WorkflowDocument, WorkflowEmitItems, WorkflowNode, } from './schemas/workflow.js';
130
+ export type { AcpAgentWorkflowNode, CallModelWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, MergeStrategy, RouteSwitchWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, WithContextWorkflowNode, WorkflowCustomItem, WorkflowDocument, WorkflowEmitItems, WorkflowMcpServer, WorkflowNode, } from './schemas/workflow.js';
131
131
  /** @public */
132
132
  export { MergeStrategySchema, UntilPredicateSchema, validateWorkflow, WorkflowDocumentSchema, WorkflowNodeSchema, walkWorkflow, workflowDepth, } from './schemas/workflow.js';
133
133
  /** @public */
@@ -186,7 +186,7 @@ export { BooleanQuestionSchema, ChoiceQuestionSchema, choiceValues, DECIDE_LIMIT
186
186
  /** @public */
187
187
  export type { RouteSwitchByFunctionOpts, RouteSwitchByKeyOpts, StepDecideOpts, StepInput, StepOutput, } from './builders/decide-builders.js';
188
188
  /** @public */
189
- export type { AcpAgent, AcpAgentCapabilities, AcpAgentConnection, AcpAuthMethod, AcpAvailableCommand, AcpBoundPermissionHandler, AcpClientCapabilityConfig, AcpClientHost, AcpConnectOptions, AcpContentBlock, AcpKeepAlive, AcpLiveSession, AcpLoadSessionOptions, AcpMcpServer, AcpNewSessionOptions, AcpPermissionHandler, AcpPermissionOption, AcpPermissionOutcome, AcpPermissionPolicy, AcpPermissionRequestInfo, AcpPermissionRule, AcpPermissionSteerer, AcpPlanEntry, AcpPromptCapabilities, AcpPromptOptions, AcpRequestPermissionRequest, AcpSession, AcpSessionDisposer, AcpSessionInfo, AcpSessionMode, AcpSessionModeState, AcpSessionNotification, AcpSessionPolicy, AcpStopReason, AcpToolCallContent, AcpToolCallStatus, AcpToolKind, AcpTransport, AcpTransportFactory, AcpTransportOptions, AcpTurnResult, } from '@noetic-tools/types';
189
+ export type { AcpAgent, AcpAgentCapabilities, AcpAgentConnection, AcpAgentGrant, AcpAllowlist, AcpAuthMethod, AcpAvailableCommand, AcpBoundPermissionHandler, AcpCapabilityGrant, AcpClientCapabilityConfig, AcpClientHost, AcpConnectOptions, AcpContentBlock, AcpKeepAlive, AcpLiveSession, AcpLoadSessionOptions, AcpMcpServer, AcpNewSessionOptions, AcpPermissionGrant, AcpPermissionHandler, AcpPermissionOption, AcpPermissionOutcome, AcpPermissionPolicy, AcpPermissionRequestInfo, AcpPermissionRule, AcpPermissionSteerer, AcpPlanEntry, AcpPromptCapabilities, AcpPromptOptions, AcpRequestPermissionRequest, AcpSession, AcpSessionDisposer, AcpSessionGrant, AcpSessionInfo, AcpSessionMode, AcpSessionModeState, AcpSessionNotification, AcpSessionPolicy, AcpStopReason, AcpToolCallContent, AcpToolCallStatus, AcpToolKind, AcpTransport, AcpTransportFactory, AcpTransportOptions, AcpTurnResult, } from '@noetic-tools/types';
190
190
  /** @public */
191
191
  export { ACP_AGENT_STEP_KIND, AcpCapabilityError, AcpConnectError, AcpPermissionDecision, isAcpCapabilityError, isAcpConnectError, } from '@noetic-tools/types';
192
192
  /** @public */
@@ -205,7 +205,7 @@ export { createLiveHandles } from './adapters/live-handles.js';
205
205
  /** @public */
206
206
  export type { ToolContext, ToolExecutionContext } from '@noetic-tools/types';
207
207
  /** @public */
208
- export type { ArtifactLink, ArtifactMeta, ArtifactRecord, ArtifactRetention, ArtifactStore, BlobRef, BlobRefBody, BlobReference, CallOptions, CallOutcome, CallResult, Connection, ConnectionAllowlist, ConnectionAllowlistEntry, ConnectionConfig, ConnectionEntry, ConnectionEvent, ConnectionEventInfo, ConnectionEventInit, ConnectionExpose, ConnectionHandle, ConnectionHandleOptions, ConnectionIdentity, ConnectionLease, ConnectionLook, ConnectionManifest, ConnectionMissing, ConnectionOperationInfo, ConnectionPolicy, ConnectionPoolConfig, ConnectionProvider, ConnectionRequirement, ConnectionResourceInfo, ConnectionSource, ConnectionState, ConnectionStatus, ConnectionsConfig, ConnectionTaskStatus, ConnectionTasks, ConnectionTrigger, ConnectOptions, CronOptions, CronTick, Determinism, EventStream, EventStreamMessage, FreshScope, ListenRequest, Locator, Receipt, Ref, RefBody, Secret, SecretResolver, SourceDefinition, SourceEmitEvent, Target, } from '@noetic-tools/types';
208
+ export type { ArtifactLink, ArtifactMeta, ArtifactRecord, ArtifactRetention, ArtifactStore, BlobRef, BlobRefBody, BlobReference, CallOptions, CallOutcome, CallResult, Connection, ConnectionAllowlist, ConnectionAllowlistEntry, ConnectionConfig, ConnectionEntry, ConnectionEvent, ConnectionEventInfo, ConnectionEventInit, ConnectionExpose, ConnectionHandle, ConnectionHandleOptions, ConnectionIdentity, ConnectionLease, ConnectionLook, ConnectionManifest, ConnectionMissing, ConnectionOperationInfo, ConnectionPolicy, ConnectionPoolConfig, ConnectionProvider, ConnectionRequirement, ConnectionResourceInfo, ConnectionSource, ConnectionState, ConnectionStatus, ConnectionsConfig, ConnectionTaskStatus, ConnectionTasks, ConnectionTrigger, ConnectOptions, CronOptions, CronTick, Determinism, EventStream, EventStreamMessage, FreshScope, ListenRequest, Locator, McpAllowlist, McpCommandGrant, McpUrlGrant, Receipt, Ref, RefBody, Secret, SecretResolver, SourceDefinition, SourceEmitEvent, Target, } from '@noetic-tools/types';
209
209
  /** @public */
210
210
  /** @public */
211
211
  export { ARTIFACT_URI_PREFIX, artifactDigest, artifactUri, ConnectionUnsatisfiedError, DEFAULT_ARTIFACT_MAX_BYTES_PER_RUN, DEFAULT_ARTIFACT_MAX_COUNT_PER_RUN, isBlobRef, isConnectionUnsatisfiedError, isRef, isSecret, refId, secret, } from '@noetic-tools/types';
@@ -3,5 +3,5 @@
3
3
  * consumers can validate workflow documents without importing core.
4
4
  * This barrel keeps core's public and intra-core import paths unchanged.
5
5
  */
6
- export type { AcpAgentWorkflowNode, CallModelWorkflowNode, CallWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, OutputCodecRef, RouteSwitchWorkflowNode, RunCodeWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, VerifyWorkflowNode, WaitWorkflowNode, WithContextWorkflowNode, WorkflowArgs, WorkflowConnectionRef, WorkflowConnectionRequirement, WorkflowCustomItem, WorkflowDocument, WorkflowEmitItems, WorkflowExprValue, WorkflowGraph, WorkflowLiteralValue, WorkflowNode, WorkflowOpShorthand, WorkflowReplayKey, WorkflowSecretValue, WorkflowStepEntry, WorkflowStepList, WorkflowValue, WorkflowVerifyClose, WorkflowVerifyMatcher, } from '@noetic-tools/types';
6
+ export type { AcpAgentWorkflowNode, CallModelWorkflowNode, CallWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, OutputCodecRef, RouteSwitchWorkflowNode, RunCodeWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, VerifyWorkflowNode, WaitWorkflowNode, WithContextWorkflowNode, WorkflowArgs, WorkflowConnectionRef, WorkflowConnectionRequirement, WorkflowCustomItem, WorkflowDocument, WorkflowEmitItems, WorkflowExprValue, WorkflowGraph, WorkflowLiteralValue, WorkflowMcpServer, WorkflowNode, WorkflowOpShorthand, WorkflowReplayKey, WorkflowSecretValue, WorkflowStepEntry, WorkflowStepList, WorkflowValue, WorkflowVerifyClose, WorkflowVerifyMatcher, } from '@noetic-tools/types';
7
7
  export { isWorkflowOpShorthand, MergeStrategy, MergeStrategySchema, shorthandStepId, stepEntryToNode, stepListEntries, UntilPredicateSchema, validateWorkflow, verifyMatcherFromJson, WorkflowArgsSchema, WorkflowConnectionRequirementSchema, WorkflowDocumentSchema, WorkflowNodeSchema, WorkflowOpShorthandSchema, WorkflowValueSchema, WorkflowVerifyMatcherSchema, walkWorkflow, workflowDepth, workflowGraph, } from '@noetic-tools/types';
@@ -11,6 +11,8 @@ export interface HarnessInternalSlots {
11
11
  connectionRegistry: unknown;
12
12
  /** The verifier `step.verify` uses (spec 37). */
13
13
  verifier: unknown;
14
+ /** The harness's `environment.secrets` resolver (spec 35 § Secrets). */
15
+ secrets: unknown;
14
16
  }
15
17
  type HarnessInternalKey = keyof HarnessInternalSlots;
16
18
  /** Records internal slots of a harness, merged over any it already has. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noetic-tools/core",
3
- "version": "5.19.2",
3
+ "version": "5.19.3",
4
4
  "type": "module",
5
5
  "description": "Step primitives, interpreter, runtime, and context layer contract for Noetic agents.",
6
6
  "license": "Apache-2.0",
@@ -69,7 +69,7 @@
69
69
  },
70
70
  "dependencies": {
71
71
  "@noetic-tools/context": "^1.11.1",
72
- "@noetic-tools/types": "^3.17.1",
72
+ "@noetic-tools/types": "^3.17.2",
73
73
  "@openrouter/agent": "^0.11.0",
74
74
  "@openrouter/sdk": "1.4.25",
75
75
  "jsonata": "2.2.2",
@@ -2572,7 +2572,24 @@
2572
2572
  "type": "string"
2573
2573
  },
2574
2574
  "value": {
2575
- "type": "string"
2575
+ "anyOf": [
2576
+ {
2577
+ "type": "string"
2578
+ },
2579
+ {
2580
+ "type": "object",
2581
+ "properties": {
2582
+ "$secret": {
2583
+ "type": "string",
2584
+ "minLength": 1
2585
+ }
2586
+ },
2587
+ "required": [
2588
+ "$secret"
2589
+ ],
2590
+ "additionalProperties": false
2591
+ }
2592
+ ]
2576
2593
  }
2577
2594
  },
2578
2595
  "required": [
@@ -2614,7 +2631,24 @@
2614
2631
  "type": "string"
2615
2632
  },
2616
2633
  "value": {
2617
- "type": "string"
2634
+ "anyOf": [
2635
+ {
2636
+ "type": "string"
2637
+ },
2638
+ {
2639
+ "type": "object",
2640
+ "properties": {
2641
+ "$secret": {
2642
+ "type": "string",
2643
+ "minLength": 1
2644
+ }
2645
+ },
2646
+ "required": [
2647
+ "$secret"
2648
+ ],
2649
+ "additionalProperties": false
2650
+ }
2651
+ ]
2618
2652
  }
2619
2653
  },
2620
2654
  "required": [
@@ -2659,7 +2693,24 @@
2659
2693
  "type": "string"
2660
2694
  },
2661
2695
  "value": {
2662
- "type": "string"
2696
+ "anyOf": [
2697
+ {
2698
+ "type": "string"
2699
+ },
2700
+ {
2701
+ "type": "object",
2702
+ "properties": {
2703
+ "$secret": {
2704
+ "type": "string",
2705
+ "minLength": 1
2706
+ }
2707
+ },
2708
+ "required": [
2709
+ "$secret"
2710
+ ],
2711
+ "additionalProperties": false
2712
+ }
2713
+ ]
2663
2714
  }
2664
2715
  },
2665
2716
  "required": [