@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,537 @@
1
+ /**
2
+ * What `call` and `wait` steps share (spec 35 § Steps, § Durability; spec 23a
3
+ * § Connection Steps): finding the harness registry, resolving the step's
4
+ * connection through it, deriving idempotency keys, and the pending ledger
5
+ * entries a resumed run picks up from.
6
+ *
7
+ * Steps never hold a provider's `Connection`: everything goes through the
8
+ * registry contract in `connections/registry-types.ts`.
9
+ */
10
+ import { frameworkCast, NoeticConfigError, NoeticErrorImpl } from '@noetic-tools/types';
11
+ import { z } from 'zod';
12
+ import { resumeDecision } from '../connections/durability.js';
13
+ import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
14
+ import { ContextImpl } from '../runtime/context-impl.js';
15
+ import { harnessInternal } from '../util/harness-internals.js';
16
+ import { someStep } from './step-walk.js';
17
+ //#endregion
18
+ //#region Constants
19
+ const PendingEntrySchema = z.object({
20
+ stepId: z.string(),
21
+ kind: z.enum([
22
+ 'call',
23
+ 'wait',
24
+ ]),
25
+ connection: z.string(),
26
+ key: z.string(),
27
+ identity: z.object({
28
+ surface: z.string(),
29
+ instance: z.string(),
30
+ epoch: z.number().optional(),
31
+ }),
32
+ taskId: z.string().optional(),
33
+ leaseId: z.string().optional(),
34
+ cursor: z.string().nullish(),
35
+ deadline: z.number().optional(),
36
+ });
37
+ function harnessOf(ctx) {
38
+ return {
39
+ connectionRegistry: harnessInternal(ctx.harness, 'connectionRegistry'),
40
+ config: frameworkCast(ctx.harness).config,
41
+ };
42
+ }
43
+ /**
44
+ * The harness's connection registry.
45
+ *
46
+ * @throws `NoeticConfigError` `CONNECTION_UNKNOWN` when the harness has no connections.
47
+ */
48
+ export function connectionRegistryOf(ctx, name) {
49
+ const registry = harnessOf(ctx).connectionRegistry;
50
+ if (registry) {
51
+ return registry;
52
+ }
53
+ throw new NoeticConfigError({
54
+ code: 'CONNECTION_UNKNOWN',
55
+ message: `Connection '${name}' is used, but the harness has no connections.`,
56
+ hint: `Add it to the harness: new AgentHarness({ connections: { ${name}: mcp('…') } }).`,
57
+ });
58
+ }
59
+ /** The topmost ancestor of `ctx`: the run's root context, whose id names the run. */
60
+ export function runRootOf(ctx) {
61
+ let current = ctx;
62
+ while (current.parent) {
63
+ current = current.parent;
64
+ }
65
+ return current;
66
+ }
67
+ /** The abort signal of `ctx`, or one that never fires for a context without one (test stubs). */
68
+ export function signalOf(ctx) {
69
+ const signal = frameworkCast(ctx).abortSignal;
70
+ return signal ?? new AbortController().signal;
71
+ }
72
+ /**
73
+ * The lease scope of a resolution. `fresh: 'run'` scopes to the run; `fresh:
74
+ * 'path'` to the parallel path the step runs on (the nearest context that is not
75
+ * the run root — each `inParallel` path runs in its own child context).
76
+ */
77
+ export function scopeFor(ctx, fresh) {
78
+ const root = runRootOf(ctx);
79
+ return {
80
+ executionId: root.id,
81
+ threadId: ctx.threadId,
82
+ scopeKey: fresh === 'path' ? pathScopeKey(ctx) : root.id,
83
+ signal: signalOf(ctx),
84
+ };
85
+ }
86
+ /** The lease scope key of a `fresh: 'path'` connection drawn on `ctx`. */
87
+ export function pathScopeKey(ctx) {
88
+ return `${runRootOf(ctx).id}:path:${ctx.id}`;
89
+ }
90
+ /**
91
+ * Returns every `fresh: 'path'` lease the given parallel path contexts hold
92
+ * (spec 35 § Fresh connections: "gives it back when the scope ends"). A no-op
93
+ * when the harness has no connections.
94
+ */
95
+ export async function releasePathLeases(paths) {
96
+ for (const path of paths) {
97
+ const registry = harnessOf(path).connectionRegistry;
98
+ if (!registry) {
99
+ return;
100
+ }
101
+ await registry.releaseScope(pathScopeKey(path)).catch(() => undefined);
102
+ }
103
+ }
104
+ /** The ledger path of the step running on `ctx`, when it runs on a lane. */
105
+ export function stepPathOf(ctx) {
106
+ const path = ctx instanceof ContextImpl ? ctx.currentPath() : '';
107
+ return path.length > 0 ? path : undefined;
108
+ }
109
+ /** The run-and-step key a call carries, stable across a resume of the same run (spec 35 § Durability). */
110
+ export function idempotencyKeyFor(ctx, stepId, ledgerKey) {
111
+ return `${runRootOf(ctx).id}:${ledgerKey ?? stepPathOf(ctx) ?? stepId}`;
112
+ }
113
+ //#endregion
114
+ //#region Target and requirement
115
+ function isHandle(value) {
116
+ return (typeof value === 'object' &&
117
+ value !== null &&
118
+ 'kind' in value &&
119
+ value.kind === 'connection-handle');
120
+ }
121
+ /**
122
+ * Evaluates a step's connection target.
123
+ *
124
+ * @throws `NoeticConfigError` `CONNECTION_INVALID` when it gives neither a handle nor a non-empty name.
125
+ */
126
+ export async function evaluateTarget(target, input, ctx, stepId) {
127
+ const value = typeof target === 'function' ? await target(input, ctx) : target;
128
+ if (isHandle(value)) {
129
+ return {
130
+ name: value.name,
131
+ handle: value,
132
+ };
133
+ }
134
+ if (typeof value === 'string' && value.length > 0) {
135
+ return {
136
+ name: value,
137
+ };
138
+ }
139
+ throw new NoeticConfigError({
140
+ code: 'CONNECTION_INVALID',
141
+ message: `Step '${stepId}' did not name a connection.`,
142
+ hint: "Pass a handle from connection('name', profile) or a harness connection name.",
143
+ });
144
+ }
145
+ function extensionsOf(handle) {
146
+ const entries = handle.options.extensions ?? [];
147
+ if (entries.length === 0) {
148
+ return undefined;
149
+ }
150
+ const out = {};
151
+ for (const entry of entries) {
152
+ if (entry.kind === 'extension-range') {
153
+ out[entry.extension.id] = entry.range;
154
+ continue;
155
+ }
156
+ out[entry.id] = entry.defaultRange;
157
+ }
158
+ return out;
159
+ }
160
+ /** What a handle (or a bare name) requires for one use: its profile and extensions, plus the op or event. */
161
+ export function requirementFor(target, use) {
162
+ const handle = target.handle;
163
+ // A JSON document's handle carries its manifest entry's requirement (see `documentHandle`).
164
+ const documentRequirement = handle
165
+ ? frameworkCast(handle)._requirement
166
+ : undefined;
167
+ if (documentRequirement) {
168
+ return documentRequirement;
169
+ }
170
+ const profile = handle?.profile;
171
+ const extensions = handle ? extensionsOf(handle) : undefined;
172
+ return {
173
+ ...(profile
174
+ ? {
175
+ profile: {
176
+ name: profile.name,
177
+ range: handle?.range ?? profile.defaultRange,
178
+ },
179
+ }
180
+ : {}),
181
+ ...(extensions
182
+ ? {
183
+ extensions,
184
+ }
185
+ : {}),
186
+ ...(use.op
187
+ ? {
188
+ operations: [
189
+ use.op,
190
+ ],
191
+ }
192
+ : {}),
193
+ ...(use.event
194
+ ? {
195
+ events: [
196
+ use.event,
197
+ ],
198
+ }
199
+ : {}),
200
+ };
201
+ }
202
+ /**
203
+ * Every connection need a graph states up front: each `call` and `wait` whose
204
+ * connection is a static handle, with its profile and requirement. The harness
205
+ * registers these profiles (ref kinds) and requirements (start-time
206
+ * negotiation, renegotiated on a manifest change) when it is built.
207
+ */
208
+ export function graphConnectionNeeds(graph) {
209
+ const needs = [];
210
+ someStep(graph, (step) => {
211
+ if (step.kind !== 'call' && step.kind !== 'wait') {
212
+ return false;
213
+ }
214
+ const target = step.connection;
215
+ if (!isHandle(target)) {
216
+ return false;
217
+ }
218
+ const use = step.kind === 'call'
219
+ ? {
220
+ op: step.op,
221
+ }
222
+ : {
223
+ event: step.event,
224
+ };
225
+ needs.push({
226
+ name: target.options.from ?? target.name,
227
+ ...(target.profile
228
+ ? {
229
+ profile: target.profile,
230
+ }
231
+ : {}),
232
+ requirement: requirementFor({
233
+ name: target.name,
234
+ handle: target,
235
+ }, use),
236
+ setup: Object.keys(target.options.setup ?? {}).length > 0,
237
+ });
238
+ return false;
239
+ });
240
+ return needs;
241
+ }
242
+ //#endregion
243
+ //#region Resolution
244
+ /**
245
+ * Resolves the step's connection through the registry and prepares what a
246
+ * gated call or listen needs. Throws whatever `registry.resolve` throws.
247
+ */
248
+ export async function resolveStepConnection(opts) {
249
+ const { ctx, stepId, target, use, ledgerKey } = opts;
250
+ const registry = connectionRegistryOf(ctx, target.name);
251
+ const options = target.handle?.options;
252
+ const scope = scopeFor(ctx, options?.fresh);
253
+ const resolved = await registry.resolve({
254
+ name: target.name,
255
+ scope,
256
+ ctx,
257
+ requirement: requirementFor(target, use),
258
+ ...(target.handle?.profile
259
+ ? {
260
+ profile: target.handle.profile,
261
+ }
262
+ : {}),
263
+ ...(options?.fresh
264
+ ? {
265
+ fresh: options.fresh,
266
+ }
267
+ : {}),
268
+ ...(options?.from
269
+ ? {
270
+ from: options.from,
271
+ }
272
+ : {}),
273
+ ...(options?.setup
274
+ ? {
275
+ setup: options.setup,
276
+ }
277
+ : {}),
278
+ });
279
+ noteConnectionUse(ctx, ledgerKey, resolved);
280
+ return {
281
+ resolved,
282
+ scope,
283
+ idempotencyKey: idempotencyKeyFor(ctx, stepId, ledgerKey),
284
+ pending: pendingEntriesFor(ctx, ledgerKey),
285
+ };
286
+ }
287
+ //#endregion
288
+ //#region Witness guard
289
+ /**
290
+ * Witness names each verify's `act` is running against, by the id of the
291
+ * context it runs on (a step's lane is a view sharing its context's id).
292
+ */
293
+ const WITNESS_GUARDS = new Map();
294
+ /**
295
+ * Runs `fn` (a verify's `act`) with `witnesses` guarded: any `call` on one of
296
+ * them that has effects — however its connection was named, by a function or
297
+ * an expression too — is refused with `VERIFY_INVALID` (spec 37 § Witnesses).
298
+ */
299
+ export async function withWitnessGuard(ctx, witnesses, fn) {
300
+ if (witnesses.length === 0) {
301
+ return fn();
302
+ }
303
+ const guard = new Set(witnesses);
304
+ const guards = WITNESS_GUARDS.get(ctx.id) ?? [];
305
+ guards.push(guard);
306
+ WITNESS_GUARDS.set(ctx.id, guards);
307
+ try {
308
+ return await fn();
309
+ }
310
+ finally {
311
+ const index = guards.indexOf(guard);
312
+ if (index >= 0) {
313
+ guards.splice(index, 1);
314
+ }
315
+ if (guards.length === 0) {
316
+ WITNESS_GUARDS.delete(ctx.id);
317
+ }
318
+ }
319
+ }
320
+ function isGuardedWitness(ctx, name) {
321
+ for (let current = ctx; current; current = current.parent) {
322
+ if (WITNESS_GUARDS.get(current.id)?.some((guard) => guard.has(name))) {
323
+ return true;
324
+ }
325
+ }
326
+ return false;
327
+ }
328
+ /**
329
+ * Refuses a call on a witness inside a verify's `act` unless the operation is
330
+ * declared without effects.
331
+ *
332
+ * @throws `NoeticConfigError` `VERIFY_INVALID`.
333
+ */
334
+ export function refuseWitnessAct(ctx, resolved, op) {
335
+ if (!isGuardedWitness(ctx, resolved.name)) {
336
+ return;
337
+ }
338
+ const info = resolved.manifest.operations[op];
339
+ if (info !== undefined && info.effects !== true) {
340
+ return;
341
+ }
342
+ throw new NoeticConfigError({
343
+ code: 'VERIFY_INVALID',
344
+ message: `A verify's act asked witness '${resolved.name}' to run '${op}', which ${info ? 'has effects' : 'it does not offer'}.`,
345
+ hint: 'A witness can look and cannot touch: act on the subject, or make the connection the subject.',
346
+ });
347
+ }
348
+ //#endregion
349
+ //#region Pending entries
350
+ /**
351
+ * Pending ledger entries for one run (spec 23a § Connection Steps): written
352
+ * before a call or wait reaches a server, removed once it has a result. Kept
353
+ * in the harness `StorageAdapter` next to the run's ledger.
354
+ */
355
+ export class PendingEntries {
356
+ storage;
357
+ key;
358
+ constructor(storage, key) {
359
+ this.storage = storage;
360
+ this.key = key;
361
+ }
362
+ /** The entry a previous attempt left, or undefined when there is none (or it does not parse). */
363
+ async load() {
364
+ const raw = await this.storage.get(this.key);
365
+ if (raw === null) {
366
+ return undefined;
367
+ }
368
+ const parsed = PendingEntrySchema.safeParse(raw);
369
+ return parsed.success ? parsed.data : undefined;
370
+ }
371
+ async write(entry) {
372
+ try {
373
+ await this.storage.set(this.key, entry);
374
+ }
375
+ catch (error) {
376
+ console.warn(`connection step: failed to write pending entry "${this.key}":`, error instanceof Error ? error.message : String(error));
377
+ }
378
+ }
379
+ async clear() {
380
+ try {
381
+ await this.storage.delete(this.key);
382
+ }
383
+ catch (error) {
384
+ console.warn(`connection step: failed to clear pending entry "${this.key}":`, error instanceof Error ? error.message : String(error));
385
+ }
386
+ }
387
+ }
388
+ /** The storage key of a step's pending entry. */
389
+ export function pendingEntryKey(executionId, ledgerKey) {
390
+ return `execution:${executionId}:pending:${ledgerKey}`;
391
+ }
392
+ /**
393
+ * Deletes every pending entry a completed run left behind (an entry is normally
394
+ * cleared when its step gets a result; this catches steps a run never resumed).
395
+ */
396
+ export async function clearPendingEntries(storage, executionId) {
397
+ const keys = await storage.list(`execution:${executionId}:pending:`);
398
+ await Promise.all(keys.map((key) => storage.delete(key)));
399
+ }
400
+ /** Pending entries apply only to a durable run: one with a ledger, a ledger key and storage. */
401
+ function pendingEntriesFor(ctx, ledgerKey) {
402
+ const storage = harnessOf(ctx).config?.storage;
403
+ const durable = ctx instanceof ContextImpl && ctx.ledger !== undefined;
404
+ if (!storage || !durable || ledgerKey === undefined) {
405
+ return undefined;
406
+ }
407
+ return new PendingEntries(storage, pendingEntryKey(runRootOf(ctx).id, ledgerKey));
408
+ }
409
+ /**
410
+ * Decides what a resumed step does with the pending entry a previous attempt
411
+ * left (spec 35 § Durability), through the one resume policy in
412
+ * `connections/durability.ts`. Against the same identity instance it returns the
413
+ * entry so the step picks up where it was. Against a replaced connection:
414
+ * `harness.restore(id, { rerun })` naming it, or `replayPrefix: 'free'`, runs
415
+ * live; `'costly'` with a reset resets first; anything else — including a
416
+ * connection that declares no determinism — refuses.
417
+ *
418
+ * @throws `NoeticErrorImpl` `connection_resume_refused` when the replaced connection cannot be driven again.
419
+ */
420
+ export async function reconcilePending(connection, signal, ctx) {
421
+ const entry = await connection.pending?.load();
422
+ if (!entry) {
423
+ return undefined;
424
+ }
425
+ const current = connection.resolved.identity();
426
+ const executionId = connection.scope.executionId;
427
+ const registry = ctx ? harnessOf(ctx).connectionRegistry : undefined;
428
+ const decision = resumeDecision({
429
+ recorded: entry.identity,
430
+ current,
431
+ determinism: connection.resolved.manifest.determinism,
432
+ rerunAllowed: registry?.rerunAllowed?.(executionId, connection.resolved.name) ?? false,
433
+ canReset: connection.resolved.reset !== undefined,
434
+ });
435
+ if (decision === 'keep') {
436
+ return entry;
437
+ }
438
+ if (decision === 'refuse') {
439
+ throw new NoeticErrorImpl({
440
+ kind: 'connection_resume_refused',
441
+ connection: connection.resolved.name,
442
+ reason: `its identity changed from '${entry.identity.instance}' to '${current.instance}' and it cannot be driven again; restore with { rerun: ['${connection.resolved.name}'] } to run it live.`,
443
+ });
444
+ }
445
+ if (decision === 'reset') {
446
+ await connection.resolved.reset?.({
447
+ signal,
448
+ });
449
+ }
450
+ await connection.pending?.clear();
451
+ return undefined;
452
+ }
453
+ /** Records on the run's ledger that the step at `ledgerKey` used `resolved` (spec 35 § Durability). */
454
+ function noteConnectionUse(ctx, ledgerKey, resolved) {
455
+ if (!(ctx instanceof ContextImpl) || !ctx.ledger || ledgerKey === undefined) {
456
+ return;
457
+ }
458
+ const identity = resolved.identity();
459
+ ctx.ledger.noteConnection(ledgerKey, {
460
+ name: resolved.name,
461
+ surface: identity.surface,
462
+ instance: identity.instance,
463
+ });
464
+ }
465
+ /**
466
+ * Before a resumed run replays anything, checks every connection its ledger
467
+ * and pending entries were recorded against (spec 35 § Durability). For a
468
+ * replaced connection that may run live (after a reset when that is the
469
+ * decision), the ledger is discarded from the first entry that used it —
470
+ * everything after runs live too, model rounds included — and its pending
471
+ * entries are dropped (their idempotency keys derive from the run and step,
472
+ * so `once` calls still carry their original keys). Resolves the number of
473
+ * ledger entries discarded.
474
+ *
475
+ * @throws `NoeticErrorImpl` `connection_resume_refused` when a replaced connection cannot be driven again.
476
+ */
477
+ export async function reconcileResumedConnections(opts) {
478
+ const { ctx, registry, storage, signal } = opts;
479
+ const ledger = ctx instanceof ContextImpl ? ctx.ledger : undefined;
480
+ const decided = new Map();
481
+ const decide = async (name, recorded) => {
482
+ const replaced = decided.get(name);
483
+ if (replaced !== undefined && replaced !== 'keep') {
484
+ return replaced;
485
+ }
486
+ const decision = await registry.checkResume({
487
+ executionId: ctx.id,
488
+ name,
489
+ recorded,
490
+ signal,
491
+ });
492
+ decided.set(name, decision);
493
+ return decision;
494
+ };
495
+ let discardFrom;
496
+ for (const { seq, uses } of ledger?.connectionUses() ?? []) {
497
+ for (const use of uses) {
498
+ const decision = await decide(use.name, use);
499
+ if (decision !== 'keep') {
500
+ discardFrom = Math.min(discardFrom ?? seq, seq);
501
+ }
502
+ }
503
+ }
504
+ await dropReplacedPending(ctx.id, storage, decide);
505
+ if (discardFrom === undefined || !ledger) {
506
+ return 0;
507
+ }
508
+ return ledger.discardFrom(discardFrom);
509
+ }
510
+ async function dropReplacedPending(executionId, storage, decide) {
511
+ if (!storage) {
512
+ return;
513
+ }
514
+ const keys = await storage.list(`execution:${executionId}:pending:`);
515
+ for (const key of keys) {
516
+ const parsed = PendingEntrySchema.safeParse(await storage.get(key));
517
+ if (!parsed.success) {
518
+ continue;
519
+ }
520
+ const decision = await decide(parsed.data.connection, parsed.data.identity);
521
+ if (decision !== 'keep') {
522
+ await storage.delete(key);
523
+ }
524
+ }
525
+ }
526
+ //#endregion
527
+ //#region Events
528
+ /** Emits a connection framework event (`connection_event`, `connection_task`, `stream_changed`). */
529
+ export function emitConnectionEvent(ctx, eventType, data) {
530
+ emitFrameworkEvent({
531
+ broadcaster: getBroadcaster(ctx),
532
+ agentName: ctx.harness.config.name,
533
+ eventType,
534
+ data,
535
+ });
536
+ }
537
+ //#endregion
@@ -1,8 +1,8 @@
1
1
  /**
2
- * Action step handlers: run, llm, spawn, provide, tool.
2
+ * Action step handlers: run, llm, spawn, provide.
3
3
  */
4
4
  import type { ItemSchemaRegistry, LayerStateStore } from './action-deps.js';
5
- import type { AgentHarnessContract, Context, ContextLayer, ExecuteStepFn, StepCallModel, StepInvokeTool, StepRunCode, StepSpawn, StepWithContext, StorageAdapter } from './action-types.js';
5
+ import type { Context, ContextLayer, ExecuteStepFn, StepCallModel, StepRunCode, StepSpawn, StepWithContext, StorageAdapter } from './action-types.js';
6
6
  export declare function executeRunCode<TContext, I, O>(step: StepRunCode<TContext, I, O>, input: I, ctx: Context<TContext>): Promise<O>;
7
7
  /**
8
8
  * Resolves a `Lazy<T>` step field. If the value is a function, it is invoked
@@ -44,9 +44,3 @@ export interface ExecuteWithContextOpts {
44
44
  * is neither initialized nor disposed here.
45
45
  */
46
46
  export declare function executeWithContext<TContext, I, O>(step: StepWithContext<TContext, I, O>, input: I, ctx: Context<TContext>, executeStep: ExecuteStepFn, opts?: ExecuteWithContextOpts): Promise<O>;
47
- /**
48
- * Runs an `invokeTool` step inside a `tool.call` span under `ctx.span`. The span
49
- * covers validation, the steering gate, and execution, so a denied or failing
50
- * call is traced with its error.
51
- */
52
- export declare function executeInvokeTool<TContext, I, O>(step: StepInvokeTool<TContext, I, O>, input: I, ctx: Context<TContext>, harness: AgentHarnessContract, layers?: ContextLayer[]): Promise<O>;