@noetic-tools/core 5.19.1 → 5.20.0-next.1

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 (146) 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 +16 -1
  6. package/dist/builders/dynamic-workflow.js +222 -11
  7. package/dist/builders/every.d.ts +3 -3
  8. package/dist/builders/every.js +2 -1
  9. package/dist/builders/provide-builder.d.ts +3 -2
  10. package/dist/builders/provide-builder.js +2 -1
  11. package/dist/builders/sequence.d.ts +14 -0
  12. package/dist/builders/sequence.js +103 -0
  13. package/dist/builders/spawn-builder.d.ts +3 -2
  14. package/dist/builders/spawn-builder.js +3 -2
  15. package/dist/builders/step-builders.d.ts +80 -1
  16. package/dist/builders/step-builders.js +115 -1
  17. package/dist/builders/verify-builder.d.ts +79 -0
  18. package/dist/builders/verify-builder.js +69 -0
  19. package/dist/builders/workflow-child-nodes.d.ts +21 -0
  20. package/dist/builders/workflow-child-nodes.js +335 -0
  21. package/dist/builders/workflow-connection-nodes.d.ts +17 -0
  22. package/dist/builders/workflow-connection-nodes.js +160 -0
  23. package/dist/builders/workflow-connections.d.ts +90 -0
  24. package/dist/builders/workflow-connections.js +560 -0
  25. package/dist/builders/workflow-control-nodes.d.ts +13 -0
  26. package/dist/builders/workflow-control-nodes.js +213 -0
  27. package/dist/builders/workflow-hydrator.d.ts +44 -3
  28. package/dist/builders/workflow-hydrator.js +53 -495
  29. package/dist/builders/workflow-verify.d.ts +19 -0
  30. package/dist/builders/workflow-verify.js +194 -0
  31. package/dist/conditions/conditions.d.ts +7 -5
  32. package/dist/conditions/conditions.js +7 -4
  33. package/dist/connections/blobs.d.ts +33 -0
  34. package/dist/connections/blobs.js +77 -0
  35. package/dist/connections/cron-schedule.d.ts +32 -0
  36. package/dist/connections/cron-schedule.js +213 -0
  37. package/dist/connections/durability.d.ts +65 -0
  38. package/dist/connections/durability.js +54 -0
  39. package/dist/connections/errors.d.ts +30 -0
  40. package/dist/connections/errors.js +100 -0
  41. package/dist/connections/event-stream.d.ts +24 -0
  42. package/dist/connections/event-stream.js +176 -0
  43. package/dist/connections/gates.d.ts +94 -0
  44. package/dist/connections/gates.js +271 -0
  45. package/dist/connections/glob.d.ts +10 -0
  46. package/dist/connections/glob.js +46 -0
  47. package/dist/connections/handle.d.ts +22 -0
  48. package/dist/connections/handle.js +84 -0
  49. package/dist/connections/harness-wiring.d.ts +52 -0
  50. package/dist/connections/harness-wiring.js +143 -0
  51. package/dist/connections/in-memory-connection.d.ts +147 -0
  52. package/dist/connections/in-memory-connection.js +593 -0
  53. package/dist/connections/index.d.ts +34 -0
  54. package/dist/connections/index.js +23 -0
  55. package/dist/connections/json-schema.d.ts +28 -0
  56. package/dist/connections/json-schema.js +338 -0
  57. package/dist/connections/model-tools.d.ts +46 -0
  58. package/dist/connections/model-tools.js +466 -0
  59. package/dist/connections/negotiation.d.ts +30 -0
  60. package/dist/connections/negotiation.js +159 -0
  61. package/dist/connections/policy.d.ts +21 -0
  62. package/dist/connections/policy.js +34 -0
  63. package/dist/connections/pool.d.ts +111 -0
  64. package/dist/connections/pool.js +339 -0
  65. package/dist/connections/refs.d.ts +74 -0
  66. package/dist/connections/refs.js +316 -0
  67. package/dist/connections/registry-types.d.ts +141 -0
  68. package/dist/connections/registry-types.js +14 -0
  69. package/dist/connections/registry.d.ts +125 -0
  70. package/dist/connections/registry.js +775 -0
  71. package/dist/connections/secrets.d.ts +59 -0
  72. package/dist/connections/secrets.js +153 -0
  73. package/dist/connections/settle.d.ts +9 -0
  74. package/dist/connections/settle.js +26 -0
  75. package/dist/connections/sources.d.ts +27 -0
  76. package/dist/connections/sources.js +300 -0
  77. package/dist/connections/triggers.d.ts +78 -0
  78. package/dist/connections/triggers.js +310 -0
  79. package/dist/connections/values.d.ts +26 -0
  80. package/dist/connections/values.js +93 -0
  81. package/dist/connections/views.d.ts +31 -0
  82. package/dist/connections/views.js +176 -0
  83. package/dist/expression/check.js +80 -1
  84. package/dist/expression/jsonata.d.ts +14 -4
  85. package/dist/expression/jsonata.js +27 -9
  86. package/dist/expression/step-outputs.d.ts +25 -0
  87. package/dist/expression/step-outputs.js +78 -0
  88. package/dist/harness/agent-harness.d.ts +69 -166
  89. package/dist/harness/agent-harness.js +170 -262
  90. package/dist/harness/call-span-collector.d.ts +33 -0
  91. package/dist/harness/call-span-collector.js +83 -0
  92. package/dist/harness/connection-gate.d.ts +78 -0
  93. package/dist/harness/connection-gate.js +169 -0
  94. package/dist/harness/deps/interpreter.d.ts +1 -0
  95. package/dist/harness/deps/interpreter.js +1 -0
  96. package/dist/harness/deps/runtime.d.ts +1 -1
  97. package/dist/harness/deps/types.d.ts +1 -1
  98. package/dist/harness/harness-options.d.ts +153 -0
  99. package/dist/harness/harness-options.js +36 -0
  100. package/dist/harness/harness-tracing.d.ts +16 -0
  101. package/dist/harness/harness-tracing.js +35 -0
  102. package/dist/harness/llm-client.d.ts +71 -0
  103. package/dist/harness/llm-client.js +218 -0
  104. package/dist/harness/model-call.d.ts +2 -7
  105. package/dist/harness/model-call.js +21 -549
  106. package/dist/harness/model-request.d.ts +42 -0
  107. package/dist/harness/model-request.js +159 -0
  108. package/dist/harness/model-stream.d.ts +39 -0
  109. package/dist/harness/model-stream.js +131 -0
  110. package/dist/harness/model-tool-round.d.ts +37 -0
  111. package/dist/harness/model-tool-round.js +197 -0
  112. package/dist/harness/spend.d.ts +2 -0
  113. package/dist/harness/spend.js +5 -1
  114. package/dist/index.d.ts +31 -6
  115. package/dist/index.js +18 -1
  116. package/dist/interpreter/connection-steps.d.ts +194 -0
  117. package/dist/interpreter/connection-steps.js +537 -0
  118. package/dist/interpreter/execute-action.d.ts +2 -8
  119. package/dist/interpreter/execute-action.js +3 -178
  120. package/dist/interpreter/execute-call.d.ts +19 -0
  121. package/dist/interpreter/execute-call.js +99 -0
  122. package/dist/interpreter/execute-control.d.ts +6 -1
  123. package/dist/interpreter/execute-control.js +14 -0
  124. package/dist/interpreter/execute-invoke-tool.d.ts +11 -0
  125. package/dist/interpreter/execute-invoke-tool.js +183 -0
  126. package/dist/interpreter/execute-verify.d.ts +21 -0
  127. package/dist/interpreter/execute-verify.js +391 -0
  128. package/dist/interpreter/execute-wait.d.ts +21 -0
  129. package/dist/interpreter/execute-wait.js +233 -0
  130. package/dist/interpreter/execute.js +24 -133
  131. package/dist/interpreter/step-kind-dispatch.d.ts +24 -0
  132. package/dist/interpreter/step-kind-dispatch.js +157 -0
  133. package/dist/interpreter/step-walk.d.ts +2 -0
  134. package/dist/interpreter/step-walk.js +24 -0
  135. package/dist/interpreter/verify-host.d.ts +40 -0
  136. package/dist/interpreter/verify-host.js +245 -0
  137. package/dist/runtime/durable/step-ledger.d.ts +31 -1
  138. package/dist/runtime/durable/step-ledger.js +87 -1
  139. package/dist/runtime/in-memory-artifact-store.d.ts +24 -0
  140. package/dist/runtime/in-memory-artifact-store.js +240 -0
  141. package/dist/schemas/workflow.d.ts +2 -2
  142. package/dist/schemas/workflow.js +1 -1
  143. package/dist/util/harness-internals.d.ts +23 -0
  144. package/dist/util/harness-internals.js +35 -0
  145. package/package.json +3 -3
  146. package/schema/noetic-workflow.schema.json +1170 -92
@@ -0,0 +1,271 @@
1
+ /**
2
+ * The gates (spec 35 § Gates). Every connection call — from the model, a
3
+ * step, or a document — passes the same gates, in order:
4
+ *
5
+ * 1. The operation exists on the connection, and for steps and documents is
6
+ * declared by the manifest or handle.
7
+ * 2. Its arguments match the operation's schema. Nothing is defaulted.
8
+ * 3. Its refs were issued by this harness to this thread, for this connection.
9
+ * 4. The connection's `policy`; `guarded` operations need approval unless the
10
+ * policy allows them.
11
+ * 5. `beforeToolCall` layers and the harness approver, as for any tool.
12
+ * 6. Secrets are filled in, and the call is sent.
13
+ *
14
+ * A refusal throws `steering_denied` (a step fails with it; a model tool
15
+ * returns it as a tool error). A server that refuses with `guarded` is asked
16
+ * for approval and retried with `_meta["tools.noetic/confirmed"]`. Long
17
+ * operations are waited on, with progress reported as `connection_task`.
18
+ */
19
+ import { SteeringAction } from '@noetic-tools/types';
20
+ import { attachBlobs, checkBlobs } from './blobs.js';
21
+ import { deniedError, failedError, inputRequiredError } from './errors.js';
22
+ import { validateJsonSchema } from './json-schema.js';
23
+ import { evaluatePolicy } from './policy.js';
24
+ import { checkSecrets, fillSecrets } from './secrets.js';
25
+ //#endregion
26
+ //#region Helpers
27
+ function refuse(decision, fallback) {
28
+ throw deniedError(decision.guidance ?? fallback);
29
+ }
30
+ function toolNameOf(connection, op) {
31
+ return `${connection}_${op.replace(/[^A-Za-z0-9_-]/g, '_')}`;
32
+ }
33
+ function operationInfo(gc, op, opts) {
34
+ const info = gc.connection.manifest.operations[op];
35
+ if (!info) {
36
+ throw deniedError(`operation '${op}' is not offered by connection '${gc.name}'`);
37
+ }
38
+ if (opts.declaredOps && !opts.declaredOps.includes(op)) {
39
+ throw deniedError(`operation '${op}' on connection '${gc.name}' is not declared by the handle or manifest`);
40
+ }
41
+ return info;
42
+ }
43
+ function checkArguments(info, args, connection) {
44
+ const errors = validateJsonSchema(info.inputSchema, args);
45
+ if (errors.length === 0) {
46
+ return;
47
+ }
48
+ throw deniedError(`arguments for '${info.name}' on connection '${connection}' do not match its schema: ${errors.join('; ')}`);
49
+ }
50
+ async function approve(gc, request) {
51
+ const approver = gc.hooks.approve;
52
+ if (!approver) {
53
+ throw deniedError(`operation '${request.op}' on connection '${gc.name}' needs approval, but the harness has no approver`);
54
+ }
55
+ const decision = await approver(request);
56
+ if (decision.action !== SteeringAction.Allow) {
57
+ refuse(decision, `operation '${request.op}' on connection '${gc.name}' was not approved`);
58
+ }
59
+ }
60
+ async function runHarnessGates(gc, request, needsApproval) {
61
+ if (request.caller !== 'model' && gc.hooks.beforeCall) {
62
+ const decision = await gc.hooks.beforeCall(request);
63
+ if (decision.action !== SteeringAction.Allow) {
64
+ refuse(decision, `operation '${request.op}' was refused by a steering layer`);
65
+ }
66
+ }
67
+ if (needsApproval) {
68
+ await approve(gc, request);
69
+ }
70
+ }
71
+ /** Waits for a long operation, answering questions through the hooks when someone can. */
72
+ async function awaitTask(gc, request) {
73
+ const controller = new AbortController();
74
+ const onParentAbort = () => controller.abort(request.signal.reason);
75
+ request.signal.addEventListener('abort', onParentAbort, {
76
+ once: true,
77
+ });
78
+ let unanswered;
79
+ const answering = new Set();
80
+ const answer = async (status) => {
81
+ const question = status.request;
82
+ if (!question || answering.has(question.id)) {
83
+ return;
84
+ }
85
+ answering.add(question.id);
86
+ const reply = await gc.hooks.answerInput?.({
87
+ ...request,
88
+ status,
89
+ });
90
+ if (!reply) {
91
+ unanswered = status;
92
+ controller.abort();
93
+ return;
94
+ }
95
+ await gc.connection.tasks.respond(request.taskId, question.id, reply.answer);
96
+ };
97
+ try {
98
+ return await gc.connection.tasks.result(request.taskId, {
99
+ signal: controller.signal,
100
+ onProgress: (status) => {
101
+ // The registry emits `connection_task` (to the caller's run when it has a ctx).
102
+ gc.onTask?.(request.op, status, request.stepId);
103
+ request.onTask?.(status);
104
+ if (status.state === 'input_required') {
105
+ void answer(status);
106
+ }
107
+ },
108
+ });
109
+ }
110
+ catch (e) {
111
+ if (unanswered?.request) {
112
+ await gc.connection.tasks.cancel(request.taskId).catch(() => undefined);
113
+ throw inputRequiredError(gc.name, unanswered.request);
114
+ }
115
+ if (request.signal.aborted) {
116
+ await gc.connection.tasks.cancel(request.taskId).catch(() => undefined);
117
+ }
118
+ throw e;
119
+ }
120
+ finally {
121
+ request.signal.removeEventListener('abort', onParentAbort);
122
+ }
123
+ }
124
+ /** Sends the call, retrying once with `confirmed` after a server's `guarded` refusal is approved. */
125
+ async function send(gc, request) {
126
+ const result = await gc.connection.call(request.op, request.filled, {
127
+ signal: request.opts.signal,
128
+ idempotencyKey: request.opts.idempotencyKey,
129
+ ...(request.confirmed
130
+ ? {
131
+ confirmed: true,
132
+ }
133
+ : {}),
134
+ });
135
+ if (result.status === 'error' && result.error.code === 'guarded' && !request.confirmed) {
136
+ if (!request.policyAllows) {
137
+ await approve(gc, {
138
+ ...request,
139
+ reason: 'guarded',
140
+ });
141
+ }
142
+ return send(gc, {
143
+ ...request,
144
+ confirmed: true,
145
+ });
146
+ }
147
+ if (result.status !== 'task') {
148
+ return result;
149
+ }
150
+ return awaitTask(gc, {
151
+ ...request,
152
+ taskId: result.taskId,
153
+ signal: request.opts.signal,
154
+ stepId: request.opts.stepId,
155
+ onTask: request.opts.onTask,
156
+ });
157
+ }
158
+ /** Scrubs secrets, seals refs and links blobs in a value coming in from a connection. */
159
+ export async function admitIncoming(gc, value, stepPath) {
160
+ const scrubbed = gc.scrubber.scrub(value);
161
+ const sealed = await gc.refs.sealAll(scrubbed, gc.refScope);
162
+ await attachBlobs(sealed, gc.artifacts, {
163
+ executionId: gc.executionId,
164
+ source: gc.name,
165
+ stepPath,
166
+ });
167
+ return sealed;
168
+ }
169
+ /** Turns a call's outcome into its output: errors throw, effects are counted, the rest is admitted. */
170
+ async function outputOf(gc, result) {
171
+ const { op, info, outcome, stepId } = result;
172
+ if (outcome.status === 'error') {
173
+ throw failedError(gc.name, op, gc.scrubber.scrub(outcome.error));
174
+ }
175
+ if (info?.effects || info?.once) {
176
+ gc.onEffect?.();
177
+ }
178
+ return admitIncoming(gc, outcome.output, stepId);
179
+ }
180
+ //#endregion
181
+ //#region Public API
182
+ /**
183
+ * Waits on a long operation a previous attempt started, instead of sending the
184
+ * operation again (spec 35 § Durability: "waiting on the same task"). Its
185
+ * outcome is handled exactly as `gatedCall`'s.
186
+ *
187
+ * @throws NoeticErrorImpl `connection_failed` or `connection_input_required`.
188
+ */
189
+ export async function gatedAwaitTask(gc, task) {
190
+ const { op, taskId, opts } = task;
191
+ const outcome = await awaitTask(gc, {
192
+ connection: gc.name,
193
+ op,
194
+ args: {},
195
+ caller: opts.caller,
196
+ toolName: toolNameOf(gc.name, op),
197
+ callId: opts.toolCallId ?? opts.stepId,
198
+ ctx: opts.ctx,
199
+ taskId,
200
+ signal: opts.signal,
201
+ stepId: opts.stepId,
202
+ onTask: opts.onTask,
203
+ });
204
+ return outputOf(gc, {
205
+ op,
206
+ info: gc.connection.manifest.operations[op],
207
+ outcome,
208
+ stepId: opts.stepId,
209
+ });
210
+ }
211
+ /**
212
+ * Runs one call through gates 1–6 and returns its output.
213
+ *
214
+ * @throws NoeticErrorImpl `steering_denied` when a gate refuses,
215
+ * `connection_ref_invalid`, `connection_secret_refused`, `connection_failed`
216
+ * or `connection_input_required`.
217
+ */
218
+ export async function gatedCall(gc, call) {
219
+ const { op, args, opts } = call;
220
+ const info = operationInfo(gc, op, opts);
221
+ // Secrets first: one in a field that is not `sensitive` is refused as such
222
+ // (`connection_secret_refused`), not as a schema mismatch.
223
+ checkSecrets(args, {
224
+ connection: gc.name,
225
+ op,
226
+ caller: opts.caller,
227
+ inputSchema: info.inputSchema,
228
+ ...(opts.caller === 'document'
229
+ ? {
230
+ allowedSecrets: opts.documentSecrets ?? [],
231
+ }
232
+ : {}),
233
+ });
234
+ checkArguments(info, args, gc.name);
235
+ await checkBlobs(args, gc.artifacts, gc.name);
236
+ await gc.refs.checkAll(args, gc.refScope);
237
+ const verdict = evaluatePolicy(gc.policy, op, info.guarded === true);
238
+ if (verdict.kind === 'deny') {
239
+ throw deniedError(verdict.reason);
240
+ }
241
+ const request = {
242
+ connection: gc.name,
243
+ op,
244
+ args,
245
+ caller: opts.caller,
246
+ toolName: toolNameOf(gc.name, op),
247
+ callId: opts.toolCallId ?? opts.stepId,
248
+ ctx: opts.ctx,
249
+ reason: verdict.needsApproval ? 'policy' : undefined,
250
+ };
251
+ await runHarnessGates(gc, request, verdict.needsApproval);
252
+ const filled = await fillSecrets(args, {
253
+ resolver: gc.secrets,
254
+ scrubber: gc.scrubber,
255
+ signal: opts.signal,
256
+ });
257
+ const outcome = await send(gc, {
258
+ ...request,
259
+ filled,
260
+ opts,
261
+ confirmed: verdict.needsApproval,
262
+ policyAllows: verdict.explicitlyAllowed,
263
+ });
264
+ return outputOf(gc, {
265
+ op,
266
+ info,
267
+ outcome,
268
+ stepId: opts.stepId,
269
+ });
270
+ }
271
+ //#endregion
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Glob matching over dotted operation and event names (spec 35 § Gates,
3
+ * § What a document may use). `*` matches any run of characters, including
4
+ * dots, so `'ui.*'` covers `ui.tap` and `com.slack.admin.*` covers every admin
5
+ * operation; `?` matches one character. Everything else is literal.
6
+ */
7
+ /** Whether `name` matches the glob `pattern`. */
8
+ export declare function matchesGlob(pattern: string, name: string): boolean;
9
+ /** Whether `name` matches any of `patterns`. An absent or empty list matches nothing. */
10
+ export declare function matchesAnyGlob(patterns: ReadonlyArray<string> | undefined, name: string): boolean;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Glob matching over dotted operation and event names (spec 35 § Gates,
3
+ * § What a document may use). `*` matches any run of characters, including
4
+ * dots, so `'ui.*'` covers `ui.tap` and `com.slack.admin.*` covers every admin
5
+ * operation; `?` matches one character. Everything else is literal.
6
+ */
7
+ //#region Helpers
8
+ const cache = new Map();
9
+ function escapeLiteral(char) {
10
+ return /[\\^$.|+()[\]{}]/.test(char) ? `\\${char}` : char;
11
+ }
12
+ function compile(pattern) {
13
+ const cached = cache.get(pattern);
14
+ if (cached) {
15
+ return cached;
16
+ }
17
+ let source = '';
18
+ for (const char of pattern) {
19
+ if (char === '*') {
20
+ source += '.*';
21
+ continue;
22
+ }
23
+ if (char === '?') {
24
+ source += '.';
25
+ continue;
26
+ }
27
+ source += escapeLiteral(char);
28
+ }
29
+ const compiled = new RegExp(`^${source}$`);
30
+ cache.set(pattern, compiled);
31
+ return compiled;
32
+ }
33
+ //#endregion
34
+ //#region Public API
35
+ /** Whether `name` matches the glob `pattern`. */
36
+ export function matchesGlob(pattern, name) {
37
+ return compile(pattern).test(name);
38
+ }
39
+ /** Whether `name` matches any of `patterns`. An absent or empty list matches nothing. */
40
+ export function matchesAnyGlob(patterns, name) {
41
+ if (!patterns) {
42
+ return false;
43
+ }
44
+ return patterns.some((pattern) => matchesGlob(pattern, name));
45
+ }
46
+ //#endregion
@@ -0,0 +1,22 @@
1
+ /**
2
+ * `connection(name, profile?, options?)` (spec 35 § Steps): declares a
3
+ * connection a workflow needs and returns a handle. With a profile, `op`,
4
+ * `args` and outputs are typed by it, and the profile's range defaults to the
5
+ * installed package's version (`^1.2.0`); `browser.range('^1.1')` overrides it.
6
+ * The handle binds to the harness connection of the same name, or to
7
+ * `options.from`.
8
+ */
9
+ import type { ConnectionFn, ConnectionHandle } from '@noetic-tools/types';
10
+ /** Connection names: a letter, then letters, digits, `_` and `-` (the same rule JSON manifests use). */
11
+ export declare const CONNECTION_NAME_PATTERN: RegExp;
12
+ /**
13
+ * @public
14
+ * Declares a connection a workflow needs and returns a handle steps use.
15
+ *
16
+ * @throws NoeticConfigError `CONNECTION_INVALID` for a malformed name or options.
17
+ */
18
+ export declare const connection: ConnectionFn;
19
+ /** @public Whether `value` is a handle `connection()` returned. */
20
+ export declare function isConnectionHandle(value: unknown): value is ConnectionHandle;
21
+ /** The harness connection (or pool) a handle binds to. */
22
+ export declare function handleTarget(handle: ConnectionHandle): string;
@@ -0,0 +1,84 @@
1
+ /**
2
+ * `connection(name, profile?, options?)` (spec 35 § Steps): declares a
3
+ * connection a workflow needs and returns a handle. With a profile, `op`,
4
+ * `args` and outputs are typed by it, and the profile's range defaults to the
5
+ * installed package's version (`^1.2.0`); `browser.range('^1.1')` overrides it.
6
+ * The handle binds to the harness connection of the same name, or to
7
+ * `options.from`.
8
+ */
9
+ import { frameworkCast } from '@noetic-tools/types';
10
+ import { invalidConnectionError } from './errors.js';
11
+ //#region Constants
12
+ /** Connection names: a letter, then letters, digits, `_` and `-` (the same rule JSON manifests use). */
13
+ export const CONNECTION_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]*$/;
14
+ //#endregion
15
+ //#region Helpers
16
+ function requireName(name, what) {
17
+ if (CONNECTION_NAME_PATTERN.test(name)) {
18
+ return;
19
+ }
20
+ throw invalidConnectionError(`${what} '${name}' is not a valid connection name.`, 'Start with a letter and use only letters, digits, _ and -.');
21
+ }
22
+ function requireOptions(name, options) {
23
+ if (options.from !== undefined) {
24
+ requireName(options.from, `connection('${name}') option from`);
25
+ }
26
+ if (options.fresh !== undefined && options.fresh !== 'run' && options.fresh !== 'path') {
27
+ throw invalidConnectionError(`connection('${name}') has fresh '${String(options.fresh)}'.`, "Use fresh: 'run' (one per run) or fresh: 'path' (one per parallel path).");
28
+ }
29
+ if (options.setup !== undefined && options.fresh === undefined) {
30
+ throw invalidConnectionError(`connection('${name}') passes setup without fresh.`, "setup is given to a pool's provider; add fresh: 'run' or fresh: 'path'.");
31
+ }
32
+ }
33
+ function isProfileRange(value) {
34
+ return value.kind === 'profile-range';
35
+ }
36
+ function makeHandle(name, profile, options = {}) {
37
+ requireName(name, 'connection()');
38
+ requireOptions(name, options);
39
+ if (!profile) {
40
+ return {
41
+ kind: 'connection-handle',
42
+ name,
43
+ profile: undefined,
44
+ options,
45
+ };
46
+ }
47
+ if (isProfileRange(profile)) {
48
+ return {
49
+ kind: 'connection-handle',
50
+ name,
51
+ profile: profile.profile,
52
+ range: profile.range,
53
+ options,
54
+ };
55
+ }
56
+ return {
57
+ kind: 'connection-handle',
58
+ name,
59
+ profile,
60
+ range: profile.defaultRange,
61
+ options,
62
+ };
63
+ }
64
+ //#endregion
65
+ //#region Public API
66
+ /**
67
+ * @public
68
+ * Declares a connection a workflow needs and returns a handle steps use.
69
+ *
70
+ * @throws NoeticConfigError `CONNECTION_INVALID` for a malformed name or options.
71
+ */
72
+ export const connection = frameworkCast(makeHandle);
73
+ /** @public Whether `value` is a handle `connection()` returned. */
74
+ export function isConnectionHandle(value) {
75
+ return (typeof value === 'object' &&
76
+ value !== null &&
77
+ 'kind' in value &&
78
+ value.kind === 'connection-handle');
79
+ }
80
+ /** The harness connection (or pool) a handle binds to. */
81
+ export function handleTarget(handle) {
82
+ return handle.options.from ?? handle.name;
83
+ }
84
+ //#endregion
@@ -0,0 +1,52 @@
1
+ /**
2
+ * How an `AgentHarness` holds its connections (spec 35 § Configuring
3
+ * connections, § Triggers; spec 08 § Connections and Triggers): the registry,
4
+ * the trigger runner, the connection view layers, and the gate hooks that
5
+ * route gate 5 through the harness's `beforeToolCall` layers and approver.
6
+ *
7
+ * Construction is synchronous and validates the configuration; providers
8
+ * connect and triggers start listening in `start()`.
9
+ */
10
+ import type { ArtifactStore, ConnectionsConfig, ConnectionTrigger, Context, ContextLayer, ExecuteInput, ExecuteOptions, SecretResolver, SessionScope, SteeringDecision, StorageAdapter, Tool, ToolApprover } from '@noetic-tools/types';
11
+ import type { EventBroadcaster } from '../runtime/event-broadcaster.js';
12
+ import type { ConnectionRuntime } from './registry.js';
13
+ /** The harness surface the wiring calls back into. */
14
+ export interface WiredHarness {
15
+ readonly config: {
16
+ readonly name: string;
17
+ readonly approveToolCall?: ToolApprover;
18
+ };
19
+ beforeToolCall(layers: ContextLayer[], toolName: string, toolArgs: unknown, ctx: Context, callId?: string): Promise<SteeringDecision>;
20
+ execute(input: ExecuteInput, options?: ExecuteOptions): Promise<void>;
21
+ getAgentResponse(scope?: SessionScope): Promise<unknown>;
22
+ }
23
+ /** `createHarnessConnections` options. */
24
+ export interface HarnessConnectionsOptions {
25
+ readonly harness: WiredHarness;
26
+ readonly connections?: ConnectionsConfig;
27
+ readonly triggers?: ReadonlyArray<ConnectionTrigger>;
28
+ readonly storage: StorageAdapter;
29
+ readonly artifacts: ArtifactStore;
30
+ readonly secrets?: SecretResolver;
31
+ /** Every session broadcaster, for events that concern no one context. */
32
+ readonly broadcasters: () => Iterable<EventBroadcaster>;
33
+ }
34
+ /** A harness's connections. */
35
+ export interface HarnessConnections {
36
+ readonly registry: ConnectionRuntime;
37
+ /** One view layer per non-pool connection. */
38
+ readonly views: ReadonlyArray<ContextLayer>;
39
+ /** Connects providers and starts triggers. Idempotent. */
40
+ start(): Promise<void>;
41
+ /** Stops triggers and releases every connection. */
42
+ close(): Promise<void>;
43
+ /** This turn's connection tools. */
44
+ tools(): Tool[];
45
+ }
46
+ /**
47
+ * Builds a harness's connections from its options.
48
+ *
49
+ * @throws NoeticConfigError `CONNECTION_INVALID` for a malformed entry or trigger,
50
+ * `CONNECTION_UNKNOWN` for a trigger naming an unknown connection.
51
+ */
52
+ export declare function createHarnessConnections(options: HarnessConnectionsOptions): HarnessConnections;
@@ -0,0 +1,143 @@
1
+ /**
2
+ * How an `AgentHarness` holds its connections (spec 35 § Configuring
3
+ * connections, § Triggers; spec 08 § Connections and Triggers): the registry,
4
+ * the trigger runner, the connection view layers, and the gate hooks that
5
+ * route gate 5 through the harness's `beforeToolCall` layers and approver.
6
+ *
7
+ * Construction is synchronous and validates the configuration; providers
8
+ * connect and triggers start listening in `start()`.
9
+ */
10
+ import { CONNECTION_EVENT_ITEM_TYPE, createMessage, frameworkCast, SteeringAction, } from '@noetic-tools/types';
11
+ import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
12
+ import { buildConnectionTools } from './model-tools.js';
13
+ import { createConnectionRuntime } from './registry.js';
14
+ import { runEvery } from './settle.js';
15
+ import { TriggerRunner, validateTriggers } from './triggers.js';
16
+ import { connectionViewLayers } from './views.js';
17
+ //#endregion
18
+ //#region Helpers
19
+ function deny(guidance) {
20
+ return {
21
+ action: SteeringAction.Deny,
22
+ guidance,
23
+ };
24
+ }
25
+ function gateHooks(harness) {
26
+ return {
27
+ async beforeCall(request) {
28
+ const layers = request.ctx?.layers;
29
+ if (!request.ctx || !layers || layers.length === 0) {
30
+ return {
31
+ action: SteeringAction.Allow,
32
+ };
33
+ }
34
+ return harness.beforeToolCall(layers, request.toolName, request.args, request.ctx, request.callId);
35
+ },
36
+ async approve(request) {
37
+ const approver = harness.config.approveToolCall;
38
+ if (!approver) {
39
+ return deny(`'${request.op}' on connection '${request.connection}' needs approval, but the harness has no approveToolCall`);
40
+ }
41
+ if (!request.ctx) {
42
+ return deny(`'${request.op}' needs approval, but the call has no context to ask from`);
43
+ }
44
+ try {
45
+ return await approver({
46
+ toolName: request.toolName,
47
+ toolArgs: request.args,
48
+ callId: request.callId,
49
+ ctx: request.ctx,
50
+ });
51
+ }
52
+ catch (e) {
53
+ return deny(`approval failed: ${e instanceof Error ? e.message : String(e)}`);
54
+ }
55
+ },
56
+ };
57
+ }
58
+ function broadcast(options, event) {
59
+ const data = frameworkCast(event.data);
60
+ const own = event.ctx ? getBroadcaster(event.ctx) : undefined;
61
+ const targets = own
62
+ ? [
63
+ own,
64
+ ]
65
+ : [
66
+ ...options.broadcasters(),
67
+ ];
68
+ for (const broadcaster of targets) {
69
+ emitFrameworkEvent({
70
+ broadcaster,
71
+ agentName: options.harness.config.name,
72
+ eventType: event.type,
73
+ data,
74
+ });
75
+ }
76
+ }
77
+ async function deliverTurn(harness, delivery) {
78
+ const eventItem = frameworkCast({
79
+ type: CONNECTION_EVENT_ITEM_TYPE,
80
+ id: `connection-event-${delivery.messageId}`,
81
+ trigger: delivery.trigger,
82
+ event: delivery.event,
83
+ });
84
+ await harness.execute([
85
+ createMessage(delivery.input, 'user'),
86
+ eventItem,
87
+ ], {
88
+ threadId: delivery.threadId,
89
+ messageId: delivery.messageId,
90
+ });
91
+ await harness.getAgentResponse({
92
+ threadId: delivery.threadId,
93
+ });
94
+ }
95
+ //#endregion
96
+ //#region Public API
97
+ /**
98
+ * Builds a harness's connections from its options.
99
+ *
100
+ * @throws NoeticConfigError `CONNECTION_INVALID` for a malformed entry or trigger,
101
+ * `CONNECTION_UNKNOWN` for a trigger naming an unknown connection.
102
+ */
103
+ export function createHarnessConnections(options) {
104
+ const registry = createConnectionRuntime({
105
+ connections: options.connections,
106
+ storage: options.storage,
107
+ artifacts: options.artifacts,
108
+ secrets: options.secrets,
109
+ hooks: gateHooks(options.harness),
110
+ onFrameworkEvent: (event) => broadcast(options, event),
111
+ });
112
+ const triggers = options.triggers ?? [];
113
+ validateTriggers(triggers, registry.names());
114
+ const runner = triggers.length > 0
115
+ ? new TriggerRunner({
116
+ runtime: registry,
117
+ triggers,
118
+ storage: options.storage,
119
+ deliver: (delivery) => deliverTurn(options.harness, delivery),
120
+ })
121
+ : undefined;
122
+ const views = connectionViewLayers(registry);
123
+ let starting;
124
+ return {
125
+ registry,
126
+ views,
127
+ start() {
128
+ starting ??= (async () => {
129
+ await registry.start();
130
+ await runner?.start();
131
+ })();
132
+ return starting;
133
+ },
134
+ async close() {
135
+ await runEvery([
136
+ () => runner?.close(),
137
+ () => registry.close(),
138
+ ]);
139
+ },
140
+ tools: () => buildConnectionTools(registry),
141
+ };
142
+ }
143
+ //#endregion