@noetic-tools/core 5.13.0 → 6.0.0

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.
@@ -19,16 +19,18 @@ export interface StorageEnvironmentConfig {
19
19
  adapter?: StorageAdapter;
20
20
  /**
21
21
  * Checkpoint store used by `harness.checkpoint(ctx)` / `harness.restore()`.
22
- * When absent, checkpoint/restore are no-ops — a zero-config harness keeps
23
- * its current ephemeral semantics. Construct with `createCheckpointStore`
24
- * to enable durable execution.
22
+ * Defaults to a store over `adapter` when one is given, so configuring durable
23
+ * storage is enough for a later harness on the same storage to resume this one's
24
+ * executions (see the harness `durability` option to turn that off). With no
25
+ * adapter and no store, checkpoint/restore are no-ops — a zero-config harness keeps
26
+ * its ephemeral semantics.
25
27
  */
26
28
  checkpointStore?: CheckpointStore;
27
29
  /** Layer-state store override. Defaults to an in-memory store. */
28
30
  layerStateStore?: LayerStateStore;
29
31
  /**
30
32
  * Bounds on the step-completion ledger that backs step-level resume. Only meaningful
31
- * alongside a `checkpointStore`. Defaults to `DEFAULT_STEP_LEDGER_RETENTION` — 128 KiB
33
+ * when durability is on (a `checkpointStore`, given or defaulted). Defaults to `DEFAULT_STEP_LEDGER_RETENTION` — 128 KiB
32
34
  * per entry, 1000 entries per execution — so an unbounded run cannot grow an unbounded
33
35
  * ledger. Exceeding either cap costs resumability for the affected steps (they re-run),
34
36
  * never correctness.
@@ -57,6 +59,14 @@ interface AgentHarnessOpts<TParams extends Record<string, unknown> = Record<stri
57
59
  agentGraph?: Step<ContextData, string, string>;
58
60
  /** Default context layers applied to every context created via `createContext()` / `execute()`. */
59
61
  contextLayers?: ContextLayer[];
62
+ /**
63
+ * Whether runs and sessions are durable: checkpointed, recorded to the step ledger,
64
+ * and resumable on a later harness over the same storage. Defaults to true whenever
65
+ * `environment.storage` gives an adapter or a checkpoint store. `false` turns every
66
+ * durability surface off even then — the adapter still backs context-layer
67
+ * persistence.
68
+ */
69
+ durability?: boolean;
60
70
  hooks?: AgentHooks;
61
71
  /**
62
72
  * Harness-wide tool pool. Merged (identity-deduplicated) with tools
@@ -147,7 +157,8 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
147
157
  readonly checkpointStore?: CheckpointStore;
148
158
  /**
149
159
  * Append-only step ledger backing resume. Present exactly when durability is on
150
- * (a `CheckpointStore` is configured), so a zero-config harness records nothing.
160
+ * (a `CheckpointStore` is configured or defaulted), so a zero-config harness records
161
+ * nothing.
151
162
  * @internal
152
163
  */
153
164
  readonly stepLedgerStore?: StepLedgerStore;
@@ -177,6 +188,10 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
177
188
  * re-entrant run depth — see `executeClosingChannels`.
178
189
  */
179
190
  private readonly liveRoots;
191
+ /** Stored sessions for `execute()` threads. Present exactly when durability is on. */
192
+ private readonly sessionStore?;
193
+ /** Checkpoint capture in flight per execution id — see `saveCheckpoint`. */
194
+ private readonly pendingCheckpoints;
180
195
  private readonly callModelOverride?;
181
196
  private readonly defaultDeliveryMode;
182
197
  private readonly sessions;
@@ -268,6 +283,8 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
268
283
  getUsage(scope?: SessionScope): SessionUsage;
269
284
  seedSessionHistory(threadId: string, items: ReadonlyArray<Item>): void;
270
285
  private getOrCreateSession;
286
+ /** The stored record for `threadId`, when durability is on. */
287
+ private threadRecord;
271
288
  private requireSession;
272
289
  callModel(request: CallModelRequest): Promise<LLMResponse>;
273
290
  decide(request: DecideRequest): Promise<DecideResponse>;
@@ -292,6 +309,29 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
292
309
  * close anything.
293
310
  */
294
311
  private executeClosingChannels;
312
+ /**
313
+ * Fix the point a resume of this run starts from, and queue it for saving — so even
314
+ * a run whose first step dies leaves a snapshot to restore. The save is not awaited:
315
+ * the steps' own checkpoints queue behind it.
316
+ *
317
+ * When the context's last run never finished, the run repeats it, and it does so
318
+ * from storage — the stored baseline and ledger — exactly as a new harness resuming
319
+ * the execution would, not from what the failed attempt left in memory.
320
+ */
321
+ private beginDurableRun;
322
+ /**
323
+ * Stand `ctx` at its stored baseline and give it the stored ledger. Without a
324
+ * snapshot (its save failed), the baseline the context fixed in memory when the run
325
+ * began is the best record left.
326
+ */
327
+ private rebuildFromStorage;
328
+ /**
329
+ * A finished run is the next run's starting point: persist the live log and counts,
330
+ * then drop the run's positional ledger entries, which no later resume can reach.
331
+ * They are kept when the snapshot failed to land, since that snapshot still points
332
+ * at this run's start. A failed run skips this entirely — it is what a resume repeats.
333
+ */
334
+ private endDurableRun;
295
335
  /**
296
336
  * Idempotently run layer `init` hooks for `ctx` (keyed by `ctx.id`). Init
297
337
  * MUST complete before any recall/store fires so init-bearing layers are not
@@ -371,6 +411,13 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
371
411
  * logic live beside the other durability machinery.
372
412
  */
373
413
  checkpoint(ctx: Context): Promise<void>;
414
+ /**
415
+ * Capture `ctx` behind any capture still in flight for the same execution, and
416
+ * resolve true when this one landed. Every step in the tree checkpoints its root,
417
+ * and concurrent paths would otherwise race their writes: on a networked adapter an
418
+ * older snapshot could land last and win.
419
+ */
420
+ private saveCheckpoint;
374
421
  /**
375
422
  * Rebuild a `Context` from what a previous run of `executionId` recorded: its
376
423
  * checkpoint snapshot, its step-completion ledger, or both. Without a snapshot the
@@ -7,9 +7,10 @@ import { callDecide } from './decide-call.js';
7
7
  import { createInMemoryFsAdapter, createInMemoryShellAdapter, createInMemorySubprocessAdapter, OpenRouter, OpenRouterSdk, } from './deps/adapters.js';
8
8
  import { afterModelCallLayers, allocateBudgets, assembleView, beforeToolCallLayers, completeLayers, contextToExecCtx, createContextCacheStore, createLayerStateStore, createRecallCache, DEFAULT_PROJECTION, disposeLayers, executeRerender, initLayers, notifyDecision, projectHistoryLayers, recallLayers, recallLayersAtomic, recallLayersEventual, resolveLayerTools, runAppendPipeline, storeLayers, } from './deps/context.js';
9
9
  import { collectAllTools, deduplicateTools, dispatchStepThroughAdapter, execute, prepareBandedView, someStep, } from './deps/interpreter.js';
10
- import { buildItemStream, ChannelStore, ContextImpl, captureCheckpoint, clearCheckpoint, collectContextTree, createInMemoryStorage, createStepLedgerStore, filterReasoningStream, filterTextStream, resolveStepLedgerRetention, restoreFromCheckpoint, rootIdOf, SessionRunner, StepLedger, snapshotCwdState, warnToConsole, } from './deps/runtime.js';
10
+ import { buildItemStream, ChannelStore, ContextImpl, captureCheckpoint, clearCheckpoint, collectContextTree, createCheckpointStore, createInMemoryStorage, createSessionStore, createStepLedgerStore, filterReasoningStream, filterTextStream, resolveStepLedgerRetention, restoreFromCheckpoint, rootIdOf, SessionRunner, StepLedger, snapshotCwdState, warnToConsole, } from './deps/runtime.js';
11
11
  import { SteeringAction } from './deps/types.js';
12
12
  import { AgentHarnessModelCaller, noLlmProviderError } from './model-call.js';
13
+ import { ThreadRecord } from './thread-record.js';
13
14
  export { createStreamIdleWatchdog } from './model-call.js';
14
15
  import { buildItemSchemaRegistry } from './model-schema.js';
15
16
  //#endregion
@@ -156,6 +157,24 @@ function createDecisionsClient(config) {
156
157
  serverURL: resolved.serverURL,
157
158
  });
158
159
  }
160
+ /**
161
+ * The checkpoint store a harness runs with: the one given, else a store over the
162
+ * configured storage adapter, so durable storage alone turns resume on. None when
163
+ * the harness sets `durability: false`.
164
+ */
165
+ function resolveCheckpointStore(storage, durability) {
166
+ if (durability === false) {
167
+ return undefined;
168
+ }
169
+ if (storage?.checkpointStore) {
170
+ return storage.checkpointStore;
171
+ }
172
+ return storage?.adapter
173
+ ? createCheckpointStore({
174
+ storage: storage.adapter,
175
+ })
176
+ : undefined;
177
+ }
159
178
  //#region AgentHarness
160
179
  /**
161
180
  * Default agent harness for executing agent steps with built-in channel, context, and trace support.
@@ -180,7 +199,8 @@ export class AgentHarness {
180
199
  checkpointStore;
181
200
  /**
182
201
  * Append-only step ledger backing resume. Present exactly when durability is on
183
- * (a `CheckpointStore` is configured), so a zero-config harness records nothing.
202
+ * (a `CheckpointStore` is configured or defaulted), so a zero-config harness records
203
+ * nothing.
184
204
  * @internal
185
205
  */
186
206
  stepLedgerStore;
@@ -210,6 +230,10 @@ export class AgentHarness {
210
230
  * re-entrant run depth — see `executeClosingChannels`.
211
231
  */
212
232
  liveRoots = new Map();
233
+ /** Stored sessions for `execute()` threads. Present exactly when durability is on. */
234
+ sessionStore;
235
+ /** Checkpoint capture in flight per execution id — see `saveCheckpoint`. */
236
+ pendingCheckpoints = new Map();
213
237
  callModelOverride;
214
238
  defaultDeliveryMode;
215
239
  sessions = new Map();
@@ -311,13 +335,16 @@ export class AgentHarness {
311
335
  this.fs = environment?.fs ?? createInMemoryFsAdapter();
312
336
  this.shell = environment?.shell ?? createInMemoryShellAdapter();
313
337
  this.subprocess = environment?.subprocess ?? createInMemorySubprocessAdapter();
314
- this.checkpointStore = storageEnv?.checkpointStore;
315
- this.stepLedgerStore = storageEnv?.checkpointStore
338
+ this.checkpointStore = resolveCheckpointStore(storageEnv, opts.durability);
339
+ this.stepLedgerStore = this.checkpointStore
316
340
  ? createStepLedgerStore({
317
341
  storage: this.config.storage ?? createInMemoryStorage(),
318
342
  })
319
343
  : undefined;
320
344
  this.stepLedgerRetention = resolveStepLedgerRetention(storageEnv?.stepLedgerRetention);
345
+ this.sessionStore = this.checkpointStore
346
+ ? createSessionStore(this.config.storage ?? createInMemoryStorage())
347
+ : undefined;
321
348
  this.agentGraph = opts.agentGraph;
322
349
  this.harnessTools = opts.tools ?? [];
323
350
  this._contextLayers = opts.contextLayers;
@@ -448,6 +475,11 @@ export class AgentHarness {
448
475
  }
449
476
  seedSessionHistory(threadId, items) {
450
477
  const session = this.getOrCreateSession(threadId);
478
+ if (session.record) {
479
+ // Queued ahead of any turn on this thread, so the next turn reads it back.
480
+ void session.record.seed(items);
481
+ return;
482
+ }
451
483
  session.accumulatedItems = [
452
484
  ...items,
453
485
  ];
@@ -457,8 +489,10 @@ export class AgentHarness {
457
489
  if (existing) {
458
490
  return existing;
459
491
  }
492
+ const record = this.threadRecord(threadId);
460
493
  const session = {
461
494
  accumulatedItems: [],
495
+ record,
462
496
  runner: new SessionRunner({
463
497
  threadId,
464
498
  agentName: this.config.name,
@@ -467,21 +501,29 @@ export class AgentHarness {
467
501
  // together (queue flush), later messages' values for these fields
468
502
  // are ignored. `deliveryMode` is resolved per-message at enqueue
469
503
  // time and doesn't apply here.
470
- createContext: (items, _turnId, messages) => {
504
+ createContext: async (items, _turnId, messages) => {
471
505
  const perTurnOptions = messages[0]?.options ?? {};
472
- const allItems = [
473
- ...session.accumulatedItems,
474
- ...items,
475
- ];
476
- const ctx = this.createContext({
477
- items: allItems,
478
- threadId,
479
- resourceId: perTurnOptions.resourceId,
506
+ const messageIds = messages.map((m) => m.id);
507
+ const history = record ? await record.history() : session.accumulatedItems;
508
+ // A re-delivery of a cut-off turn's messages picks that turn up where it died.
509
+ const resumed = await record?.resume(messageIds, {
480
510
  state: perTurnOptions.state,
481
511
  contextLayers: perTurnOptions.contextLayers,
482
- extraContextLayers: perTurnOptions.extraContextLayers,
483
512
  _broadcaster: session.runner.broadcaster,
484
513
  });
514
+ const ctx = resumed ??
515
+ this.createContext({
516
+ items: [
517
+ ...history,
518
+ ...items,
519
+ ],
520
+ threadId,
521
+ resourceId: perTurnOptions.resourceId,
522
+ state: perTurnOptions.state,
523
+ contextLayers: perTurnOptions.contextLayers,
524
+ extraContextLayers: perTurnOptions.extraContextLayers,
525
+ _broadcaster: session.runner.broadcaster,
526
+ });
485
527
  const ext = frameworkCast(ctx);
486
528
  ext._sessionQueue = session.runner.queue;
487
529
  ext._sessionBetweenRounds = true;
@@ -493,6 +535,7 @@ export class AgentHarness {
493
535
  ...this.harnessTools,
494
536
  ]);
495
537
  }
538
+ await record?.begin(ctx, messageIds);
496
539
  return ctx;
497
540
  },
498
541
  runTurn: async (ctx, _turn, signal) => {
@@ -515,17 +558,42 @@ export class AgentHarness {
515
558
  });
516
559
  }
517
560
  const result = await this.initAndRun(this.agentGraph, '', ctx);
561
+ if (record) {
562
+ await record.end(ctx, ctx.itemLog.items);
563
+ return result;
564
+ }
518
565
  // Snapshot final items into session history for the next turn.
519
566
  session.accumulatedItems = [
520
567
  ...ctx.itemLog.items,
521
568
  ];
522
569
  return result;
523
570
  },
571
+ // Stored totals are the session's usage; the runner only mirrors them.
572
+ onTurnUsage: record
573
+ ? async (spent) => {
574
+ session.runner.seedUsage(await record.addUsage(spent));
575
+ }
576
+ : undefined,
524
577
  }),
525
578
  };
526
579
  this.sessions.set(threadId, session);
580
+ if (record) {
581
+ void record.usage().then((usage) => session.runner.seedUsage(usage));
582
+ }
527
583
  return session;
528
584
  }
585
+ /** The stored record for `threadId`, when durability is on. */
586
+ threadRecord(threadId) {
587
+ if (!this.sessionStore) {
588
+ return undefined;
589
+ }
590
+ return new ThreadRecord({
591
+ store: this.sessionStore,
592
+ restore: (executionId, opts) => this.restore(executionId, opts),
593
+ clearCheckpoint: (executionId) => this.clearCheckpoint(executionId),
594
+ parseItems: (raw) => this.itemSchemas.parseMany(raw),
595
+ }, threadId);
596
+ }
529
597
  requireSession(scope) {
530
598
  const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
531
599
  let session = this.sessions.get(threadId);
@@ -622,27 +690,91 @@ export class AgentHarness {
622
690
  return execute(s, input, ctx);
623
691
  }
624
692
  const live = this.liveRoots.get(ctx.id);
625
- if (!live) {
626
- // A restored or sequentially re-run root context reuses its id — clear
627
- // any closure from a previous completion so its channels work again.
628
- this.channelStore.openExecution(ctx.id);
629
- }
630
693
  const entry = live ?? {
631
694
  ctx,
632
695
  depth: 0,
696
+ failed: false,
697
+ ready: Promise.resolve(),
633
698
  };
634
699
  entry.depth += 1;
635
700
  this.liveRoots.set(ctx.id, entry);
701
+ if (!live) {
702
+ // A restored or sequentially re-run root context reuses its id — clear
703
+ // any closure from a previous completion so its channels work again.
704
+ this.channelStore.openExecution(ctx.id);
705
+ entry.ready = this.beginDurableRun(ctx);
706
+ }
636
707
  try {
708
+ await entry.ready;
637
709
  return await execute(s, input, ctx);
638
710
  }
711
+ catch (error) {
712
+ entry.failed = true;
713
+ throw error;
714
+ }
639
715
  finally {
640
716
  entry.depth -= 1;
641
717
  if (entry.depth <= 0) {
642
718
  this.liveRoots.delete(ctx.id);
643
719
  this.channelStore.closeExecution(ctx.id);
644
720
  await this.acpSessions.closeOwnedBy(ctx.id);
721
+ if (!entry.failed) {
722
+ await this.endDurableRun(ctx);
723
+ }
724
+ }
725
+ }
726
+ }
727
+ /**
728
+ * Fix the point a resume of this run starts from, and queue it for saving — so even
729
+ * a run whose first step dies leaves a snapshot to restore. The save is not awaited:
730
+ * the steps' own checkpoints queue behind it.
731
+ *
732
+ * When the context's last run never finished, the run repeats it, and it does so
733
+ * from storage — the stored baseline and ledger — exactly as a new harness resuming
734
+ * the execution would, not from what the failed attempt left in memory.
735
+ */
736
+ async beginDurableRun(ctx) {
737
+ if (!this.checkpointStore || !(ctx instanceof ContextImpl)) {
738
+ return;
739
+ }
740
+ if (ctx.hasUnfinishedRun()) {
741
+ await this.rebuildFromStorage(ctx);
742
+ }
743
+ ctx.beginRun();
744
+ void this.saveCheckpoint(ctx);
745
+ }
746
+ /**
747
+ * Stand `ctx` at its stored baseline and give it the stored ledger. Without a
748
+ * snapshot (its save failed), the baseline the context fixed in memory when the run
749
+ * began is the best record left.
750
+ */
751
+ async rebuildFromStorage(ctx) {
752
+ await this.pendingCheckpoints.get(ctx.id);
753
+ const snapshot = await this.checkpointStore?.load(ctx.id).catch(() => null);
754
+ ctx.rebase(snapshot
755
+ ? {
756
+ items: this.itemSchemas.parseMany(snapshot.itemLog.items),
757
+ occurrences: snapshot.occurrences,
645
758
  }
759
+ : ctx.runBaseline());
760
+ const recovered = await this.stepLedgerStore?.load(ctx.id);
761
+ if (recovered) {
762
+ ctx.ledger?.adopt(recovered);
763
+ }
764
+ }
765
+ /**
766
+ * A finished run is the next run's starting point: persist the live log and counts,
767
+ * then drop the run's positional ledger entries, which no later resume can reach.
768
+ * They are kept when the snapshot failed to land, since that snapshot still points
769
+ * at this run's start. A failed run skips this entirely — it is what a resume repeats.
770
+ */
771
+ async endDurableRun(ctx) {
772
+ if (!this.checkpointStore || !(ctx instanceof ContextImpl)) {
773
+ return;
774
+ }
775
+ ctx.endRun();
776
+ if (await this.saveCheckpoint(ctx)) {
777
+ await ctx.ledger?.dropPaths();
646
778
  }
647
779
  }
648
780
  /**
@@ -839,11 +971,12 @@ export class AgentHarness {
839
971
  // Read-only: if the session doesn't exist, treat history as empty rather
840
972
  // than allocating a SessionRunner for a debug/preview call.
841
973
  const existingSession = this.sessions.get(threadId);
842
- const historyItems = existingSession
843
- ? [
844
- ...existingSession.accumulatedItems,
845
- ]
846
- : [];
974
+ const record = existingSession?.record ?? this.threadRecord(threadId);
975
+ const historyItems = record
976
+ ? await record.history()
977
+ : [
978
+ ...(existingSession?.accumulatedItems ?? []),
979
+ ];
847
980
  const ctx = this.createContext({
848
981
  items: historyItems,
849
982
  threadId,
@@ -936,7 +1069,24 @@ export class AgentHarness {
936
1069
  * logic live beside the other durability machinery.
937
1070
  */
938
1071
  async checkpoint(ctx) {
939
- return captureCheckpoint(this, ctx);
1072
+ await this.saveCheckpoint(ctx);
1073
+ }
1074
+ /**
1075
+ * Capture `ctx` behind any capture still in flight for the same execution, and
1076
+ * resolve true when this one landed. Every step in the tree checkpoints its root,
1077
+ * and concurrent paths would otherwise race their writes: on a networked adapter an
1078
+ * older snapshot could land last and win.
1079
+ */
1080
+ saveCheckpoint(ctx) {
1081
+ const prior = this.pendingCheckpoints.get(ctx.id);
1082
+ const next = (prior ?? Promise.resolve(true)).then(() => captureCheckpoint(this, ctx));
1083
+ this.pendingCheckpoints.set(ctx.id, next);
1084
+ void next.finally(() => {
1085
+ if (this.pendingCheckpoints.get(ctx.id) === next) {
1086
+ this.pendingCheckpoints.delete(ctx.id);
1087
+ }
1088
+ });
1089
+ return next;
940
1090
  }
941
1091
  /**
942
1092
  * Rebuild a `Context` from what a previous run of `executionId` recorded: its
@@ -3,12 +3,16 @@ export { ChannelStore, warnToConsole } from '../../runtime/channel-store.js';
3
3
  export { ContextImpl, collectContextTree, rootIdOf } from '../../runtime/context-impl.js';
4
4
  export { snapshotCwdState } from '../../runtime/cwd-helpers.js';
5
5
  export type { CheckpointStore } from '../../runtime/durable/index.js';
6
+ export { createCheckpointStore } from '../../runtime/durable/checkpoint-store.js';
6
7
  export type { RestoreCheckpointOptions } from '../../runtime/durable/harness-checkpoints.js';
7
8
  export { captureCheckpoint, clearCheckpoint, restoreFromCheckpoint, } from '../../runtime/durable/harness-checkpoints.js';
9
+ export type { SessionStore } from '../../runtime/durable/session-store.js';
10
+ export { createSessionStore } from '../../runtime/durable/session-store.js';
8
11
  export type { StepLedgerEntry, StepLedgerRetention, StepLedgerStore, } from '../../runtime/durable/step-ledger.js';
9
12
  export { createStepLedgerStore, resolveStepLedgerRetention, StepLedger, } from '../../runtime/durable/step-ledger.js';
10
13
  export type { EventBroadcaster } from '../../runtime/event-broadcaster.js';
11
14
  export { createInMemoryStorage } from '../../runtime/in-memory-storage.js';
12
15
  export type { QueuedMessage } from '../../runtime/message-queue.js';
16
+ export type { TurnUsage } from '../../runtime/session-runner.js';
13
17
  export { SessionRunner } from '../../runtime/session-runner.js';
14
18
  export { buildItemStream, filterReasoningStream, filterTextStream, } from '../../runtime/session-streams.js';
@@ -1,7 +1,9 @@
1
1
  export { ChannelStore, warnToConsole } from '../../runtime/channel-store.js';
2
2
  export { ContextImpl, collectContextTree, rootIdOf } from '../../runtime/context-impl.js';
3
3
  export { snapshotCwdState } from '../../runtime/cwd-helpers.js';
4
+ export { createCheckpointStore } from '../../runtime/durable/checkpoint-store.js';
4
5
  export { captureCheckpoint, clearCheckpoint, restoreFromCheckpoint, } from '../../runtime/durable/harness-checkpoints.js';
6
+ export { createSessionStore } from '../../runtime/durable/session-store.js';
5
7
  export { createStepLedgerStore, resolveStepLedgerRetention, StepLedger, } from '../../runtime/durable/step-ledger.js';
6
8
  export { createInMemoryStorage } from '../../runtime/in-memory-storage.js';
7
9
  export { SessionRunner } from '../../runtime/session-runner.js';
@@ -5,6 +5,7 @@ import { isFunctionCall } from '../interpreter/typeguards.js';
5
5
  import { GenAI, NoeticAttr, ToolAttr } from '../observability/genai-attributes.js';
6
6
  import { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broadcaster-utils.js';
7
7
  import { exportSpans } from './deps/context.js';
8
+ import { RoundLedger } from './model-rounds.js';
8
9
  import { buildItemSchemaRegistry, createToolResultItem } from './model-schema.js';
9
10
  const MAX_TOOL_ROUNDS = 32;
10
11
  const MAX_RECOVERY_CONTINUATIONS = 3;
@@ -481,6 +482,8 @@ export class AgentHarnessModelCaller {
481
482
  // the assembled view was cached (see `noteCacheOutcome`).
482
483
  const rounds = [];
483
484
  let totalCost = 0;
485
+ // What replayed rounds supplied, so the response can report what was paid now.
486
+ let replayedCost;
484
487
  let servedTier;
485
488
  const conversationInput = itemsToInput(prepared.remaining);
486
489
  const textFormat = request.outputSchema
@@ -490,7 +493,56 @@ export class AgentHarnessModelCaller {
490
493
  let invalidRecoveryContinuations = 0;
491
494
  let toolLimitRecoveryContinuations = 0;
492
495
  let useEphemeralContinue = false;
496
+ const roundLedger = RoundLedger.open(request.ctx);
497
+ const replaySchemas = buildItemSchemaRegistry({
498
+ base: this.opts.itemSchemas,
499
+ layers: request.layers,
500
+ tools: request.tools,
501
+ });
502
+ // Where the loop's lists stood when the current round began, for its record.
503
+ let marks = {
504
+ round: -1,
505
+ log: 0,
506
+ input: 0,
507
+ items: 0,
508
+ };
493
509
  while (!request.signal?.aborted) {
510
+ const replayed = roundLedger?.take(round, replaySchemas);
511
+ if (replayed) {
512
+ allItems.push(...replayed.items);
513
+ conversationInput.push(...frameworkCast(replayed.input));
514
+ for (const item of replayed.appended) {
515
+ request.ctx?.itemLog.append(item);
516
+ }
517
+ rounds.push(replayed.usage);
518
+ totalUsage.inputTokens += replayed.usage.inputTokens;
519
+ totalUsage.outputTokens += replayed.usage.outputTokens;
520
+ totalUsage.cachedTokens += replayed.usage.cachedTokens ?? 0;
521
+ totalCost += replayed.cost;
522
+ replayedCost = (replayedCost ?? 0) + replayed.cost;
523
+ prepared.emitIfAllowed('model_round_replayed', {
524
+ round,
525
+ });
526
+ round += 1;
527
+ const replayLimit = this.handleToolRoundLimit({
528
+ round,
529
+ toolLimitRecoveryContinuations,
530
+ emitIfAllowed: prepared.emitIfAllowed,
531
+ });
532
+ if (replayLimit.kind === 'continue') {
533
+ toolLimitRecoveryContinuations = replayLimit.toolLimitRecoveryContinuations;
534
+ useEphemeralContinue = true;
535
+ }
536
+ continue;
537
+ }
538
+ if (marks.round !== round) {
539
+ marks = {
540
+ round,
541
+ log: roundLedger?.mark() ?? 0,
542
+ input: conversationInput.length,
543
+ items: allItems.length,
544
+ };
545
+ }
494
546
  const recoveryContinuation = useEphemeralContinue;
495
547
  useEphemeralContinue = false;
496
548
  if (round > 0 && request.ctx && hasSessionQueue(request.ctx)) {
@@ -557,6 +609,10 @@ export class AgentHarnessModelCaller {
557
609
  }
558
610
  },
559
611
  });
612
+ // A dropped connection rejects the response and the event pipe together; the
613
+ // response's rejection is the one that propagates. Unobserved, the pipe's would
614
+ // surface as an unhandled rejection and take the host process down with it.
615
+ pipePromise.catch(() => { });
560
616
  let sdkResponse;
561
617
  try {
562
618
  sdkResponse = await awaitWithAbort(callResult.getResponse(), roundSignal);
@@ -641,6 +697,14 @@ export class AgentHarnessModelCaller {
641
697
  spans,
642
698
  modelSpan,
643
699
  });
700
+ if (!request.signal?.aborted) {
701
+ await roundLedger?.record(round, marks.log, {
702
+ items: allItems.slice(marks.items),
703
+ input: conversationInput.slice(marks.input),
704
+ usage: roundUsage,
705
+ cost: roundCost,
706
+ });
707
+ }
644
708
  round += 1;
645
709
  const limitRecovery = this.handleToolRoundLimit({
646
710
  round,
@@ -665,6 +729,11 @@ export class AgentHarnessModelCaller {
665
729
  },
666
730
  rounds,
667
731
  cost: totalCost > 0 ? totalCost : undefined,
732
+ ...(replayedCost !== undefined
733
+ ? {
734
+ billedCost: totalCost - replayedCost,
735
+ }
736
+ : {}),
668
737
  ...(servedTier
669
738
  ? {
670
739
  serviceTier: servedTier,
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Durable rounds for the model loop.
3
+ *
4
+ * One `callModel` step can run many rounds: the model asks for tools, the harness
5
+ * runs them, the model answers again. The step ledger records the step only when the
6
+ * whole loop ends, so without this a failure on round five throws rounds one to four
7
+ * away — each paid for again on resume, and each tool run again.
8
+ *
9
+ * Each finished round is recorded under `<step path>/round#<n>`, carrying what it
10
+ * added to the loop: the model's output and tool results, the conversation input
11
+ * those became, the items appended to the item log (messages injected between rounds),
12
+ * and the round's usage. A resumed loop replays rounds in order and stops at the first
13
+ * one it does not find; every round after that runs live, because a recorded round
14
+ * belongs to the conversation the earlier recorded rounds built. When the step
15
+ * finishes and records, the ledger prunes its rounds.
16
+ */
17
+ import type { Item, ItemSchemaRegistry, RoundUsage } from '@noetic-tools/types';
18
+ /** What one finished round added to the loop. */
19
+ export interface RoundRecord {
20
+ /** Model output items and tool result items, in the order the loop gathered them. */
21
+ items: Item[];
22
+ /** Conversation input entries the round appended, in SDK input shape. */
23
+ input: unknown[];
24
+ usage: RoundUsage;
25
+ cost: number;
26
+ }
27
+ /** A replayed round: its record plus the items it appended to the item log. */
28
+ export interface ReplayedRound extends RoundRecord {
29
+ appended: Item[];
30
+ }
31
+ /**
32
+ * The round ledger for one model loop. `open` gives none when the call is not running
33
+ * as a step on a context with a ledger.
34
+ */
35
+ export declare class RoundLedger {
36
+ private readonly ctx;
37
+ private readonly dispatch;
38
+ private replaying;
39
+ private constructor();
40
+ /** Undefined when the loop has nothing to record into. */
41
+ static open(ctx: unknown): RoundLedger | undefined;
42
+ /**
43
+ * The recorded round `round`, with its items parsed, or undefined once replay has
44
+ * stopped — at the first round with no usable record, and for good after that.
45
+ */
46
+ take(round: number, schemas: ItemSchemaRegistry): ReplayedRound | undefined;
47
+ /** Mark where the log stood when a round began, so its appends can be recorded. */
48
+ mark(): number;
49
+ /** Record a finished round. `logMark` is what `mark()` returned when it began. */
50
+ record(round: number, logMark: number, record: RoundRecord): Promise<void>;
51
+ private key;
52
+ }