@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,316 @@
1
+ /**
2
+ * Refs (spec 35 § Refs and blobs). A ref is
3
+ * `{ $ref: { connection, kind, id, seal } }`. `seal` is an HMAC over the rest
4
+ * and the issuing thread and, for refs a profile marks volatile, over the
5
+ * connection's identity instance too. The harness seals refs on the way in
6
+ * (outputs, reads, event payloads) and checks them on the way out, so a ref
7
+ * cannot be forged, used from another thread, or reused after the thing it
8
+ * pointed into was replaced. Refs a profile marks `public` skip the thread
9
+ * check.
10
+ *
11
+ * Seal format: `<keyId>.<mac>` for a stable ref, `<keyId>.<mac>.<instanceMac>`
12
+ * for a volatile one, where `mac` covers connection, kind, id and thread and
13
+ * `instanceMac` covers `mac` and the instance. A volatile ref whose `mac`
14
+ * verifies but whose `instanceMac` does not is stale rather than forged.
15
+ *
16
+ * Signing keys live in the harness `StorageAdapter` and rotate with an
17
+ * overlap, so refs survive a restart.
18
+ */
19
+ import { isRef, profileFieldOf } from '@noetic-tools/types';
20
+ import { z } from 'zod';
21
+ import { refInvalidError } from './errors.js';
22
+ import { findDeep, isPlainRecord, mapDeep } from './values.js';
23
+ //#endregion
24
+ //#region Constants
25
+ const KEYS_STORAGE_KEY = 'noetic/connections/ref-keys';
26
+ /** A new signing key is made after this long. */
27
+ const ROTATE_MS = 7 * 24 * 3600e3;
28
+ /** Old keys still verify for this long after they stop signing. */
29
+ const OVERLAP_MS = 7 * 24 * 3600e3;
30
+ const STABLE = {
31
+ volatile: false,
32
+ public: false,
33
+ };
34
+ const StoredKeysSchema = z.object({
35
+ keys: z.array(z.object({
36
+ id: z.string(),
37
+ secret: z.string(),
38
+ createdAt: z.number(),
39
+ })),
40
+ });
41
+ //#endregion
42
+ //#region Helpers
43
+ function bytesToBase64Url(bytes) {
44
+ let binary = '';
45
+ for (const byte of bytes) {
46
+ binary += String.fromCharCode(byte);
47
+ }
48
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
49
+ }
50
+ function base64ToBytes(text) {
51
+ const binary = atob(text);
52
+ const bytes = new Uint8Array(binary.length);
53
+ for (let i = 0; i < binary.length; i++) {
54
+ bytes[i] = binary.charCodeAt(i);
55
+ }
56
+ return bytes;
57
+ }
58
+ function newStoredKey(now) {
59
+ const raw = crypto.getRandomValues(new Uint8Array(32));
60
+ let binary = '';
61
+ for (const byte of raw) {
62
+ binary += String.fromCharCode(byte);
63
+ }
64
+ return {
65
+ id: crypto.randomUUID().slice(0, 8),
66
+ secret: btoa(binary),
67
+ createdAt: now,
68
+ };
69
+ }
70
+ /** A ref body a provider handed out, not yet sealed: `kind` and `id`, no `seal`. */
71
+ function isIssuedRef(value) {
72
+ if (!isPlainRecord(value) || !isPlainRecord(value.$ref)) {
73
+ return false;
74
+ }
75
+ const body = value.$ref;
76
+ return (Object.keys(value).length === 1 &&
77
+ typeof body.kind === 'string' &&
78
+ typeof body.id === 'string' &&
79
+ body.seal === undefined);
80
+ }
81
+ //#endregion
82
+ //#region RefSealer
83
+ /** Seals and checks refs with keys kept in storage. */
84
+ export class RefSealer {
85
+ storage;
86
+ now;
87
+ keysPromise;
88
+ cryptoKeys = new Map();
89
+ constructor(storage, now = Date.now) {
90
+ this.storage = storage;
91
+ this.now = now;
92
+ }
93
+ /** Seals a provider-issued ref for `scope`. */
94
+ async seal(body, scope) {
95
+ const keys = await this.keys();
96
+ const key = keys[keys.length - 1];
97
+ if (!key) {
98
+ throw new Error('ref signing key missing');
99
+ }
100
+ const info = scope.kindInfo(body.kind);
101
+ const mac = await this.mac(key, [
102
+ scope.connection,
103
+ body.kind,
104
+ body.id,
105
+ info.public ? '' : scope.threadId,
106
+ ...leasePart(scope),
107
+ ]);
108
+ const parts = [
109
+ key.id,
110
+ mac,
111
+ ];
112
+ if (info.volatile) {
113
+ parts.push(await this.mac(key, [
114
+ mac,
115
+ scope.instance,
116
+ ]));
117
+ }
118
+ return {
119
+ $ref: {
120
+ connection: scope.connection,
121
+ kind: body.kind,
122
+ id: body.id,
123
+ seal: parts.join('.'),
124
+ },
125
+ };
126
+ }
127
+ /**
128
+ * Checks a ref going out to `scope.connection`.
129
+ *
130
+ * @throws NoeticErrorImpl `connection_ref_invalid` when the ref belongs to another
131
+ * connection, was not issued here (or to this thread), or is stale.
132
+ */
133
+ async check(ref, scope) {
134
+ if (ref.connection !== scope.connection) {
135
+ throw refInvalidError(scope.connection, `ref ${ref.kind} '${ref.id}' belongs to connection '${ref.connection}'`);
136
+ }
137
+ const [keyId, mac, instanceMac] = ref.seal.split('.');
138
+ const keys = await this.keys();
139
+ const key = keys.find((k) => k.id === keyId);
140
+ const info = scope.kindInfo(ref.kind);
141
+ const expected = key
142
+ ? await this.mac(key, [
143
+ ref.connection,
144
+ ref.kind,
145
+ ref.id,
146
+ info.public ? '' : scope.threadId,
147
+ ...leasePart(scope),
148
+ ])
149
+ : undefined;
150
+ if (!key || expected !== mac) {
151
+ throw refInvalidError(scope.connection, `ref ${ref.kind} '${ref.id}' was not issued by this harness to this thread${scope.lease ? ' on this lease' : ''}`);
152
+ }
153
+ if (!info.volatile) {
154
+ return;
155
+ }
156
+ const expectedInstance = await this.mac(key, [
157
+ mac,
158
+ scope.instance,
159
+ ]);
160
+ if (expectedInstance !== instanceMac) {
161
+ throw refInvalidError(scope.connection, `ref ${ref.kind} '${ref.id}' is stale: the connection was replaced`);
162
+ }
163
+ }
164
+ /** A copy of `value` with every provider-issued ref sealed for `scope`. */
165
+ async sealAll(value, scope) {
166
+ const issued = findDeep(value, isIssuedRef);
167
+ if (issued.length === 0) {
168
+ return value;
169
+ }
170
+ const sealed = new Map();
171
+ for (const found of issued) {
172
+ const body = found.value.$ref;
173
+ const cacheKey = `${body.kind}\u0000${body.id}`;
174
+ if (!sealed.has(cacheKey)) {
175
+ sealed.set(cacheKey, await this.seal(body, scope));
176
+ }
177
+ }
178
+ return mapDeep(value, (node) => isIssuedRef(node.value)
179
+ ? {
180
+ replace: sealed.get(`${node.value.$ref.kind}\u0000${node.value.$ref.id}`),
181
+ }
182
+ : undefined);
183
+ }
184
+ /** Checks every ref in `value` (see `check`). */
185
+ async checkAll(value, scope) {
186
+ for (const found of findDeep(value, isRef)) {
187
+ await this.check(found.value.$ref, scope);
188
+ }
189
+ }
190
+ async keys() {
191
+ if (!this.keysPromise) {
192
+ this.keysPromise = this.loadKeys().catch((e) => {
193
+ this.keysPromise = undefined;
194
+ throw e;
195
+ });
196
+ }
197
+ const keys = await this.keysPromise;
198
+ const newest = keys[keys.length - 1];
199
+ if (newest && this.now() - newest.createdAt < ROTATE_MS) {
200
+ return keys;
201
+ }
202
+ this.keysPromise = this.rotate(keys);
203
+ return this.keysPromise;
204
+ }
205
+ async loadKeys() {
206
+ const parsed = StoredKeysSchema.safeParse(await this.storage.get(KEYS_STORAGE_KEY));
207
+ if (parsed.success && parsed.data.keys.length > 0) {
208
+ return parsed.data.keys;
209
+ }
210
+ return this.rotate([]);
211
+ }
212
+ async rotate(keys) {
213
+ const now = this.now();
214
+ const kept = keys.filter((k) => now - k.createdAt < ROTATE_MS + OVERLAP_MS);
215
+ const next = [
216
+ ...kept,
217
+ newStoredKey(now),
218
+ ];
219
+ await this.storage.set(KEYS_STORAGE_KEY, {
220
+ keys: next,
221
+ });
222
+ return next;
223
+ }
224
+ cryptoKey(key) {
225
+ const cached = this.cryptoKeys.get(key.id);
226
+ if (cached) {
227
+ return cached;
228
+ }
229
+ const imported = crypto.subtle.importKey('raw', base64ToBytes(key.secret), {
230
+ name: 'HMAC',
231
+ hash: 'SHA-256',
232
+ }, false, [
233
+ 'sign',
234
+ ]);
235
+ this.cryptoKeys.set(key.id, imported);
236
+ return imported;
237
+ }
238
+ async mac(key, parts) {
239
+ const data = new TextEncoder().encode(JSON.stringify(parts));
240
+ const signature = await crypto.subtle.sign('HMAC', await this.cryptoKey(key), data);
241
+ return bytesToBase64Url(new Uint8Array(signature)).slice(0, 32);
242
+ }
243
+ }
244
+ //#endregion
245
+ //#region Ref kinds from profiles
246
+ function collectFromSchema(schema, into, depth) {
247
+ if (depth > 32) {
248
+ return;
249
+ }
250
+ const meta = profileFieldOf(schema);
251
+ if (meta?.kind === 'ref') {
252
+ into.set(meta.refKind, {
253
+ volatile: meta.volatile,
254
+ public: meta.public,
255
+ });
256
+ return;
257
+ }
258
+ const next = depth + 1;
259
+ if (schema instanceof z.ZodObject) {
260
+ for (const child of Object.values(schema.shape)) {
261
+ collectFromSchema(child, into, next);
262
+ }
263
+ return;
264
+ }
265
+ if (schema instanceof z.ZodArray) {
266
+ collectFromSchema(schema.element, into, next);
267
+ return;
268
+ }
269
+ if (schema instanceof z.ZodOptional ||
270
+ schema instanceof z.ZodNullable ||
271
+ schema instanceof z.ZodDefault) {
272
+ collectFromSchema(schema.unwrap(), into, next);
273
+ return;
274
+ }
275
+ if (schema instanceof z.ZodUnion) {
276
+ for (const option of schema.options) {
277
+ collectFromSchema(option, into, next);
278
+ }
279
+ return;
280
+ }
281
+ if (schema instanceof z.ZodRecord) {
282
+ collectFromSchema(schema.valueType, into, next);
283
+ }
284
+ }
285
+ /** Every ref kind a profile's operations, reads and events hand out, with its flags. */
286
+ export function refKindsOf(profile) {
287
+ const kinds = new Map();
288
+ for (const op of Object.values(profile.operations)) {
289
+ collectFromSchema(op.input, kinds, 0);
290
+ collectFromSchema(op.output, kinds, 0);
291
+ }
292
+ for (const read of Object.values(profile.reads)) {
293
+ collectFromSchema(read.schema, kinds, 0);
294
+ }
295
+ for (const event of Object.values(profile.events)) {
296
+ collectFromSchema(event.payload, kinds, 0);
297
+ }
298
+ return kinds;
299
+ }
300
+ /** The MAC part binding a ref to its lease; empty for a connection held without one. */
301
+ function leasePart(scope) {
302
+ return scope.lease
303
+ ? [
304
+ `lease:${scope.lease}`,
305
+ ]
306
+ : [];
307
+ }
308
+ /** Looks a ref kind up in `kinds`; unknown kinds are stable and private. */
309
+ export function kindInfoFrom(kinds) {
310
+ return (kind) => kinds.get(kind) ?? STABLE;
311
+ }
312
+ /** The connections the refs in `value` were issued by. */
313
+ export function refConnections(value) {
314
+ return new Set(findDeep(value, isRef).map((found) => found.value.$ref.connection));
315
+ }
316
+ //#endregion
@@ -0,0 +1,141 @@
1
+ /**
2
+ * The connection registry contract inside core (spec 35 § Connection registry).
3
+ *
4
+ * Steps, tools and documents never hold a provider's `Connection`. They resolve
5
+ * connections by name through the harness registry when they run; the registry
6
+ * wraps each one with the gates, refs, blobs, secrets, identity tracking,
7
+ * reconnection and pool leases, so a step that runs after a reconnect uses the
8
+ * new connection and nothing reaches a server around the harness.
9
+ *
10
+ * This file is the seam between the slices that implement connection steps,
11
+ * verification and the registry itself: they code against these types.
12
+ */
13
+ import type { AnyProfile, ConnectionEvent, ConnectionIdentity, ConnectionLease, ConnectionManifest, ConnectionRequirement, ConnectionStatus, ConnectionTaskStatus, Context, EventStream, FreshScope } from '@noetic-tools/types';
14
+ /** Who is calling: the gates differ only in what each may use (secrets never from the model). */
15
+ export type ConnectionCaller = 'model' | 'step' | 'document';
16
+ /** Where a resolution happens: identifies the lease scope and the thread refs are sealed to. */
17
+ export interface ConnectionScope {
18
+ readonly executionId: string;
19
+ /** Refs are sealed to this thread; spawned children and parallel paths share their parent's. */
20
+ readonly threadId: string;
21
+ /**
22
+ * The lease holder for a fresh connection: the run id for `fresh: 'run'`, the
23
+ * parallel path key for `fresh: 'path'`. Released by `releaseScope`.
24
+ */
25
+ readonly scopeKey: string;
26
+ readonly signal: AbortSignal;
27
+ }
28
+ /** One request to resolve a connection by name. */
29
+ export interface ResolveRequest {
30
+ /** A harness connection name (after document `bindings` are applied). */
31
+ readonly name: string;
32
+ readonly scope: ConnectionScope;
33
+ /** What the caller needs; checked at negotiation. Absent for model tools. */
34
+ readonly requirement?: ConnectionRequirement;
35
+ /** Draw a fresh connection from the pool `from` (default `name`) for this scope. */
36
+ readonly fresh?: FreshScope;
37
+ readonly from?: string;
38
+ /** Passed to the pool's provider; `hostOnly` fields are refused (`CONNECTION_NOT_ALLOWED`). */
39
+ readonly setup?: Readonly<Record<string, unknown>>;
40
+ /** The profile the handle names: ref kinds, parent ranges, setup schema and host-only fields. */
41
+ readonly profile?: AnyProfile;
42
+ /** The context resolving it, so gates and framework events reach its run. */
43
+ readonly ctx?: Context;
44
+ }
45
+ /** Options for one gated call. */
46
+ export interface GatedCallOptions {
47
+ readonly signal: AbortSignal;
48
+ readonly caller: ConnectionCaller;
49
+ /** Derived from the run and the step's ledger key, or the turn and tool call id. */
50
+ readonly idempotencyKey: string;
51
+ readonly stepId?: string;
52
+ readonly toolCallId?: string;
53
+ /**
54
+ * For steps and documents: the operations the handle or manifest declares
55
+ * (gate 1). Absent for model tools, which may call anything exposed.
56
+ */
57
+ readonly declaredOps?: ReadonlyArray<string>;
58
+ /**
59
+ * For documents: the secrets the node's arguments write out, each with the
60
+ * dotted field it fills. A document call sending any other secret (one an
61
+ * expression produced) is refused — it was never checked against the allowlist.
62
+ */
63
+ readonly documentSecrets?: ReadonlyArray<{
64
+ readonly name: string;
65
+ readonly field: string;
66
+ }>;
67
+ /** Progress of a long operation, also emitted as `connection_task`. */
68
+ readonly onTask?: (status: ConnectionTaskStatus) => void;
69
+ /**
70
+ * The calling context: gate 5 runs its `beforeToolCall` layers and passes it
71
+ * to the harness approver, and framework events reach its stream.
72
+ */
73
+ readonly ctx?: Context;
74
+ }
75
+ /**
76
+ * A connection as steps and tools see it. Every method runs through the
77
+ * registry: gates 1–6 on `call`, ref sealing/unsealing, secret resolution and
78
+ * redaction, blob storage, and long-operation waiting.
79
+ *
80
+ * `call` throws `NoeticErrorImpl` with kind `steering_denied` (a gate refused),
81
+ * `connection_failed`, `connection_unavailable`, `connection_ref_invalid`,
82
+ * `connection_secret_refused` or `connection_input_required`.
83
+ */
84
+ export interface ResolvedConnection {
85
+ /** The harness connection name. */
86
+ readonly name: string;
87
+ readonly manifest: ConnectionManifest;
88
+ /** The current identity; changes when the thing is replaced. */
89
+ identity(): ConnectionIdentity;
90
+ /** Present when this resolution holds a pool lease. */
91
+ readonly lease?: ConnectionLease;
92
+ /** Runs one operation and returns its output, waiting on long operations. */
93
+ call(op: string, args: unknown, opts: GatedCallOptions): Promise<unknown>;
94
+ read(resource: string, opts: {
95
+ signal: AbortSignal;
96
+ }): Promise<unknown>;
97
+ /** Listens in memory; events arrive stamped with `connection`, buffered up to `WAIT_BUFFER_LIMIT`. */
98
+ listen(req: {
99
+ event: string;
100
+ arguments?: Readonly<Record<string, unknown>>;
101
+ cursor?: string | null;
102
+ signal: AbortSignal;
103
+ }): EventStream<ConnectionEvent>;
104
+ /** Resets the connection (`determinism.reset` not `'none'`). */
105
+ reset?(opts: {
106
+ signal: AbortSignal;
107
+ }): Promise<void>;
108
+ /**
109
+ * Waits on a long operation a previous attempt started (`taskId` from its
110
+ * pending entry) instead of sending it again, with the same output handling
111
+ * as `call` (spec 35 § Durability).
112
+ */
113
+ awaitTask?(taskId: string, op: string, opts: GatedCallOptions): Promise<unknown>;
114
+ }
115
+ /** The harness's connection registry. */
116
+ export interface ConnectionRegistry {
117
+ /** Harness connection names, pools included. */
118
+ names(): ReadonlyArray<string>;
119
+ /**
120
+ * Resolves a connection by name.
121
+ *
122
+ * @throws NoeticConfigError `CONNECTION_UNKNOWN` for an unknown name,
123
+ * `ConnectionUnsatisfiedError` (`CONNECTION_UNSATISFIED`) when `requirement` is not met,
124
+ * `CONNECTION_NOT_ALLOWED` for a host-only setup field;
125
+ * NoeticErrorImpl `connection_unavailable` when it is down or its pool stayed full past `waitMs`.
126
+ */
127
+ resolve(request: ResolveRequest): Promise<ResolvedConnection>;
128
+ /** Returns every lease a scope holds to its pool. */
129
+ releaseScope(scopeKey: string): Promise<void>;
130
+ /**
131
+ * Returns every lease a run holds: its `fresh: 'run'` lease (scope key = the
132
+ * root context id) and each of its `fresh: 'path'` leases (`<rootId>:path:<id>`).
133
+ */
134
+ releaseRun(rootId: string): Promise<void>;
135
+ /** Stops renewing a failed run's leases so they are reclaimed unless a resume takes them back. */
136
+ orphanRun?(rootId: string): void;
137
+ /** `harness.getConnectionStatus(name?)`. */
138
+ status(name?: string): ReadonlyArray<ConnectionStatus>;
139
+ /** Whether `harness.restore(executionId, { rerun })` named connection `name`. */
140
+ rerunAllowed?(executionId: string, name: string): boolean;
141
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The connection registry contract inside core (spec 35 § Connection registry).
3
+ *
4
+ * Steps, tools and documents never hold a provider's `Connection`. They resolve
5
+ * connections by name through the harness registry when they run; the registry
6
+ * wraps each one with the gates, refs, blobs, secrets, identity tracking,
7
+ * reconnection and pool leases, so a step that runs after a reconnect uses the
8
+ * new connection and nothing reaches a server around the harness.
9
+ *
10
+ * This file is the seam between the slices that implement connection steps,
11
+ * verification and the registry itself: they code against these types.
12
+ */
13
+ export {};
14
+ //#endregion
@@ -0,0 +1,125 @@
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 type { AnyProfile, ArtifactStore, Connection, ConnectionChangedEventData, ConnectionConfig, ConnectionEventEventData, ConnectionFrameworkEvent, ConnectionIdentity, ConnectionRequirement, ConnectionsConfig, ConnectionTaskEventData, Context, EventStream, SecretResolver, StorageAdapter, StreamChangedEventData } from '@noetic-tools/types';
16
+ import type { ResumeDecision } from './durability.js';
17
+ import type { GateHooks } from './gates.js';
18
+ import type { ConnectionRegistry, ResolvedConnection, ResolveRequest } from './registry-types.js';
19
+ /** A framework event the registry emits (`<agent>:<type>` on `getFullStream()`). */
20
+ export interface ConnectionFrameworkEventRecord {
21
+ readonly type: ConnectionFrameworkEvent;
22
+ readonly data: ConnectionChangedEventData | ConnectionEventEventData | ConnectionTaskEventData | StreamChangedEventData;
23
+ /** The context it concerns, when there is one. */
24
+ readonly ctx?: Context;
25
+ }
26
+ /** Options for `createConnectionRuntime`. */
27
+ export interface ConnectionRuntimeOptions {
28
+ readonly connections?: ConnectionsConfig;
29
+ readonly storage: StorageAdapter;
30
+ readonly artifacts: ArtifactStore;
31
+ readonly secrets?: SecretResolver;
32
+ readonly hooks?: GateHooks;
33
+ readonly onFrameworkEvent?: (event: ConnectionFrameworkEventRecord) => void;
34
+ /** Profiles known up front (from the graph's handles); handles add theirs when they resolve. */
35
+ readonly profiles?: ReadonlyArray<AnyProfile>;
36
+ readonly now?: () => number;
37
+ /** Delay before reconnect attempt `n` (from 0). Default: 1 s doubling to 30 s. */
38
+ readonly reconnectDelayMs?: (attempt: number) => number;
39
+ }
40
+ /** A resolve request with the extras the registry understands (now part of `ResolveRequest`). */
41
+ export type RuntimeResolveRequest = ResolveRequest;
42
+ /** The registry the harness holds: the `ConnectionRegistry` contract plus lifecycle. */
43
+ /** How a graph uses a connection, as far as negotiation cares. */
44
+ export interface NeedOptions {
45
+ /**
46
+ * The handle passes a setup. A pool's provider may answer each setup with a
47
+ * different manifest, so a pool checks such a need on the lease instead.
48
+ */
49
+ readonly setup?: boolean;
50
+ }
51
+ export interface ConnectionRuntime extends ConnectionRegistry {
52
+ resolve(request: RuntimeResolveRequest): Promise<ResolvedConnection>;
53
+ /** Connects every provider and starts every pool. Idempotent. */
54
+ start(): Promise<void>;
55
+ /**
56
+ * Stops renewing every lease a failed run holds, so it is reclaimed after the
57
+ * reclaim window unless a resume takes it back first.
58
+ */
59
+ orphanRun(rootId: string): void;
60
+ /** Whether `harness.restore(executionId, { rerun })` named connection `name` for this run. */
61
+ rerunAllowed(executionId: string, name: string): boolean;
62
+ /** Releases every connection and lease. */
63
+ close(): Promise<void>;
64
+ /** The harness configuration of a connection. */
65
+ config(name: string): ConnectionConfig | undefined;
66
+ /** The live provider connection behind a non-pool name, when it is ready. */
67
+ current(name: string): Connection | undefined;
68
+ /** Bumped every time an operation with effects runs on the connection. */
69
+ effectCount(name: string): number;
70
+ /** Records what the harness graph requires of a connection; renegotiated on manifest changes. */
71
+ require(name: string, requirement: ConnectionRequirement, options?: NeedOptions): void;
72
+ /**
73
+ * Checks a requirement against the connection's current manifest without
74
+ * recording it: how a `run()` root that is not the harness's `agentGraph` is
75
+ * negotiated before it executes. A pool is checked against the manifest its
76
+ * connections offer. Returns false when there is no manifest to check yet (the
77
+ * connection is down, or the pool has provisioned nothing), leaving the
78
+ * requirement to fail when the connection is used.
79
+ *
80
+ * A need that passes a pool a setup has nothing to check before the lease, so
81
+ * it returns true and the lease checks it.
82
+ *
83
+ * @throws `NoeticConfigError` `CONNECTION_UNSATISFIED` when the manifest falls short.
84
+ */
85
+ check(name: string, requirement: ConnectionRequirement, options?: NeedOptions): boolean;
86
+ /** Registers a profile's ref kinds. */
87
+ registerProfile(profile: AnyProfile): void;
88
+ /** Lets `harness.restore(id, { rerun })` drive replaced connections again. */
89
+ allowRerun(executionId: string, names: ReadonlyArray<string>): void;
90
+ /**
91
+ * Decides what a resumed run does about a connection recorded against `recorded`,
92
+ * resetting it when that is the decision.
93
+ *
94
+ * @throws NoeticErrorImpl `connection_resume_refused` when it cannot safely be driven again.
95
+ */
96
+ checkResume(params: {
97
+ readonly executionId: string;
98
+ readonly name: string;
99
+ readonly recorded: ConnectionIdentity;
100
+ readonly signal: AbortSignal;
101
+ }): Promise<ResumeDecision>;
102
+ /** Unsealed, un-buffered events for a trigger; the caller seals them per thread. */
103
+ listenRaw(name: string, request: {
104
+ readonly event: string;
105
+ readonly arguments?: Readonly<Record<string, unknown>>;
106
+ readonly cursor?: string | null;
107
+ readonly signal: AbortSignal;
108
+ }): Promise<EventStream>;
109
+ /** Scrubs secrets from, seals refs in, and links blobs in a value for a thread. */
110
+ admit(name: string, value: unknown, scope: {
111
+ readonly threadId: string;
112
+ readonly executionId: string;
113
+ }): Promise<unknown>;
114
+ /** Emits a framework event (used by triggers and steps). */
115
+ emit(event: ConnectionFrameworkEventRecord): void;
116
+ /** `value` with every sensitive blob withheld, for anything the model will see. */
117
+ withholdSensitive(value: unknown): Promise<unknown>;
118
+ }
119
+ /**
120
+ * Creates a harness connection registry. Construction validates the
121
+ * configuration synchronously; providers connect in `start()`.
122
+ *
123
+ * @throws NoeticConfigError `CONNECTION_INVALID` for a malformed entry.
124
+ */
125
+ export declare function createConnectionRuntime(options: ConnectionRuntimeOptions): ConnectionRuntime;