@noetic-tools/core 5.20.0 → 5.22.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 (84) hide show
  1. package/dist/builders/tool-builder.d.ts +20 -0
  2. package/dist/builders/tool-builder.js +23 -1
  3. package/dist/builders/workflow-hydrator.d.ts +19 -0
  4. package/dist/builders/workflow-hydrator.js +19 -0
  5. package/dist/builders/workflow-step.js +7 -1
  6. package/dist/connections/cron-schedule.js +12 -3
  7. package/dist/connections/durability.d.ts +1 -2
  8. package/dist/connections/durability.js +1 -4
  9. package/dist/connections/gates.js +6 -2
  10. package/dist/connections/harness-wiring.d.ts +5 -0
  11. package/dist/connections/harness-wiring.js +76 -10
  12. package/dist/connections/in-memory-connection.d.ts +4 -0
  13. package/dist/connections/in-memory-connection.js +10 -0
  14. package/dist/connections/model-tools.js +5 -1
  15. package/dist/connections/registry.d.ts +6 -2
  16. package/dist/connections/registry.js +10 -0
  17. package/dist/connections/sources.js +261 -20
  18. package/dist/connections/triggers.d.ts +62 -2
  19. package/dist/connections/triggers.js +375 -35
  20. package/dist/harness/agent-harness.d.ts +263 -4
  21. package/dist/harness/agent-harness.js +1156 -95
  22. package/dist/harness/connection-gate.d.ts +3 -0
  23. package/dist/harness/connection-gate.js +4 -0
  24. package/dist/harness/deps/runtime.d.ts +3 -0
  25. package/dist/harness/deps/runtime.js +2 -0
  26. package/dist/harness/flow-version.d.ts +13 -0
  27. package/dist/harness/flow-version.js +66 -0
  28. package/dist/harness/harness-options.d.ts +82 -0
  29. package/dist/harness/model-call.d.ts +0 -1
  30. package/dist/harness/model-call.js +8 -48
  31. package/dist/harness/model-rounds.d.ts +30 -0
  32. package/dist/harness/model-rounds.js +146 -1
  33. package/dist/harness/model-tool-round.d.ts +3 -0
  34. package/dist/harness/model-tool-round.js +201 -19
  35. package/dist/harness/park-watchers.d.ts +93 -0
  36. package/dist/harness/park-watchers.js +217 -0
  37. package/dist/harness/read-decision.d.ts +23 -0
  38. package/dist/harness/read-decision.js +100 -0
  39. package/dist/harness/spend.js +4 -0
  40. package/dist/harness/steer-inbox.js +3 -1
  41. package/dist/harness/thread-record.d.ts +77 -1
  42. package/dist/harness/thread-record.js +272 -13
  43. package/dist/index.d.ts +17 -7
  44. package/dist/index.js +10 -2
  45. package/dist/interpreter/acp-resume.d.ts +77 -0
  46. package/dist/interpreter/acp-resume.js +164 -0
  47. package/dist/interpreter/acp-tools.d.ts +11 -0
  48. package/dist/interpreter/acp-tools.js +94 -7
  49. package/dist/interpreter/connection-steps.d.ts +24 -1
  50. package/dist/interpreter/connection-steps.js +77 -2
  51. package/dist/interpreter/execute-acp-agent.js +111 -15
  52. package/dist/interpreter/execute-action.js +7 -0
  53. package/dist/interpreter/execute-call.js +30 -4
  54. package/dist/interpreter/execute-control.js +21 -0
  55. package/dist/interpreter/execute-invoke-tool.js +149 -5
  56. package/dist/interpreter/execute-wait.js +67 -9
  57. package/dist/interpreter/execute.js +4 -0
  58. package/dist/interpreter/turn-ending.d.ts +15 -0
  59. package/dist/interpreter/turn-ending.js +46 -0
  60. package/dist/portable/builders.d.ts +1 -1
  61. package/dist/portable/builders.js +1 -1
  62. package/dist/runtime/durable/parking.d.ts +61 -0
  63. package/dist/runtime/durable/parking.js +137 -0
  64. package/dist/runtime/durable/session-store.d.ts +38 -0
  65. package/dist/runtime/durable/session-store.js +79 -1
  66. package/dist/runtime/durable/step-ledger.d.ts +121 -2
  67. package/dist/runtime/durable/step-ledger.js +352 -15
  68. package/dist/runtime/durable/turn-lease.d.ts +128 -0
  69. package/dist/runtime/durable/turn-lease.js +307 -0
  70. package/dist/runtime/held-calls.d.ts +192 -0
  71. package/dist/runtime/held-calls.js +496 -0
  72. package/dist/runtime/in-memory-storage.d.ts +10 -1
  73. package/dist/runtime/in-memory-storage.js +20 -2
  74. package/dist/runtime/message-queue.d.ts +2 -0
  75. package/dist/runtime/message-queue.js +8 -0
  76. package/dist/runtime/session-runner.d.ts +18 -2
  77. package/dist/runtime/session-runner.js +88 -3
  78. package/dist/runtime/tool-approval.d.ts +46 -6
  79. package/dist/runtime/tool-approval.js +160 -38
  80. package/dist/runtime/tool-call.d.ts +34 -2
  81. package/dist/runtime/tool-call.js +182 -13
  82. package/dist/runtime/tool-context.d.ts +15 -1
  83. package/dist/runtime/tool-context.js +38 -2
  84. package/package.json +3 -3
@@ -1,20 +1,99 @@
1
- import { CONNECTION_EVENT_ITEM_TYPE, frameworkCast, ItemSchemaRegistry, NoeticConfigError, } from '@noetic-tools/types';
1
+ import { CONNECTION_EVENT_ITEM_TYPE, frameworkCast, ItemSchemaRegistry, isDecisionItem, isNoeticError, NoeticConfigError, NoeticErrorImpl, } from '@noetic-tools/types';
2
2
  import { toStep } from '../builders/sequence.js';
3
3
  import { runEvery } from '../connections/settle.js';
4
+ import { pendingTasksOf, resumableWaitsOf } from '../interpreter/connection-steps.js';
5
+ import { turnEndingIn } from '../interpreter/turn-ending.js';
4
6
  import { AcpSessionStore } from '../runtime/acp-session-store.js';
7
+ import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
8
+ import { stubOf } from '../runtime/durable/step-ledger.js';
9
+ import { heldCallsOf, toHeldCall } from '../runtime/held-calls.js';
10
+ import { awaitApproval } from '../runtime/tool-approval.js';
5
11
  import { ConnectionGate } from './connection-gate.js';
6
12
  import { afterModelCallLayers, allocateBudgets, assembleView, beforeToolCallLayers, completeLayers, contextToExecCtx, createContextCacheStore, createLayerStateStore, createRecallCache, DEFAULT_PROJECTION, disposeLayers, executeRerender, initLayers, notifyDecision, onSteerLayers, projectHistoryLayers, recallLayers, recallLayersAtomic, recallLayersEventual, resolveLayerTools, runAppendPipeline, storeLayers, } from './deps/context.js';
7
13
  import { clearPendingEntries, collectAllTools, collectCustomItems, deduplicateTools, dispatchStepThroughAdapter, execute, isRootRunning, prepareBandedView, runRootOf, } from './deps/interpreter.js';
8
- import { buildItemStream, ChannelStore, ContextImpl, captureCheckpoint, clearCheckpoint, collectContextTree, createInMemoryStorage, createSessionStore, createSpendLog, createStepLedgerStore, customItemGates, Drains, filterReasoningStream, filterTextStream, INTERRUPT_REASON, isSteer, resolveStepLedgerRetention, restoreFromCheckpoint, rootIdOf, SessionRunner, StepLedger, snapshotCwdState, } from './deps/runtime.js';
14
+ import { buildItemStream, ChannelStore, ContextImpl, canSwap, captureCheckpoint, clearCheckpoint, collectContextTree, createInMemoryStorage, createSessionStore, createSpendLog, createStepLedgerStore, customItemGates, DEFAULT_LEASE_TTL_MS, DEFAULT_PARK_GRACE_MS, Drains, filterReasoningStream, filterTextStream, heldElsewhere, heldElsewhereUntil, INTERRUPT_REASON, isSteer, PARK_REASON, resolveStepLedgerRetention, restoreFromCheckpoint, rootIdOf, SessionRunner, StepLedger, snapshotCwdState, TurnLease, } from './deps/runtime.js';
9
15
  import { SteeringAction } from './deps/types.js';
16
+ import { flowVersionOf } from './flow-version.js';
10
17
  import { resolveCheckpointStore, resolveEnvironmentAdapters } from './harness-options.js';
11
18
  import { createHarnessSpan, recordChannelWarning, resolveTraceExporter } from './harness-tracing.js';
12
19
  import { LlmGateway } from './llm-client.js';
13
20
  import { buildItemSchemaRegistry } from './model-schema.js';
21
+ import { DEFAULT_TASK_POLL_MS, DEFAULT_WAKE_DEBOUNCE_MS, ParkWatchers } from './park-watchers.js';
22
+ import { readDecision } from './read-decision.js';
14
23
  import { Spend } from './spend.js';
15
24
  import { ThreadRecord } from './thread-record.js';
25
+ /** Keep `message` in storage for after the thread's parked turn, with its options. */
26
+ function keepForLater(session, record, message) {
27
+ session.keptOptions.set(message.id, message.options);
28
+ return record.keepQueued(message);
29
+ }
16
30
  //#endregion
17
31
  const DEFAULT_THREAD_ID = '__default__';
32
+ /** What a `turn_stuck` error says about where the turn stopped, or undefined for any other error. */
33
+ function stuckOf(error) {
34
+ const ending = turnEndingIn(error)?.noeticError;
35
+ if (ending?.kind !== 'turn_stuck') {
36
+ return undefined;
37
+ }
38
+ const { path, from, to } = ending;
39
+ return {
40
+ path,
41
+ from,
42
+ to,
43
+ };
44
+ }
45
+ /** True when `execute()` was handed a list. `Array.isArray` does not narrow a readonly one. */
46
+ function isItemList(input) {
47
+ return Array.isArray(input);
48
+ }
49
+ function isLeaseLost(error) {
50
+ return isNoeticError(error) && error.noeticError.kind === 'lease_lost';
51
+ }
52
+ /** Added to the lease period for the default wait on a held lease. */
53
+ const LEASE_WAIT_MARGIN_MS = 1e3;
54
+ /** What a turn's run resolves to when it parked instead of finishing. */
55
+ const PARKED = Symbol('parked');
56
+ /** When the turn on `ctx` parked until, or undefined when it did not park. */
57
+ function parkedUntil(ctx) {
58
+ if (ctx.abortReason !== PARK_REASON || !(ctx instanceof ContextImpl)) {
59
+ return undefined;
60
+ }
61
+ return ctx.ledger?.parking.parkedUntil;
62
+ }
63
+ /** The grace before a turn parks, or undefined when parking is off. */
64
+ function resolveParkGrace(park) {
65
+ if (!park) {
66
+ return undefined;
67
+ }
68
+ return park === true ? DEFAULT_PARK_GRACE_MS : (park.graceMs ?? DEFAULT_PARK_GRACE_MS);
69
+ }
70
+ /** Lease settings for sessions on `storage`, or none when it cannot compare-and-set. */
71
+ function resolveLeaseOptions(storage, config) {
72
+ if (!canSwap(storage)) {
73
+ return undefined;
74
+ }
75
+ const ttlMs = config?.ttlMs ?? DEFAULT_LEASE_TTL_MS;
76
+ // One lease period, and a little more: a dead holder's lease runs out in that time.
77
+ const waitMs = config?.waitMs ?? ttlMs + LEASE_WAIT_MARGIN_MS;
78
+ // A lease of no length is lost before the turn's first write; one that never
79
+ // ends is never taken over.
80
+ const ttlOk = Number.isFinite(ttlMs) && ttlMs > 0;
81
+ const waitOk = Number.isFinite(waitMs) && waitMs >= 0;
82
+ if (!ttlOk || !waitOk || config?.holder === '') {
83
+ throw new NoeticConfigError({
84
+ code: 'INVALID_LEASE_OPTIONS',
85
+ message: `environment.storage.lease is not usable: ttlMs ${ttlMs}, waitMs ${waitMs}, holder ${JSON.stringify(config?.holder)}.`,
86
+ hint: 'Give ttlMs a finite number of milliseconds above 0, waitMs a finite number from 0 up, and holder a non-empty name, or leave them out for the defaults.',
87
+ });
88
+ }
89
+ return {
90
+ storage,
91
+ holder: config?.holder ?? crypto.randomUUID(),
92
+ ttlMs,
93
+ waitMs,
94
+ now: config?.now ?? Date.now,
95
+ };
96
+ }
18
97
  /** Default idle-timeout for a single model call's streaming response. Chosen to be
19
98
  * long enough that slow models aren't falsely aborted, but short enough that a
20
99
  * stalled SSE becomes a visible error rather than a silent hang. */
@@ -98,6 +177,20 @@ export class AgentHarness {
98
177
  liveRoots = new Map();
99
178
  /** Stored sessions for `execute()` threads. Present exactly when durability is on. */
100
179
  sessionStore;
180
+ /** Set when sessions are durable and storage can compare-and-set. */
181
+ leaseOptions;
182
+ /** The flow version this harness runs, when the host names one. */
183
+ version;
184
+ /** Set when turns park (`environment.storage.park`): the grace before one does. */
185
+ parkGraceMs;
186
+ /** Set when this harness wakes the turns it parked (`park.autoWake`). */
187
+ parkWatchers;
188
+ /** Who hears when the next wake time changes (`onWakeTimeChange`). */
189
+ wakeTimeListeners = new Set();
190
+ /** The wake time listeners last heard; `null` until they have heard one. */
191
+ announcedWakeTime = null;
192
+ /** The announcement in flight, so two never run out of order. */
193
+ announcing = Promise.resolve();
101
194
  /** Checkpoint capture in flight per execution id — see `saveCheckpoint`. */
102
195
  pendingCheckpoints = new Map();
103
196
  defaultDeliveryMode;
@@ -205,6 +298,7 @@ export class AgentHarness {
205
298
  decisionModel: opts.decisionModel,
206
299
  emitItemsOnReplay: opts.emitItemsOnReplay,
207
300
  approveToolCall: opts.approveToolCall,
301
+ now: opts.now,
208
302
  };
209
303
  const adapters = resolveEnvironmentAdapters(environment);
210
304
  this.fs = adapters.fs;
@@ -220,10 +314,17 @@ export class AgentHarness {
220
314
  this.sessionStore = this.checkpointStore
221
315
  ? createSessionStore(this.config.storage ?? createInMemoryStorage())
222
316
  : undefined;
317
+ this.leaseOptions = resolveLeaseOptions(this.sessionStore ? this.config.storage : undefined, {
318
+ now: opts.now,
319
+ ...storageEnv?.lease,
320
+ });
321
+ this.parkGraceMs = resolveParkGrace(this.leaseOptions ? storageEnv?.park : undefined);
322
+ this.parkWatchers = this.createParkWatchers(storageEnv?.park);
223
323
  this.spend = this.checkpointStore
224
324
  ? this.createSpend(this.config.storage ?? createInMemoryStorage())
225
325
  : undefined;
226
326
  this.agentGraph = opts.agentGraph ? toStep(opts.agentGraph) : undefined;
327
+ this.version = opts.version ?? flowVersionOf(frameworkCast(this.agentGraph));
227
328
  this.harnessTools = opts.tools ?? [];
228
329
  this._contextLayers = opts.contextLayers;
229
330
  this.llm = new LlmGateway({
@@ -255,11 +356,10 @@ export class AgentHarness {
255
356
  ...(this.agentGraph
256
357
  ? collectCustomItems(frameworkCast(this.agentGraph)).map((item) => item.type)
257
358
  : []),
258
- ...(opts.triggers && opts.triggers.length > 0
259
- ? [
260
- CONNECTION_EVENT_ITEM_TYPE,
261
- ]
262
- : []),
359
+ // Always known: a trigger can be added while the harness runs, and one added
360
+ // on an earlier run comes back from storage, so its turns must be able to
361
+ // carry the event.
362
+ CONNECTION_EVENT_ITEM_TYPE,
263
363
  ]),
264
364
  });
265
365
  this.rootCwdState = {
@@ -270,6 +370,7 @@ export class AgentHarness {
270
370
  harness: this,
271
371
  connections: opts.connections,
272
372
  triggers: opts.triggers,
373
+ onSchedule: () => this.announceWakeTimeQuietly(),
273
374
  storage: this.config.storage ?? createInMemoryStorage(),
274
375
  artifacts: this.artifacts,
275
376
  secrets: environment?.secrets,
@@ -288,6 +389,78 @@ export class AgentHarness {
288
389
  */
289
390
  async start() {
290
391
  await this.#connections.start();
392
+ // Once started, a scheduled source's next event is known: say when it is.
393
+ if (this.announcedWakeTime === null) {
394
+ await this.announceWakeTime();
395
+ }
396
+ }
397
+ /**
398
+ * Hear when `getNextWakeTime()` changes: a turn parks, resumes or ends, a
399
+ * trigger is added or removed, or a scheduled source's event is read. `listener`
400
+ * gets the new time, or `undefined` when there is nothing to wake for. The first
401
+ * call comes when the harness starts. A host with no process of its own between
402
+ * events sets its alarm from it.
403
+ *
404
+ * The harness waits for the listener before a parking turn answers, and a
405
+ * listener that throws there fails that turn's response: a turn nothing will
406
+ * wake must not look safely parked. Anywhere else a throw is logged.
407
+ *
408
+ * It does not replace the harness's own timer (`park.autoWake`).
409
+ *
410
+ * @returns a function that stops the listener hearing.
411
+ * @public
412
+ */
413
+ onWakeTimeChange(listener) {
414
+ this.wakeTimeListeners.add(listener);
415
+ return () => {
416
+ this.wakeTimeListeners.delete(listener);
417
+ };
418
+ }
419
+ /** Tell the listeners the next wake time, when it is not the one they last heard. */
420
+ announceWakeTime() {
421
+ if (this.wakeTimeListeners.size === 0) {
422
+ return Promise.resolve();
423
+ }
424
+ const run = this.announcing.then(async () => {
425
+ const at = await this.getNextWakeTime();
426
+ if (at === this.announcedWakeTime) {
427
+ return;
428
+ }
429
+ for (const listener of this.wakeTimeListeners) {
430
+ await listener(at);
431
+ }
432
+ this.announcedWakeTime = at;
433
+ });
434
+ this.announcing = run.catch(() => undefined);
435
+ return run;
436
+ }
437
+ /** `announceWakeTime`, where a listener's failure has no turn to land on. */
438
+ async announceWakeTimeQuietly() {
439
+ try {
440
+ await this.announceWakeTime();
441
+ }
442
+ catch (error) {
443
+ console.warn('[noetic] onWakeTimeChange listener error:', error);
444
+ }
445
+ }
446
+ /**
447
+ * Resolves once the harness has nothing in hand: every scheduled event that is
448
+ * due has been read by its trigger, and every turn has finished or parked. A
449
+ * serverless host awaits it after `start()` and `wake()`, before it lets its
450
+ * process go.
451
+ * @public
452
+ */
453
+ async waitForIdle() {
454
+ for (;;) {
455
+ await this.#connections.triggers.idle();
456
+ const busy = [
457
+ ...this.sessions.values(),
458
+ ].filter((session) => session.runner.getStatus().kind !== 'idle');
459
+ if (busy.length === 0) {
460
+ return;
461
+ }
462
+ await Promise.allSettled(busy.map((session) => session.runner.getAgentResponse()));
463
+ }
291
464
  }
292
465
  /**
293
466
  * Each connection's state, identity and pool usage; one entry for `name`, or all.
@@ -305,6 +478,7 @@ export class AgentHarness {
305
478
  * @public
306
479
  */
307
480
  async close() {
481
+ this.parkWatchers?.stopAll();
308
482
  await runEvery([
309
483
  () => this.#connections.close(),
310
484
  () => this.closeAcpSessions(),
@@ -324,7 +498,110 @@ export class AgentHarness {
324
498
  this.rootCwdState.cwd = nextCwd;
325
499
  }
326
500
  //#region Session Accessors
327
- execute(input, options) {
501
+ /**
502
+ * Hand the thread a message, a person's decision, or both.
503
+ *
504
+ * A {@link DecisionItem} answers a tool call the thread's turn holds, or settles
505
+ * its stuck turn. It is not written to the conversation, and input that holds
506
+ * nothing else starts no turn: the turn the decision is for goes on.
507
+ *
508
+ * Several decisions in one list are read first, so a malformed one changes
509
+ * nothing, and then taken in order: one the thread's state refuses throws, and
510
+ * those before it stay taken. `options` reach the turn a decision resumes.
511
+ *
512
+ * @throws NoeticError `hold_refused` when an answer to a held call cannot be
513
+ * taken: the thread holds no such call, `argsHash` names other arguments, the
514
+ * answer is the wrong kind for the hold, the call was already answered
515
+ * differently, its `output` is not a JSON value, or a `function_call_output`
516
+ * item names a held call.
517
+ * @throws NoeticError `decision_refused` when a decision does not fit what the
518
+ * thread is waiting on: no turn is stuck, it carries both an `action` and an
519
+ * `output`, or its action is the wrong kind for a decision with, or without,
520
+ * a `callId`.
521
+ * @public
522
+ */
523
+ async execute(input, options) {
524
+ const message = await this.takeDecisions(input, options);
525
+ if (message === undefined) {
526
+ return;
527
+ }
528
+ return this.deliverInput(message, options);
529
+ }
530
+ /**
531
+ * Act on the decisions in `input` and resolve what is left of it: the message to
532
+ * deliver, or undefined when the input was decisions only.
533
+ *
534
+ * Every decision is read before any is acted on, so a list with a malformed one
535
+ * changes nothing. They are then acted on in order: one the thread's state
536
+ * refuses throws, and those before it stay taken.
537
+ */
538
+ async takeDecisions(input, options) {
539
+ if (typeof input === 'string') {
540
+ return input;
541
+ }
542
+ const threadId = options?.threadId ?? DEFAULT_THREAD_ID;
543
+ const given = isItemList(input)
544
+ ? input
545
+ : [
546
+ input,
547
+ ];
548
+ const rest = [];
549
+ const decisions = [];
550
+ for (const item of given) {
551
+ if (isDecisionItem(item)) {
552
+ decisions.push(readDecision(threadId, item));
553
+ continue;
554
+ }
555
+ rest.push(item);
556
+ }
557
+ await this.refuseResultsForHeldCalls(threadId, rest);
558
+ for (const decision of decisions) {
559
+ await this.takeDecision(decision, options);
560
+ }
561
+ if (rest.length === given.length) {
562
+ return frameworkCast(input);
563
+ }
564
+ return rest.length === 0 ? undefined : rest;
565
+ }
566
+ /**
567
+ * A held call's result comes in a decision. A `function_call_output` for one
568
+ * would go into the conversation and leave the call waiting, so it is refused.
569
+ */
570
+ async refuseResultsForHeldCalls(threadId, items) {
571
+ const outputs = items.filter((item) => item.type === 'function_call_output');
572
+ if (outputs.length === 0) {
573
+ return;
574
+ }
575
+ const held = new Set((await this.pending({
576
+ threadId,
577
+ })).map((call) => call.callId));
578
+ for (const item of outputs) {
579
+ if ('callId' in item && typeof item.callId === 'string' && held.has(item.callId)) {
580
+ throw new NoeticErrorImpl({
581
+ kind: 'hold_refused',
582
+ callId: item.callId,
583
+ reason: "a held call's result is given in a decision item, not a function_call_output",
584
+ });
585
+ }
586
+ }
587
+ }
588
+ /** Act on one decision: an answer to a held call, or the settling of a stuck turn. */
589
+ async takeDecision(decision, options) {
590
+ if ('answer' in decision) {
591
+ await this.resolveHeld(decision.scope, decision.answer, options);
592
+ return;
593
+ }
594
+ if (await this.settleStuckTurn(decision.threadId, decision.settle, options)) {
595
+ return;
596
+ }
597
+ throw new NoeticErrorImpl({
598
+ kind: 'decision_refused',
599
+ threadId: decision.threadId,
600
+ action: decision.settle,
601
+ reason: 'the thread has no stuck turn',
602
+ });
603
+ }
604
+ deliverInput(input, options) {
328
605
  if (!this.agentGraph) {
329
606
  return Promise.reject(new NoeticConfigError({
330
607
  code: 'NO_STEP_CONFIGURED',
@@ -352,12 +629,40 @@ export class AgentHarness {
352
629
  void session.runner.abort(INTERRUPT_REASON);
353
630
  return Promise.resolve();
354
631
  }
632
+ return this.deliver(session, message);
633
+ }
634
+ /**
635
+ * Hand a message to its thread. One at a time per thread: what to do with a
636
+ * message is decided by looking at the thread and then acting, and two
637
+ * deliveries doing that at once would each miss the other.
638
+ */
639
+ deliver(session, message) {
640
+ const turn = (session.delivering ?? Promise.resolve())
641
+ .catch(() => undefined)
642
+ .then(() => this.deliverOne(session, message));
643
+ session.delivering = turn;
644
+ return turn;
645
+ }
646
+ async deliverOne(session, message) {
647
+ if (await this.deliverToParked(session, message)) {
648
+ return;
649
+ }
650
+ if (await this.answerAgain(session, message)) {
651
+ return;
652
+ }
653
+ if (await this.inHand(session, message)) {
654
+ return;
655
+ }
355
656
  const steersRunningTurn = session.runner.getStatus().kind === 'generating' && isSteer(message);
356
657
  session.runner.enqueue(message);
357
658
  if (steersRunningTurn) {
358
659
  void session.record?.keepSteer(message);
660
+ // A round waiting on a held call offers the steer to the layers at once.
661
+ const running = session.runner.context;
662
+ if (running) {
663
+ heldCallsOf(this).notify(rootIdOf(running));
664
+ }
359
665
  }
360
- return Promise.resolve();
361
666
  }
362
667
  /** The turn's response. `items` holds final items: standard ones and the graph's declared custom items. */
363
668
  getAgentResponse(scope) {
@@ -387,7 +692,10 @@ export class AgentHarness {
387
692
  }
388
693
  async abort(scope) {
389
694
  const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
390
- const session = this.sessions.get(threadId);
695
+ // A parked turn lives in storage, so a harness that never ran the thread can
696
+ // still be the one asked to abort it.
697
+ const session = this.sessions.get(threadId) ??
698
+ (this.sessionStore ? this.getOrCreateSession(threadId) : undefined);
391
699
  if (!session) {
392
700
  return undefined;
393
701
  }
@@ -395,6 +703,14 @@ export class AgentHarness {
395
703
  const ctx = runner.context;
396
704
  if (!ctx) {
397
705
  await runner.abort(scope?.reason);
706
+ // Nothing is running, but a parked turn is still the thread's turn: drop it,
707
+ // or the next wake would bring back what the host just cancelled.
708
+ await runner.whenIdle();
709
+ if ((await session.record?.turn())?.parked) {
710
+ this.parkWatchers?.stop(threadId);
711
+ await session.record?.drop();
712
+ await this.announceWakeTimeQuietly();
713
+ }
398
714
  return undefined;
399
715
  }
400
716
  const draining = this.drains.stop(ctx);
@@ -501,8 +817,12 @@ export class AgentHarness {
501
817
  }
502
818
  const record = this.threadRecord(threadId);
503
819
  // Save a turn's items as the thread's history for the next turn.
504
- const keepHistory = async (ctx) => {
820
+ const keepHistory = async (ctx, answer) => {
505
821
  if (record) {
822
+ // A finished turn's answer is kept, so its messages delivered again get it back.
823
+ if (answer !== undefined) {
824
+ await record.answered(ctx, answer);
825
+ }
506
826
  await record.end(ctx, ctx.itemLog.items, session.runner.queue.peekAll().map((message) => message.id));
507
827
  return;
508
828
  }
@@ -512,6 +832,7 @@ export class AgentHarness {
512
832
  };
513
833
  const session = {
514
834
  accumulatedItems: [],
835
+ keptOptions: new Map(),
515
836
  record,
516
837
  runner: new SessionRunner({
517
838
  threadId,
@@ -522,88 +843,46 @@ export class AgentHarness {
522
843
  // are ignored. `deliveryMode` is resolved per-message at enqueue
523
844
  // time and doesn't apply here.
524
845
  createContext: async (items, _turnId, messages) => {
525
- const perTurnOptions = messages[0]?.options ?? {};
526
- const messageIds = messages.map((m) => m.id);
527
- const history = record ? await record.history() : session.accumulatedItems;
528
- const graph = this.agentGraph ? frameworkCast(this.agentGraph) : undefined;
529
- const views = this.#connections.turnViews(perTurnOptions.connections, graph);
530
- // A re-delivery of a cut-off turn's messages picks that turn up where it died.
531
- const resumed = await record?.resume(messageIds, {
532
- state: perTurnOptions.state,
533
- contextLayers: perTurnOptions.contextLayers,
534
- _broadcaster: session.runner.broadcaster,
535
- });
536
- const ctx = resumed ??
537
- this.createContext({
538
- items: [
539
- ...history,
540
- ...items,
541
- ],
542
- threadId,
543
- resourceId: perTurnOptions.resourceId,
544
- state: perTurnOptions.state,
545
- contextLayers: perTurnOptions.contextLayers,
546
- extraContextLayers: perTurnOptions.extraContextLayers,
547
- _connectionViews: views.layers,
548
- _broadcaster: session.runner.broadcaster,
549
- });
550
- // A resumed context was made without the turn's view layers.
551
- if (!resumed) {
552
- views.bind(ctx);
553
- }
554
- frameworkCast(ctx)._sessionQueue = session.runner.queue;
555
- await this.start();
556
- const connectionTools = await this.#connections.openTurn(ctx, perTurnOptions.connections, graph);
557
- if (this.agentGraph || this.harnessTools.length > 0 || connectionTools.length > 0) {
558
- const stepTools = this.agentGraph ? collectAllTools(this.agentGraph) : [];
559
- this.setUnifiedTools(ctx, [
560
- ...stepTools,
561
- ...this.harnessTools,
562
- ...connectionTools,
563
- ]);
564
- }
565
- // Steers the last harness accepted but never applied go back in the queue;
566
- // ones already in the conversation are skipped when offered.
567
- for (const steer of (await record?.steers()) ?? []) {
568
- const queued = session.runner.queue.peekAll().some((m) => m.id === steer.id);
569
- if (!queued && !messageIds.includes(steer.id)) {
570
- session.runner.queue.enqueue(steer);
846
+ // One harness drives a thread's turn: take its lease before reading anything.
847
+ const lease = record && this.leaseOptions
848
+ ? await TurnLease.take(this.leaseOptions, threadId, {
849
+ // Aborting the thread ends the wait for a lease held elsewhere.
850
+ signal: session.runner.signal,
851
+ // A lease record that was deleted must not start again below the
852
+ // term the thread's own record was last written at.
853
+ above: await record.term(),
854
+ })
855
+ : undefined;
856
+ record?.hold(lease);
857
+ session.lease = lease;
858
+ try {
859
+ if (record && (await this.setAside(session, record, messages))) {
860
+ await this.releaseLease(session);
861
+ return undefined;
571
862
  }
863
+ return await buildTurnContext(items, messages, lease);
864
+ }
865
+ catch (error) {
866
+ await this.releaseLease(session);
867
+ throw error;
572
868
  }
573
- await record?.begin(ctx, messageIds);
574
- return ctx;
575
869
  },
576
870
  runTurn: async (ctx, _turn, signal) => {
577
- if (!this.agentGraph) {
578
- await this.#connections.release(ctx.id);
579
- throw new NoeticConfigError({
580
- code: 'NO_STEP_CONFIGURED',
581
- message: 'No agentGraph configured on this harness.',
582
- hint: 'Pass `agentGraph` in constructor options.',
583
- });
871
+ try {
872
+ return await runTurn(ctx, signal);
584
873
  }
585
- // Wire signal-abort to context-abort so the interpreter bails cleanly.
586
- if (signal.aborted) {
587
- ctx.abort(signal.reason ? String(signal.reason) : 'aborted');
588
- }
589
- else {
590
- signal.addEventListener('abort', () => {
591
- ctx.abort(signal.reason ? String(signal.reason) : 'aborted');
592
- }, {
593
- once: true,
594
- });
595
- }
596
- const result = await this.initAndRun(this.agentGraph, '', ctx).catch(async (error) => {
597
- // An interrupted turn restarts from what it finished, so the
598
- // interrupting message lands after the work it interrupted.
599
- if (ctx.abortReason === INTERRUPT_REASON) {
600
- await keepHistory(ctx);
874
+ finally {
875
+ await this.releaseLease(session);
876
+ // An answer that landed while this harness still held the lease could not
877
+ // wake the turn. Now that it is free, do that.
878
+ if (parkedUntil(ctx) !== undefined) {
879
+ void this.wakeIfAnswered(threadId, ctx.id);
601
880
  }
602
- throw error;
603
- });
604
- await keepHistory(ctx);
605
- return result;
881
+ }
606
882
  },
883
+ heldCalls: async (ctx) => (await heldCallsOf(this).list(rootIdOf(ctx)))
884
+ .filter((held) => held.resolution === undefined)
885
+ .map(toHeldCall),
607
886
  // Stored totals are the session's usage; the runner only mirrors them.
608
887
  onTurnUsage: record
609
888
  ? async (spent) => {
@@ -612,12 +891,748 @@ export class AgentHarness {
612
891
  : undefined,
613
892
  }),
614
893
  };
894
+ const buildTurnContext = async (items, messages, lease) => {
895
+ const perTurnOptions = messages[0]?.options ?? {};
896
+ // The turn is starting or resuming here: nothing needs to watch over it.
897
+ session.turnOptions = perTurnOptions;
898
+ this.parkWatchers?.stop(threadId);
899
+ const messageIds = messages.map((m) => m.id);
900
+ const history = record ? await record.history() : session.accumulatedItems;
901
+ const graph = this.agentGraph ? frameworkCast(this.agentGraph) : undefined;
902
+ const views = this.#connections.turnViews(perTurnOptions.connections, graph);
903
+ // A re-delivery of a cut-off turn's messages picks that turn up where it died.
904
+ const resumed = await record?.resume(messageIds, {
905
+ state: perTurnOptions.state,
906
+ contextLayers: perTurnOptions.contextLayers,
907
+ _broadcaster: session.runner.broadcaster,
908
+ });
909
+ const ctx = resumed ??
910
+ this.createContext({
911
+ items: [
912
+ ...history,
913
+ ...items,
914
+ ],
915
+ threadId,
916
+ resourceId: perTurnOptions.resourceId,
917
+ state: perTurnOptions.state,
918
+ contextLayers: perTurnOptions.contextLayers,
919
+ extraContextLayers: perTurnOptions.extraContextLayers,
920
+ _connectionViews: views.layers,
921
+ _broadcaster: session.runner.broadcaster,
922
+ });
923
+ if (lease) {
924
+ lease.bind(ctx.id);
925
+ if (ctx instanceof ContextImpl) {
926
+ ctx.ledger?.fence(lease);
927
+ }
928
+ lease.keep((reason) => ctx.abort(`lease_lost: ${reason}`));
929
+ if (this.parkGraceMs !== undefined && ctx instanceof ContextImpl) {
930
+ ctx.ledger?.parking.arm({
931
+ graceMs: this.parkGraceMs,
932
+ onPark: () => ctx.abort(PARK_REASON),
933
+ });
934
+ }
935
+ }
936
+ // A resumed context was made without the turn's view layers.
937
+ if (!resumed) {
938
+ views.bind(ctx);
939
+ }
940
+ frameworkCast(ctx)._sessionQueue = session.runner.queue;
941
+ await this.start();
942
+ const connectionTools = await this.#connections.openTurn(ctx, perTurnOptions.connections, graph);
943
+ if (this.agentGraph || this.harnessTools.length > 0 || connectionTools.length > 0) {
944
+ const stepTools = this.agentGraph ? collectAllTools(this.agentGraph) : [];
945
+ this.setUnifiedTools(ctx, [
946
+ ...stepTools,
947
+ ...this.harnessTools,
948
+ ...connectionTools,
949
+ ]);
950
+ }
951
+ // Steers the last harness accepted but never applied go back in the queue;
952
+ // ones already in the conversation are skipped when offered.
953
+ for (const steer of (await record?.steers()) ?? []) {
954
+ const queued = session.runner.queue.peekAll().some((m) => m.id === steer.id);
955
+ if (!queued && !messageIds.includes(steer.id)) {
956
+ // With the options it was sent with, when this process is the one it was sent to.
957
+ const options = session.keptOptions.get(steer.id) ?? steer.options;
958
+ session.keptOptions.delete(steer.id);
959
+ session.runner.queue.enqueue({
960
+ ...steer,
961
+ options,
962
+ });
963
+ }
964
+ }
965
+ // A stuck turn the host chose to go on with may discard what no longer matches.
966
+ const accept = (await record?.turn())?.accept;
967
+ if (accept && ctx instanceof ContextImpl) {
968
+ ctx.ledger?.acceptVersionLoss(typeof accept === 'string' ? accept : undefined);
969
+ }
970
+ await record?.begin(ctx, messageIds);
971
+ // A turn on record can be cut off from here on. A host that sleeps between
972
+ // requests has to know when to come back and look (see `turnDueAt`).
973
+ if (record && this.leaseOptions) {
974
+ await this.announceWakeTimeQuietly();
975
+ }
976
+ return ctx;
977
+ };
978
+ /**
979
+ * A parked turn is not a failed one: its record stays, marked with when to wake
980
+ * it, and the response says so. Resolves true when the turn on `ctx` parked.
981
+ */
982
+ const closeOutPark = async (ctx) => {
983
+ const wakeAt = parkedUntil(ctx);
984
+ if (wakeAt === undefined || !record) {
985
+ return false;
986
+ }
987
+ // Messages still queued wait in storage, not in this process: the woken
988
+ // turn gets them back, and the runner is left with nothing to start.
989
+ const interrupts = [];
990
+ for (const queued of session.runner.queue.drainAll()) {
991
+ if (queued.deliveryMode === 'interrupt') {
992
+ interrupts.push(queued);
993
+ continue;
994
+ }
995
+ await keepForLater(session, record, queued);
996
+ }
997
+ // An interrupt replaces the turn, parked or not: it stays for the runner to start.
998
+ for (const interrupt of interrupts.reverse()) {
999
+ session.runner.queue.prepend(interrupt);
1000
+ }
1001
+ const until = Number.isFinite(wakeAt) ? wakeAt : undefined;
1002
+ await record.park(ctx, until);
1003
+ await this.#connections.release(ctx.id);
1004
+ this.parkWatchers?.watch(threadId, {
1005
+ executionId: ctx.id,
1006
+ until,
1007
+ options: session.turnOptions ?? {},
1008
+ });
1009
+ // Before the turn answers as parked: whoever wakes it has to know when.
1010
+ await this.announceWakeTime();
1011
+ return true;
1012
+ };
1013
+ const runTurn = async (ctx, signal) => {
1014
+ if (!this.agentGraph) {
1015
+ await this.#connections.release(ctx.id);
1016
+ throw new NoeticConfigError({
1017
+ code: 'NO_STEP_CONFIGURED',
1018
+ message: 'No agentGraph configured on this harness.',
1019
+ hint: 'Pass `agentGraph` in constructor options.',
1020
+ });
1021
+ }
1022
+ // Wire signal-abort to context-abort so the interpreter bails cleanly.
1023
+ if (signal.aborted) {
1024
+ ctx.abort(signal.reason ? String(signal.reason) : 'aborted');
1025
+ }
1026
+ else {
1027
+ signal.addEventListener('abort', () => {
1028
+ ctx.abort(signal.reason ? String(signal.reason) : 'aborted');
1029
+ }, {
1030
+ once: true,
1031
+ });
1032
+ }
1033
+ const result = await this.initAndRun(this.agentGraph, '', ctx).catch(async (error) => {
1034
+ // An interrupted turn restarts from what it finished, so the
1035
+ // interrupting message lands after the work it interrupted.
1036
+ if (ctx.abortReason === INTERRUPT_REASON) {
1037
+ await keepHistory(ctx);
1038
+ }
1039
+ // A parked turn is not a failed one: its record stays, marked with when
1040
+ // to wake it, and the response says so.
1041
+ if (await closeOutPark(ctx)) {
1042
+ return PARKED;
1043
+ }
1044
+ // The turn ended here, in a live process. Say so, or a routine wake would
1045
+ // take it for one cut off by a crash and run it again, every time.
1046
+ // It stopped rather than redo a recorded effect under a newer flow version:
1047
+ // it waits, marked, for the host to settle it.
1048
+ const stuck = stuckOf(error);
1049
+ if (record && stuck) {
1050
+ await record.stick(ctx, stuck);
1051
+ await this.announceWakeTimeQuietly();
1052
+ throw error;
1053
+ }
1054
+ // A harness that was replaced says nothing about the turn: it is the new
1055
+ // holder's now, and marking it stopped would keep a wake from resuming it.
1056
+ const replaced = isLeaseLost(error) || session.lease?.lost === true;
1057
+ if (ctx.aborted && !replaced && ctx.abortReason !== INTERRUPT_REASON) {
1058
+ await heldCallsOf(this).clear(ctx.id);
1059
+ }
1060
+ if (record && !replaced && ctx.abortReason !== INTERRUPT_REASON) {
1061
+ await record.stop(ctx, error instanceof Error ? error.message : String(error), this.now());
1062
+ }
1063
+ await this.announceWakeTimeQuietly();
1064
+ throw error;
1065
+ });
1066
+ // A flow that caught the wait's cancellation and returned is parked all the
1067
+ // same: the wait it was in has not ended, and the woken turn goes back to it.
1068
+ if (result === PARKED || (await closeOutPark(ctx))) {
1069
+ return '';
1070
+ }
1071
+ await keepHistory(ctx, result);
1072
+ this.parkWatchers?.forget(threadId, ctx.id);
1073
+ await this.announceWakeTimeQuietly();
1074
+ return result;
1075
+ };
615
1076
  this.sessions.set(threadId, session);
616
1077
  if (record) {
617
1078
  void record.usage().then((usage) => session.runner.seedUsage(usage));
618
1079
  }
619
1080
  return session;
620
1081
  }
1082
+ /**
1083
+ * Resume turns that are parked or were cut off (spec 23 § Parked turns).
1084
+ *
1085
+ * With no `threadId`, every stored thread is looked at: a parked turn is resumed
1086
+ * once its wake time has come, and a cut-off turn at once. With a `threadId`, that
1087
+ * thread's turn is resumed whether or not it is due — the call a host makes when
1088
+ * it knows the event a parked turn waits for has arrived. A turn another harness
1089
+ * holds, or one already running here, is left alone.
1090
+ *
1091
+ * A resumed turn replays what it finished and goes on. `options` are the
1092
+ * `execute()` options it runs with; a stored turn keeps none of its own.
1093
+ *
1094
+ * Resolves the ids of the threads it resumed. Durable sessions only.
1095
+ * @public
1096
+ */
1097
+ async wake(scope) {
1098
+ if (!this.sessionStore) {
1099
+ return [];
1100
+ }
1101
+ const now = this.now();
1102
+ const threadIds = scope?.threadId
1103
+ ? [
1104
+ scope.threadId,
1105
+ ]
1106
+ : await this.sessionStore.threads();
1107
+ const woken = [];
1108
+ for (const threadId of threadIds) {
1109
+ // A turn asked for by name may be closing out its park this instant: its
1110
+ // runner is busy, though nothing is running. Wait for it rather than skip.
1111
+ const closing = scope?.threadId ? this.sessions.get(threadId)?.runner : undefined;
1112
+ if (closing && closing.context === undefined) {
1113
+ await closing.whenIdle();
1114
+ }
1115
+ const turn = (await this.sessionStore.load(threadId))?.turn;
1116
+ // A stuck turn waits for the host to settle it, however the wake was asked for.
1117
+ if (!turn || turn.stuck) {
1118
+ continue;
1119
+ }
1120
+ // A routine wake leaves alone a parked turn that is not due, one with no
1121
+ // deadline at all (it waits for an answer, not for a time), and one that
1122
+ // failed or was cancelled here: only a turn cut off by a crash resumes unasked.
1123
+ const notDue = turn.parked && (turn.parked.until === undefined || turn.parked.until > now);
1124
+ if (!scope?.threadId && (notDue || (turn.stopped && !turn.parked))) {
1125
+ // A parked turn found in storage, as at boot, is watched over from here on.
1126
+ if (turn.parked && this.parkWatchers && !this.parkWatchers.has(threadId)) {
1127
+ this.parkWatchers.watch(threadId, {
1128
+ executionId: turn.executionId,
1129
+ until: turn.parked.until,
1130
+ options: scope?.options ?? {},
1131
+ });
1132
+ }
1133
+ continue;
1134
+ }
1135
+ const session = this.getOrCreateSession(threadId);
1136
+ if (session.runner.getStatus().kind !== 'idle' || session.runner.queue.size > 0) {
1137
+ continue;
1138
+ }
1139
+ // A routine wake leaves a turn another harness holds for a later pass. One
1140
+ // asked for by name goes ahead: taking the lease waits for the holder's to
1141
+ // run out, and if it does not, that is an error the caller hears about.
1142
+ const held = this.leaseOptions && (await heldElsewhere(this.leaseOptions, threadId));
1143
+ if (held && !scope?.threadId) {
1144
+ continue;
1145
+ }
1146
+ // Re-deliver the turn's own messages: the same ids resume it, and a resumed
1147
+ // turn reads its input from its checkpoint, not from these. They go back as
1148
+ // one arrival: handed over one at a time, the first would start a turn of
1149
+ // its own and that turn would not be this one.
1150
+ session.runner.queue.enqueueAll(turn.messageIds.map((id) => ({
1151
+ id,
1152
+ input: [],
1153
+ deliveryMode: 'next-turn',
1154
+ options: scope?.options ?? {},
1155
+ enqueuedAt: Date.now(),
1156
+ })));
1157
+ woken.push(threadId);
1158
+ }
1159
+ return woken;
1160
+ }
1161
+ /**
1162
+ * The earliest time the harness has something to do, in epoch ms: a parked turn
1163
+ * that needs waking, or the next event of a scheduled source a trigger listens
1164
+ * to (`cron()`). Undefined when there is neither. A host with no process of its
1165
+ * own between events (a serverless worker) schedules its next `start()` and
1166
+ * `wake()` from this.
1167
+ * @public
1168
+ */
1169
+ async getNextWakeTime() {
1170
+ let earliest = await this.#connections.triggers.nextDue();
1171
+ if (!this.sessionStore) {
1172
+ return earliest;
1173
+ }
1174
+ const now = this.now();
1175
+ for (const threadId of await this.sessionStore.threads()) {
1176
+ const due = await this.turnDueAt(threadId, now);
1177
+ if (due !== undefined) {
1178
+ earliest = earliest === undefined ? due : Math.min(earliest, due);
1179
+ }
1180
+ }
1181
+ return earliest;
1182
+ }
1183
+ /**
1184
+ * When a routine `wake()` would have something to do for the thread's turn: a
1185
+ * parked turn at its deadline, a turn cut off by a crash at once. Never before
1186
+ * another harness's lease on it runs out, since a wake before then does nothing.
1187
+ * Undefined for a turn that waits on something other than time, and one that is
1188
+ * stuck or stopped. A turn this harness is running is due one lease period from
1189
+ * now: the time to come back if the process running it is gone.
1190
+ */
1191
+ async turnDueAt(threadId, now) {
1192
+ const turn = (await this.sessionStore?.load(threadId))?.turn;
1193
+ if (!turn || turn.stuck || (turn.stopped && !turn.parked)) {
1194
+ return undefined;
1195
+ }
1196
+ if (turn.parked && turn.parked.until === undefined) {
1197
+ return undefined;
1198
+ }
1199
+ // A turn with no park on record is cut off, unless it is simply running here.
1200
+ // (One that is parked may still be closing out in this process: it counts.)
1201
+ const runner = this.sessions.get(threadId)?.runner;
1202
+ if (!turn.parked && runner && runner.getStatus().kind !== 'idle') {
1203
+ // Running here. Should this process die, the turn is cut off, and it can be
1204
+ // picked up once the lease it held has run out: that is when to look again.
1205
+ // The turn ending, or parking, replaces this time with the real one.
1206
+ return this.leaseOptions ? now + this.leaseOptions.ttlMs + LEASE_WAIT_MARGIN_MS : undefined;
1207
+ }
1208
+ const due = turn.parked?.until ?? now;
1209
+ const heldUntil = this.leaseOptions
1210
+ ? await heldElsewhereUntil(this.leaseOptions, threadId)
1211
+ : undefined;
1212
+ return heldUntil === undefined ? due : Math.max(due, heldUntil);
1213
+ }
1214
+ /**
1215
+ * The tool calls a thread's turn holds for a person (spec 08 § Held tool calls):
1216
+ * calls waiting for approval, and calls whose tool left its result open. Each
1217
+ * carries what a decision needs to answer it.
1218
+ * @public
1219
+ */
1220
+ async pending(scope) {
1221
+ const executionId = await this.heldExecutionId(scope);
1222
+ if (executionId === undefined) {
1223
+ return [];
1224
+ }
1225
+ const records = await heldCallsOf(this).list(executionId);
1226
+ return records.filter((record) => record.resolution === undefined).map(toHeldCall);
1227
+ }
1228
+ /**
1229
+ * Answer a held tool call: a decision for one that waits for approval, an output
1230
+ * for one that waits for its result. The turn then goes on — at once when it is
1231
+ * running here, and by being woken when it is parked.
1232
+ *
1233
+ * `scope` names the thread, or with `{ executionId }` an execution a host runs
1234
+ * itself through `harness.run()`.
1235
+ *
1236
+ * The first answer wins. The same answer again is a no-op, so a host may retry.
1237
+ * Pass the `argsHash` the call was shown with to make sure the answer is for it.
1238
+ *
1239
+ * @throws NoeticError `hold_refused` when the thread holds no such call,
1240
+ * `argsHash` names different arguments, the answer is the wrong kind for the
1241
+ * hold, or the call was already answered differently.
1242
+ * @internal Hosts answer through `execute()` with a `DecisionItem`, which
1243
+ * carries an `executionId` for a call held by a run the host started itself.
1244
+ * This is what that calls.
1245
+ */
1246
+ async resolveHeld(scope, answer, options) {
1247
+ const executionId = await this.heldExecutionId(scope);
1248
+ if (executionId === undefined) {
1249
+ throw new NoeticErrorImpl({
1250
+ kind: 'hold_refused',
1251
+ callId: answer.callId,
1252
+ reason: 'the thread has no turn holding a call',
1253
+ });
1254
+ }
1255
+ const { callId, argsHash, ...resolution } = answer;
1256
+ await heldCallsOf(this).resolve(executionId, {
1257
+ callId,
1258
+ argsHash,
1259
+ resolution,
1260
+ });
1261
+ // A turn running here was told; a parked one has to be resumed. An execution
1262
+ // the host runs itself is the host's to resume.
1263
+ if (scope && 'executionId' in scope) {
1264
+ return;
1265
+ }
1266
+ const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
1267
+ const runner = this.sessions.get(threadId)?.runner;
1268
+ if (runner?.context === undefined) {
1269
+ await this.wake({
1270
+ threadId,
1271
+ options,
1272
+ });
1273
+ return;
1274
+ }
1275
+ // The turn is running here and was told. But it may have been parking as the
1276
+ // answer landed, too late to hear it: once it has come to rest, look again.
1277
+ void runner
1278
+ .whenIdle()
1279
+ .then(async () => {
1280
+ if ((await this.sessionStore?.load(threadId))?.turn?.parked) {
1281
+ await this.wake({
1282
+ threadId,
1283
+ options,
1284
+ });
1285
+ }
1286
+ })
1287
+ .catch(() => undefined);
1288
+ }
1289
+ //#region Versions and the trail
1290
+ /**
1291
+ * The turns that stopped rather than redo a step that had a lasting effect under
1292
+ * another flow version (spec 23 § Versions). Each waits for a `DecisionItem`
1293
+ * with `continue`, `restart` or `abandon`, passed to `execute()` on its thread.
1294
+ * @public
1295
+ */
1296
+ async listStuckRuns() {
1297
+ if (!this.sessionStore) {
1298
+ return [];
1299
+ }
1300
+ const found = [];
1301
+ for (const threadId of await this.sessionStore.threads()) {
1302
+ const turn = (await this.sessionStore.load(threadId))?.turn;
1303
+ if (!turn?.stuck) {
1304
+ continue;
1305
+ }
1306
+ found.push({
1307
+ threadId,
1308
+ executionId: turn.executionId,
1309
+ ...turn.stuck,
1310
+ });
1311
+ }
1312
+ return found;
1313
+ }
1314
+ /**
1315
+ * Settle a stuck turn (spec 23 § Versions). Resolves false when the thread has none.
1316
+ *
1317
+ * - `continue`: accept the difference. The turn resumes on this harness's
1318
+ * version, and the step that no longer matches runs again.
1319
+ * - `restart`: forget what the turn recorded and run it from the top on this
1320
+ * harness's version. Every step runs again, effects included.
1321
+ * - `abandon`: drop the turn. Its trail is kept.
1322
+ */
1323
+ async settleStuckTurn(threadId, action, options) {
1324
+ const record = this.threadRecord(threadId);
1325
+ const turn = await record?.settle(action);
1326
+ if (!turn) {
1327
+ return false;
1328
+ }
1329
+ if (action === 'abandon') {
1330
+ await this.clearCheckpoint(turn.executionId);
1331
+ return true;
1332
+ }
1333
+ if (action === 'restart') {
1334
+ // The snapshot stays: it holds the turn's input. What the run recorded goes.
1335
+ // What the first run did still happened: its marks go on the trail first.
1336
+ const store = this.stepLedgerStore;
1337
+ if (store) {
1338
+ const { entries, seqs } = await store.load(turn.executionId);
1339
+ for (const [path, entry] of entries) {
1340
+ const seq = seqs.get(path);
1341
+ if (seq !== undefined) {
1342
+ await store.mark(turn.executionId, seq, stubOf(entry));
1343
+ }
1344
+ }
1345
+ await store.clear(turn.executionId);
1346
+ }
1347
+ await heldCallsOf(this).clear(turn.executionId);
1348
+ if (this.config.storage) {
1349
+ await clearPendingEntries(this.config.storage, turn.executionId);
1350
+ }
1351
+ }
1352
+ await this.wake({
1353
+ threadId,
1354
+ options,
1355
+ });
1356
+ return true;
1357
+ }
1358
+ /**
1359
+ * What a run did, step by step: who ran each step, under which flow version, and
1360
+ * the receipt of a step with a lasting effect (spec 23 § The trail). Marks outlive
1361
+ * the ledger entries they came from, so the trail of a finished run stays readable.
1362
+ *
1363
+ * `scope` names an execution, or a thread, whose recent turns are then listed in
1364
+ * order.
1365
+ * @public
1366
+ */
1367
+ async getAuditTrail(scope) {
1368
+ const store = this.stepLedgerStore;
1369
+ if (!store) {
1370
+ return [];
1371
+ }
1372
+ const executionIds = 'executionId' in scope
1373
+ ? [
1374
+ scope.executionId,
1375
+ ]
1376
+ : ((await this.threadRecord(scope.threadId ?? DEFAULT_THREAD_ID)?.executions()) ?? []);
1377
+ const marks = [];
1378
+ for (const executionId of executionIds) {
1379
+ const kept = await store.trail(executionId);
1380
+ const live = [
1381
+ ...(await store.load(executionId)).entries.values(),
1382
+ ].map(stubOf);
1383
+ for (const mark of [
1384
+ ...kept,
1385
+ ...live,
1386
+ ]) {
1387
+ marks.push({
1388
+ executionId,
1389
+ ...mark,
1390
+ });
1391
+ }
1392
+ }
1393
+ return marks;
1394
+ }
1395
+ //#endregion
1396
+ //#region Triggers
1397
+ /**
1398
+ * Add a trigger while the harness runs (spec 35 § Triggers). A trigger written
1399
+ * with expressions only is kept in storage, so it is there again after a restart;
1400
+ * one with a function in it lasts for this process.
1401
+ *
1402
+ * @throws NoeticConfigError `CONNECTION_INVALID` for an id already in use, a
1403
+ * missing event or an expression that does not parse; `CONNECTION_UNKNOWN` for
1404
+ * an unknown connection.
1405
+ * @public
1406
+ */
1407
+ async addTrigger(trigger) {
1408
+ await this.start();
1409
+ await this.#connections.triggers.add(trigger);
1410
+ await this.announceWakeTimeQuietly();
1411
+ }
1412
+ /**
1413
+ * Stop and forget a trigger. Resolves false when there is none with that id.
1414
+ * @public
1415
+ */
1416
+ async removeTrigger(id) {
1417
+ // Started first, so a trigger kept from an earlier run is known to be there.
1418
+ await this.#connections.start();
1419
+ const removed = await this.#connections.triggers.remove(id);
1420
+ await this.announceWakeTimeQuietly();
1421
+ return removed;
1422
+ }
1423
+ /**
1424
+ * Every trigger the harness has: its own, and those added while it ran.
1425
+ * @public
1426
+ */
1427
+ listTriggers() {
1428
+ return this.#connections.triggers.list();
1429
+ }
1430
+ //#endregion
1431
+ /** The watchers that wake this harness's parked turns, when auto-wake is on. */
1432
+ createParkWatchers(park) {
1433
+ if (this.parkGraceMs === undefined) {
1434
+ return undefined;
1435
+ }
1436
+ const config = park === true || park === undefined || park === false ? {} : park;
1437
+ if (config.autoWake === false) {
1438
+ return undefined;
1439
+ }
1440
+ const storage = this.config.storage;
1441
+ return new ParkWatchers({
1442
+ listen: async (connection, request) => {
1443
+ await this.start();
1444
+ return this.#connections.registry.listenRaw(connection, request);
1445
+ },
1446
+ waits: async (executionId) => (storage ? resumableWaitsOf(storage, executionId) : []),
1447
+ tasks: async (executionId) => (storage ? pendingTasksOf(storage, executionId) : []),
1448
+ taskState: async (task, signal) => {
1449
+ try {
1450
+ await this.start();
1451
+ const status = await this.#connections.registry.taskStatus(task.connection, task.taskId, signal);
1452
+ return status.state;
1453
+ }
1454
+ catch {
1455
+ return undefined;
1456
+ }
1457
+ },
1458
+ wake: async (threadId, options) => (await this.wake({
1459
+ threadId,
1460
+ options,
1461
+ })).length > 0,
1462
+ parked: async (threadId) => {
1463
+ const turn = (await this.sessionStore?.load(threadId))?.turn;
1464
+ return turn?.parked && !turn.stuck ? turn.executionId : undefined;
1465
+ },
1466
+ now: () => this.now(),
1467
+ }, config.wakeDebounceMs ?? DEFAULT_WAKE_DEBOUNCE_MS, config.taskPollMs ?? DEFAULT_TASK_POLL_MS);
1468
+ }
1469
+ /**
1470
+ * Messages that reached the runner while the thread's turn is parked or stuck
1471
+ * (one that landed as the turn was closing out, say). Starting a turn with them
1472
+ * would throw the waiting one away, so they are kept in storage for after it. A
1473
+ * steer wakes a parked turn, as one delivered a moment later would. An
1474
+ * `interrupt` is not set aside: replacing the turn is what it asks for.
1475
+ * Resolves true when the messages were set aside.
1476
+ */
1477
+ async setAside(session, record, messages) {
1478
+ const turn = await record.turn();
1479
+ if (!turn || (!turn.parked && !turn.stuck)) {
1480
+ return false;
1481
+ }
1482
+ if (messages.some((message) => message.deliveryMode === 'interrupt')) {
1483
+ return false;
1484
+ }
1485
+ if (messages.every((message) => turn.messageIds.includes(message.id))) {
1486
+ return false;
1487
+ }
1488
+ for (const message of messages) {
1489
+ if (!turn.messageIds.includes(message.id)) {
1490
+ await keepForLater(session, record, message);
1491
+ }
1492
+ }
1493
+ if (turn.parked && messages.some(isSteer)) {
1494
+ const { threadId } = session.runner;
1495
+ void session.runner.whenIdle().then(() => this.wake({
1496
+ threadId,
1497
+ options: messages[0]?.options,
1498
+ }));
1499
+ }
1500
+ return true;
1501
+ }
1502
+ /** Resume a parked turn when one of its held calls already has an answer. */
1503
+ async wakeIfAnswered(threadId, executionId) {
1504
+ const records = await heldCallsOf(this).list(executionId);
1505
+ if (!records.some((record) => record.resolution !== undefined)) {
1506
+ return;
1507
+ }
1508
+ // The runner is still closing the parked turn out; let it go idle first.
1509
+ await this.sessions.get(threadId)?.runner.whenIdle();
1510
+ await this.wake({
1511
+ threadId,
1512
+ });
1513
+ }
1514
+ /**
1515
+ * A message delivered again after its turn finished (spec 23a § Sessions): a queue
1516
+ * that delivers at least once, or a webhook the sender retried. It is answered
1517
+ * with the answer that turn gave, and nothing runs. Resolves true when it was.
1518
+ */
1519
+ async answerAgain(session, message) {
1520
+ const record = session.record;
1521
+ if (!record || session.runner.getStatus().kind !== 'idle' || session.runner.queue.size > 0) {
1522
+ return false;
1523
+ }
1524
+ const text = await record.answerFor(message.id);
1525
+ if (text === undefined) {
1526
+ return false;
1527
+ }
1528
+ session.runner.answerWith({
1529
+ items: await record.history(),
1530
+ usage: {
1531
+ inputTokens: 0,
1532
+ outputTokens: 0,
1533
+ },
1534
+ text,
1535
+ replayed: true,
1536
+ }, message.id);
1537
+ return true;
1538
+ }
1539
+ /**
1540
+ * A message delivered again while this harness already has it in hand: its turn is
1541
+ * running, it is queued to run, or its turn finished a moment ago and the runner
1542
+ * has not gone idle yet (spec 23a § Sessions). Queuing it would run the same
1543
+ * message as a second turn once the first ends. It is dropped; the caller reads
1544
+ * the answer of the turn that has it. Resolves true when it was.
1545
+ */
1546
+ async inHand(session, message) {
1547
+ if (message.deliveryMode === 'interrupt') {
1548
+ return false;
1549
+ }
1550
+ const { runner, record } = session;
1551
+ if (runner.getStatus().kind === 'idle' && runner.queue.size === 0) {
1552
+ return false;
1553
+ }
1554
+ if (runner.queue.peekAll().some((queued) => queued.id === message.id)) {
1555
+ return true;
1556
+ }
1557
+ // Known from the first instant of the turn, before its record is written and
1558
+ // on a harness with no storage at all.
1559
+ if (runner.isRunning(message.id)) {
1560
+ return true;
1561
+ }
1562
+ if (!record) {
1563
+ return false;
1564
+ }
1565
+ if ((await record.turn())?.messageIds.includes(message.id)) {
1566
+ return true;
1567
+ }
1568
+ if ((await record.answerFor(message.id)) === undefined) {
1569
+ return false;
1570
+ }
1571
+ // Its turn finished earlier, and another is running now. It is not run again,
1572
+ // and it is not left unanswered: once the thread rests it is delivered again,
1573
+ // and answered from the record then (`turn_replayed` carries the answer).
1574
+ void runner
1575
+ .whenIdle()
1576
+ .then(() => this.deliver(session, message))
1577
+ .catch(() => undefined);
1578
+ return true;
1579
+ }
1580
+ /**
1581
+ * A message for a thread whose turn is parked (spec 23 § Parked turns). It must not
1582
+ * start a turn of its own: the thread has one in flight, and starting another would
1583
+ * abandon it. Resolves true when the message was taken care of here.
1584
+ *
1585
+ * - `next-turn` waits in storage for the parked turn to end.
1586
+ * - A steer wakes the turn, which offers it to the context layers as it would mid-round.
1587
+ * - `interrupt` is not handled here: it replaces the turn, as it does a running one.
1588
+ */
1589
+ async deliverToParked(session, message) {
1590
+ const record = session.record;
1591
+ if (!record || message.deliveryMode === 'interrupt') {
1592
+ return false;
1593
+ }
1594
+ if (session.runner.getStatus().kind !== 'idle' || session.runner.queue.size > 0) {
1595
+ return false;
1596
+ }
1597
+ const turn = await record.turn();
1598
+ if (!turn?.parked || turn.messageIds.includes(message.id)) {
1599
+ return false;
1600
+ }
1601
+ await keepForLater(session, record, message);
1602
+ if (isSteer(message)) {
1603
+ await this.wake({
1604
+ threadId: session.runner.threadId,
1605
+ options: message.options,
1606
+ });
1607
+ }
1608
+ return true;
1609
+ }
1610
+ /** The execution whose held calls `scope` names. */
1611
+ heldExecutionId(scope) {
1612
+ if (scope && 'executionId' in scope) {
1613
+ return Promise.resolve(scope.executionId);
1614
+ }
1615
+ return this.turnExecutionId(scope?.threadId ?? DEFAULT_THREAD_ID);
1616
+ }
1617
+ /** The execution of the thread's turn in flight: running here, or stored. */
1618
+ async turnExecutionId(threadId) {
1619
+ const running = this.sessions.get(threadId)?.runner.context;
1620
+ if (running) {
1621
+ return rootIdOf(running);
1622
+ }
1623
+ return (await this.sessionStore?.load(threadId))?.turn?.executionId;
1624
+ }
1625
+ /** The harness clock. */
1626
+ now() {
1627
+ return this.config.now?.() ?? Date.now();
1628
+ }
1629
+ /** Hand the turn's lease back and return the thread record to best-effort writes. */
1630
+ async releaseLease(session) {
1631
+ const lease = session.lease;
1632
+ session.lease = undefined;
1633
+ session.record?.hold(undefined);
1634
+ await lease?.release();
1635
+ }
621
1636
  /** The stored record for `threadId`, when durability is on. */
622
1637
  threadRecord(threadId) {
623
1638
  if (!this.sessionStore) {
@@ -625,6 +1640,7 @@ export class AgentHarness {
625
1640
  }
626
1641
  return new ThreadRecord({
627
1642
  store: this.sessionStore,
1643
+ version: this.version,
628
1644
  restore: (executionId, opts) => this.restore(executionId, opts),
629
1645
  clearCheckpoint: (executionId) => this.clearCheckpoint(executionId),
630
1646
  parseItems: (raw) => this.itemSchemas.parseMany(raw),
@@ -654,6 +1670,33 @@ export class AgentHarness {
654
1670
  async decide(request) {
655
1671
  return this.llm.decide(request, (r) => this.callModel(r));
656
1672
  }
1673
+ /**
1674
+ * The approval seam (spec 08 § Held tool calls): the `approveToolCall` approver
1675
+ * decides, and with none, or when it answers `hold`, the action is held until
1676
+ * a decision answers it. Resolves the settled decision.
1677
+ * @public
1678
+ */
1679
+ async approve(request) {
1680
+ const approval = await awaitApproval({
1681
+ harness: this,
1682
+ toolName: request.toolName,
1683
+ toolArgs: request.toolArgs,
1684
+ callId: request.callId,
1685
+ ctx: request.ctx,
1686
+ park: request.park,
1687
+ onHeld: (held) => {
1688
+ emitFrameworkEvent({
1689
+ broadcaster: getBroadcaster(request.ctx),
1690
+ agentName: this.config.name,
1691
+ eventType: 'tool_call_held',
1692
+ data: {
1693
+ ...held,
1694
+ },
1695
+ });
1696
+ },
1697
+ });
1698
+ return approval.decision;
1699
+ }
657
1700
  async notifyDecision(layers, record, ctx) {
658
1701
  await this.trackHook(ctx, notifyDecision({
659
1702
  layers,
@@ -953,6 +1996,14 @@ export class AgentHarness {
953
1996
  * can be keyed to it — the ledger's storage keys and `ctx.id` must agree for a
954
1997
  * later `restore()` to find what this run recorded. */
955
1998
  const executionId = crypto.randomUUID();
1999
+ const ledger = this.stepLedgerStore
2000
+ ? new StepLedger({
2001
+ executionId,
2002
+ store: this.stepLedgerStore,
2003
+ retention: this.stepLedgerRetention,
2004
+ })
2005
+ : undefined;
2006
+ ledger?.runAs(this.version);
956
2007
  return new ContextImpl({
957
2008
  ...rest,
958
2009
  id: executionId,
@@ -964,13 +2015,7 @@ export class AgentHarness {
964
2015
  // Without this `ctx.checkpoint()` is inert, and the boundaries below never
965
2016
  // persist anything (a no-op when no CheckpointStore is configured).
966
2017
  checkpointFn: (c) => this.checkpoint(c),
967
- ledger: this.stepLedgerStore
968
- ? new StepLedger({
969
- executionId,
970
- store: this.stepLedgerStore,
971
- retention: this.stepLedgerRetention,
972
- })
973
- : undefined,
2018
+ ledger,
974
2019
  });
975
2020
  }
976
2021
  send(channel, value, ctx) {
@@ -1202,7 +2247,13 @@ export class AgentHarness {
1202
2247
  */
1203
2248
  saveCheckpoint(ctx) {
1204
2249
  const prior = this.pendingCheckpoints.get(ctx.id);
1205
- const next = (prior ?? Promise.resolve(true)).then(() => captureCheckpoint(this, ctx));
2250
+ const next = (prior ?? Promise.resolve(true)).then(() => {
2251
+ // A harness that was replaced must not overwrite the new holder's snapshot.
2252
+ if (ctx instanceof ContextImpl && ctx.ledger?.isHeld === false) {
2253
+ return false;
2254
+ }
2255
+ return captureCheckpoint(this, ctx);
2256
+ });
1206
2257
  this.pendingCheckpoints.set(ctx.id, next);
1207
2258
  void next.finally(() => {
1208
2259
  if (this.pendingCheckpoints.get(ctx.id) === next) {
@@ -1245,6 +2296,10 @@ export class AgentHarness {
1245
2296
  if (restored.fromSnapshot) {
1246
2297
  this.restoredExecutions.add(executionId);
1247
2298
  }
2299
+ // The restored ledger is a new one: it records under this harness's version too.
2300
+ if (restored.ctx instanceof ContextImpl) {
2301
+ restored.ctx.ledger?.runAs(this.version);
2302
+ }
1248
2303
  await this.spend?.adopt(restored.ctx);
1249
2304
  // Granted only to the context this restore returns: a restore that fails, or a
1250
2305
  // later plain restore of the same id, never inherits it (spec 35 § Durability).
@@ -1267,7 +2322,13 @@ export class AgentHarness {
1267
2322
  * behind, and nothing else enumerates them.
1268
2323
  */
1269
2324
  async clearCheckpoint(executionId) {
1270
- return clearCheckpoint(this, executionId);
2325
+ await clearCheckpoint(this, executionId);
2326
+ // Calls the execution held for a person have nobody left to answer to.
2327
+ await heldCallsOf(this).clear(executionId);
2328
+ // Nor is anything left to pick up what its steps were waiting on.
2329
+ if (this.config.storage) {
2330
+ await clearPendingEntries(this.config.storage, executionId);
2331
+ }
1271
2332
  }
1272
2333
  //#endregion
1273
2334
  //#region Spend