@noetic-tools/core 5.21.0 → 5.22.0-next.2

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 (101) hide show
  1. package/dist/adapters/openrouter.d.ts +6 -1
  2. package/dist/adapters/openrouter.js +10 -0
  3. package/dist/builders/decide-builders.d.ts +7 -0
  4. package/dist/builders/tool-builder.d.ts +25 -1
  5. package/dist/builders/tool-builder.js +25 -1
  6. package/dist/builders/workflow-control-nodes.js +1 -0
  7. package/dist/builders/workflow-hydrator.d.ts +19 -0
  8. package/dist/builders/workflow-hydrator.js +19 -0
  9. package/dist/builders/workflow-step.js +7 -1
  10. package/dist/connections/cron-schedule.js +12 -3
  11. package/dist/connections/durability.d.ts +1 -2
  12. package/dist/connections/durability.js +1 -4
  13. package/dist/connections/gates.js +6 -2
  14. package/dist/connections/harness-wiring.d.ts +5 -0
  15. package/dist/connections/harness-wiring.js +76 -10
  16. package/dist/connections/in-memory-connection.d.ts +4 -0
  17. package/dist/connections/in-memory-connection.js +10 -0
  18. package/dist/connections/model-tools.js +5 -1
  19. package/dist/connections/registry.d.ts +6 -2
  20. package/dist/connections/registry.js +10 -0
  21. package/dist/connections/sources.js +261 -20
  22. package/dist/connections/triggers.d.ts +62 -2
  23. package/dist/connections/triggers.js +375 -35
  24. package/dist/harness/agent-harness.d.ts +317 -4
  25. package/dist/harness/agent-harness.js +1264 -96
  26. package/dist/harness/connection-gate.d.ts +3 -0
  27. package/dist/harness/connection-gate.js +4 -0
  28. package/dist/harness/decide-call.d.ts +15 -0
  29. package/dist/harness/decide-call.js +57 -7
  30. package/dist/harness/deps/runtime.d.ts +3 -0
  31. package/dist/harness/deps/runtime.js +2 -0
  32. package/dist/harness/flow-version.d.ts +13 -0
  33. package/dist/harness/flow-version.js +66 -0
  34. package/dist/harness/harness-options.d.ts +91 -0
  35. package/dist/harness/llm-client.d.ts +2 -0
  36. package/dist/harness/llm-client.js +9 -5
  37. package/dist/harness/model-call.js +8 -0
  38. package/dist/harness/model-rounds.d.ts +30 -0
  39. package/dist/harness/model-rounds.js +146 -1
  40. package/dist/harness/model-tool-round.d.ts +3 -0
  41. package/dist/harness/model-tool-round.js +249 -22
  42. package/dist/harness/park-watchers.d.ts +93 -0
  43. package/dist/harness/park-watchers.js +217 -0
  44. package/dist/harness/read-decision.d.ts +23 -0
  45. package/dist/harness/read-decision.js +100 -0
  46. package/dist/harness/spend.js +4 -0
  47. package/dist/harness/steer-inbox.js +3 -1
  48. package/dist/harness/thread-record.d.ts +77 -1
  49. package/dist/harness/thread-record.js +272 -13
  50. package/dist/index.d.ts +22 -8
  51. package/dist/index.js +12 -2
  52. package/dist/interpreter/acp-resume.d.ts +77 -0
  53. package/dist/interpreter/acp-resume.js +164 -0
  54. package/dist/interpreter/acp-tools.d.ts +11 -0
  55. package/dist/interpreter/acp-tools.js +94 -7
  56. package/dist/interpreter/connection-steps.d.ts +24 -1
  57. package/dist/interpreter/connection-steps.js +77 -2
  58. package/dist/interpreter/execute-acp-agent.js +111 -15
  59. package/dist/interpreter/execute-action.js +7 -0
  60. package/dist/interpreter/execute-call.js +30 -4
  61. package/dist/interpreter/execute-control.js +21 -0
  62. package/dist/interpreter/execute-decide.js +5 -0
  63. package/dist/interpreter/execute-invoke-tool.js +149 -5
  64. package/dist/interpreter/execute-wait.js +67 -9
  65. package/dist/interpreter/execute.js +4 -0
  66. package/dist/interpreter/turn-ending.d.ts +15 -0
  67. package/dist/interpreter/turn-ending.js +46 -0
  68. package/dist/portable/builders.d.ts +1 -1
  69. package/dist/portable/builders.js +1 -1
  70. package/dist/portable/runtime.d.ts +4 -0
  71. package/dist/portable/runtime.js +2 -0
  72. package/dist/runtime/durable/parking.d.ts +61 -0
  73. package/dist/runtime/durable/parking.js +137 -0
  74. package/dist/runtime/durable/session-store.d.ts +38 -0
  75. package/dist/runtime/durable/session-store.js +79 -1
  76. package/dist/runtime/durable/step-ledger.d.ts +121 -2
  77. package/dist/runtime/durable/step-ledger.js +352 -15
  78. package/dist/runtime/durable/turn-lease.d.ts +128 -0
  79. package/dist/runtime/durable/turn-lease.js +307 -0
  80. package/dist/runtime/event-broadcaster.d.ts +9 -1
  81. package/dist/runtime/event-broadcaster.js +16 -1
  82. package/dist/runtime/held-calls.d.ts +192 -0
  83. package/dist/runtime/held-calls.js +496 -0
  84. package/dist/runtime/in-memory-storage.d.ts +10 -1
  85. package/dist/runtime/in-memory-storage.js +20 -2
  86. package/dist/runtime/message-queue.d.ts +2 -0
  87. package/dist/runtime/message-queue.js +8 -0
  88. package/dist/runtime/output-store.d.ts +88 -0
  89. package/dist/runtime/output-store.js +241 -0
  90. package/dist/runtime/session-runner.d.ts +18 -2
  91. package/dist/runtime/session-runner.js +88 -3
  92. package/dist/runtime/session-streams.d.ts +28 -7
  93. package/dist/runtime/session-streams.js +112 -67
  94. package/dist/runtime/tool-approval.d.ts +46 -6
  95. package/dist/runtime/tool-approval.js +160 -38
  96. package/dist/runtime/tool-call.d.ts +34 -2
  97. package/dist/runtime/tool-call.js +182 -13
  98. package/dist/runtime/tool-context.d.ts +15 -1
  99. package/dist/runtime/tool-context.js +38 -2
  100. package/package.json +3 -3
  101. package/schema/noetic-workflow.schema.json +27 -0
@@ -0,0 +1,164 @@
1
+ /**
2
+ * What an ACP step keeps so a resumed run can go on with the agent's own session
3
+ * instead of starting it over (spec 27 § Resuming a step).
4
+ *
5
+ * Two records, both beneath the step's place in the run:
6
+ *
7
+ * - The agent's session id, written when the step opens a session. A resumed step
8
+ * reloads that session (`session/load`) when the agent can.
9
+ * - Each tool call the agent made through the bridge, written as it finishes. A
10
+ * resumed agent that makes the same call again gets the recorded result.
11
+ */
12
+ import { frameworkCast } from '@noetic-tools/types';
13
+ import { z } from 'zod';
14
+ import { stepPathOf } from '../connections/durability.js';
15
+ import { ContextImpl } from '../runtime/context-impl.js';
16
+ import { hashStepInput } from '../runtime/durable/step-ledger.js';
17
+ import { pendingEntryKey, runRootOf } from './connection-steps.js';
18
+ //#region Types
19
+ const AcpSessionRecordSchema = z.object({
20
+ sessionId: z.string(),
21
+ agentId: z.string(),
22
+ });
23
+ const BridgedOutputSchema = z.object({
24
+ output: z.string(),
25
+ result: z.unknown().optional(),
26
+ error: z.boolean().optional(),
27
+ });
28
+ /** The kind of a bridged call's ledger entry. */
29
+ const BRIDGED_KIND = 'acp-tool';
30
+ /**
31
+ * @public
32
+ * What a resumed ACP step tells the agent before its prompt, when it reloaded the
33
+ * agent's session.
34
+ */
35
+ export const ACP_RESUME_NOTICE = 'Your previous turn on this task was cut off before it finished. Continue the task below from where you stopped. Do not redo work that is already done.';
36
+ function storageOf(ctx) {
37
+ return frameworkCast(ctx.harness).config?.storage;
38
+ }
39
+ function warn(action, key, error) {
40
+ console.warn(`acp step: failed to ${action} session record "${key}":`, error instanceof Error ? error.message : String(error));
41
+ }
42
+ //#endregion
43
+ //#region Public API
44
+ /**
45
+ * The session record of the ACP step running on `ctx`, or undefined when the run
46
+ * is not durable: no ledger, no storage, or no place in the run.
47
+ */
48
+ export function acpSessionRecords(ctx) {
49
+ const storage = storageOf(ctx);
50
+ const path = stepPathOf(ctx);
51
+ const ledger = ctx instanceof ContextImpl ? ctx.ledger : undefined;
52
+ if (!storage || !ledger || path === undefined) {
53
+ return undefined;
54
+ }
55
+ // With the run's pending entries, so clearing the run clears it.
56
+ const key = pendingEntryKey(runRootOf(ctx).id, `${path}/acp-session`);
57
+ return {
58
+ async load() {
59
+ const parsed = AcpSessionRecordSchema.safeParse(await storage.get(key));
60
+ return parsed.success ? parsed.data : undefined;
61
+ },
62
+ async write(record) {
63
+ if (!ledger.isHeld) {
64
+ return;
65
+ }
66
+ await storage.set(key, record).catch((error) => warn('write', key, error));
67
+ },
68
+ async clear() {
69
+ if (!ledger.isHeld) {
70
+ return;
71
+ }
72
+ await storage.delete(key).catch((error) => warn('clear', key, error));
73
+ },
74
+ };
75
+ }
76
+ /**
77
+ * Hands out the record of each bridged call of one step run. A call is known by
78
+ * its tool, its arguments, and its place among the calls with that tool and those
79
+ * arguments: a resumed agent's ids are new, but what it asks for is not.
80
+ */
81
+ export class BridgedCallRecords {
82
+ seen = new Map();
83
+ reloaded = false;
84
+ /**
85
+ * The agent's session was reloaded: it has its own record of the calls it
86
+ * finished, and was told not to redo them. A call it makes now is a new call,
87
+ * even with a tool and arguments it used before, so it must not be answered
88
+ * from a record. Each call's order starts after the ones already recorded.
89
+ *
90
+ * An agent that starts over in a new session makes its calls again from the
91
+ * first, and those are answered from the record.
92
+ */
93
+ sessionReloaded() {
94
+ this.reloaded = true;
95
+ }
96
+ recordFor(opts) {
97
+ const { ctx, stepId, tool, wireName } = opts;
98
+ const inputHash = hashStepInput({
99
+ name: wireName,
100
+ arguments: opts.args,
101
+ });
102
+ const step = stepPathOf(ctx) ?? stepId;
103
+ const call = `${wireName}:${inputHash ?? 'unhashed'}`;
104
+ const ledger = ctx instanceof ContextImpl ? ctx.ledger : undefined;
105
+ const pathAt = (n) => `${step}/bridged:${call}#${n}`;
106
+ const key = `${step}\u0000${call}`;
107
+ let order = this.seen.get(key);
108
+ if (order === undefined) {
109
+ order = 0;
110
+ // Past what a reloaded agent already finished: those are not coming again.
111
+ while (this.reloaded && ledger?.has(pathAt(order))) {
112
+ order += 1;
113
+ }
114
+ }
115
+ this.seen.set(key, order + 1);
116
+ const path = pathAt(order);
117
+ // `durable: false` records nothing; unhashable arguments cannot be matched.
118
+ const records = ledger !== undefined && tool?.durable !== false && inputHash !== undefined;
119
+ return {
120
+ id: `acp:${path}`,
121
+ take: () => {
122
+ if (!records) {
123
+ return undefined;
124
+ }
125
+ const entry = ledger.take(path, {
126
+ id: stepId,
127
+ kind: BRIDGED_KIND,
128
+ inputHash,
129
+ });
130
+ const parsed = entry ? BridgedOutputSchema.safeParse(entry.output) : undefined;
131
+ return parsed?.success ? parsed.data : undefined;
132
+ },
133
+ store: async (result) => {
134
+ if (!records || result.held !== undefined) {
135
+ return false;
136
+ }
137
+ if (tool?.durable === true) {
138
+ ledger.noteEffect(path);
139
+ }
140
+ return ledger.record({
141
+ path,
142
+ stepId,
143
+ kind: BRIDGED_KIND,
144
+ inputHash,
145
+ output: {
146
+ output: result.output,
147
+ ...(result.result === undefined
148
+ ? {}
149
+ : {
150
+ result: result.result,
151
+ }),
152
+ ...(result.error === undefined
153
+ ? {}
154
+ : {
155
+ error: result.error,
156
+ }),
157
+ },
158
+ completedAt: new Date().toISOString(),
159
+ });
160
+ },
161
+ };
162
+ }
163
+ }
164
+ //#endregion
@@ -61,6 +61,8 @@ export declare class AcpToolRunner implements AcpToolHost {
61
61
  private readonly announced;
62
62
  /** Ids already given to a call this session; an agent may not reuse one. */
63
63
  private readonly claimed;
64
+ /** What each call recorded, so a resumed step replays it (spec 27 § Resuming a step). */
65
+ private readonly records;
64
66
  constructor(source: ReadonlyArray<Tool>);
65
67
  /** Point the runner at the step whose turn is about to start. */
66
68
  bind(binding: AcpToolBinding): void;
@@ -72,6 +74,8 @@ export declare class AcpToolRunner implements AcpToolHost {
72
74
  * turn, as an in-flight `callModel` call belongs to its aborted round.
73
75
  */
74
76
  idle(): Promise<void>;
77
+ /** The agent's session was reloaded: see `BridgedCallRecords.sessionReloaded`. */
78
+ sessionReloaded(): void;
75
79
  /** The tool's wire name when `title` is how an agent titles a call to it. */
76
80
  wireNameOf(title: string): string | undefined;
77
81
  /** Note an agent `tool_call`, so a call without an id in `_meta` can take its id. */
@@ -90,6 +94,13 @@ export declare class AcpToolRunner implements AcpToolHost {
90
94
  private callIdFor;
91
95
  private announcedId;
92
96
  private unwrap;
97
+ /**
98
+ * Run the call to a result. A call held for a person waits here, with the agent
99
+ * waiting on it: the turn stays live, since the agent's process is what holds its
100
+ * place. The result is recorded before the call's intent or hold is dropped, so a
101
+ * step cut off in between asks again rather than runs again.
102
+ */
103
+ private settle;
93
104
  private execute;
94
105
  }
95
106
  /**
@@ -13,8 +13,10 @@ import { orderedCallId } from '../connections/durability.js';
13
13
  import { offeredTools, stepConnectionsOf } from '../connections/step-tools.js';
14
14
  import { ToolAttr } from '../observability/genai-attributes.js';
15
15
  import { drainsOf } from '../runtime/drain.js';
16
+ import { heldCallsOf, heldScopeOf, mayWriteHolds, waitOnHeldCalls } from '../runtime/held-calls.js';
16
17
  import { createToolResultItem, executeToolCall, resolveWireJsonSchema } from '../runtime/tool-call.js';
17
18
  import { sanitizeToolNameForWire } from '../util/tool-name.js';
19
+ import { BridgedCallRecords } from './acp-resume.js';
18
20
  import { openChildSpan, traceChild } from './child-span.js';
19
21
  import { deduplicateTools } from './collect-tools.js';
20
22
  import { resolveLazy, resolveToolsAndRestrictions, splitResolvedTools } from './execute-action.js';
@@ -169,6 +171,8 @@ export class AcpToolRunner {
169
171
  announced = new Map();
170
172
  /** Ids already given to a call this session; an agent may not reuse one. */
171
173
  claimed = new Set();
174
+ /** What each call recorded, so a resumed step replays it (spec 27 § Resuming a step). */
175
+ records = new BridgedCallRecords();
172
176
  constructor(source) {
173
177
  this.source = source;
174
178
  const wrapped = new Set();
@@ -218,6 +222,10 @@ export class AcpToolRunner {
218
222
  await settled;
219
223
  } while (settled !== this.queue);
220
224
  }
225
+ /** The agent's session was reloaded: see `BridgedCallRecords.sessionReloaded`. */
226
+ sessionReloaded() {
227
+ this.records.sessionReloaded();
228
+ }
221
229
  /** The tool's wire name when `title` is how an agent titles a call to it. */
222
230
  wireNameOf(title) {
223
231
  return this.tools.find((tool) => bridgedToolTitles(this.serverName, tool.name).includes(title))
@@ -344,21 +352,100 @@ export class AcpToolRunner {
344
352
  }
345
353
  return Reflect.get(call.args, WRAPPED_ARG);
346
354
  }
355
+ /**
356
+ * Run the call to a result. A call held for a person waits here, with the agent
357
+ * waiting on it: the turn stays live, since the agent's process is what holds its
358
+ * place. The result is recorded before the call's intent or hold is dropped, so a
359
+ * step cut off in between asks again rather than runs again.
360
+ */
361
+ async settle(binding, record, call) {
362
+ const { ctx } = binding;
363
+ const { params, signal } = call;
364
+ let result = await executeToolCall(params);
365
+ let announced;
366
+ while (result.held !== undefined) {
367
+ const { held } = result;
368
+ // Said once per question, under the id the agent's other events carry.
369
+ if (announced !== held.reason) {
370
+ announced = held.reason;
371
+ binding.events.toolEvent('tool_call_held', {
372
+ ...held,
373
+ callId: params.callId ?? held.callId,
374
+ heldAs: held.callId,
375
+ });
376
+ }
377
+ await waitOnHeldCalls({
378
+ harness: ctx.harness,
379
+ ctx,
380
+ callIds: [
381
+ held.callId,
382
+ ],
383
+ signal,
384
+ park: false,
385
+ });
386
+ // The agent stopped waiting for this call: nobody is left to give an answer to.
387
+ if (signal.aborted) {
388
+ if (mayWriteHolds(ctx)) {
389
+ await heldCallsOf(ctx.harness).close(heldScopeOf(ctx), held.callId);
390
+ }
391
+ return {
392
+ output: CANCELLED_OUTPUT,
393
+ error: true,
394
+ };
395
+ }
396
+ result = await executeToolCall(params);
397
+ }
398
+ const stored = await record.store(result);
399
+ if (!mayWriteHolds(ctx)) {
400
+ return result;
401
+ }
402
+ const holds = heldCallsOf(ctx.harness);
403
+ if (result.armed && stored) {
404
+ await holds.disarm(heldScopeOf(ctx), record.id);
405
+ }
406
+ if (result.settled) {
407
+ await holds.close(heldScopeOf(ctx), record.id);
408
+ }
409
+ return result;
410
+ }
347
411
  async execute(binding, call, callId, tool) {
348
412
  const args = this.unwrap(call);
349
413
  binding.events.toolEvent('tool_call_started', {
350
414
  name: call.name,
351
415
  callId,
352
416
  });
353
- const result = await executeToolCall({
354
- toolName: call.name,
417
+ const record = this.records.recordFor({
418
+ ctx: binding.ctx,
419
+ stepId: binding.stepId,
420
+ tool,
421
+ wireName: call.name,
355
422
  args,
356
- tools: this.source,
357
- context: binding.ctx,
358
- harness: binding.ctx.harness,
359
- layers: binding.layers,
360
- callId,
361
423
  });
424
+ const replayed = record.take();
425
+ if (replayed && mayWriteHolds(binding.ctx)) {
426
+ // A host that died after recording this result, and before dropping the call's
427
+ // intent or its answered hold, left them behind. The record says it is done.
428
+ const holds = heldCallsOf(binding.ctx.harness);
429
+ const executionId = heldScopeOf(binding.ctx);
430
+ await holds.disarm(executionId, record.id);
431
+ if (await holds.load(executionId, record.id)) {
432
+ await holds.close(executionId, record.id);
433
+ }
434
+ }
435
+ const result = replayed ??
436
+ (await this.settle(binding, record, {
437
+ signal: call.signal,
438
+ params: {
439
+ toolName: call.name,
440
+ args,
441
+ tools: this.source,
442
+ context: binding.ctx,
443
+ harness: binding.ctx.harness,
444
+ layers: binding.layers,
445
+ callId,
446
+ recordId: record.id,
447
+ },
448
+ }));
362
449
  const callItem = {
363
450
  id: callId,
364
451
  type: 'function_call',
@@ -49,6 +49,8 @@ declare const PendingEntrySchema: z.ZodObject<{
49
49
  leaseId: z.ZodOptional<z.ZodString>;
50
50
  cursor: z.ZodOptional<z.ZodNullable<z.ZodString>>;
51
51
  deadline: z.ZodOptional<z.ZodNumber>;
52
+ event: z.ZodOptional<z.ZodString>;
53
+ durable: z.ZodOptional<z.ZodBoolean>;
52
54
  }, z.core.$strip>;
53
55
  /**
54
56
  * The harness's connection registry.
@@ -135,12 +137,33 @@ export declare function refuseWitnessAct(ctx: Context, resolved: ResolvedConnect
135
137
  export declare class PendingEntries {
136
138
  private readonly storage;
137
139
  private readonly key;
138
- constructor(storage: StorageAdapter, key: string);
140
+ /** False once the run writes under a lease it no longer holds. */
141
+ private readonly mayWrite;
142
+ constructor(storage: StorageAdapter, key: string,
143
+ /** False once the run writes under a lease it no longer holds. */
144
+ mayWrite?: () => boolean);
139
145
  /** The entry a previous attempt left, or undefined when there is none (or it does not parse). */
140
146
  load(): Promise<PendingEntry | undefined>;
141
147
  write(entry: PendingEntry): Promise<void>;
142
148
  clear(): Promise<void>;
143
149
  }
150
+ /**
151
+ * The events an execution's waits listen for and can pick up again from a cursor:
152
+ * what a watcher needs to wake a parked turn (spec 23 § Parked turns).
153
+ */
154
+ export declare function resumableWaitsOf(storage: StorageAdapter, executionId: string): Promise<Array<{
155
+ connection: string;
156
+ event: string;
157
+ cursor: string | null;
158
+ }>>;
159
+ /**
160
+ * The long operations an execution's calls wait on: what a watcher polls to know
161
+ * when a parked turn can go on (spec 23 § Parked turns).
162
+ */
163
+ export declare function pendingTasksOf(storage: StorageAdapter, executionId: string): Promise<Array<{
164
+ connection: string;
165
+ taskId: string;
166
+ }>>;
144
167
  /** The storage key of a step's pending entry. */
145
168
  export declare function pendingEntryKey(executionId: string, ledgerKey: string): string;
146
169
  /**
@@ -33,6 +33,14 @@ const PendingEntrySchema = z.object({
33
33
  leaseId: z.string().optional(),
34
34
  cursor: z.string().nullish(),
35
35
  deadline: z.number().optional(),
36
+ /** On a `wait`: the event it listens for, so a parked turn can be watched over. */
37
+ event: z.string().optional(),
38
+ /**
39
+ * Set on a `wait` whose event replays from a cursor (`replay: 'durable'`). Such
40
+ * a wait does not depend on the connection instance it began on: any instance of
41
+ * the same surface can listen again from the cursor (spec 35 § Durability).
42
+ */
43
+ durable: z.boolean().optional(),
36
44
  });
37
45
  function harnessOf(ctx) {
38
46
  return {
@@ -377,9 +385,13 @@ export function refuseWitnessAct(ctx, resolved, op) {
377
385
  export class PendingEntries {
378
386
  storage;
379
387
  key;
380
- constructor(storage, key) {
388
+ mayWrite;
389
+ constructor(storage, key,
390
+ /** False once the run writes under a lease it no longer holds. */
391
+ mayWrite = () => true) {
381
392
  this.storage = storage;
382
393
  this.key = key;
394
+ this.mayWrite = mayWrite;
383
395
  }
384
396
  /** The entry a previous attempt left, or undefined when there is none (or it does not parse). */
385
397
  async load() {
@@ -391,6 +403,9 @@ export class PendingEntries {
391
403
  return parsed.success ? parsed.data : undefined;
392
404
  }
393
405
  async write(entry) {
406
+ if (!this.mayWrite()) {
407
+ return;
408
+ }
394
409
  try {
395
410
  await this.storage.set(this.key, entry);
396
411
  }
@@ -399,6 +414,9 @@ export class PendingEntries {
399
414
  }
400
415
  }
401
416
  async clear() {
417
+ if (!this.mayWrite()) {
418
+ return;
419
+ }
402
420
  try {
403
421
  await this.storage.delete(this.key);
404
422
  }
@@ -407,6 +425,44 @@ export class PendingEntries {
407
425
  }
408
426
  }
409
427
  }
428
+ /**
429
+ * The events an execution's waits listen for and can pick up again from a cursor:
430
+ * what a watcher needs to wake a parked turn (spec 23 § Parked turns).
431
+ */
432
+ export async function resumableWaitsOf(storage, executionId) {
433
+ const waits = [];
434
+ for (const key of await storage.list(`execution:${executionId}:pending:`)) {
435
+ const parsed = PendingEntrySchema.safeParse(await storage.get(key));
436
+ const resumable = parsed.success && parsed.data.kind === 'wait' && resumesFromCursor(parsed.data);
437
+ if (!parsed.success || !resumable || parsed.data.event === undefined) {
438
+ continue;
439
+ }
440
+ waits.push({
441
+ connection: parsed.data.connection,
442
+ event: parsed.data.event,
443
+ cursor: parsed.data.cursor ?? null,
444
+ });
445
+ }
446
+ return waits;
447
+ }
448
+ /**
449
+ * The long operations an execution's calls wait on: what a watcher polls to know
450
+ * when a parked turn can go on (spec 23 § Parked turns).
451
+ */
452
+ export async function pendingTasksOf(storage, executionId) {
453
+ const tasks = [];
454
+ for (const key of await storage.list(`execution:${executionId}:pending:`)) {
455
+ const parsed = PendingEntrySchema.safeParse(await storage.get(key));
456
+ if (!parsed.success || parsed.data.kind !== 'call' || parsed.data.taskId === undefined) {
457
+ continue;
458
+ }
459
+ tasks.push({
460
+ connection: parsed.data.connection,
461
+ taskId: parsed.data.taskId,
462
+ });
463
+ }
464
+ return tasks;
465
+ }
410
466
  /** The storage key of a step's pending entry. */
411
467
  export function pendingEntryKey(executionId, ledgerKey) {
412
468
  return `execution:${executionId}:pending:${ledgerKey}`;
@@ -426,7 +482,8 @@ function pendingEntriesFor(ctx, ledgerKey) {
426
482
  if (!storage || !durable || ledgerKey === undefined) {
427
483
  return undefined;
428
484
  }
429
- return new PendingEntries(storage, pendingEntryKey(runRootOf(ctx).id, ledgerKey));
485
+ const ledger = ctx.ledger;
486
+ return new PendingEntries(storage, pendingEntryKey(runRootOf(ctx).id, ledgerKey), () => ledger?.isHeld ?? true);
430
487
  }
431
488
  /**
432
489
  * Decides what a resumed step does with the pending entry a previous attempt
@@ -445,6 +502,9 @@ export async function reconcilePending(connection, signal, ctx) {
445
502
  return undefined;
446
503
  }
447
504
  const current = connection.resolved.identity();
505
+ if (resumesFromCursor(entry) && entry.identity.surface === current.surface) {
506
+ return entry;
507
+ }
448
508
  const executionId = connection.scope.executionId;
449
509
  const registry = ctx ? harnessOf(ctx).connectionRegistry : undefined;
450
510
  const decision = resumeDecision({
@@ -472,6 +532,17 @@ export async function reconcilePending(connection, signal, ctx) {
472
532
  await connection.pending?.clear();
473
533
  return undefined;
474
534
  }
535
+ /**
536
+ * True for a pending entry that any instance of its surface can pick up: a `wait`
537
+ * that replays from a cursor, or a `call` whose long operation has an id the server
538
+ * keeps. Neither depends on the connection instance it began on.
539
+ */
540
+ function resumesFromCursor(entry) {
541
+ if (entry.kind === 'call') {
542
+ return entry.taskId !== undefined;
543
+ }
544
+ return entry.durable === true;
545
+ }
475
546
  /** Records on the run's ledger that the step at `ledgerKey` used `resolved` (spec 35 § Durability). */
476
547
  function noteConnectionUse(ctx, ledgerKey, resolved) {
477
548
  if (!(ctx instanceof ContextImpl) || !ctx.ledger || ledgerKey === undefined) {
@@ -539,6 +610,10 @@ async function dropReplacedPending(executionId, storage, decide) {
539
610
  if (!parsed.success) {
540
611
  continue;
541
612
  }
613
+ // A wait that replays from a cursor is settled when its step runs again.
614
+ if (resumesFromCursor(parsed.data)) {
615
+ continue;
616
+ }
542
617
  const decision = await decide(parsed.data.connection, parsed.data.identity);
543
618
  if (decision !== 'keep') {
544
619
  await storage.delete(key);