@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,775 @@
1
+ /**
2
+ * The connection registry (spec 35 § Connection registry). Steps, tools and
3
+ * documents never hold a provider's `Connection`: they resolve connections by
4
+ * name when they run, and the registry wraps each one with the gates, refs,
5
+ * blobs, secrets, identity tracking, reconnection and pool leases. A step that
6
+ * runs after a reconnect therefore uses the new connection, and nothing can
7
+ * reach a server around the harness.
8
+ *
9
+ * Providers connect in `start()` (the harness's `start()`, called by the first
10
+ * `execute()` or `run()`). A connection that drops is marked unavailable and
11
+ * reconnected with backoff while every other connection keeps working. When a
12
+ * connection's manifest changes it is renegotiated against what the harness
13
+ * graph requires; one that no longer satisfies it becomes unavailable.
14
+ */
15
+ import { isConnectionProvider, normalizeConnectionEntry } from '@noetic-tools/types';
16
+ import { withholdSensitiveBlobs } from './blobs.js';
17
+ import { resumeDecision } from './durability.js';
18
+ import { invalidConnectionError, notAllowedConnectionError, resumeRefusedError, unavailableError, unknownConnectionError, } from './errors.js';
19
+ import { bufferedEventStream } from './event-stream.js';
20
+ import { admitIncoming, gatedAwaitTask, gatedCall } from './gates.js';
21
+ import { CONNECTION_NAME_PATTERN } from './handle.js';
22
+ import { checkRequirement } from './negotiation.js';
23
+ import { ConnectionPool } from './pool.js';
24
+ import { kindInfoFrom, RefSealer, refKindsOf } from './refs.js';
25
+ import { SecretScrubber } from './secrets.js';
26
+ import { runEvery } from './settle.js';
27
+ //#endregion
28
+ //#region Helpers
29
+ const EXPOSE_VALUES = new Set([
30
+ 'eager',
31
+ 'all',
32
+ 'none',
33
+ ]);
34
+ function defaultReconnectDelay(attempt) {
35
+ return Math.min(3e4, 1e3 * 2 ** attempt);
36
+ }
37
+ function errorReason(e) {
38
+ return e instanceof Error ? e.message : String(e);
39
+ }
40
+ function unrefTimeout(timer) {
41
+ if (typeof timer === 'object' && timer !== null && 'unref' in timer) {
42
+ timer.unref();
43
+ }
44
+ }
45
+ function validateEntry(name, config) {
46
+ if (!CONNECTION_NAME_PATTERN.test(name)) {
47
+ throw invalidConnectionError(`Connection name '${name}' is not valid.`, 'Start with a letter and use only letters, digits, _ and -.');
48
+ }
49
+ if (!isConnectionProvider(config.provider)) {
50
+ throw invalidConnectionError(`Connection '${name}' has no provider.`, 'Pass mcp(…), a source, or any ConnectionProvider (an object with connect()).');
51
+ }
52
+ if (config.expose !== undefined && !EXPOSE_VALUES.has(config.expose)) {
53
+ throw invalidConnectionError(`Connection '${name}' has expose '${String(config.expose)}'.`, "Use expose: 'eager', 'all' or 'none'.");
54
+ }
55
+ }
56
+ function hostOnlyViolation(profile, setup) {
57
+ const hostOnly = profile?.definition.setup?.hostOnly ?? [];
58
+ return hostOnly.find((field) => setup !== undefined && field in setup);
59
+ }
60
+ function validateSetup(name, profile, setup) {
61
+ const field = hostOnlyViolation(profile, setup);
62
+ if (field !== undefined) {
63
+ throw notAllowedConnectionError(`Setup field '${field}' of connection '${name}' is reserved to the host.`, "Set host-only setup fields (an app's command or path) in the pool's own configuration.");
64
+ }
65
+ const schema = profile?.definition.setup?.schema;
66
+ if (!schema || setup === undefined) {
67
+ return;
68
+ }
69
+ const parsed = schema.safeParse(setup);
70
+ if (!parsed.success) {
71
+ throw invalidConnectionError(`Setup for connection '${name}' does not match the ${profile.name} profile: ${parsed.error.message}`, "Pass only the setup fields the profile's setup schema accepts.");
72
+ }
73
+ }
74
+ //#endregion
75
+ //#region Runtime
76
+ class Runtime {
77
+ options;
78
+ entries = new Map();
79
+ sealer;
80
+ scrubber = new SecretScrubber();
81
+ refKinds = new Map();
82
+ /** Every profile handles name, by id, handed to providers when they connect. */
83
+ profiles = new Map();
84
+ reruns = new Map();
85
+ controller = new AbortController();
86
+ starting;
87
+ now;
88
+ constructor(options) {
89
+ this.options = options;
90
+ this.now = options.now ?? Date.now;
91
+ this.sealer = new RefSealer(options.storage, this.now);
92
+ for (const profile of options.profiles ?? []) {
93
+ this.registerProfile(profile);
94
+ }
95
+ for (const [name, raw] of Object.entries(options.connections ?? {})) {
96
+ const config = normalizeConnectionEntry(raw);
97
+ validateEntry(name, config);
98
+ this.entries.set(name, {
99
+ name,
100
+ config,
101
+ pool: config.pool ? this.createPool(name, config) : undefined,
102
+ state: 'connecting',
103
+ effects: 0,
104
+ attempts: 0,
105
+ requirements: [],
106
+ });
107
+ }
108
+ }
109
+ //#region Registry contract
110
+ names() {
111
+ return [
112
+ ...this.entries.keys(),
113
+ ];
114
+ }
115
+ async resolve(request) {
116
+ const target = request.from ?? request.name;
117
+ const entry = this.entries.get(target);
118
+ if (!entry) {
119
+ throw unknownConnectionError(target, this.names());
120
+ }
121
+ if (request.profile) {
122
+ this.registerProfile(request.profile);
123
+ }
124
+ if (entry.pool) {
125
+ return this.resolvePooled(entry, request);
126
+ }
127
+ if (request.fresh) {
128
+ throw invalidConnectionError(`Connection '${target}' is not a pool, so it cannot give a fresh connection.`, `Give '${target}' a \`pool\` in the harness connections, or drop \`fresh\` from the handle.`);
129
+ }
130
+ await this.ensureConnected(entry);
131
+ const connection = this.requireReady(entry);
132
+ this.negotiate(entry.name, connection.manifest, request);
133
+ return this.wrap(entry, request.scope, request.ctx);
134
+ }
135
+ async releaseScope(scopeKey) {
136
+ for (const entry of this.entries.values()) {
137
+ await entry.pool?.release(scopeKey);
138
+ }
139
+ }
140
+ async releaseRun(rootId) {
141
+ // A rerun allowance covers one restore of the run; it ends with the run.
142
+ this.reruns.delete(rootId);
143
+ for (const [pool, holder] of this.runHolders(rootId)) {
144
+ await pool.release(holder);
145
+ }
146
+ }
147
+ orphanRun(rootId) {
148
+ this.reruns.delete(rootId);
149
+ for (const [pool, holder] of this.runHolders(rootId)) {
150
+ pool.orphan(holder);
151
+ }
152
+ }
153
+ /** Every (pool, holder) pair a run holds: its `fresh: 'run'` lease and each `fresh: 'path'` lease. */
154
+ runHolders(rootId) {
155
+ const pathPrefix = `${rootId}:path:`;
156
+ const found = [];
157
+ for (const entry of this.entries.values()) {
158
+ const pool = entry.pool;
159
+ if (!pool) {
160
+ continue;
161
+ }
162
+ for (const holder of pool.holders()) {
163
+ if (holder === rootId || holder.startsWith(pathPrefix)) {
164
+ found.push([
165
+ pool,
166
+ holder,
167
+ ]);
168
+ }
169
+ }
170
+ }
171
+ return found;
172
+ }
173
+ status(name) {
174
+ const entries = name
175
+ ? [
176
+ this.entries.get(name),
177
+ ].filter((e) => e !== undefined)
178
+ : [
179
+ ...this.entries.values(),
180
+ ];
181
+ return entries.map((entry) => this.statusOf(entry));
182
+ }
183
+ //#endregion
184
+ //#region Lifecycle
185
+ start() {
186
+ if (!this.starting) {
187
+ this.starting = this.startAll();
188
+ }
189
+ return this.starting;
190
+ }
191
+ async close() {
192
+ this.controller.abort();
193
+ // Every entry is closed even when one throws; the first failure is rethrown.
194
+ await runEvery([
195
+ ...this.entries.values(),
196
+ ].map((entry) => () => this.closeEntry(entry)));
197
+ }
198
+ async closeEntry(entry) {
199
+ if (entry.reconnectTimer) {
200
+ clearTimeout(entry.reconnectTimer);
201
+ }
202
+ const connection = entry.connection;
203
+ try {
204
+ await runEvery([
205
+ () => entry.unsubscribe?.(),
206
+ () => entry.pool?.close(),
207
+ ]);
208
+ }
209
+ finally {
210
+ entry.connection = undefined;
211
+ this.setState(entry, 'closed', 'the harness closed');
212
+ await connection?.release().catch(() => undefined);
213
+ }
214
+ }
215
+ config(name) {
216
+ return this.entries.get(name)?.config;
217
+ }
218
+ current(name) {
219
+ const entry = this.entries.get(name);
220
+ return entry?.state === 'ready' ? entry.connection : undefined;
221
+ }
222
+ effectCount(name) {
223
+ return this.entries.get(name)?.effects ?? 0;
224
+ }
225
+ require(name, requirement, options) {
226
+ const entry = this.entries.get(name);
227
+ if (!entry) {
228
+ throw unknownConnectionError(name, this.names());
229
+ }
230
+ if (entry.pool && options?.setup) {
231
+ return;
232
+ }
233
+ entry.requirements.push(requirement);
234
+ }
235
+ check(name, requirement, options) {
236
+ const entry = this.entries.get(name);
237
+ if (entry?.pool && options?.setup) {
238
+ return true;
239
+ }
240
+ const manifest = entry ? this.manifestOf(entry) : undefined;
241
+ if (!manifest) {
242
+ return false;
243
+ }
244
+ checkRequirement(name, manifest, requirement);
245
+ return true;
246
+ }
247
+ /** The manifest an entry offers now: its connection's, or for a pool its members'. */
248
+ manifestOf(entry) {
249
+ if (entry.pool) {
250
+ return entry.pool.manifest();
251
+ }
252
+ return entry.connection?.manifest;
253
+ }
254
+ registerProfile(profile) {
255
+ this.profiles.set(profile.id, profile);
256
+ for (const [kind, info] of refKindsOf(profile)) {
257
+ this.refKinds.set(kind, info);
258
+ }
259
+ }
260
+ rerunAllowed(executionId, name) {
261
+ return this.reruns.get(executionId)?.has(name) ?? false;
262
+ }
263
+ allowRerun(executionId, names) {
264
+ const set = this.reruns.get(executionId) ?? new Set();
265
+ for (const name of names) {
266
+ set.add(name);
267
+ }
268
+ this.reruns.set(executionId, set);
269
+ }
270
+ async checkResume(params) {
271
+ const entry = this.entries.get(params.name);
272
+ if (!entry) {
273
+ throw unknownConnectionError(params.name, this.names());
274
+ }
275
+ const connection = entry.pool
276
+ ? this.pooledFor(entry.pool, params.executionId, params.recorded)
277
+ : await this.readyConnection(entry);
278
+ const decision = resumeDecision({
279
+ recorded: params.recorded,
280
+ current: connection?.identity ?? {
281
+ surface: params.recorded.surface,
282
+ instance: '(lease no longer held)',
283
+ },
284
+ determinism: connection?.manifest.determinism,
285
+ rerunAllowed: this.rerunAllowed(params.executionId, params.name),
286
+ canReset: connection?.reset !== undefined,
287
+ });
288
+ if (decision === 'refuse') {
289
+ throw resumeRefusedError(params.name, `connection '${params.name}' was replaced (instance ${params.recorded.instance} → ${connection?.identity.instance ?? 'a new lease'}) and is not safe to drive again; restore with { rerun: ['${params.name}'] } to run it live`);
290
+ }
291
+ if (decision === 'reset') {
292
+ await connection?.reset?.({
293
+ signal: params.signal,
294
+ });
295
+ }
296
+ return decision;
297
+ }
298
+ async readyConnection(entry) {
299
+ await this.ensureConnected(entry);
300
+ return this.requireReady(entry);
301
+ }
302
+ /**
303
+ * The connection a run still holds from `pool` with the recorded identity, or
304
+ * — when its lease is gone — any connection of the pool, whose determinism
305
+ * stands for the pool's (undefined when none is held: treated as unsafe).
306
+ */
307
+ pooledFor(pool, executionId, recorded) {
308
+ const pathPrefix = `${executionId}:path:`;
309
+ const held = pool
310
+ .holders()
311
+ .map((holder) => pool.heldBy(holder))
312
+ .filter((h) => h !== undefined);
313
+ const own = held.find((h) => (h.lease.holder === executionId || h.lease.holder.startsWith(pathPrefix)) &&
314
+ h.connection.identity.instance === recorded.instance);
315
+ return own?.connection ?? held[0]?.connection;
316
+ }
317
+ async listenRaw(name, request) {
318
+ const entry = this.entries.get(name);
319
+ if (!entry) {
320
+ throw unknownConnectionError(name, this.names());
321
+ }
322
+ await this.ensureConnected(entry);
323
+ return this.requireReady(entry).listen(request);
324
+ }
325
+ async admit(name, value, scope) {
326
+ const entry = this.entries.get(name);
327
+ const connection = entry?.connection;
328
+ if (!entry || !connection) {
329
+ throw unavailableError(name, 'the connection is not connected');
330
+ }
331
+ return admitIncoming({
332
+ scrubber: this.scrubber,
333
+ refs: this.sealer,
334
+ refScope: this.refScope(name, connection, scope.threadId),
335
+ artifacts: this.options.artifacts,
336
+ executionId: scope.executionId,
337
+ name,
338
+ }, value);
339
+ }
340
+ emit(event) {
341
+ this.options.onFrameworkEvent?.(event);
342
+ }
343
+ withholdSensitive(value) {
344
+ return withholdSensitiveBlobs(value, this.options.artifacts);
345
+ }
346
+ //#endregion
347
+ //#region Connecting
348
+ async startAll() {
349
+ const work = [];
350
+ for (const entry of this.entries.values()) {
351
+ if (entry.pool) {
352
+ work.push(entry.pool.start().then(() => this.setState(entry, 'ready'), (e) => this.setState(entry, 'unavailable', errorReason(e))));
353
+ continue;
354
+ }
355
+ work.push(this.ensureConnected(entry).catch(() => undefined));
356
+ }
357
+ await Promise.all(work);
358
+ for (const entry of [
359
+ ...this.entries.values(),
360
+ ]) {
361
+ if (entry.pool) {
362
+ this.renegotiatePool(entry, entry.pool);
363
+ continue;
364
+ }
365
+ if (entry.connection) {
366
+ this.renegotiate(entry, entry.connection);
367
+ }
368
+ }
369
+ }
370
+ /**
371
+ * Checks what the harness graph requires of a pool against the manifest its
372
+ * connections offer, once it has provisioned one; a pool that falls short is
373
+ * unavailable, as a single connection would be.
374
+ */
375
+ renegotiatePool(entry, pool) {
376
+ const manifest = pool.manifest();
377
+ if (!manifest || entry.state !== 'ready') {
378
+ return;
379
+ }
380
+ for (const requirement of entry.requirements) {
381
+ try {
382
+ checkRequirement(entry.name, manifest, requirement);
383
+ }
384
+ catch (e) {
385
+ this.setState(entry, 'unavailable', errorReason(e));
386
+ return;
387
+ }
388
+ }
389
+ }
390
+ ensureConnected(entry) {
391
+ if (entry.connection || entry.pool || entry.state === 'closed') {
392
+ return Promise.resolve();
393
+ }
394
+ if (!entry.connecting) {
395
+ entry.connecting = this.connect(entry).finally(() => {
396
+ entry.connecting = undefined;
397
+ });
398
+ }
399
+ return entry.connecting;
400
+ }
401
+ async connect(entry) {
402
+ this.setState(entry, 'connecting');
403
+ try {
404
+ const connections = await entry.config.provider.connect({
405
+ name: entry.name,
406
+ signal: this.controller.signal,
407
+ artifacts: this.options.artifacts,
408
+ profiles: [
409
+ ...this.profiles.values(),
410
+ ],
411
+ });
412
+ const [first, ...extra] = connections;
413
+ if (!first) {
414
+ throw new Error('the provider returned no connections');
415
+ }
416
+ this.attach(entry, first);
417
+ this.attachExtra(entry, extra);
418
+ }
419
+ catch (e) {
420
+ this.setState(entry, 'unavailable', errorReason(e));
421
+ this.scheduleReconnect(entry);
422
+ throw unavailableError(entry.name, errorReason(e));
423
+ }
424
+ }
425
+ /** A provider serving several instances: each further one is `<name>-<id>`. */
426
+ attachExtra(entry, extra) {
427
+ for (const connection of extra) {
428
+ const name = `${entry.name}-${connection.id.replace(/[^A-Za-z0-9_-]/g, '_')}`;
429
+ const existing = this.entries.get(name);
430
+ const sibling = existing ?? {
431
+ name,
432
+ config: entry.config,
433
+ state: 'connecting',
434
+ effects: 0,
435
+ attempts: 0,
436
+ requirements: [],
437
+ };
438
+ this.entries.set(name, sibling);
439
+ this.attach(sibling, connection);
440
+ }
441
+ }
442
+ attach(entry, connection) {
443
+ entry.unsubscribe?.();
444
+ entry.connection = connection;
445
+ entry.attempts = 0;
446
+ entry.unsubscribe = connection.onChange((change) => {
447
+ if (change === 'manifest') {
448
+ this.renegotiate(entry, connection);
449
+ return;
450
+ }
451
+ this.emitChanged(entry);
452
+ });
453
+ this.setState(entry, 'ready');
454
+ void connection.closed.then(({ reason }) => {
455
+ if (entry.connection !== connection || entry.state === 'closed') {
456
+ return;
457
+ }
458
+ entry.unsubscribe?.();
459
+ entry.unsubscribe = undefined;
460
+ entry.connection = undefined;
461
+ this.setState(entry, 'unavailable', reason);
462
+ this.scheduleReconnect(entry);
463
+ });
464
+ }
465
+ scheduleReconnect(entry) {
466
+ if (this.controller.signal.aborted || entry.reconnectTimer) {
467
+ return;
468
+ }
469
+ const delay = (this.options.reconnectDelayMs ?? defaultReconnectDelay)(entry.attempts);
470
+ entry.attempts += 1;
471
+ entry.reconnectTimer = setTimeout(() => {
472
+ entry.reconnectTimer = undefined;
473
+ void this.ensureConnected(entry).catch(() => undefined);
474
+ }, delay);
475
+ unrefTimeout(entry.reconnectTimer);
476
+ }
477
+ renegotiate(entry, connection) {
478
+ const down = connection.unavailable;
479
+ if (down !== undefined) {
480
+ this.setState(entry, 'unavailable', down);
481
+ return;
482
+ }
483
+ for (const requirement of entry.requirements) {
484
+ try {
485
+ checkRequirement(entry.name, connection.manifest, requirement);
486
+ }
487
+ catch (e) {
488
+ this.setState(entry, 'unavailable', errorReason(e));
489
+ return;
490
+ }
491
+ }
492
+ if (entry.state !== 'ready') {
493
+ this.setState(entry, 'ready');
494
+ return;
495
+ }
496
+ this.emitChanged(entry);
497
+ }
498
+ requireReady(entry) {
499
+ const connection = entry.connection;
500
+ if (entry.state !== 'ready' || !connection) {
501
+ throw unavailableError(entry.name, entry.reason ?? `the connection is ${entry.state}`);
502
+ }
503
+ return connection;
504
+ }
505
+ negotiate(name, manifest, request) {
506
+ const requirement = request.requirement;
507
+ if (!requirement) {
508
+ return;
509
+ }
510
+ const parents = request.profile && requirement.profile?.name === request.profile.name
511
+ ? request.profile.parents
512
+ : undefined;
513
+ checkRequirement(name, manifest, {
514
+ ...requirement,
515
+ parents,
516
+ });
517
+ }
518
+ //#endregion
519
+ //#region Pools
520
+ createPool(name, config) {
521
+ const pool = config.pool;
522
+ if (!pool) {
523
+ throw invalidConnectionError(`Connection '${name}' has no pool.`, 'Internal error.');
524
+ }
525
+ return new ConnectionPool({
526
+ name,
527
+ provider: config.provider,
528
+ config: pool,
529
+ storage: this.options.storage,
530
+ now: this.options.now,
531
+ connectOptions: (signal) => ({
532
+ name,
533
+ signal,
534
+ artifacts: this.options.artifacts,
535
+ profiles: [
536
+ ...this.profiles.values(),
537
+ ],
538
+ }),
539
+ onLease: (lease, change) => this.emitLease(name, lease, change),
540
+ });
541
+ }
542
+ async resolvePooled(entry, request) {
543
+ const pool = entry.pool;
544
+ if (!pool) {
545
+ throw unavailableError(entry.name, 'the pool is missing');
546
+ }
547
+ validateSetup(entry.name, request.profile, request.setup);
548
+ const held = await pool.acquire({
549
+ scopeKey: request.scope.scopeKey,
550
+ scope: request.fresh ?? 'run',
551
+ setup: request.setup ?? {},
552
+ signal: request.scope.signal,
553
+ });
554
+ try {
555
+ this.negotiate(entry.name, held.connection.manifest, request);
556
+ }
557
+ catch (e) {
558
+ await pool.release(request.scope.scopeKey);
559
+ throw e;
560
+ }
561
+ return this.wrap(entry, request.scope, request.ctx, held.lease);
562
+ }
563
+ //#endregion
564
+ //#region Wrapping
565
+ refScope(name, connection, threadId, lease) {
566
+ return {
567
+ connection: name,
568
+ threadId,
569
+ instance: connection.identity.instance,
570
+ ...(lease
571
+ ? {
572
+ lease: lease.id,
573
+ }
574
+ : {}),
575
+ kindInfo: kindInfoFrom(this.refKinds),
576
+ };
577
+ }
578
+ connectionFor(entry, scopeKey, lease) {
579
+ if (!lease) {
580
+ return this.requireReady(entry);
581
+ }
582
+ const held = entry.pool?.heldBy(scopeKey);
583
+ if (!held || held.lease.id !== lease.id) {
584
+ throw unavailableError(entry.name, `lease ${lease.id} is no longer held`);
585
+ }
586
+ return held.connection;
587
+ }
588
+ gateContext(entry, scope, connection, ctx, lease) {
589
+ return {
590
+ name: entry.name,
591
+ connection,
592
+ policy: entry.config.policy,
593
+ executionId: scope.executionId,
594
+ refScope: this.refScope(entry.name, connection, scope.threadId, lease),
595
+ refs: this.sealer,
596
+ scrubber: this.scrubber,
597
+ secrets: this.options.secrets,
598
+ artifacts: this.options.artifacts,
599
+ hooks: this.options.hooks ?? {},
600
+ onTask: (op, status, stepId) => this.emitTask(entry.name, op, status, ctx, stepId),
601
+ onEffect: () => {
602
+ entry.effects += 1;
603
+ },
604
+ };
605
+ }
606
+ wrap(entry, scope, ctx, lease) {
607
+ const current = () => this.connectionFor(entry, scope.scopeKey, lease);
608
+ const resolved = {
609
+ name: entry.name,
610
+ lease,
611
+ get manifest() {
612
+ return current().manifest;
613
+ },
614
+ identity: () => current().identity,
615
+ call: async (op, args, opts) => gatedCall(this.gateContext(entry, scope, current(), opts.ctx ?? ctx, lease), {
616
+ op,
617
+ args,
618
+ opts: {
619
+ ...opts,
620
+ ctx: opts.ctx ?? ctx,
621
+ },
622
+ }),
623
+ awaitTask: async (taskId, op, opts) => gatedAwaitTask(this.gateContext(entry, scope, current(), opts.ctx ?? ctx, lease), {
624
+ op,
625
+ taskId,
626
+ opts: {
627
+ ...opts,
628
+ ctx: opts.ctx ?? ctx,
629
+ },
630
+ }),
631
+ read: async (resource, opts) => {
632
+ const connection = current();
633
+ const value = await connection.read(resource, opts);
634
+ return admitIncoming(this.gateContext(entry, scope, connection, ctx, lease), value);
635
+ },
636
+ listen: (req) => this.listenWrapped(entry, scope, current(), {
637
+ ...req,
638
+ ctx,
639
+ lease,
640
+ }),
641
+ ...(current().reset
642
+ ? {
643
+ reset: (opts) => current().reset?.(opts) ?? Promise.resolve(),
644
+ }
645
+ : {}),
646
+ };
647
+ return resolved;
648
+ }
649
+ listenWrapped(entry, scope, connection, req) {
650
+ const gc = this.gateContext(entry, scope, connection, req.ctx, req.lease);
651
+ const source = connection.listen({
652
+ event: req.event,
653
+ arguments: req.arguments,
654
+ cursor: req.cursor,
655
+ signal: req.signal,
656
+ });
657
+ return bufferedEventStream(source, {
658
+ transform: async (event) => {
659
+ const payload = await admitIncoming(gc, event.payload);
660
+ return {
661
+ ...event,
662
+ payload,
663
+ connection: entry.name,
664
+ };
665
+ },
666
+ onEvent: (event) => this.emit({
667
+ type: 'connection_event',
668
+ data: {
669
+ connection: entry.name,
670
+ event,
671
+ },
672
+ ctx: req.ctx,
673
+ }),
674
+ onChange: (change) => this.emit({
675
+ type: 'stream_changed',
676
+ data: {
677
+ connection: entry.name,
678
+ event: req.event,
679
+ change: change.change,
680
+ reason: change.reason,
681
+ },
682
+ ctx: req.ctx,
683
+ }),
684
+ });
685
+ }
686
+ //#endregion
687
+ //#region Status and events
688
+ statusOf(entry) {
689
+ return {
690
+ name: entry.name,
691
+ state: entry.state,
692
+ ...(entry.connection
693
+ ? {
694
+ identity: entry.connection.identity,
695
+ }
696
+ : {}),
697
+ ...(entry.reason && entry.state !== 'ready'
698
+ ? {
699
+ reason: entry.reason,
700
+ }
701
+ : {}),
702
+ ...(entry.pool
703
+ ? {
704
+ pool: entry.pool.status(),
705
+ }
706
+ : {}),
707
+ };
708
+ }
709
+ setState(entry, state, reason) {
710
+ entry.state = state;
711
+ entry.reason = reason;
712
+ this.emitChanged(entry);
713
+ }
714
+ emitChanged(entry) {
715
+ this.emit({
716
+ type: 'connection_changed',
717
+ data: {
718
+ connection: entry.name,
719
+ state: entry.state,
720
+ ...(entry.connection
721
+ ? {
722
+ identity: entry.connection.identity,
723
+ }
724
+ : {}),
725
+ ...(entry.reason
726
+ ? {
727
+ reason: entry.reason,
728
+ }
729
+ : {}),
730
+ },
731
+ });
732
+ }
733
+ emitLease(name, lease, change) {
734
+ const entry = this.entries.get(name);
735
+ this.emit({
736
+ type: 'connection_changed',
737
+ data: {
738
+ connection: name,
739
+ state: entry?.state ?? 'ready',
740
+ lease: {
741
+ ...lease,
742
+ change,
743
+ },
744
+ },
745
+ });
746
+ }
747
+ emitTask(name, op, status, ctx, stepId) {
748
+ this.emit({
749
+ type: 'connection_task',
750
+ data: {
751
+ connection: name,
752
+ op,
753
+ ...(stepId
754
+ ? {
755
+ stepId,
756
+ }
757
+ : {}),
758
+ status,
759
+ },
760
+ ctx,
761
+ });
762
+ }
763
+ }
764
+ //#endregion
765
+ //#region Public API
766
+ /**
767
+ * Creates a harness connection registry. Construction validates the
768
+ * configuration synchronously; providers connect in `start()`.
769
+ *
770
+ * @throws NoeticConfigError `CONNECTION_INVALID` for a malformed entry.
771
+ */
772
+ export function createConnectionRuntime(options) {
773
+ return new Runtime(options);
774
+ }
775
+ //#endregion