@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,34 @@
1
+ /**
2
+ * A connection's `policy` (spec 35 § Gates, gate 4): `allow`, `deny` and
3
+ * `approve` globs over operation names. `deny` wins; a non-empty `allow` list
4
+ * refuses everything it does not match; `approve` matches need approval.
5
+ * Operations a profile marks `guarded` need approval unless `allow` names
6
+ * them explicitly.
7
+ */
8
+ import { matchesAnyGlob } from './glob.js';
9
+ //#endregion
10
+ //#region Public API
11
+ /** Applies `policy` to operation `op` (`guarded` from the operation's info). */
12
+ export function evaluatePolicy(policy, op, guarded) {
13
+ if (matchesAnyGlob(policy?.deny, op)) {
14
+ return {
15
+ kind: 'deny',
16
+ reason: `operation '${op}' is denied by the connection policy`,
17
+ };
18
+ }
19
+ const allowList = policy?.allow;
20
+ const explicitlyAllowed = matchesAnyGlob(allowList, op);
21
+ if (allowList && allowList.length > 0 && !explicitlyAllowed) {
22
+ return {
23
+ kind: 'deny',
24
+ reason: `operation '${op}' is not in the connection policy's allow list`,
25
+ };
26
+ }
27
+ const approve = matchesAnyGlob(policy?.approve, op);
28
+ return {
29
+ kind: 'allow',
30
+ needsApproval: approve || (guarded && !explicitlyAllowed),
31
+ explicitlyAllowed,
32
+ };
33
+ }
34
+ //#endregion
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Pools and leases (spec 35 § Pools and leases, § Fresh connections). A
3
+ * pool's provider implements `provision`. A lease is held by one run or one
4
+ * parallel path and is never shared with another. The holding harness renews
5
+ * it every 15 s; one not renewed for 2 min is reclaimed, so a crashed process
6
+ * frees its connections, and a process that resumes within that time keeps
7
+ * the same lease (lease records live in the harness `StorageAdapter`).
8
+ *
9
+ * A pool that is full queues the request until a connection is free or
10
+ * `waitMs` passes. Connections are fresh: a released one is released to its
11
+ * provider, never handed to another holder. `warm` connections are
12
+ * provisioned ahead with an empty setup and serve requests that pass none.
13
+ */
14
+ import type { Connection, ConnectionLease, ConnectionManifest, ConnectionPoolConfig, ConnectionProvider, ConnectOptions, FreshScope, StorageAdapter } from '@noetic-tools/types';
15
+ /** A lease change, as reported in `connection_changed`. */
16
+ export type LeaseChange = 'acquired' | 'renewed' | 'released' | 'reclaimed';
17
+ /** What a pool needs from the registry. */
18
+ export interface PoolDeps {
19
+ readonly name: string;
20
+ readonly provider: ConnectionProvider;
21
+ readonly config: ConnectionPoolConfig;
22
+ readonly storage: StorageAdapter;
23
+ readonly connectOptions: (signal: AbortSignal) => ConnectOptions;
24
+ readonly onLease?: (lease: ConnectionLease, change: LeaseChange) => void;
25
+ readonly now?: () => number;
26
+ /** Test hooks; default `LEASE_RENEW_MS` and `LEASE_RECLAIM_MS`. */
27
+ readonly renewMs?: number;
28
+ readonly reclaimMs?: number;
29
+ }
30
+ /** A connection held under a lease. */
31
+ export interface HeldConnection {
32
+ readonly lease: ConnectionLease;
33
+ readonly connection: Connection;
34
+ }
35
+ /** One request for a fresh connection. */
36
+ export interface AcquireRequest {
37
+ /** The holder: the run id for `'run'`, the parallel path key for `'path'`. */
38
+ readonly scopeKey: string;
39
+ readonly scope: FreshScope;
40
+ readonly setup: Readonly<Record<string, unknown>>;
41
+ readonly signal: AbortSignal;
42
+ }
43
+ /** How long a request queues on a full pool when `waitMs` is unset. */
44
+ export declare const DEFAULT_POOL_WAIT_MS = 60000;
45
+ /** One pool of fresh connections. */
46
+ export declare class ConnectionPool {
47
+ private readonly deps;
48
+ private readonly held;
49
+ /** Holders that stopped renewing (a failed run): reclaimed once their lease expires. */
50
+ private readonly orphaned;
51
+ private readonly acquiring;
52
+ private readonly idle;
53
+ private provisioning;
54
+ /** Connections handed to an acquisition but not yet recorded as held. */
55
+ private unrecorded;
56
+ private readonly waiters;
57
+ private timer;
58
+ private closed;
59
+ /** The manifest of the last connection provisioned with no setup, kept after it is released. */
60
+ private baseManifest;
61
+ private readonly now;
62
+ private readonly renewMs;
63
+ private readonly reclaimMs;
64
+ private readonly controller;
65
+ constructor(deps: PoolDeps);
66
+ /** Starts lease renewal and provisions `warm` connections. */
67
+ start(): Promise<void>;
68
+ /**
69
+ * Leases a fresh connection to `request.scopeKey`, or returns the one it already holds.
70
+ *
71
+ * @throws NoeticErrorImpl `connection_unavailable` when the pool stays full past `waitMs`.
72
+ */
73
+ acquire(request: AcquireRequest): Promise<HeldConnection>;
74
+ /** Returns the lease `scopeKey` holds, releasing its connection. */
75
+ release(scopeKey: string, change?: LeaseChange): Promise<void>;
76
+ /**
77
+ * Stops renewing the lease `scopeKey` holds without releasing it: a failed
78
+ * run keeps its connection for a resume within the reclaim window, after
79
+ * which `sweep` reclaims it (spec 35 § Pools and leases).
80
+ */
81
+ orphan(scopeKey: string): void;
82
+ /** Reclaims every lease whose holder stopped renewing it. */
83
+ sweep(): Promise<void>;
84
+ /** The lease `scopeKey` holds, if any. */
85
+ heldBy(scopeKey: string): HeldConnection | undefined;
86
+ /** Every scope holding a lease. */
87
+ holders(): ReadonlyArray<string>;
88
+ /**
89
+ * The manifest a connection provisioned with no setup offers: undefined until
90
+ * the pool has provisioned one. A provider may answer a setup with a
91
+ * different manifest, so only this one stands for the pool when a need that
92
+ * passes no setup is negotiated (spec 35 § Negotiation).
93
+ */
94
+ manifest(): ConnectionManifest | undefined;
95
+ status(): {
96
+ max: number;
97
+ leased: number;
98
+ idle: number;
99
+ };
100
+ /** Releases every connection and stops renewing. */
101
+ close(): Promise<void>;
102
+ private acquireNew;
103
+ private connectionFor;
104
+ private inUse;
105
+ private provision;
106
+ private waitForSpace;
107
+ private wake;
108
+ private leaseKey;
109
+ private leaseFor;
110
+ private renewAll;
111
+ }
@@ -0,0 +1,339 @@
1
+ /**
2
+ * Pools and leases (spec 35 § Pools and leases, § Fresh connections). A
3
+ * pool's provider implements `provision`. A lease is held by one run or one
4
+ * parallel path and is never shared with another. The holding harness renews
5
+ * it every 15 s; one not renewed for 2 min is reclaimed, so a crashed process
6
+ * frees its connections, and a process that resumes within that time keeps
7
+ * the same lease (lease records live in the harness `StorageAdapter`).
8
+ *
9
+ * A pool that is full queues the request until a connection is free or
10
+ * `waitMs` passes. Connections are fresh: a released one is released to its
11
+ * provider, never handed to another holder. `warm` connections are
12
+ * provisioned ahead with an empty setup and serve requests that pass none.
13
+ */
14
+ import { LEASE_RECLAIM_MS, LEASE_RENEW_MS } from '@noetic-tools/types';
15
+ import { z } from 'zod';
16
+ import { invalidConnectionError, unavailableError } from './errors.js';
17
+ import { runEvery } from './settle.js';
18
+ //#endregion
19
+ //#region Constants
20
+ /** How long a request queues on a full pool when `waitMs` is unset. */
21
+ export const DEFAULT_POOL_WAIT_MS = 6e4;
22
+ const StoredLeaseSchema = z.object({
23
+ id: z.string(),
24
+ expiresAt: z.number(),
25
+ });
26
+ //#endregion
27
+ //#region Helpers
28
+ function unrefTimer(timer) {
29
+ if (typeof timer === 'object' && timer !== null && 'unref' in timer) {
30
+ timer.unref();
31
+ }
32
+ }
33
+ //#endregion
34
+ //#region ConnectionPool
35
+ /** One pool of fresh connections. */
36
+ export class ConnectionPool {
37
+ deps;
38
+ held = new Map();
39
+ /** Holders that stopped renewing (a failed run): reclaimed once their lease expires. */
40
+ orphaned = new Set();
41
+ acquiring = new Map();
42
+ idle = [];
43
+ provisioning = 0;
44
+ /** Connections handed to an acquisition but not yet recorded as held. */
45
+ unrecorded = 0;
46
+ waiters = new Set();
47
+ timer;
48
+ closed = false;
49
+ /** The manifest of the last connection provisioned with no setup, kept after it is released. */
50
+ baseManifest;
51
+ now;
52
+ renewMs;
53
+ reclaimMs;
54
+ controller = new AbortController();
55
+ constructor(deps) {
56
+ this.deps = deps;
57
+ const max = deps.config.max;
58
+ if (!Number.isInteger(max) || max < 1) {
59
+ throw invalidConnectionError(`Pool '${deps.name}' has max ${String(max)}.`, 'Set pool.max to a whole number of at least 1.');
60
+ }
61
+ if (!deps.provider.provision) {
62
+ throw invalidConnectionError(`Connection '${deps.name}' is a pool but its provider cannot provision connections.`, 'Use a provider that implements provision(), or drop the pool setting.');
63
+ }
64
+ this.now = deps.now ?? Date.now;
65
+ this.renewMs = deps.renewMs ?? LEASE_RENEW_MS;
66
+ this.reclaimMs = deps.reclaimMs ?? LEASE_RECLAIM_MS;
67
+ }
68
+ /** Starts lease renewal and provisions `warm` connections. */
69
+ async start() {
70
+ if (!this.timer) {
71
+ this.timer = setInterval(() => {
72
+ void this.renewAll().then(() => this.sweep());
73
+ }, this.renewMs);
74
+ unrefTimer(this.timer);
75
+ }
76
+ const warm = Math.min(this.deps.config.warm ?? 0, this.deps.config.max);
77
+ while (this.idle.length + this.provisioning < warm) {
78
+ this.idle.push(await this.provision({}));
79
+ }
80
+ }
81
+ /**
82
+ * Leases a fresh connection to `request.scopeKey`, or returns the one it already holds.
83
+ *
84
+ * @throws NoeticErrorImpl `connection_unavailable` when the pool stays full past `waitMs`.
85
+ */
86
+ acquire(request) {
87
+ const existing = this.held.get(request.scopeKey);
88
+ if (existing) {
89
+ // A resume within the reclaim window takes its lease back and renews it again.
90
+ this.orphaned.delete(request.scopeKey);
91
+ return Promise.resolve(existing);
92
+ }
93
+ const inFlight = this.acquiring.get(request.scopeKey);
94
+ if (inFlight) {
95
+ return inFlight;
96
+ }
97
+ const acquiring = this.acquireNew(request).finally(() => {
98
+ this.acquiring.delete(request.scopeKey);
99
+ });
100
+ this.acquiring.set(request.scopeKey, acquiring);
101
+ return acquiring;
102
+ }
103
+ /** Returns the lease `scopeKey` holds, releasing its connection. */
104
+ async release(scopeKey, change = 'released') {
105
+ const held = this.held.get(scopeKey);
106
+ if (!held) {
107
+ return;
108
+ }
109
+ this.held.delete(scopeKey);
110
+ this.orphaned.delete(scopeKey);
111
+ await this.deps.storage.delete(this.leaseKey(scopeKey));
112
+ this.deps.onLease?.(held.lease, change);
113
+ this.wake();
114
+ await held.connection.release().catch(() => undefined);
115
+ }
116
+ /**
117
+ * Stops renewing the lease `scopeKey` holds without releasing it: a failed
118
+ * run keeps its connection for a resume within the reclaim window, after
119
+ * which `sweep` reclaims it (spec 35 § Pools and leases).
120
+ */
121
+ orphan(scopeKey) {
122
+ if (this.held.has(scopeKey)) {
123
+ this.orphaned.add(scopeKey);
124
+ }
125
+ }
126
+ /** Reclaims every lease whose holder stopped renewing it. */
127
+ async sweep() {
128
+ const now = this.now();
129
+ for (const [scopeKey, held] of [
130
+ ...this.held,
131
+ ]) {
132
+ if (held.lease.expiresAt < now) {
133
+ await this.release(scopeKey, 'reclaimed');
134
+ }
135
+ }
136
+ }
137
+ /** The lease `scopeKey` holds, if any. */
138
+ heldBy(scopeKey) {
139
+ return this.held.get(scopeKey);
140
+ }
141
+ /** Every scope holding a lease. */
142
+ holders() {
143
+ return [
144
+ ...this.held.keys(),
145
+ ];
146
+ }
147
+ /**
148
+ * The manifest a connection provisioned with no setup offers: undefined until
149
+ * the pool has provisioned one. A provider may answer a setup with a
150
+ * different manifest, so only this one stands for the pool when a need that
151
+ * passes no setup is negotiated (spec 35 § Negotiation).
152
+ */
153
+ manifest() {
154
+ return this.baseManifest;
155
+ }
156
+ status() {
157
+ return {
158
+ max: this.deps.config.max,
159
+ leased: this.held.size,
160
+ idle: this.idle.length,
161
+ };
162
+ }
163
+ /** Releases every connection and stops renewing. */
164
+ async close() {
165
+ this.closed = true;
166
+ this.controller.abort();
167
+ if (this.timer) {
168
+ clearInterval(this.timer);
169
+ this.timer = undefined;
170
+ }
171
+ try {
172
+ await runEvery([
173
+ ...[
174
+ ...this.held.keys(),
175
+ ].map((scopeKey) => () => this.release(scopeKey)),
176
+ ...this.idle
177
+ .splice(0)
178
+ .map((connection) => () => connection.release().catch(() => undefined)),
179
+ ]);
180
+ }
181
+ finally {
182
+ this.wake();
183
+ }
184
+ }
185
+ async acquireNew(request) {
186
+ const connection = await this.connectionFor(request);
187
+ let lease;
188
+ try {
189
+ lease = await this.leaseFor(request);
190
+ }
191
+ catch (e) {
192
+ this.unrecorded -= 1;
193
+ await connection.release().catch(() => undefined);
194
+ this.wake();
195
+ throw e;
196
+ }
197
+ const held = {
198
+ lease,
199
+ connection,
200
+ };
201
+ this.unrecorded -= 1;
202
+ this.held.set(request.scopeKey, held);
203
+ this.deps.onLease?.(lease, 'acquired');
204
+ return held;
205
+ }
206
+ async connectionFor(request) {
207
+ const wantsWarm = Object.keys(request.setup).length === 0;
208
+ const deadline = this.now() + (this.deps.config.waitMs ?? DEFAULT_POOL_WAIT_MS);
209
+ for (;;) {
210
+ if (this.closed) {
211
+ throw unavailableError(this.deps.name, 'the pool is closed');
212
+ }
213
+ if (wantsWarm && this.idle.length > 0) {
214
+ const warm = this.idle.shift();
215
+ if (warm) {
216
+ this.unrecorded += 1;
217
+ return warm;
218
+ }
219
+ }
220
+ if (this.inUse() < this.deps.config.max) {
221
+ const fresh = await this.provision(request.setup);
222
+ this.unrecorded += 1;
223
+ return fresh;
224
+ }
225
+ const spare = this.idle.shift();
226
+ if (spare) {
227
+ await spare.release().catch(() => undefined);
228
+ continue;
229
+ }
230
+ const remaining = deadline - this.now();
231
+ if (remaining <= 0) {
232
+ throw unavailableError(this.deps.name, 'the pool stayed full past waitMs');
233
+ }
234
+ await this.waitForSpace(remaining, request.signal);
235
+ }
236
+ }
237
+ inUse() {
238
+ return this.held.size + this.unrecorded + this.idle.length + this.provisioning;
239
+ }
240
+ async provision(setup) {
241
+ const provision = this.deps.provider.provision;
242
+ if (!provision) {
243
+ throw unavailableError(this.deps.name, 'the provider cannot provision connections');
244
+ }
245
+ this.provisioning += 1;
246
+ try {
247
+ const connection = await provision.call(this.deps.provider, {
248
+ ...setup,
249
+ }, this.deps.connectOptions(this.controller.signal));
250
+ if (Object.keys(setup).length === 0) {
251
+ this.baseManifest = connection.manifest;
252
+ }
253
+ return connection;
254
+ }
255
+ catch (e) {
256
+ this.wake();
257
+ const reason = e instanceof Error ? e.message : String(e);
258
+ throw unavailableError(this.deps.name, `provisioning failed: ${reason}`);
259
+ }
260
+ finally {
261
+ this.provisioning -= 1;
262
+ }
263
+ }
264
+ waitForSpace(ms, signal) {
265
+ return new Promise((resolve, reject) => {
266
+ const done = () => {
267
+ clearTimeout(timeout);
268
+ signal.removeEventListener('abort', onAbort);
269
+ this.waiters.delete(done);
270
+ resolve();
271
+ };
272
+ const onAbort = () => {
273
+ clearTimeout(timeout);
274
+ this.waiters.delete(done);
275
+ reject(unavailableError(this.deps.name, 'the request was cancelled while the pool was full'));
276
+ };
277
+ const timeout = setTimeout(done, ms);
278
+ if (signal.aborted) {
279
+ onAbort();
280
+ return;
281
+ }
282
+ signal.addEventListener('abort', onAbort, {
283
+ once: true,
284
+ });
285
+ this.waiters.add(done);
286
+ });
287
+ }
288
+ wake() {
289
+ for (const waiter of [
290
+ ...this.waiters,
291
+ ]) {
292
+ waiter();
293
+ }
294
+ }
295
+ leaseKey(scopeKey) {
296
+ return `noetic/connections/leases/${this.deps.name}/${scopeKey}`;
297
+ }
298
+ async leaseFor(request) {
299
+ const now = this.now();
300
+ const stored = StoredLeaseSchema.safeParse(await this.deps.storage.get(this.leaseKey(request.scopeKey)));
301
+ const id = stored.success && stored.data.expiresAt > now ? stored.data.id : crypto.randomUUID();
302
+ const lease = {
303
+ id,
304
+ pool: this.deps.name,
305
+ scope: request.scope,
306
+ holder: request.scopeKey,
307
+ expiresAt: now + this.reclaimMs,
308
+ };
309
+ await this.deps.storage.set(this.leaseKey(request.scopeKey), {
310
+ id,
311
+ expiresAt: lease.expiresAt,
312
+ });
313
+ return lease;
314
+ }
315
+ async renewAll() {
316
+ const now = this.now();
317
+ for (const [scopeKey, held] of [
318
+ ...this.held,
319
+ ]) {
320
+ if (this.orphaned.has(scopeKey)) {
321
+ continue;
322
+ }
323
+ const lease = {
324
+ ...held.lease,
325
+ expiresAt: now + this.reclaimMs,
326
+ };
327
+ this.held.set(scopeKey, {
328
+ lease,
329
+ connection: held.connection,
330
+ });
331
+ await this.deps.storage.set(this.leaseKey(scopeKey), {
332
+ id: lease.id,
333
+ expiresAt: lease.expiresAt,
334
+ });
335
+ this.deps.onLease?.(lease, 'renewed');
336
+ }
337
+ }
338
+ }
339
+ //#endregion
@@ -0,0 +1,74 @@
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 type { AnyProfile, Ref, RefBody, StorageAdapter } from '@noetic-tools/types';
20
+ /** What a profile says about refs of one kind. */
21
+ export interface RefKindInfo {
22
+ readonly volatile: boolean;
23
+ readonly public: boolean;
24
+ }
25
+ /** Where a ref is sealed or checked. */
26
+ export interface RefScope {
27
+ /** The harness connection name. */
28
+ readonly connection: string;
29
+ readonly threadId: string;
30
+ /** The connection's current identity instance. */
31
+ readonly instance: string;
32
+ /**
33
+ * The pool lease the connection is held under. A leased connection is never
34
+ * shared with another holder, so its refs — of every kind — are bound to the
35
+ * lease: a ref from one path's browser is refused by another path's.
36
+ */
37
+ readonly lease?: string;
38
+ readonly kindInfo: (kind: string) => RefKindInfo;
39
+ }
40
+ /** Seals and checks refs with keys kept in storage. */
41
+ export declare class RefSealer {
42
+ private readonly storage;
43
+ private readonly now;
44
+ private keysPromise;
45
+ private readonly cryptoKeys;
46
+ constructor(storage: StorageAdapter, now?: () => number);
47
+ /** Seals a provider-issued ref for `scope`. */
48
+ seal(body: {
49
+ readonly kind: string;
50
+ readonly id: string;
51
+ }, scope: RefScope): Promise<Ref>;
52
+ /**
53
+ * Checks a ref going out to `scope.connection`.
54
+ *
55
+ * @throws NoeticErrorImpl `connection_ref_invalid` when the ref belongs to another
56
+ * connection, was not issued here (or to this thread), or is stale.
57
+ */
58
+ check(ref: RefBody, scope: RefScope): Promise<void>;
59
+ /** A copy of `value` with every provider-issued ref sealed for `scope`. */
60
+ sealAll(value: unknown, scope: RefScope): Promise<unknown>;
61
+ /** Checks every ref in `value` (see `check`). */
62
+ checkAll(value: unknown, scope: RefScope): Promise<void>;
63
+ private keys;
64
+ private loadKeys;
65
+ private rotate;
66
+ private cryptoKey;
67
+ private mac;
68
+ }
69
+ /** Every ref kind a profile's operations, reads and events hand out, with its flags. */
70
+ export declare function refKindsOf(profile: AnyProfile): Map<string, RefKindInfo>;
71
+ /** Looks a ref kind up in `kinds`; unknown kinds are stable and private. */
72
+ export declare function kindInfoFrom(kinds: ReadonlyMap<string, RefKindInfo>): (kind: string) => RefKindInfo;
73
+ /** The connections the refs in `value` were issued by. */
74
+ export declare function refConnections(value: unknown): ReadonlySet<string>;