@noetic-tools/core 5.13.0 → 6.1.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.
Files changed (42) hide show
  1. package/dist/builders/decide-builders.d.ts +2 -2
  2. package/dist/builders/dynamic-workflow.js +2 -0
  3. package/dist/builders/provide-builder.d.ts +2 -2
  4. package/dist/builders/spawn-builder.d.ts +2 -2
  5. package/dist/builders/step-builders.d.ts +5 -5
  6. package/dist/builders/workflow-hydrator.d.ts +1 -1
  7. package/dist/builders/workflow-hydrator.js +53 -3
  8. package/dist/expression/check.js +14 -0
  9. package/dist/expression/jsonata.d.ts +7 -0
  10. package/dist/expression/jsonata.js +11 -1
  11. package/dist/harness/agent-harness.d.ts +59 -5
  12. package/dist/harness/agent-harness.js +176 -25
  13. package/dist/harness/deps/runtime.d.ts +4 -0
  14. package/dist/harness/deps/runtime.js +2 -0
  15. package/dist/harness/model-call.js +69 -0
  16. package/dist/harness/model-rounds.d.ts +52 -0
  17. package/dist/harness/model-rounds.js +115 -0
  18. package/dist/harness/thread-record.d.ts +54 -0
  19. package/dist/harness/thread-record.js +159 -0
  20. package/dist/index.d.ts +2 -2
  21. package/dist/interpreter/emit-items.d.ts +19 -0
  22. package/dist/interpreter/emit-items.js +106 -0
  23. package/dist/interpreter/execute-action.js +3 -0
  24. package/dist/interpreter/execute-control.js +3 -0
  25. package/dist/interpreter/execute.js +66 -9
  26. package/dist/runtime/context-impl.d.ts +106 -4
  27. package/dist/runtime/context-impl.js +224 -14
  28. package/dist/runtime/durable/harness-checkpoints.d.ts +13 -3
  29. package/dist/runtime/durable/harness-checkpoints.js +66 -7
  30. package/dist/runtime/durable/session-store.d.ts +37 -0
  31. package/dist/runtime/durable/session-store.js +58 -0
  32. package/dist/runtime/durable/step-ledger.d.ts +77 -40
  33. package/dist/runtime/durable/step-ledger.js +193 -73
  34. package/dist/runtime/item-log-impl.d.ts +6 -0
  35. package/dist/runtime/item-log-impl.js +12 -0
  36. package/dist/runtime/session-runner.d.ts +25 -1
  37. package/dist/runtime/session-runner.js +83 -11
  38. package/dist/schemas/workflow.d.ts +1 -1
  39. package/dist/types/checkpoint.d.ts +21 -4
  40. package/dist/types/checkpoint.js +33 -3
  41. package/package.json +2 -2
  42. package/schema/noetic-workflow.schema.json +391 -0
@@ -18,6 +18,7 @@ export declare class ContextImpl implements Context<ContextData> {
18
18
  stepCount: number;
19
19
  tokens: TokenUsage;
20
20
  cost: number;
21
+ billedCost: number;
21
22
  state: unknown;
22
23
  readonly parent: Context<ContextData> | null;
23
24
  readonly usageParent: Context<ContextData> | null;
@@ -26,6 +27,8 @@ export declare class ContextImpl implements Context<ContextData> {
26
27
  readonly threadId: string;
27
28
  readonly resourceId?: string;
28
29
  readonly itemLog: ItemLog;
30
+ /** The same log, typed for `rebase`. */
31
+ private readonly log;
29
32
  lastStepMeta: StepMeta | null;
30
33
  lastLayerUsage: LastLayerUsage | undefined;
31
34
  readonly harness: AgentHarnessContract;
@@ -96,6 +99,21 @@ export declare class ContextImpl implements Context<ContextData> {
96
99
  * @internal
97
100
  */
98
101
  readonly ledger?: StepLedger;
102
+ /**
103
+ * The dispatch this view belongs to. Undefined on the context itself; a lane (see
104
+ * `enterStep`) reads its own here.
105
+ * @internal
106
+ */
107
+ private readonly _lane?;
108
+ /**
109
+ * The item log and dispatch counts as they stood when the outermost run on this
110
+ * context began. A checkpoint persists these rather than the live values, because a
111
+ * resumed run starts that run over: its recorded steps replay and re-append their
112
+ * items, so the log must not already hold them. Unset between runs, and kept after a
113
+ * run that failed — that run is what a resume repeats.
114
+ * @internal
115
+ */
116
+ private _baseline?;
99
117
  constructor(opts: {
100
118
  harness: AgentHarnessContract;
101
119
  parent?: Context;
@@ -174,12 +192,29 @@ export declare class ContextImpl implements Context<ContextData> {
174
192
  /**
175
193
  * @internal
176
194
  * Register `frame` as in flight and return the lane its step runs on: a view of
177
- * this context that shares everything except its execution path. `execute()` hands
178
- * the lane to the step, so steps the step dispatches hang under its path no matter
179
- * how other dispatches on this context interleave. The occurrence ordinal is taken
180
- * here, at dispatch, never at settle.
195
+ * this context that shares everything except its execution path and the record of
196
+ * items appended through it. `execute()` hands the lane to the step, so steps the
197
+ * step dispatches hang under its path no matter how other dispatches on this context
198
+ * interleave. The occurrence ordinal is taken here, at dispatch, never at settle.
181
199
  */
182
200
  enterStep(frame: FrontierFrame): ContextImpl;
201
+ /**
202
+ * @internal
203
+ * Mark this lane's step as kept out of the ledger (`durable: false`, `schedule`, a
204
+ * failed `replayKey`), so nothing running inside it records under its identity.
205
+ */
206
+ skipLedger(): void;
207
+ /**
208
+ * @internal
209
+ * The dispatch this lane belongs to, or undefined on the context itself and on a
210
+ * lane kept out of the ledger. Lets code running inside a step (the model loop's
211
+ * rounds) record under the step's identity.
212
+ */
213
+ currentDispatch(): {
214
+ path: string;
215
+ stepId: string;
216
+ inputHash: string | undefined;
217
+ } | undefined;
183
218
  /**
184
219
  * @internal
185
220
  * The execution path of the step this lane belongs to — the ledger key identifying
@@ -187,12 +222,74 @@ export declare class ContextImpl implements Context<ContextData> {
187
222
  * what lets a resumed run line recorded outputs up with the steps that produced them.
188
223
  */
189
224
  currentPath(): string;
225
+ /**
226
+ * @internal
227
+ * Items appended to the item log through this lane, including by steps it
228
+ * dispatched on the same context. Empty on the context itself.
229
+ */
230
+ appendedItems(): Item[];
231
+ /**
232
+ * @internal
233
+ * Indices into `appendedItems()` of the items appended through `appendEmitted`, which
234
+ * a replay streams again under the harness's `emitItemsOnReplay`.
235
+ */
236
+ emittedIndices(): number[];
237
+ /**
238
+ * @internal
239
+ * Append an item a step emitted (`step.emitItems`), marking it in this lane's record
240
+ * and every record above it, so the ledger entry that holds it knows to stream it
241
+ * again on replay.
242
+ */
243
+ appendEmitted(item: Item): void;
190
244
  /**
191
245
  * @internal
192
246
  * Drop `frame` from the in-flight set. Called when its step resolves, success or
193
247
  * failure.
194
248
  */
195
249
  leaveStep(frame: FrontierFrame): void;
250
+ /**
251
+ * @internal
252
+ * Give back this lane's ordinal after its step failed, so a retry runs at the same
253
+ * path. A resumed run never sees the failed attempt — nothing records a failure — so
254
+ * without this a retry would take the next ordinal and every later dispatch would sit
255
+ * one position past where the resume looks for it. Only the latest dispatch of a key
256
+ * can give its ordinal back; once a later one has taken the next, the ordinal stays.
257
+ */
258
+ releaseDispatch(): void;
259
+ /**
260
+ * @internal
261
+ * Mark the start of the outermost run on this context. See `_baseline`.
262
+ */
263
+ beginRun(): void;
264
+ /**
265
+ * @internal
266
+ * Mark a run as finished, so checkpoints record the live log and counts again.
267
+ */
268
+ endRun(): void;
269
+ /**
270
+ * @internal
271
+ * What a checkpoint persists for the item log and dispatch counts — see `_baseline`.
272
+ */
273
+ runBaseline(): RunBaseline;
274
+ /**
275
+ * @internal
276
+ * Whether a run on this context began and never finished — it failed, or is in
277
+ * flight. A run starting now repeats it.
278
+ */
279
+ hasUnfinishedRun(): boolean;
280
+ /**
281
+ * @internal
282
+ * Stand the context back at a stored run baseline: the item log and dispatch counts
283
+ * a checkpoint recorded. For a run retried in place, which must see what a resume on
284
+ * a new harness would — not the items and counts its failed attempt left in memory.
285
+ */
286
+ rebase(baseline: RunBaseline): void;
287
+ /**
288
+ * @internal
289
+ * Seed the dispatch counts a restored run starts from, so a resumed context numbers
290
+ * its dispatches where the recorded run did rather than from zero.
291
+ */
292
+ restoreOccurrences(occurrences: Record<string, number>): void;
196
293
  /**
197
294
  * @internal
198
295
  * Return a defensive copy of the current frontier. Consumed by the
@@ -200,6 +297,11 @@ export declare class ContextImpl implements Context<ContextData> {
200
297
  */
201
298
  serialiseFrontier(): FrontierFrame[];
202
299
  }
300
+ /** @internal Item log and dispatch counts at the start of a run — see `ContextImpl._baseline`. */
301
+ export interface RunBaseline {
302
+ items: Item[];
303
+ occurrences: Record<string, number>;
304
+ }
203
305
  /**
204
306
  * @internal
205
307
  * The context a lane views, or `ctx` itself when it is not a lane. For per-execution
@@ -1,4 +1,5 @@
1
1
  import { buildContextData, defaultItemSchemaRegistry } from './context-deps.js';
2
+ import { hashStepInput } from './durable/step-ledger.js';
2
3
  import { ItemLogImpl } from './item-log-impl.js';
3
4
  const EMPTY_CONTEXT = Object.freeze({});
4
5
  class NoopSpan {
@@ -48,6 +49,7 @@ export class ContextImpl {
48
49
  total: 0,
49
50
  };
50
51
  cost = 0;
52
+ billedCost = 0;
51
53
  state;
52
54
  parent;
53
55
  usageParent;
@@ -56,6 +58,8 @@ export class ContextImpl {
56
58
  threadId;
57
59
  resourceId;
58
60
  itemLog;
61
+ /** The same log, typed for `rebase`. */
62
+ log;
59
63
  lastStepMeta = null;
60
64
  lastLayerUsage = undefined;
61
65
  harness;
@@ -126,6 +130,21 @@ export class ContextImpl {
126
130
  * @internal
127
131
  */
128
132
  ledger;
133
+ /**
134
+ * The dispatch this view belongs to. Undefined on the context itself; a lane (see
135
+ * `enterStep`) reads its own here.
136
+ * @internal
137
+ */
138
+ _lane;
139
+ /**
140
+ * The item log and dispatch counts as they stood when the outermost run on this
141
+ * context began. A checkpoint persists these rather than the live values, because a
142
+ * resumed run starts that run over: its recorded steps replay and re-append their
143
+ * items, so the log must not already hold them. Unset between runs, and kept after a
144
+ * run that failed — that run is what a resume repeats.
145
+ * @internal
146
+ */
147
+ _baseline;
129
148
  constructor(opts) {
130
149
  this.id = opts.id ?? crypto.randomUUID();
131
150
  this._createdAt = Date.now();
@@ -155,6 +174,7 @@ export class ContextImpl {
155
174
  }
156
175
  }
157
176
  this.itemLog = log;
177
+ this.log = log;
158
178
  // Join the parent's abort cascade last, so the child is fully constructed
159
179
  // before an already-aborted parent aborts it.
160
180
  if (this.parent instanceof ContextImpl) {
@@ -295,17 +315,51 @@ export class ContextImpl {
295
315
  /**
296
316
  * @internal
297
317
  * Register `frame` as in flight and return the lane its step runs on: a view of
298
- * this context that shares everything except its execution path. `execute()` hands
299
- * the lane to the step, so steps the step dispatches hang under its path no matter
300
- * how other dispatches on this context interleave. The occurrence ordinal is taken
301
- * here, at dispatch, never at settle.
318
+ * this context that shares everything except its execution path and the record of
319
+ * items appended through it. `execute()` hands the lane to the step, so steps the
320
+ * step dispatches hang under its path no matter how other dispatches on this context
321
+ * interleave. The occurrence ordinal is taken here, at dispatch, never at settle.
302
322
  */
303
323
  enterStep(frame) {
304
324
  const key = `${this._path}/${frame.stepId}`;
305
325
  const occurrence = this._occurrences.get(key) ?? 0;
306
326
  this._occurrences.set(key, occurrence + 1);
307
327
  this._inFlight.add(frame);
308
- return laneOf(this, `${key}#${occurrence}`);
328
+ return laneOf(this, {
329
+ path: `${key}#${occurrence}`,
330
+ key,
331
+ occurrence,
332
+ stepId: frame.stepId,
333
+ inputHash: this.ledger ? hashStepInput(frame.input) : undefined,
334
+ recorded: true,
335
+ appended: new AppendRecord(this._lane?.appended),
336
+ });
337
+ }
338
+ /**
339
+ * @internal
340
+ * Mark this lane's step as kept out of the ledger (`durable: false`, `schedule`, a
341
+ * failed `replayKey`), so nothing running inside it records under its identity.
342
+ */
343
+ skipLedger() {
344
+ if (this._lane) {
345
+ this._lane.recorded = false;
346
+ }
347
+ }
348
+ /**
349
+ * @internal
350
+ * The dispatch this lane belongs to, or undefined on the context itself and on a
351
+ * lane kept out of the ledger. Lets code running inside a step (the model loop's
352
+ * rounds) record under the step's identity.
353
+ */
354
+ currentDispatch() {
355
+ const lane = this._lane;
356
+ return lane?.recorded
357
+ ? {
358
+ path: lane.path,
359
+ stepId: lane.stepId,
360
+ inputHash: lane.inputHash,
361
+ }
362
+ : undefined;
309
363
  }
310
364
  /**
311
365
  * @internal
@@ -316,6 +370,43 @@ export class ContextImpl {
316
370
  currentPath() {
317
371
  return this._path;
318
372
  }
373
+ /**
374
+ * @internal
375
+ * Items appended to the item log through this lane, including by steps it
376
+ * dispatched on the same context. Empty on the context itself.
377
+ */
378
+ appendedItems() {
379
+ return [
380
+ ...(this._lane?.appended.items ?? []),
381
+ ];
382
+ }
383
+ /**
384
+ * @internal
385
+ * Indices into `appendedItems()` of the items appended through `appendEmitted`, which
386
+ * a replay streams again under the harness's `emitItemsOnReplay`.
387
+ */
388
+ emittedIndices() {
389
+ const record = this._lane?.appended;
390
+ if (!record) {
391
+ return [];
392
+ }
393
+ return record.items.flatMap((item, i) => record.emitted.has(item)
394
+ ? [
395
+ i,
396
+ ]
397
+ : []);
398
+ }
399
+ /**
400
+ * @internal
401
+ * Append an item a step emitted (`step.emitItems`), marking it in this lane's record
402
+ * and every record above it, so the ledger entry that holds it knows to stream it
403
+ * again on replay.
404
+ */
405
+ appendEmitted(item) {
406
+ this.itemLog.append(item);
407
+ const items = this.itemLog.items;
408
+ this._lane?.appended.markEmitted(items[items.length - 1]);
409
+ }
319
410
  /**
320
411
  * @internal
321
412
  * Drop `frame` from the in-flight set. Called when its step resolves, success or
@@ -324,6 +415,88 @@ export class ContextImpl {
324
415
  leaveStep(frame) {
325
416
  this._inFlight.delete(frame);
326
417
  }
418
+ /**
419
+ * @internal
420
+ * Give back this lane's ordinal after its step failed, so a retry runs at the same
421
+ * path. A resumed run never sees the failed attempt — nothing records a failure — so
422
+ * without this a retry would take the next ordinal and every later dispatch would sit
423
+ * one position past where the resume looks for it. Only the latest dispatch of a key
424
+ * can give its ordinal back; once a later one has taken the next, the ordinal stays.
425
+ */
426
+ releaseDispatch() {
427
+ const lane = this._lane;
428
+ if (!lane || this._occurrences.get(lane.key) !== lane.occurrence + 1) {
429
+ return;
430
+ }
431
+ this._occurrences.set(lane.key, lane.occurrence);
432
+ for (const key of [
433
+ ...this._occurrences.keys(),
434
+ ]) {
435
+ if (key.startsWith(`${lane.path}/`)) {
436
+ this._occurrences.delete(key);
437
+ }
438
+ }
439
+ }
440
+ /**
441
+ * @internal
442
+ * Mark the start of the outermost run on this context. See `_baseline`.
443
+ */
444
+ beginRun() {
445
+ this._baseline = {
446
+ items: [
447
+ ...this.itemLog.items,
448
+ ],
449
+ occurrences: Object.fromEntries(this._occurrences),
450
+ };
451
+ }
452
+ /**
453
+ * @internal
454
+ * Mark a run as finished, so checkpoints record the live log and counts again.
455
+ */
456
+ endRun() {
457
+ this._baseline = undefined;
458
+ }
459
+ /**
460
+ * @internal
461
+ * What a checkpoint persists for the item log and dispatch counts — see `_baseline`.
462
+ */
463
+ runBaseline() {
464
+ return (this._baseline ?? {
465
+ items: [
466
+ ...this.itemLog.items,
467
+ ],
468
+ occurrences: Object.fromEntries(this._occurrences),
469
+ });
470
+ }
471
+ /**
472
+ * @internal
473
+ * Whether a run on this context began and never finished — it failed, or is in
474
+ * flight. A run starting now repeats it.
475
+ */
476
+ hasUnfinishedRun() {
477
+ return this._baseline !== undefined;
478
+ }
479
+ /**
480
+ * @internal
481
+ * Stand the context back at a stored run baseline: the item log and dispatch counts
482
+ * a checkpoint recorded. For a run retried in place, which must see what a resume on
483
+ * a new harness would — not the items and counts its failed attempt left in memory.
484
+ */
485
+ rebase(baseline) {
486
+ this.log.replace(baseline.items);
487
+ this._occurrences.clear();
488
+ this.restoreOccurrences(baseline.occurrences);
489
+ }
490
+ /**
491
+ * @internal
492
+ * Seed the dispatch counts a restored run starts from, so a resumed context numbers
493
+ * its dispatches where the recorded run did rather than from zero.
494
+ */
495
+ restoreOccurrences(occurrences) {
496
+ for (const [key, count] of Object.entries(occurrences)) {
497
+ this._occurrences.set(key, count);
498
+ }
499
+ }
327
500
  /**
328
501
  * @internal
329
502
  * Return a defensive copy of the current frontier. Consumed by the
@@ -339,21 +512,58 @@ export class ContextImpl {
339
512
  }));
340
513
  }
341
514
  }
342
- //#region Lanes
515
+ /**
516
+ * Items appended through one lane. Each record also feeds its parent lane's, so a
517
+ * composite step's record holds everything appended beneath it on the same context.
518
+ */
519
+ class AppendRecord {
520
+ parent;
521
+ items = [];
522
+ /** The items among `items` a step emitted through `emitItems`. */
523
+ emitted = new Set();
524
+ constructor(parent) {
525
+ this.parent = parent;
526
+ }
527
+ add(item) {
528
+ this.items.push(item);
529
+ this.parent?.add(item);
530
+ }
531
+ markEmitted(item) {
532
+ this.emitted.add(item);
533
+ this.parent?.markEmitted(item);
534
+ }
535
+ }
343
536
  /** The context each lane views, so `laneOf` never stacks a proxy on a proxy. */
344
537
  const laneTargets = new WeakMap();
345
538
  /**
346
- * A view of `ctx` that reads `path` as its execution path and forwards every other
347
- * read and write to the context itself, so state, usage, abort, and the in-flight set
348
- * stay shared. A Proxy rather than a subclass: steps assign `ctx.state` and friends
539
+ * A view of `ctx` that reads `lane` as its dispatch and forwards every other read and
540
+ * write to the context itself, so state, usage, abort, and the in-flight set stay
541
+ * shared. Its item log appends to the shared log and notes each item in the lane's
542
+ * record. A Proxy rather than a subclass: steps assign `ctx.state` and friends
349
543
  * directly, and a copy would keep those writes to itself.
350
544
  */
351
- function laneOf(ctx, path) {
545
+ function laneOf(ctx, lane) {
352
546
  const target = laneTargets.get(ctx) ?? ctx;
353
- const lane = new Proxy(target, {
547
+ const itemLog = {
548
+ get items() {
549
+ return target.itemLog.items;
550
+ },
551
+ append(item) {
552
+ target.itemLog.append(item);
553
+ const items = target.itemLog.items;
554
+ lane.appended.add(items[items.length - 1]);
555
+ },
556
+ };
557
+ const view = new Proxy(target, {
354
558
  get(base, prop, receiver) {
355
559
  if (prop === '_path') {
356
- return path;
560
+ return lane.path;
561
+ }
562
+ if (prop === '_lane') {
563
+ return lane;
564
+ }
565
+ if (prop === 'itemLog') {
566
+ return itemLog;
357
567
  }
358
568
  return Reflect.get(base, prop, receiver);
359
569
  },
@@ -361,8 +571,8 @@ function laneOf(ctx, path) {
361
571
  return Reflect.set(base, prop, value);
362
572
  },
363
573
  });
364
- laneTargets.set(lane, target);
365
- return lane;
574
+ laneTargets.set(view, target);
575
+ return view;
366
576
  }
367
577
  /**
368
578
  * @internal
@@ -43,11 +43,16 @@ export interface CheckpointHarnessHandle {
43
43
  * `CheckpointStore` is configured — zero-config harnesses preserve
44
44
  * ephemeral semantics. Save failures are logged rather than thrown,
45
45
  * because a checkpoint failing must never abort an otherwise-successful
46
- * step.
46
+ * step. Resolves true when a snapshot landed.
47
+ *
48
+ * The item log and dispatch counts are the run's baseline (see
49
+ * `ContextImpl.runBaseline`); layer state, channels, `ctx.state`, and usage are
50
+ * live, because replay does not redo those — a replayed step neither folds into
51
+ * layers nor writes state nor spends tokens.
47
52
  *
48
53
  * @internal
49
54
  */
50
- export declare function captureCheckpoint(h: CheckpointHarnessHandle, ctx: Context): Promise<void>;
55
+ export declare function captureCheckpoint(h: CheckpointHarnessHandle, ctx: Context): Promise<boolean>;
51
56
  /**
52
57
  * What `restoreFromCheckpoint` rebuilt. `fromSnapshot` is false for a ledger-only
53
58
  * restore, whose layer state was never recovered — the harness must then let layer
@@ -61,7 +66,12 @@ export interface RestoredExecution {
61
66
  }
62
67
  /**
63
68
  * Rebuild a `Context` for `executionId` from what a previous run recorded: the
64
- * checkpoint snapshot and the step-completion ledger. Either is enough. Returns
69
+ * checkpoint snapshot and the step-completion ledger. Either is enough.
70
+ *
71
+ * The restored context stands where the interrupted run began — its item log and
72
+ * dispatch counts are that run's baseline — with the live layer state, channels,
73
+ * `ctx.state`, and usage. Re-running the same step on the same input replays every
74
+ * recorded step and continues live from the first that was not. Returns
65
75
  * `null` only when neither exists, so the caller starts a fresh execution.
66
76
  *
67
77
  * - With a snapshot, the item log, layer state, channel state, cwd, and thread/resource
@@ -8,14 +8,19 @@ import { StepLedger } from './step-ledger.js';
8
8
  * `CheckpointStore` is configured — zero-config harnesses preserve
9
9
  * ephemeral semantics. Save failures are logged rather than thrown,
10
10
  * because a checkpoint failing must never abort an otherwise-successful
11
- * step.
11
+ * step. Resolves true when a snapshot landed.
12
+ *
13
+ * The item log and dispatch counts are the run's baseline (see
14
+ * `ContextImpl.runBaseline`); layer state, channels, `ctx.state`, and usage are
15
+ * live, because replay does not redo those — a replayed step neither folds into
16
+ * layers nor writes state nor spends tokens.
12
17
  *
13
18
  * @internal
14
19
  */
15
20
  export async function captureCheckpoint(h, ctx) {
16
21
  const store = h.checkpointStore;
17
22
  if (!store) {
18
- return;
23
+ return false;
19
24
  }
20
25
  const impl = ctx instanceof ContextImpl ? ctx : null;
21
26
  const frontier = impl ? impl.serialiseFrontier() : [];
@@ -26,6 +31,13 @@ export async function captureCheckpoint(h, ctx) {
26
31
  layers[layer.id] = state;
27
32
  }
28
33
  }
34
+ const baseline = impl?.runBaseline() ?? {
35
+ items: [
36
+ ...ctx.itemLog.items,
37
+ ],
38
+ occurrences: {},
39
+ };
40
+ const state = jsonCopy(ctx.state);
29
41
  const snapshot = {
30
42
  schemaVersion: CheckpointSchemaVersion,
31
43
  executionId: ctx.id,
@@ -43,9 +55,19 @@ export async function captureCheckpoint(h, ctx) {
43
55
  // means future producers don't bump the schema version.
44
56
  askUser: [],
45
57
  itemLog: {
46
- items: [
47
- ...ctx.itemLog.items,
48
- ],
58
+ items: baseline.items,
59
+ },
60
+ occurrences: baseline.occurrences,
61
+ ...(state.ok
62
+ ? {
63
+ state: state.value,
64
+ }
65
+ : {}),
66
+ usage: {
67
+ tokens: {
68
+ ...ctx.tokens,
69
+ },
70
+ cost: ctx.cost,
49
71
  },
50
72
  // Channel state belongs to the root execution, so a child checkpoint
51
73
  // carries the channels its root used.
@@ -54,14 +76,40 @@ export async function captureCheckpoint(h, ctx) {
54
76
  };
55
77
  try {
56
78
  await store.save(snapshot);
79
+ return true;
57
80
  }
58
81
  catch (err) {
59
82
  console.warn(`AgentHarness.checkpoint: failed to persist snapshot for execution "${ctx.id}":`, err);
83
+ return false;
84
+ }
85
+ }
86
+ /** A JSON round-trip copy of `value`, or `ok: false` when it does not survive one. */
87
+ function jsonCopy(value) {
88
+ try {
89
+ const json = JSON.stringify(value);
90
+ return json === undefined
91
+ ? {
92
+ ok: false,
93
+ }
94
+ : {
95
+ ok: true,
96
+ value: JSON.parse(json),
97
+ };
98
+ }
99
+ catch {
100
+ return {
101
+ ok: false,
102
+ };
60
103
  }
61
104
  }
62
105
  /**
63
106
  * Rebuild a `Context` for `executionId` from what a previous run recorded: the
64
- * checkpoint snapshot and the step-completion ledger. Either is enough. Returns
107
+ * checkpoint snapshot and the step-completion ledger. Either is enough.
108
+ *
109
+ * The restored context stands where the interrupted run began — its item log and
110
+ * dispatch counts are that run's baseline — with the live layer state, channels,
111
+ * `ctx.state`, and usage. Re-running the same step on the same input replays every
112
+ * recorded step and continues live from the first that was not. Returns
65
113
  * `null` only when neither exists, so the caller starts a fresh execution.
66
114
  *
67
115
  * - With a snapshot, the item log, layer state, channel state, cwd, and thread/resource
@@ -117,13 +165,24 @@ function contextFromSnapshot(h, snapshot, opts) {
117
165
  /* Caller wiring first, snapshot second: a host may legitimately swap the context
118
166
  * layers or hang the restored execution under a new parent, but it must never be
119
167
  * able to override the identity/history the snapshot is the record of. */
120
- return h.createContext({
168
+ const ctx = h.createContext({
121
169
  ...opts,
170
+ state: opts?.state ?? snapshot.state,
122
171
  items: h.itemSchemas.parseMany(snapshot.itemLog.items),
123
172
  threadId: snapshot.threadId,
124
173
  resourceId: snapshot.resourceId,
125
174
  cwdInit: snapshot.cwd?.current ?? undefined,
126
175
  });
176
+ if (ctx instanceof ContextImpl) {
177
+ ctx.restoreOccurrences(snapshot.occurrences);
178
+ if (snapshot.usage) {
179
+ ctx.tokens = {
180
+ ...snapshot.usage.tokens,
181
+ };
182
+ ctx.cost = snapshot.usage.cost;
183
+ }
184
+ }
185
+ return ctx;
127
186
  }
128
187
  /**
129
188
  * Give `ctx` the original execution id and the ledger recorded under it.
@@ -0,0 +1,37 @@
1
+ /**
2
+ * What a session (`harness.execute()`) keeps in storage so a new harness can pick a
3
+ * thread up: the thread's history, what its turns spent, and the turn in flight.
4
+ *
5
+ * A turn's record is written before the turn runs and cleared when it finishes. A
6
+ * harness that finds one still set knows the turn was cut off. If the same messages
7
+ * arrive again — a host with at-least-once delivery re-sends what it never saw
8
+ * answered — the turn resumes on its recorded execution: finished steps replay and
9
+ * the turn continues from the step that was cut off.
10
+ */
11
+ import type { StorageAdapter } from '@noetic-tools/context';
12
+ import { z } from 'zod';
13
+ declare const SessionRecordSchema: z.ZodObject<{
14
+ items: z.ZodArray<z.ZodUnknown>;
15
+ usage: z.ZodOptional<z.ZodObject<{
16
+ inputTokens: z.ZodNumber;
17
+ outputTokens: z.ZodNumber;
18
+ cachedTokens: z.ZodOptional<z.ZodNumber>;
19
+ cost: z.ZodOptional<z.ZodNumber>;
20
+ billedCost: z.ZodOptional<z.ZodNumber>;
21
+ }, z.core.$strip>>;
22
+ turn: z.ZodOptional<z.ZodObject<{
23
+ executionId: z.ZodString;
24
+ messageIds: z.ZodArray<z.ZodString>;
25
+ }, z.core.$strip>>;
26
+ }, z.core.$strip>;
27
+ /** @internal One thread's stored session. */
28
+ export type SessionRecord = z.infer<typeof SessionRecordSchema>;
29
+ /** @internal Reads and writes session records under `session:<threadId>`. */
30
+ export interface SessionStore {
31
+ /** The thread's record, or undefined when none is stored or it does not parse. */
32
+ load(threadId: string): Promise<SessionRecord | undefined>;
33
+ save(threadId: string, record: SessionRecord): Promise<void>;
34
+ }
35
+ /** @internal */
36
+ export declare function createSessionStore(storage: StorageAdapter): SessionStore;
37
+ export {};