@noetic-tools/core 5.19.1 → 5.19.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/dist/adapters/openrouter.js +5 -0
  2. package/dist/builders/control-flow-builders.d.ts +15 -6
  3. package/dist/builders/control-flow-builders.js +8 -0
  4. package/dist/builders/decide-builders.d.ts +2 -5
  5. package/dist/builders/dynamic-workflow.d.ts +54 -2
  6. package/dist/builders/dynamic-workflow.js +247 -12
  7. package/dist/builders/every.d.ts +3 -3
  8. package/dist/builders/every.js +2 -1
  9. package/dist/builders/mcp-url-pattern.d.ts +13 -0
  10. package/dist/builders/mcp-url-pattern.js +85 -0
  11. package/dist/builders/provide-builder.d.ts +3 -2
  12. package/dist/builders/provide-builder.js +2 -1
  13. package/dist/builders/sequence.d.ts +14 -0
  14. package/dist/builders/sequence.js +103 -0
  15. package/dist/builders/spawn-builder.d.ts +3 -2
  16. package/dist/builders/spawn-builder.js +3 -2
  17. package/dist/builders/step-builders.d.ts +80 -1
  18. package/dist/builders/step-builders.js +115 -1
  19. package/dist/builders/verify-builder.d.ts +79 -0
  20. package/dist/builders/verify-builder.js +69 -0
  21. package/dist/builders/workflow-acp-grants.d.ts +42 -0
  22. package/dist/builders/workflow-acp-grants.js +224 -0
  23. package/dist/builders/workflow-child-nodes.d.ts +21 -0
  24. package/dist/builders/workflow-child-nodes.js +336 -0
  25. package/dist/builders/workflow-connection-nodes.d.ts +25 -0
  26. package/dist/builders/workflow-connection-nodes.js +198 -0
  27. package/dist/builders/workflow-connections.d.ts +90 -0
  28. package/dist/builders/workflow-connections.js +560 -0
  29. package/dist/builders/workflow-control-nodes.d.ts +13 -0
  30. package/dist/builders/workflow-control-nodes.js +213 -0
  31. package/dist/builders/workflow-hydrator.d.ts +56 -3
  32. package/dist/builders/workflow-hydrator.js +53 -520
  33. package/dist/builders/workflow-mcp-servers.d.ts +24 -0
  34. package/dist/builders/workflow-mcp-servers.js +220 -0
  35. package/dist/builders/workflow-verify.d.ts +19 -0
  36. package/dist/builders/workflow-verify.js +194 -0
  37. package/dist/conditions/conditions.d.ts +7 -5
  38. package/dist/conditions/conditions.js +7 -4
  39. package/dist/connections/blobs.d.ts +33 -0
  40. package/dist/connections/blobs.js +77 -0
  41. package/dist/connections/cron-schedule.d.ts +32 -0
  42. package/dist/connections/cron-schedule.js +213 -0
  43. package/dist/connections/durability.d.ts +65 -0
  44. package/dist/connections/durability.js +54 -0
  45. package/dist/connections/errors.d.ts +30 -0
  46. package/dist/connections/errors.js +100 -0
  47. package/dist/connections/event-stream.d.ts +24 -0
  48. package/dist/connections/event-stream.js +176 -0
  49. package/dist/connections/gates.d.ts +94 -0
  50. package/dist/connections/gates.js +271 -0
  51. package/dist/connections/glob.d.ts +10 -0
  52. package/dist/connections/glob.js +46 -0
  53. package/dist/connections/handle.d.ts +22 -0
  54. package/dist/connections/handle.js +84 -0
  55. package/dist/connections/harness-wiring.d.ts +52 -0
  56. package/dist/connections/harness-wiring.js +143 -0
  57. package/dist/connections/in-memory-connection.d.ts +147 -0
  58. package/dist/connections/in-memory-connection.js +593 -0
  59. package/dist/connections/index.d.ts +34 -0
  60. package/dist/connections/index.js +23 -0
  61. package/dist/connections/json-schema.d.ts +28 -0
  62. package/dist/connections/json-schema.js +338 -0
  63. package/dist/connections/model-tools.d.ts +46 -0
  64. package/dist/connections/model-tools.js +466 -0
  65. package/dist/connections/negotiation.d.ts +30 -0
  66. package/dist/connections/negotiation.js +159 -0
  67. package/dist/connections/policy.d.ts +21 -0
  68. package/dist/connections/policy.js +34 -0
  69. package/dist/connections/pool.d.ts +111 -0
  70. package/dist/connections/pool.js +339 -0
  71. package/dist/connections/refs.d.ts +74 -0
  72. package/dist/connections/refs.js +316 -0
  73. package/dist/connections/registry-types.d.ts +141 -0
  74. package/dist/connections/registry-types.js +14 -0
  75. package/dist/connections/registry.d.ts +125 -0
  76. package/dist/connections/registry.js +775 -0
  77. package/dist/connections/secrets.d.ts +59 -0
  78. package/dist/connections/secrets.js +153 -0
  79. package/dist/connections/settle.d.ts +9 -0
  80. package/dist/connections/settle.js +26 -0
  81. package/dist/connections/sources.d.ts +27 -0
  82. package/dist/connections/sources.js +300 -0
  83. package/dist/connections/triggers.d.ts +78 -0
  84. package/dist/connections/triggers.js +310 -0
  85. package/dist/connections/values.d.ts +26 -0
  86. package/dist/connections/values.js +93 -0
  87. package/dist/connections/views.d.ts +31 -0
  88. package/dist/connections/views.js +176 -0
  89. package/dist/expression/check.js +80 -1
  90. package/dist/expression/jsonata.d.ts +14 -4
  91. package/dist/expression/jsonata.js +27 -9
  92. package/dist/expression/step-outputs.d.ts +25 -0
  93. package/dist/expression/step-outputs.js +78 -0
  94. package/dist/harness/agent-harness.d.ts +69 -166
  95. package/dist/harness/agent-harness.js +170 -262
  96. package/dist/harness/call-span-collector.d.ts +33 -0
  97. package/dist/harness/call-span-collector.js +83 -0
  98. package/dist/harness/connection-gate.d.ts +78 -0
  99. package/dist/harness/connection-gate.js +170 -0
  100. package/dist/harness/deps/interpreter.d.ts +1 -0
  101. package/dist/harness/deps/interpreter.js +1 -0
  102. package/dist/harness/deps/runtime.d.ts +1 -1
  103. package/dist/harness/deps/types.d.ts +1 -1
  104. package/dist/harness/harness-options.d.ts +153 -0
  105. package/dist/harness/harness-options.js +36 -0
  106. package/dist/harness/harness-tracing.d.ts +16 -0
  107. package/dist/harness/harness-tracing.js +35 -0
  108. package/dist/harness/llm-client.d.ts +71 -0
  109. package/dist/harness/llm-client.js +218 -0
  110. package/dist/harness/model-call.d.ts +2 -7
  111. package/dist/harness/model-call.js +21 -549
  112. package/dist/harness/model-request.d.ts +42 -0
  113. package/dist/harness/model-request.js +159 -0
  114. package/dist/harness/model-stream.d.ts +39 -0
  115. package/dist/harness/model-stream.js +131 -0
  116. package/dist/harness/model-tool-round.d.ts +37 -0
  117. package/dist/harness/model-tool-round.js +197 -0
  118. package/dist/harness/spend.d.ts +2 -0
  119. package/dist/harness/spend.js +5 -1
  120. package/dist/index.d.ts +33 -8
  121. package/dist/index.js +18 -1
  122. package/dist/interpreter/connection-steps.d.ts +194 -0
  123. package/dist/interpreter/connection-steps.js +537 -0
  124. package/dist/interpreter/execute-action.d.ts +2 -8
  125. package/dist/interpreter/execute-action.js +3 -178
  126. package/dist/interpreter/execute-call.d.ts +19 -0
  127. package/dist/interpreter/execute-call.js +99 -0
  128. package/dist/interpreter/execute-control.d.ts +6 -1
  129. package/dist/interpreter/execute-control.js +14 -0
  130. package/dist/interpreter/execute-invoke-tool.d.ts +11 -0
  131. package/dist/interpreter/execute-invoke-tool.js +183 -0
  132. package/dist/interpreter/execute-verify.d.ts +21 -0
  133. package/dist/interpreter/execute-verify.js +391 -0
  134. package/dist/interpreter/execute-wait.d.ts +21 -0
  135. package/dist/interpreter/execute-wait.js +233 -0
  136. package/dist/interpreter/execute.js +24 -133
  137. package/dist/interpreter/step-kind-dispatch.d.ts +24 -0
  138. package/dist/interpreter/step-kind-dispatch.js +157 -0
  139. package/dist/interpreter/step-walk.d.ts +2 -0
  140. package/dist/interpreter/step-walk.js +24 -0
  141. package/dist/interpreter/verify-host.d.ts +40 -0
  142. package/dist/interpreter/verify-host.js +245 -0
  143. package/dist/runtime/durable/step-ledger.d.ts +31 -1
  144. package/dist/runtime/durable/step-ledger.js +87 -1
  145. package/dist/runtime/in-memory-artifact-store.d.ts +24 -0
  146. package/dist/runtime/in-memory-artifact-store.js +240 -0
  147. package/dist/schemas/workflow.d.ts +2 -2
  148. package/dist/schemas/workflow.js +1 -1
  149. package/dist/util/harness-internals.d.ts +25 -0
  150. package/dist/util/harness-internals.js +35 -0
  151. package/package.json +3 -3
  152. package/schema/noetic-workflow.schema.json +1309 -180
@@ -0,0 +1,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
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Hydrates the JSON `verify` node (spec 37 § In JSON, spec 26) into a
3
+ * `StepVerify`. Operations written by name in `act` — and `call`/`wait` nodes
4
+ * without a `connection` — run on the subject. A list subject hydrates one
5
+ * verify per connection (ids `<id>.<name>`, each with `act` on its own
6
+ * subject), run in parallel under the node's id with the worst outcome.
7
+ */
8
+ import type { ContextData } from '@noetic-tools/context';
9
+ import type { Step } from '@noetic-tools/types';
10
+ import type { WorkflowNode } from '../schemas/workflow.js';
11
+ import type { HydrationContext } from './workflow-hydrator.js';
12
+ /**
13
+ * Hydrates a JSON `verify` node.
14
+ *
15
+ * @public
16
+ * @throws `NoeticConfigError` `VERIFY_INVALID` for a matcher that names no sense or event;
17
+ * `CONNECTION_UNKNOWN` for a subject or witness the document's connections do not declare.
18
+ */
19
+ export declare function hydrateVerifyNode(node: WorkflowNode, ctx: HydrationContext): Step<ContextData, string, string>;
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Hydrates the JSON `verify` node (spec 37 § In JSON, spec 26) into a
3
+ * `StepVerify`. Operations written by name in `act` — and `call`/`wait` nodes
4
+ * without a `connection` — run on the subject. A list subject hydrates one
5
+ * verify per connection (ids `<id>.<name>`, each with `act` on its own
6
+ * subject), run in parallel under the node's id with the worst outcome.
7
+ */
8
+ import { frameworkCast, NoeticConfigError, verifyMatcherFromJson } from '@noetic-tools/types';
9
+ import { VerifyConfigErrorCode } from '@noetic-tools/types/verify';
10
+ import { compileExpression, compute, readInput } from '../expression/jsonata.js';
11
+ import { stepOutputsOf } from '../expression/step-outputs.js';
12
+ import { getDefaultRegistrar } from '../types/step-registrar.js';
13
+ import { documentHandle } from './workflow-connections.js';
14
+ import { documentScopeOf, hydrateStepList } from './workflow-hydrator.js';
15
+ //#endregion
16
+ //#region Constants
17
+ const OUTCOME_RANK = {
18
+ pass: 0,
19
+ unknown: 1,
20
+ partial: 2,
21
+ fail: 3,
22
+ };
23
+ //#endregion
24
+ //#region Helpers
25
+ function registered(built) {
26
+ getDefaultRegistrar().register(frameworkCast(built));
27
+ return built;
28
+ }
29
+ /**
30
+ * A JSON matcher in its TypeScript form.
31
+ *
32
+ * @throws `NoeticConfigError` `VERIFY_INVALID` when it names no sense or event.
33
+ */
34
+ function matcherOf(json, where) {
35
+ const matcher = verifyMatcherFromJson(json);
36
+ if (matcher) {
37
+ return matcher;
38
+ }
39
+ throw new NoeticConfigError({
40
+ code: VerifyConfigErrorCode.Invalid,
41
+ message: `${where} names no sense or event: ${JSON.stringify(json)}.`,
42
+ hint: 'Write a matcher as one sense key and its matcher text, e.g. { "net": "POST /api/orders 201", "count": 1 }.',
43
+ });
44
+ }
45
+ /**
46
+ * A connection the node names, bound to its manifest entry when the document declares one.
47
+ *
48
+ * @throws `NoeticConfigError` `CONNECTION_UNKNOWN` for a name the manifest does not declare.
49
+ */
50
+ function documentTarget(name, where, ctx) {
51
+ if (!ctx.connections) {
52
+ return name;
53
+ }
54
+ const entry = ctx.connections[name];
55
+ if (entry) {
56
+ return documentHandle(name, entry, ctx.connectionUses?.get(name));
57
+ }
58
+ const declared = Object.keys(ctx.connections);
59
+ throw new NoeticConfigError({
60
+ code: 'CONNECTION_UNKNOWN',
61
+ message: `${where} uses connection '${name}', which the document's connections do not declare.`,
62
+ hint: `Use one of ${declared.join(', ') || '(none)'}, or add '${name}' to the document's "connections".`,
63
+ });
64
+ }
65
+ /** A subject expression, evaluated per run against the node's input. */
66
+ function expressionTarget(expr, where, ctx) {
67
+ const compiled = compileExpression(expr, `subject of ${where}`, ctx.expressionLimits);
68
+ return async (input, execCtx) => {
69
+ const name = await compute(compiled, readInput(input), {
70
+ steps: stepOutputsOf(execCtx, documentScopeOf(ctx)),
71
+ ...(ctx.fanOutItem === undefined
72
+ ? {}
73
+ : {
74
+ item: ctx.fanOutItem,
75
+ }),
76
+ });
77
+ if (typeof name !== 'string' || name.length === 0) {
78
+ throw new NoeticConfigError({
79
+ code: 'CONNECTION_INVALID',
80
+ message: `The subject expression of ${where} gave ${JSON.stringify(name)}, not a connection name.`,
81
+ hint: 'Write an expression that gives a declared connection name, e.g. { "$expr": "$item" } inside a fan-out.',
82
+ });
83
+ }
84
+ return documentTarget(name, where, ctx);
85
+ };
86
+ }
87
+ function hydrateOne(opts) {
88
+ const { node, id, subject, ctx } = opts;
89
+ const where = `verify node '${id}'`;
90
+ const built = {
91
+ kind: 'verify',
92
+ id,
93
+ subject: typeof subject === 'string'
94
+ ? documentTarget(subject, where, ctx)
95
+ : expressionTarget(subject.$expr, where, ctx),
96
+ act: frameworkCast(hydrateStepList({
97
+ list: node.act,
98
+ parentId: id,
99
+ ctx,
100
+ enclosing: subject,
101
+ })),
102
+ ...(node.expect === undefined
103
+ ? {}
104
+ : {
105
+ expect: node.expect.map((m, i) => matcherOf(m, `expect[${i}] of ${where}`)),
106
+ }),
107
+ ...(node.never === undefined
108
+ ? {}
109
+ : {
110
+ never: node.never.map((m, i) => matcherOf(m, `never[${i}] of ${where}`)),
111
+ }),
112
+ ...(node.claims === undefined
113
+ ? {}
114
+ : {
115
+ claims: node.claims,
116
+ }),
117
+ ...(node.constraints === undefined
118
+ ? {}
119
+ : {
120
+ constraints: node.constraints,
121
+ }),
122
+ ...(node.witnesses === undefined
123
+ ? {}
124
+ : {
125
+ witnesses: node.witnesses.map((w) => documentTarget(w, `witnesses of ${where}`, ctx)),
126
+ }),
127
+ ...(node.close === undefined
128
+ ? {}
129
+ : {
130
+ close: node.close,
131
+ }),
132
+ ...(node.intent === undefined
133
+ ? {}
134
+ : {
135
+ intent: node.intent,
136
+ }),
137
+ };
138
+ return registered(built);
139
+ }
140
+ /** One verify per listed connection, run in parallel; the worst outcome wins. */
141
+ function hydrateEach(node, names, ctx) {
142
+ const verifies = names.map((name) => ({
143
+ name,
144
+ step: hydrateOne({
145
+ node,
146
+ id: `${node.id}.${name}`,
147
+ subject: name,
148
+ ctx,
149
+ }),
150
+ }));
151
+ const built = {
152
+ kind: 'runCode',
153
+ id: node.id,
154
+ execute: async (input, execCtx) => {
155
+ const outputs = await Promise.all(verifies.map(async (v) => ({
156
+ name: v.name,
157
+ output: frameworkCast(await ctx.executeStep(v.step, input, execCtx)),
158
+ })));
159
+ const result = {
160
+ outcome: outputs.reduce((worst, o) => OUTCOME_RANK[o.output.outcome] > OUTCOME_RANK[worst] ? o.output.outcome : worst, 'pass'),
161
+ subjects: Object.fromEntries(outputs.map((o) => [
162
+ o.name,
163
+ o.output,
164
+ ])),
165
+ };
166
+ return frameworkCast(result);
167
+ },
168
+ };
169
+ return registered(built);
170
+ }
171
+ //#endregion
172
+ //#region Public API
173
+ /**
174
+ * Hydrates a JSON `verify` node.
175
+ *
176
+ * @public
177
+ * @throws `NoeticConfigError` `VERIFY_INVALID` for a matcher that names no sense or event;
178
+ * `CONNECTION_UNKNOWN` for a subject or witness the document's connections do not declare.
179
+ */
180
+ export function hydrateVerifyNode(node, ctx) {
181
+ if (node.kind !== 'verify') {
182
+ return frameworkCast(undefined);
183
+ }
184
+ if (Array.isArray(node.subject)) {
185
+ return hydrateEach(node, node.subject, ctx);
186
+ }
187
+ return hydrateOne({
188
+ node,
189
+ id: node.id,
190
+ subject: node.subject,
191
+ ctx,
192
+ });
193
+ }
194
+ //#endregion
@@ -1,5 +1,5 @@
1
1
  import type { ContextData, StorageAdapter } from '@noetic-tools/context';
2
- import type { Context, Step } from '@noetic-tools/types';
2
+ import type { Context, Step, Steps } from '@noetic-tools/types';
3
3
  import type { EmbedFn } from '../types/embed.js';
4
4
  export type Condition<I> = (input: I, ctx: Context) => Promise<boolean>;
5
5
  export interface WhenClause<TContext = ContextData, I = unknown, O = unknown> {
@@ -17,18 +17,20 @@ type Clause<TContext, I, O> = WhenClause<TContext, I, O> | OtherwiseClause<TCont
17
17
  *
18
18
  * @public
19
19
  * @param condition - Async predicate evaluated against the input and context.
20
- * @param step - Step to execute when the condition matches.
20
+ * @param step - Step to execute when the condition matches, or an array of steps run in sequence.
21
21
  * @returns A `WhenClause` for use in `semanticRoute`.
22
+ * @throws `NoeticConfigError` `EMPTY_STEP_ARRAY` or `INVALID_STEP_IN_ARRAY` for a bad array.
22
23
  */
23
- export declare function when<TContext = ContextData, I = unknown, O = unknown>(condition: Condition<I>, step: Step<TContext, I, O>): WhenClause<TContext, I, O>;
24
+ export declare function when<TContext = ContextData, I = unknown, O = unknown>(condition: Condition<I>, step: Steps<TContext, I, O>): WhenClause<TContext, I, O>;
24
25
  /**
25
26
  * Creates a fallback clause that always matches, used as the last clause in `semanticRoute`.
26
27
  *
27
28
  * @public
28
- * @param step - Step to execute when no prior `when` clause matches.
29
+ * @param step - Step to execute when no prior `when` clause matches, or an array of steps run in sequence.
29
30
  * @returns An `OtherwiseClause` for use in `semanticRoute`.
31
+ * @throws `NoeticConfigError` `EMPTY_STEP_ARRAY` or `INVALID_STEP_IN_ARRAY` for a bad array.
30
32
  */
31
- export declare function otherwise<TContext = ContextData, I = unknown, O = unknown>(step: Step<TContext, I, O>): OtherwiseClause<TContext, I, O>;
33
+ export declare function otherwise<TContext = ContextData, I = unknown, O = unknown>(step: Steps<TContext, I, O>): OtherwiseClause<TContext, I, O>;
32
34
  /**
33
35
  * Builds a route function from an ordered list of `when`/`otherwise` clauses.
34
36
  * Evaluates clauses sequentially, returning the first matching step or `null`.
@@ -1,6 +1,7 @@
1
1
  import { storageGetMany } from '@noetic-tools/context';
2
2
  import { DecideOutputError, isNoeticError, NoeticErrorImpl, trackUsage } from '@noetic-tools/types';
3
3
  import { z } from 'zod';
4
+ import { toStep } from '../builders/sequence.js';
4
5
  import { chargeSpent } from '../util/spent.js';
5
6
  import { cosineSimilarity } from './cosine-similarity.js';
6
7
  //#endregion
@@ -52,27 +53,29 @@ async function getLabelVectors(embed, labels, ref) {
52
53
  *
53
54
  * @public
54
55
  * @param condition - Async predicate evaluated against the input and context.
55
- * @param step - Step to execute when the condition matches.
56
+ * @param step - Step to execute when the condition matches, or an array of steps run in sequence.
56
57
  * @returns A `WhenClause` for use in `semanticRoute`.
58
+ * @throws `NoeticConfigError` `EMPTY_STEP_ARRAY` or `INVALID_STEP_IN_ARRAY` for a bad array.
57
59
  */
58
60
  export function when(condition, step) {
59
61
  return {
60
62
  kind: 'when',
61
63
  condition,
62
- step,
64
+ step: toStep(step),
63
65
  };
64
66
  }
65
67
  /**
66
68
  * Creates a fallback clause that always matches, used as the last clause in `semanticRoute`.
67
69
  *
68
70
  * @public
69
- * @param step - Step to execute when no prior `when` clause matches.
71
+ * @param step - Step to execute when no prior `when` clause matches, or an array of steps run in sequence.
70
72
  * @returns An `OtherwiseClause` for use in `semanticRoute`.
73
+ * @throws `NoeticConfigError` `EMPTY_STEP_ARRAY` or `INVALID_STEP_IN_ARRAY` for a bad array.
71
74
  */
72
75
  export function otherwise(step) {
73
76
  return {
74
77
  kind: 'otherwise',
75
- step,
78
+ step: toStep(step),
76
79
  };
77
80
  }
78
81
  //#endregion
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Blobs (spec 35 § Refs and blobs). A provider stores binary content in the
3
+ * artifact store and hands back `{ $blob: { uri, mimeType, bytes, sha256 } }`.
4
+ * The harness links every blob it sees in an output, read or event to the run
5
+ * that received it (retention counts per run), and checks that a blob going
6
+ * out to a connection is one the store holds.
7
+ */
8
+ import type { ArtifactStore, BlobRef } from '@noetic-tools/types';
9
+ /** Where blobs are being linked. */
10
+ export interface BlobLink {
11
+ readonly executionId: string;
12
+ /** The connection that produced them. */
13
+ readonly source: string;
14
+ readonly stepPath?: string;
15
+ }
16
+ /** What a sensitive blob shows as wherever the model would see it. */
17
+ export declare const WITHHELD_BLOB_TEXT = "[sensitive blob withheld]";
18
+ /** The blobs anywhere in `value`. */
19
+ export declare function findBlobs(value: unknown): ReadonlyArray<BlobRef>;
20
+ /** Links every blob in `value` to the run in `link`. */
21
+ export declare function attachBlobs(value: unknown, artifacts: ArtifactStore, link: BlobLink): Promise<void>;
22
+ /**
23
+ * Checks every blob in `args` is held by the artifact store and matches what it holds.
24
+ *
25
+ * @throws NoeticErrorImpl `connection_ref_invalid` for an unknown or altered blob.
26
+ */
27
+ export declare function checkBlobs(args: unknown, artifacts: ArtifactStore, connection: string): Promise<void>;
28
+ /**
29
+ * A copy of `value` with every blob the store marks sensitive (a stored session)
30
+ * replaced by `WITHHELD_BLOB_TEXT`: such blobs are never rendered to the model
31
+ * (spec 35 § Refs and blobs).
32
+ */
33
+ export declare function withholdSensitiveBlobs(value: unknown, artifacts: ArtifactStore): Promise<unknown>;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Blobs (spec 35 § Refs and blobs). A provider stores binary content in the
3
+ * artifact store and hands back `{ $blob: { uri, mimeType, bytes, sha256 } }`.
4
+ * The harness links every blob it sees in an output, read or event to the run
5
+ * that received it (retention counts per run), and checks that a blob going
6
+ * out to a connection is one the store holds.
7
+ */
8
+ import { isBlobRef } from '@noetic-tools/types';
9
+ import { refInvalidError } from './errors.js';
10
+ import { findDeep, mapDeep } from './values.js';
11
+ /** What a sensitive blob shows as wherever the model would see it. */
12
+ export const WITHHELD_BLOB_TEXT = '[sensitive blob withheld]';
13
+ //#endregion
14
+ //#region Public API
15
+ /** The blobs anywhere in `value`. */
16
+ export function findBlobs(value) {
17
+ return findDeep(value, isBlobRef).map((found) => found.value);
18
+ }
19
+ /** Links every blob in `value` to the run in `link`. */
20
+ export async function attachBlobs(value, artifacts, link) {
21
+ const seen = new Set();
22
+ for (const blob of findBlobs(value)) {
23
+ const uri = blob.$blob.uri;
24
+ if (seen.has(uri)) {
25
+ continue;
26
+ }
27
+ seen.add(uri);
28
+ await artifacts.attach(uri, {
29
+ executionId: link.executionId,
30
+ source: link.source,
31
+ stepPath: link.stepPath,
32
+ });
33
+ }
34
+ }
35
+ /**
36
+ * Checks every blob in `args` is held by the artifact store and matches what it holds.
37
+ *
38
+ * @throws NoeticErrorImpl `connection_ref_invalid` for an unknown or altered blob.
39
+ */
40
+ export async function checkBlobs(args, artifacts, connection) {
41
+ for (const blob of findBlobs(args)) {
42
+ const held = await artifacts.head(blob.$blob.uri);
43
+ if (!held) {
44
+ throw refInvalidError(connection, `blob '${blob.$blob.uri}' is not in the artifact store`);
45
+ }
46
+ if (held.sha256 !== blob.$blob.sha256 || held.bytes !== blob.$blob.bytes) {
47
+ throw refInvalidError(connection, `blob '${blob.$blob.uri}' does not match the stored content`);
48
+ }
49
+ }
50
+ }
51
+ /**
52
+ * A copy of `value` with every blob the store marks sensitive (a stored session)
53
+ * replaced by `WITHHELD_BLOB_TEXT`: such blobs are never rendered to the model
54
+ * (spec 35 § Refs and blobs).
55
+ */
56
+ export async function withholdSensitiveBlobs(value, artifacts) {
57
+ const sensitive = new Set();
58
+ for (const blob of findBlobs(value)) {
59
+ const uri = blob.$blob.uri;
60
+ if (sensitive.has(uri)) {
61
+ continue;
62
+ }
63
+ const held = await artifacts.head(uri);
64
+ if (held?.sensitive) {
65
+ sensitive.add(uri);
66
+ }
67
+ }
68
+ if (sensitive.size === 0) {
69
+ return value;
70
+ }
71
+ return mapDeep(value, (node) => isBlobRef(node.value) && sensitive.has(node.value.$blob.uri)
72
+ ? {
73
+ replace: WITHHELD_BLOB_TEXT,
74
+ }
75
+ : undefined);
76
+ }
77
+ //#endregion
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Five-field cron schedules (`minute hour day-of-month month day-of-week`) in
3
+ * an IANA timezone, for `cron()` (spec 35 § Triggers). Each field takes `*`,
4
+ * numbers, lists (`1,15`), ranges (`1-5`) and steps (`*\/15`, `0-30/10`).
5
+ * Day-of-week runs 0–6 from Sunday (7 is Sunday too). When both day fields
6
+ * are restricted, a time matches if either does, as in classic cron.
7
+ */
8
+ /** A parsed schedule. */
9
+ export interface CronSchedule {
10
+ readonly source: string;
11
+ readonly timezone: string;
12
+ readonly minutes: ReadonlySet<number>;
13
+ readonly hours: ReadonlySet<number>;
14
+ readonly days: ReadonlySet<number>;
15
+ readonly months: ReadonlySet<number>;
16
+ readonly weekdays: ReadonlySet<number>;
17
+ readonly anyDay: boolean;
18
+ readonly anyWeekday: boolean;
19
+ }
20
+ /**
21
+ * Parses a five-field cron schedule.
22
+ *
23
+ * @throws NoeticConfigError `CONNECTION_INVALID` for a malformed schedule or timezone.
24
+ */
25
+ export declare function parseCronSchedule(source: string, timezone?: string): CronSchedule;
26
+ /** Whether the minute starting at `ms` matches the schedule. */
27
+ export declare function cronMatches(schedule: CronSchedule, ms: number): boolean;
28
+ /**
29
+ * The first scheduled minute strictly after `afterMs`, as epoch ms.
30
+ * @returns `undefined` when nothing matches within four years.
31
+ */
32
+ export declare function nextCronRun(schedule: CronSchedule, afterMs: number): number | undefined;