@noetic-tools/core 5.12.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.
- package/dist/adapters/in-memory-subprocess/step-completion.d.ts +2 -2
- package/dist/adapters/in-memory-subprocess/step-completion.js +48 -52
- package/dist/adapters/in-memory-subprocess/types.d.ts +3 -6
- package/dist/adapters/in-memory-subprocess-adapter.js +30 -48
- package/dist/adapters/live-handles.d.ts +26 -0
- package/dist/adapters/live-handles.js +50 -0
- package/dist/builders/workflow-hydrator.js +1 -3
- package/dist/harness/agent-harness.d.ts +52 -5
- package/dist/harness/agent-harness.js +175 -25
- package/dist/harness/deps/runtime.d.ts +4 -0
- package/dist/harness/deps/runtime.js +2 -0
- package/dist/harness/model-call.js +69 -0
- package/dist/harness/model-rounds.d.ts +52 -0
- package/dist/harness/model-rounds.js +115 -0
- package/dist/harness/thread-record.d.ts +54 -0
- package/dist/harness/thread-record.js +159 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +2 -0
- package/dist/interpreter/execute-action.js +3 -0
- package/dist/interpreter/execute-control.js +3 -0
- package/dist/interpreter/execute.js +59 -12
- package/dist/interpreter/step-dispatcher.d.ts +2 -2
- package/dist/interpreter/step-dispatcher.js +3 -5
- package/dist/runtime/context-impl.d.ts +93 -4
- package/dist/runtime/context-impl.js +191 -14
- package/dist/runtime/durable/harness-checkpoints.d.ts +13 -3
- package/dist/runtime/durable/harness-checkpoints.js +66 -7
- package/dist/runtime/durable/session-store.d.ts +37 -0
- package/dist/runtime/durable/session-store.js +58 -0
- package/dist/runtime/durable/step-ledger.d.ts +76 -40
- package/dist/runtime/durable/step-ledger.js +188 -73
- package/dist/runtime/item-log-impl.d.ts +6 -0
- package/dist/runtime/item-log-impl.js +12 -0
- package/dist/runtime/session-runner.d.ts +25 -1
- package/dist/runtime/session-runner.js +83 -11
- package/dist/types/checkpoint.d.ts +21 -4
- package/dist/types/checkpoint.js +33 -3
- package/dist/util/detached-handle.d.ts +9 -20
- package/dist/util/detached-handle.js +7 -108
- package/package.json +2 -2
|
@@ -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
|
|
299
|
-
* the lane to the step, so steps the
|
|
300
|
-
* how other dispatches on this context
|
|
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,
|
|
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,16 @@ 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
|
+
}
|
|
319
383
|
/**
|
|
320
384
|
* @internal
|
|
321
385
|
* Drop `frame` from the in-flight set. Called when its step resolves, success or
|
|
@@ -324,6 +388,88 @@ export class ContextImpl {
|
|
|
324
388
|
leaveStep(frame) {
|
|
325
389
|
this._inFlight.delete(frame);
|
|
326
390
|
}
|
|
391
|
+
/**
|
|
392
|
+
* @internal
|
|
393
|
+
* Give back this lane's ordinal after its step failed, so a retry runs at the same
|
|
394
|
+
* path. A resumed run never sees the failed attempt — nothing records a failure — so
|
|
395
|
+
* without this a retry would take the next ordinal and every later dispatch would sit
|
|
396
|
+
* one position past where the resume looks for it. Only the latest dispatch of a key
|
|
397
|
+
* can give its ordinal back; once a later one has taken the next, the ordinal stays.
|
|
398
|
+
*/
|
|
399
|
+
releaseDispatch() {
|
|
400
|
+
const lane = this._lane;
|
|
401
|
+
if (!lane || this._occurrences.get(lane.key) !== lane.occurrence + 1) {
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
this._occurrences.set(lane.key, lane.occurrence);
|
|
405
|
+
for (const key of [
|
|
406
|
+
...this._occurrences.keys(),
|
|
407
|
+
]) {
|
|
408
|
+
if (key.startsWith(`${lane.path}/`)) {
|
|
409
|
+
this._occurrences.delete(key);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* @internal
|
|
415
|
+
* Mark the start of the outermost run on this context. See `_baseline`.
|
|
416
|
+
*/
|
|
417
|
+
beginRun() {
|
|
418
|
+
this._baseline = {
|
|
419
|
+
items: [
|
|
420
|
+
...this.itemLog.items,
|
|
421
|
+
],
|
|
422
|
+
occurrences: Object.fromEntries(this._occurrences),
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* @internal
|
|
427
|
+
* Mark a run as finished, so checkpoints record the live log and counts again.
|
|
428
|
+
*/
|
|
429
|
+
endRun() {
|
|
430
|
+
this._baseline = undefined;
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* @internal
|
|
434
|
+
* What a checkpoint persists for the item log and dispatch counts — see `_baseline`.
|
|
435
|
+
*/
|
|
436
|
+
runBaseline() {
|
|
437
|
+
return (this._baseline ?? {
|
|
438
|
+
items: [
|
|
439
|
+
...this.itemLog.items,
|
|
440
|
+
],
|
|
441
|
+
occurrences: Object.fromEntries(this._occurrences),
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* @internal
|
|
446
|
+
* Whether a run on this context began and never finished — it failed, or is in
|
|
447
|
+
* flight. A run starting now repeats it.
|
|
448
|
+
*/
|
|
449
|
+
hasUnfinishedRun() {
|
|
450
|
+
return this._baseline !== undefined;
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* @internal
|
|
454
|
+
* Stand the context back at a stored run baseline: the item log and dispatch counts
|
|
455
|
+
* a checkpoint recorded. For a run retried in place, which must see what a resume on
|
|
456
|
+
* a new harness would — not the items and counts its failed attempt left in memory.
|
|
457
|
+
*/
|
|
458
|
+
rebase(baseline) {
|
|
459
|
+
this.log.replace(baseline.items);
|
|
460
|
+
this._occurrences.clear();
|
|
461
|
+
this.restoreOccurrences(baseline.occurrences);
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* @internal
|
|
465
|
+
* Seed the dispatch counts a restored run starts from, so a resumed context numbers
|
|
466
|
+
* its dispatches where the recorded run did rather than from zero.
|
|
467
|
+
*/
|
|
468
|
+
restoreOccurrences(occurrences) {
|
|
469
|
+
for (const [key, count] of Object.entries(occurrences)) {
|
|
470
|
+
this._occurrences.set(key, count);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
327
473
|
/**
|
|
328
474
|
* @internal
|
|
329
475
|
* Return a defensive copy of the current frontier. Consumed by the
|
|
@@ -339,21 +485,52 @@ export class ContextImpl {
|
|
|
339
485
|
}));
|
|
340
486
|
}
|
|
341
487
|
}
|
|
342
|
-
|
|
488
|
+
/**
|
|
489
|
+
* Items appended through one lane. Each record also feeds its parent lane's, so a
|
|
490
|
+
* composite step's record holds everything appended beneath it on the same context.
|
|
491
|
+
*/
|
|
492
|
+
class AppendRecord {
|
|
493
|
+
parent;
|
|
494
|
+
items = [];
|
|
495
|
+
constructor(parent) {
|
|
496
|
+
this.parent = parent;
|
|
497
|
+
}
|
|
498
|
+
add(item) {
|
|
499
|
+
this.items.push(item);
|
|
500
|
+
this.parent?.add(item);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
343
503
|
/** The context each lane views, so `laneOf` never stacks a proxy on a proxy. */
|
|
344
504
|
const laneTargets = new WeakMap();
|
|
345
505
|
/**
|
|
346
|
-
* A view of `ctx` that reads `
|
|
347
|
-
*
|
|
348
|
-
*
|
|
506
|
+
* A view of `ctx` that reads `lane` as its dispatch and forwards every other read and
|
|
507
|
+
* write to the context itself, so state, usage, abort, and the in-flight set stay
|
|
508
|
+
* shared. Its item log appends to the shared log and notes each item in the lane's
|
|
509
|
+
* record. A Proxy rather than a subclass: steps assign `ctx.state` and friends
|
|
349
510
|
* directly, and a copy would keep those writes to itself.
|
|
350
511
|
*/
|
|
351
|
-
function laneOf(ctx,
|
|
512
|
+
function laneOf(ctx, lane) {
|
|
352
513
|
const target = laneTargets.get(ctx) ?? ctx;
|
|
353
|
-
const
|
|
514
|
+
const itemLog = {
|
|
515
|
+
get items() {
|
|
516
|
+
return target.itemLog.items;
|
|
517
|
+
},
|
|
518
|
+
append(item) {
|
|
519
|
+
target.itemLog.append(item);
|
|
520
|
+
const items = target.itemLog.items;
|
|
521
|
+
lane.appended.add(items[items.length - 1]);
|
|
522
|
+
},
|
|
523
|
+
};
|
|
524
|
+
const view = new Proxy(target, {
|
|
354
525
|
get(base, prop, receiver) {
|
|
355
526
|
if (prop === '_path') {
|
|
356
|
-
return path;
|
|
527
|
+
return lane.path;
|
|
528
|
+
}
|
|
529
|
+
if (prop === '_lane') {
|
|
530
|
+
return lane;
|
|
531
|
+
}
|
|
532
|
+
if (prop === 'itemLog') {
|
|
533
|
+
return itemLog;
|
|
357
534
|
}
|
|
358
535
|
return Reflect.get(base, prop, receiver);
|
|
359
536
|
},
|
|
@@ -361,8 +538,8 @@ function laneOf(ctx, path) {
|
|
|
361
538
|
return Reflect.set(base, prop, value);
|
|
362
539
|
},
|
|
363
540
|
});
|
|
364
|
-
laneTargets.set(
|
|
365
|
-
return
|
|
541
|
+
laneTargets.set(view, target);
|
|
542
|
+
return view;
|
|
366
543
|
}
|
|
367
544
|
/**
|
|
368
545
|
* @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<
|
|
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.
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
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 {};
|
|
@@ -0,0 +1,58 @@
|
|
|
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 { z } from 'zod';
|
|
12
|
+
//#region Schema
|
|
13
|
+
const SessionRecordSchema = z.object({
|
|
14
|
+
/** The thread's history after its last finished turn. */
|
|
15
|
+
items: z.array(z.unknown()),
|
|
16
|
+
/** What the thread's turns have spent, summed as each turn settles. */
|
|
17
|
+
usage: z
|
|
18
|
+
.object({
|
|
19
|
+
inputTokens: z.number(),
|
|
20
|
+
outputTokens: z.number(),
|
|
21
|
+
cachedTokens: z.number().optional(),
|
|
22
|
+
cost: z.number().optional(),
|
|
23
|
+
billedCost: z.number().optional(),
|
|
24
|
+
})
|
|
25
|
+
.optional(),
|
|
26
|
+
/** The turn in flight, if one was cut off. */
|
|
27
|
+
turn: z
|
|
28
|
+
.object({
|
|
29
|
+
executionId: z.string(),
|
|
30
|
+
/** The ids of the messages the turn delivers, in order. */
|
|
31
|
+
messageIds: z.array(z.string()),
|
|
32
|
+
})
|
|
33
|
+
.optional(),
|
|
34
|
+
});
|
|
35
|
+
/** @internal */
|
|
36
|
+
export function createSessionStore(storage) {
|
|
37
|
+
return {
|
|
38
|
+
load: async (threadId) => {
|
|
39
|
+
const raw = await storage.get(sessionKey(threadId));
|
|
40
|
+
if (raw === null) {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
const parsed = SessionRecordSchema.safeParse(raw);
|
|
44
|
+
if (!parsed.success) {
|
|
45
|
+
console.warn(`SessionStore: discarding unreadable session "${threadId}": ${parsed.error.message}`);
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
return parsed.data;
|
|
49
|
+
},
|
|
50
|
+
save: async (threadId, record) => {
|
|
51
|
+
await storage.set(sessionKey(threadId), record);
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function sessionKey(threadId) {
|
|
56
|
+
return `session:${threadId}`;
|
|
57
|
+
}
|
|
58
|
+
//#endregion
|