@noetic-tools/core 5.13.0 → 5.14.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.
- package/dist/builders/decide-builders.d.ts +2 -2
- package/dist/builders/dynamic-workflow.js +2 -0
- package/dist/builders/provide-builder.d.ts +2 -2
- package/dist/builders/spawn-builder.d.ts +2 -2
- package/dist/builders/step-builders.d.ts +5 -5
- package/dist/builders/workflow-hydrator.d.ts +1 -1
- package/dist/builders/workflow-hydrator.js +53 -3
- package/dist/expression/check.js +14 -0
- package/dist/expression/jsonata.d.ts +7 -0
- package/dist/expression/jsonata.js +11 -1
- package/dist/harness/agent-harness.d.ts +59 -5
- package/dist/harness/agent-harness.js +176 -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 +2 -2
- package/dist/interpreter/emit-items.d.ts +19 -0
- package/dist/interpreter/emit-items.js +106 -0
- package/dist/interpreter/execute-action.js +4 -1
- package/dist/interpreter/execute-control.js +7 -3
- package/dist/interpreter/execute.js +66 -9
- package/dist/observability/span-impl.d.ts +9 -0
- package/dist/observability/span-impl.js +13 -0
- package/dist/runtime/context-impl.d.ts +156 -14
- package/dist/runtime/context-impl.js +326 -28
- 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 +77 -40
- package/dist/runtime/durable/step-ledger.js +193 -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/schemas/workflow.d.ts +1 -1
- package/dist/types/checkpoint.d.ts +21 -4
- package/dist/types/checkpoint.js +33 -3
- package/package.json +2 -2
- package/schema/noetic-workflow.schema.json +391 -0
|
@@ -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
|
|
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();
|
|
@@ -306,18 +330,22 @@ export class AgentHarness {
|
|
|
306
330
|
forceAtomicRecall: opts.forceAtomicRecall,
|
|
307
331
|
contextCache: opts.contextCache,
|
|
308
332
|
decisionModel: opts.decisionModel,
|
|
333
|
+
emitItemsOnReplay: opts.emitItemsOnReplay,
|
|
309
334
|
approveToolCall: opts.approveToolCall,
|
|
310
335
|
};
|
|
311
336
|
this.fs = environment?.fs ?? createInMemoryFsAdapter();
|
|
312
337
|
this.shell = environment?.shell ?? createInMemoryShellAdapter();
|
|
313
338
|
this.subprocess = environment?.subprocess ?? createInMemorySubprocessAdapter();
|
|
314
|
-
this.checkpointStore = storageEnv
|
|
315
|
-
this.stepLedgerStore =
|
|
339
|
+
this.checkpointStore = resolveCheckpointStore(storageEnv, opts.durability);
|
|
340
|
+
this.stepLedgerStore = this.checkpointStore
|
|
316
341
|
? createStepLedgerStore({
|
|
317
342
|
storage: this.config.storage ?? createInMemoryStorage(),
|
|
318
343
|
})
|
|
319
344
|
: undefined;
|
|
320
345
|
this.stepLedgerRetention = resolveStepLedgerRetention(storageEnv?.stepLedgerRetention);
|
|
346
|
+
this.sessionStore = this.checkpointStore
|
|
347
|
+
? createSessionStore(this.config.storage ?? createInMemoryStorage())
|
|
348
|
+
: undefined;
|
|
321
349
|
this.agentGraph = opts.agentGraph;
|
|
322
350
|
this.harnessTools = opts.tools ?? [];
|
|
323
351
|
this._contextLayers = opts.contextLayers;
|
|
@@ -448,6 +476,11 @@ export class AgentHarness {
|
|
|
448
476
|
}
|
|
449
477
|
seedSessionHistory(threadId, items) {
|
|
450
478
|
const session = this.getOrCreateSession(threadId);
|
|
479
|
+
if (session.record) {
|
|
480
|
+
// Queued ahead of any turn on this thread, so the next turn reads it back.
|
|
481
|
+
void session.record.seed(items);
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
451
484
|
session.accumulatedItems = [
|
|
452
485
|
...items,
|
|
453
486
|
];
|
|
@@ -457,8 +490,10 @@ export class AgentHarness {
|
|
|
457
490
|
if (existing) {
|
|
458
491
|
return existing;
|
|
459
492
|
}
|
|
493
|
+
const record = this.threadRecord(threadId);
|
|
460
494
|
const session = {
|
|
461
495
|
accumulatedItems: [],
|
|
496
|
+
record,
|
|
462
497
|
runner: new SessionRunner({
|
|
463
498
|
threadId,
|
|
464
499
|
agentName: this.config.name,
|
|
@@ -467,21 +502,29 @@ export class AgentHarness {
|
|
|
467
502
|
// together (queue flush), later messages' values for these fields
|
|
468
503
|
// are ignored. `deliveryMode` is resolved per-message at enqueue
|
|
469
504
|
// time and doesn't apply here.
|
|
470
|
-
createContext: (items, _turnId, messages) => {
|
|
505
|
+
createContext: async (items, _turnId, messages) => {
|
|
471
506
|
const perTurnOptions = messages[0]?.options ?? {};
|
|
472
|
-
const
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
const ctx = this.createContext({
|
|
477
|
-
items: allItems,
|
|
478
|
-
threadId,
|
|
479
|
-
resourceId: perTurnOptions.resourceId,
|
|
507
|
+
const messageIds = messages.map((m) => m.id);
|
|
508
|
+
const history = record ? await record.history() : session.accumulatedItems;
|
|
509
|
+
// A re-delivery of a cut-off turn's messages picks that turn up where it died.
|
|
510
|
+
const resumed = await record?.resume(messageIds, {
|
|
480
511
|
state: perTurnOptions.state,
|
|
481
512
|
contextLayers: perTurnOptions.contextLayers,
|
|
482
|
-
extraContextLayers: perTurnOptions.extraContextLayers,
|
|
483
513
|
_broadcaster: session.runner.broadcaster,
|
|
484
514
|
});
|
|
515
|
+
const ctx = resumed ??
|
|
516
|
+
this.createContext({
|
|
517
|
+
items: [
|
|
518
|
+
...history,
|
|
519
|
+
...items,
|
|
520
|
+
],
|
|
521
|
+
threadId,
|
|
522
|
+
resourceId: perTurnOptions.resourceId,
|
|
523
|
+
state: perTurnOptions.state,
|
|
524
|
+
contextLayers: perTurnOptions.contextLayers,
|
|
525
|
+
extraContextLayers: perTurnOptions.extraContextLayers,
|
|
526
|
+
_broadcaster: session.runner.broadcaster,
|
|
527
|
+
});
|
|
485
528
|
const ext = frameworkCast(ctx);
|
|
486
529
|
ext._sessionQueue = session.runner.queue;
|
|
487
530
|
ext._sessionBetweenRounds = true;
|
|
@@ -493,6 +536,7 @@ export class AgentHarness {
|
|
|
493
536
|
...this.harnessTools,
|
|
494
537
|
]);
|
|
495
538
|
}
|
|
539
|
+
await record?.begin(ctx, messageIds);
|
|
496
540
|
return ctx;
|
|
497
541
|
},
|
|
498
542
|
runTurn: async (ctx, _turn, signal) => {
|
|
@@ -515,17 +559,42 @@ export class AgentHarness {
|
|
|
515
559
|
});
|
|
516
560
|
}
|
|
517
561
|
const result = await this.initAndRun(this.agentGraph, '', ctx);
|
|
562
|
+
if (record) {
|
|
563
|
+
await record.end(ctx, ctx.itemLog.items);
|
|
564
|
+
return result;
|
|
565
|
+
}
|
|
518
566
|
// Snapshot final items into session history for the next turn.
|
|
519
567
|
session.accumulatedItems = [
|
|
520
568
|
...ctx.itemLog.items,
|
|
521
569
|
];
|
|
522
570
|
return result;
|
|
523
571
|
},
|
|
572
|
+
// Stored totals are the session's usage; the runner only mirrors them.
|
|
573
|
+
onTurnUsage: record
|
|
574
|
+
? async (spent) => {
|
|
575
|
+
session.runner.seedUsage(await record.addUsage(spent));
|
|
576
|
+
}
|
|
577
|
+
: undefined,
|
|
524
578
|
}),
|
|
525
579
|
};
|
|
526
580
|
this.sessions.set(threadId, session);
|
|
581
|
+
if (record) {
|
|
582
|
+
void record.usage().then((usage) => session.runner.seedUsage(usage));
|
|
583
|
+
}
|
|
527
584
|
return session;
|
|
528
585
|
}
|
|
586
|
+
/** The stored record for `threadId`, when durability is on. */
|
|
587
|
+
threadRecord(threadId) {
|
|
588
|
+
if (!this.sessionStore) {
|
|
589
|
+
return undefined;
|
|
590
|
+
}
|
|
591
|
+
return new ThreadRecord({
|
|
592
|
+
store: this.sessionStore,
|
|
593
|
+
restore: (executionId, opts) => this.restore(executionId, opts),
|
|
594
|
+
clearCheckpoint: (executionId) => this.clearCheckpoint(executionId),
|
|
595
|
+
parseItems: (raw) => this.itemSchemas.parseMany(raw),
|
|
596
|
+
}, threadId);
|
|
597
|
+
}
|
|
529
598
|
requireSession(scope) {
|
|
530
599
|
const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
|
|
531
600
|
let session = this.sessions.get(threadId);
|
|
@@ -622,27 +691,91 @@ export class AgentHarness {
|
|
|
622
691
|
return execute(s, input, ctx);
|
|
623
692
|
}
|
|
624
693
|
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
694
|
const entry = live ?? {
|
|
631
695
|
ctx,
|
|
632
696
|
depth: 0,
|
|
697
|
+
failed: false,
|
|
698
|
+
ready: Promise.resolve(),
|
|
633
699
|
};
|
|
634
700
|
entry.depth += 1;
|
|
635
701
|
this.liveRoots.set(ctx.id, entry);
|
|
702
|
+
if (!live) {
|
|
703
|
+
// A restored or sequentially re-run root context reuses its id — clear
|
|
704
|
+
// any closure from a previous completion so its channels work again.
|
|
705
|
+
this.channelStore.openExecution(ctx.id);
|
|
706
|
+
entry.ready = this.beginDurableRun(ctx);
|
|
707
|
+
}
|
|
636
708
|
try {
|
|
709
|
+
await entry.ready;
|
|
637
710
|
return await execute(s, input, ctx);
|
|
638
711
|
}
|
|
712
|
+
catch (error) {
|
|
713
|
+
entry.failed = true;
|
|
714
|
+
throw error;
|
|
715
|
+
}
|
|
639
716
|
finally {
|
|
640
717
|
entry.depth -= 1;
|
|
641
718
|
if (entry.depth <= 0) {
|
|
642
719
|
this.liveRoots.delete(ctx.id);
|
|
643
720
|
this.channelStore.closeExecution(ctx.id);
|
|
644
721
|
await this.acpSessions.closeOwnedBy(ctx.id);
|
|
722
|
+
if (!entry.failed) {
|
|
723
|
+
await this.endDurableRun(ctx);
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* Fix the point a resume of this run starts from, and queue it for saving — so even
|
|
730
|
+
* a run whose first step dies leaves a snapshot to restore. The save is not awaited:
|
|
731
|
+
* the steps' own checkpoints queue behind it.
|
|
732
|
+
*
|
|
733
|
+
* When the context's last run never finished, the run repeats it, and it does so
|
|
734
|
+
* from storage — the stored baseline and ledger — exactly as a new harness resuming
|
|
735
|
+
* the execution would, not from what the failed attempt left in memory.
|
|
736
|
+
*/
|
|
737
|
+
async beginDurableRun(ctx) {
|
|
738
|
+
if (!this.checkpointStore || !(ctx instanceof ContextImpl)) {
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
if (ctx.hasUnfinishedRun()) {
|
|
742
|
+
await this.rebuildFromStorage(ctx);
|
|
743
|
+
}
|
|
744
|
+
ctx.beginRun();
|
|
745
|
+
void this.saveCheckpoint(ctx);
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* Stand `ctx` at its stored baseline and give it the stored ledger. Without a
|
|
749
|
+
* snapshot (its save failed), the baseline the context fixed in memory when the run
|
|
750
|
+
* began is the best record left.
|
|
751
|
+
*/
|
|
752
|
+
async rebuildFromStorage(ctx) {
|
|
753
|
+
await this.pendingCheckpoints.get(ctx.id);
|
|
754
|
+
const snapshot = await this.checkpointStore?.load(ctx.id).catch(() => null);
|
|
755
|
+
ctx.rebase(snapshot
|
|
756
|
+
? {
|
|
757
|
+
items: this.itemSchemas.parseMany(snapshot.itemLog.items),
|
|
758
|
+
occurrences: snapshot.occurrences,
|
|
645
759
|
}
|
|
760
|
+
: ctx.runBaseline());
|
|
761
|
+
const recovered = await this.stepLedgerStore?.load(ctx.id);
|
|
762
|
+
if (recovered) {
|
|
763
|
+
ctx.ledger?.adopt(recovered);
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* A finished run is the next run's starting point: persist the live log and counts,
|
|
768
|
+
* then drop the run's positional ledger entries, which no later resume can reach.
|
|
769
|
+
* They are kept when the snapshot failed to land, since that snapshot still points
|
|
770
|
+
* at this run's start. A failed run skips this entirely — it is what a resume repeats.
|
|
771
|
+
*/
|
|
772
|
+
async endDurableRun(ctx) {
|
|
773
|
+
if (!this.checkpointStore || !(ctx instanceof ContextImpl)) {
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
ctx.endRun();
|
|
777
|
+
if (await this.saveCheckpoint(ctx)) {
|
|
778
|
+
await ctx.ledger?.dropPaths();
|
|
646
779
|
}
|
|
647
780
|
}
|
|
648
781
|
/**
|
|
@@ -839,11 +972,12 @@ export class AgentHarness {
|
|
|
839
972
|
// Read-only: if the session doesn't exist, treat history as empty rather
|
|
840
973
|
// than allocating a SessionRunner for a debug/preview call.
|
|
841
974
|
const existingSession = this.sessions.get(threadId);
|
|
842
|
-
const
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
975
|
+
const record = existingSession?.record ?? this.threadRecord(threadId);
|
|
976
|
+
const historyItems = record
|
|
977
|
+
? await record.history()
|
|
978
|
+
: [
|
|
979
|
+
...(existingSession?.accumulatedItems ?? []),
|
|
980
|
+
];
|
|
847
981
|
const ctx = this.createContext({
|
|
848
982
|
items: historyItems,
|
|
849
983
|
threadId,
|
|
@@ -936,7 +1070,24 @@ export class AgentHarness {
|
|
|
936
1070
|
* logic live beside the other durability machinery.
|
|
937
1071
|
*/
|
|
938
1072
|
async checkpoint(ctx) {
|
|
939
|
-
|
|
1073
|
+
await this.saveCheckpoint(ctx);
|
|
1074
|
+
}
|
|
1075
|
+
/**
|
|
1076
|
+
* Capture `ctx` behind any capture still in flight for the same execution, and
|
|
1077
|
+
* resolve true when this one landed. Every step in the tree checkpoints its root,
|
|
1078
|
+
* and concurrent paths would otherwise race their writes: on a networked adapter an
|
|
1079
|
+
* older snapshot could land last and win.
|
|
1080
|
+
*/
|
|
1081
|
+
saveCheckpoint(ctx) {
|
|
1082
|
+
const prior = this.pendingCheckpoints.get(ctx.id);
|
|
1083
|
+
const next = (prior ?? Promise.resolve(true)).then(() => captureCheckpoint(this, ctx));
|
|
1084
|
+
this.pendingCheckpoints.set(ctx.id, next);
|
|
1085
|
+
void next.finally(() => {
|
|
1086
|
+
if (this.pendingCheckpoints.get(ctx.id) === next) {
|
|
1087
|
+
this.pendingCheckpoints.delete(ctx.id);
|
|
1088
|
+
}
|
|
1089
|
+
});
|
|
1090
|
+
return next;
|
|
940
1091
|
}
|
|
941
1092
|
/**
|
|
942
1093
|
* 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
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
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 { frameworkCast } from '@noetic-tools/types';
|
|
18
|
+
import { z } from 'zod';
|
|
19
|
+
import { ContextImpl } from './deps/runtime.js';
|
|
20
|
+
//#region Types
|
|
21
|
+
const ROUND_KIND = 'callModel:round';
|
|
22
|
+
const RoundOutputSchema = z.object({
|
|
23
|
+
items: z.array(z.unknown()),
|
|
24
|
+
input: z.array(z.unknown()),
|
|
25
|
+
usage: z.object({
|
|
26
|
+
inputTokens: z.number(),
|
|
27
|
+
outputTokens: z.number(),
|
|
28
|
+
cachedTokens: z.number().optional(),
|
|
29
|
+
cacheWriteTokens: z.number().optional(),
|
|
30
|
+
}),
|
|
31
|
+
cost: z.number(),
|
|
32
|
+
});
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region Public API
|
|
35
|
+
/**
|
|
36
|
+
* The round ledger for one model loop. `open` gives none when the call is not running
|
|
37
|
+
* as a step on a context with a ledger.
|
|
38
|
+
*/
|
|
39
|
+
export class RoundLedger {
|
|
40
|
+
ctx;
|
|
41
|
+
dispatch;
|
|
42
|
+
replaying = true;
|
|
43
|
+
constructor(ctx, dispatch) {
|
|
44
|
+
this.ctx = ctx;
|
|
45
|
+
this.dispatch = dispatch;
|
|
46
|
+
}
|
|
47
|
+
/** Undefined when the loop has nothing to record into. */
|
|
48
|
+
static open(ctx) {
|
|
49
|
+
if (!(ctx instanceof ContextImpl) || !ctx.ledger) {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
const dispatch = ctx.currentDispatch();
|
|
53
|
+
return dispatch ? new RoundLedger(ctx, dispatch) : undefined;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* The recorded round `round`, with its items parsed, or undefined once replay has
|
|
57
|
+
* stopped — at the first round with no usable record, and for good after that.
|
|
58
|
+
*/
|
|
59
|
+
take(round, schemas) {
|
|
60
|
+
const ledger = this.ctx.ledger;
|
|
61
|
+
if (!this.replaying || !ledger || ledger.isEmpty) {
|
|
62
|
+
this.replaying = false;
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
const entry = ledger.take(this.key(round), {
|
|
66
|
+
id: this.dispatch.stepId,
|
|
67
|
+
kind: ROUND_KIND,
|
|
68
|
+
inputHash: this.dispatch.inputHash,
|
|
69
|
+
});
|
|
70
|
+
const parsed = entry ? RoundOutputSchema.safeParse(entry.output) : undefined;
|
|
71
|
+
if (!entry || !parsed?.success) {
|
|
72
|
+
this.replaying = false;
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
return {
|
|
77
|
+
items: schemas.parseMany(parsed.data.items),
|
|
78
|
+
input: parsed.data.input,
|
|
79
|
+
usage: parsed.data.usage,
|
|
80
|
+
cost: parsed.data.cost,
|
|
81
|
+
appended: schemas.parseMany(entry.items ?? []),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
this.replaying = false;
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/** Mark where the log stood when a round began, so its appends can be recorded. */
|
|
90
|
+
mark() {
|
|
91
|
+
return this.ctx.appendedItems().length;
|
|
92
|
+
}
|
|
93
|
+
/** Record a finished round. `logMark` is what `mark()` returned when it began. */
|
|
94
|
+
async record(round, logMark, record) {
|
|
95
|
+
this.replaying = false;
|
|
96
|
+
const appended = this.ctx.appendedItems().slice(logMark);
|
|
97
|
+
await this.ctx.ledger?.record({
|
|
98
|
+
path: this.key(round),
|
|
99
|
+
stepId: this.dispatch.stepId,
|
|
100
|
+
kind: ROUND_KIND,
|
|
101
|
+
inputHash: this.dispatch.inputHash,
|
|
102
|
+
output: frameworkCast(record),
|
|
103
|
+
...(appended.length > 0
|
|
104
|
+
? {
|
|
105
|
+
items: appended,
|
|
106
|
+
}
|
|
107
|
+
: {}),
|
|
108
|
+
completedAt: new Date().toISOString(),
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
key(round) {
|
|
112
|
+
return `${this.dispatch.path}/round#${round}`;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
//#endregion
|