@noetic-tools/core 5.19.0 → 5.19.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.
@@ -4,6 +4,8 @@ export interface Bill {
4
4
  usage: RoundUsage;
5
5
  cost: number;
6
6
  }
7
+ /** The bill of a round the provider never reported on. */
8
+ export declare const noBill: Bill;
7
9
  /**
8
10
  * What one model call's rounds used and cost. Every round the provider answered
9
11
  * counts, including one the loop rejected and asked again: the provider billed it.
@@ -1,3 +1,11 @@
1
+ /** The bill of a round the provider never reported on. */
2
+ export const noBill = {
3
+ usage: {
4
+ inputTokens: 0,
5
+ outputTokens: 0,
6
+ },
7
+ cost: 0,
8
+ };
1
9
  /**
2
10
  * What one model call's rounds used and cost. Every round the provider answered
3
11
  * counts, including one the loop rejected and asked again: the provider billed it.
@@ -22,13 +30,7 @@ export class CallSpend {
22
30
  * round ledger to record.
23
31
  */
24
32
  keep() {
25
- const bill = this.held ?? {
26
- usage: {
27
- inputTokens: 0,
28
- outputTokens: 0,
29
- },
30
- cost: 0,
31
- };
33
+ const bill = this.held ?? noBill;
32
34
  if (this.held) {
33
35
  this.rounds.push({
34
36
  ...this.held,
@@ -77,13 +79,7 @@ export class CallSpend {
77
79
  */
78
80
  charge() {
79
81
  const paid = this.rounds.filter((round) => !round.replayed);
80
- const bill = addBills(this.held, ...paid) ?? {
81
- usage: {
82
- inputTokens: 0,
83
- outputTokens: 0,
84
- },
85
- cost: 0,
86
- };
82
+ const bill = addBills(this.held, ...paid) ?? noBill;
87
83
  return {
88
84
  ...bill.usage,
89
85
  cost: bill.cost,
@@ -7,7 +7,7 @@ import { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broad
7
7
  import { drainsOf } from '../runtime/drain.js';
8
8
  import { markSpent } from '../util/spent.js';
9
9
  import { isErrorStatus } from '../util/status-code.js';
10
- import { CallSpend } from './call-spend.js';
10
+ import { CallSpend, noBill } from './call-spend.js';
11
11
  import { exportSpans } from './deps/context.js';
12
12
  import { RoundLedger } from './model-rounds.js';
13
13
  import { buildItemSchemaRegistry, createToolResultItem } from './model-schema.js';
@@ -90,6 +90,13 @@ function noteStreamGeneration(dispatch, event) {
90
90
  function wasRefused(err, dispatch) {
91
91
  return isErrorStatus(err) && dispatch.record.generationId === undefined;
92
92
  }
93
+ function itemIds(items) {
94
+ return items.flatMap((item) => 'id' in item && typeof item.id === 'string'
95
+ ? [
96
+ item.id,
97
+ ]
98
+ : []);
99
+ }
93
100
  function hasItem(items, id) {
94
101
  return items.some((item) => 'id' in item && item.id === id);
95
102
  }
@@ -421,9 +428,12 @@ class CallSpanCollector {
421
428
  }
422
429
  span.end();
423
430
  }
424
- /** Open and immediately close a tool-call span under the given model span. */
431
+ /**
432
+ * Open and immediately close a tool-call span under the given model span, or under
433
+ * the call's parent when the round's model call ran in an earlier attempt.
434
+ */
425
435
  recordToolSpan(parent, toolName, needsApproval, approval) {
426
- const span = this.harness.createSpan('tool.call', parent);
436
+ const span = this.harness.createSpan('tool.call', parent ?? this.parent);
427
437
  span.setAttribute(ToolAttr.NAME, toolName);
428
438
  span.setAttribute(ToolAttr.NEEDS_APPROVAL, needsApproval);
429
439
  if (approval !== undefined) {
@@ -553,17 +563,79 @@ export class AgentHarnessModelCaller {
553
563
  input: 0,
554
564
  items: 0,
555
565
  };
556
- // Record a round the loop goes on from, so a resumed loop can replay it.
557
- const recordRound = async (bill) => {
566
+ const markRound = () => {
567
+ marks = {
568
+ round,
569
+ log: roundLedger?.mark() ?? 0,
570
+ input: conversationInput.length,
571
+ items: allItems.length,
572
+ };
573
+ };
574
+ // The current round's checkpoint writes, in order. Its own record waits for
575
+ // them, so a late checkpoint never replaces it.
576
+ let checkpoints = Promise.resolve();
577
+ const writeRound = async (record) => {
558
578
  if (!roundLedger || request.signal?.aborted) {
559
579
  return;
560
580
  }
561
- await roundLedger.record(round, marks.log, {
581
+ if (!(await roundLedger.record(round, marks.log, record))) {
582
+ return;
583
+ }
584
+ prepared.emitIfAllowed('model_round_recorded', {
585
+ round,
586
+ itemIds: itemIds(record.items),
587
+ done: !record.cut,
588
+ });
589
+ };
590
+ // A rejected round is asked again on the conversation it was asked on, or fails
591
+ // the call, so a resume must not go on from the items it streamed. The same goes
592
+ // for the round that ends the loop.
593
+ const dropCheckpoints = async () => {
594
+ await checkpoints;
595
+ await roundLedger?.drop(round);
596
+ };
597
+ const rejectRound = async (check) => {
598
+ let result;
599
+ try {
600
+ result = check();
601
+ }
602
+ catch (error) {
603
+ await dropCheckpoints();
604
+ throw error;
605
+ }
606
+ if (result.kind === 'continue') {
607
+ await dropCheckpoints();
608
+ }
609
+ return result;
610
+ };
611
+ // Record a round the loop goes on from, so a resumed loop can replay it.
612
+ const recordRound = async (bill) => {
613
+ await checkpoints;
614
+ await writeRound({
562
615
  items: allItems.slice(marks.items),
563
616
  input: conversationInput.slice(marks.input),
564
617
  ...bill,
565
618
  });
566
619
  };
620
+ // Record the output items a round has finished while it still streams, so a
621
+ // resume goes on from them rather than making them again. The input holds only
622
+ // what the round began with: the tool round adds each function call with its
623
+ // output, as it does for a round that finishes.
624
+ const checkpoint = (finished) => {
625
+ if (!roundLedger) {
626
+ return;
627
+ }
628
+ const record = {
629
+ items: [
630
+ ...allItems.slice(marks.items),
631
+ ...finished,
632
+ ],
633
+ input: conversationInput.slice(marks.input),
634
+ ...noBill,
635
+ cut: true,
636
+ };
637
+ checkpoints = checkpoints.then(() => writeRound(record));
638
+ };
567
639
  let stoppedForRecall = false;
568
640
  const steers = openSteerInbox({
569
641
  ctx: request.ctx,
@@ -575,17 +647,39 @@ export class AgentHarnessModelCaller {
575
647
  while (!request.signal?.aborted) {
576
648
  const replayed = roundLedger?.take(round, replaySchemas);
577
649
  if (replayed) {
650
+ markRound();
578
651
  allItems.push(...replayed.items);
579
652
  conversationInput.push(...frameworkCast(replayed.input));
580
653
  for (const item of replayed.appended) {
581
654
  request.ctx?.itemLog.append(item);
582
655
  }
583
- if (!replayed.charged) {
656
+ // A cut round never reported usage, so it has no bill to count.
657
+ if (!replayed.charged && !replayed.cut) {
584
658
  spend.replay(replayed);
585
659
  }
586
660
  prepared.emitIfAllowed('model_round_replayed', {
587
661
  round,
588
662
  });
663
+ if (replayed.cut && !replayed.items.some(isFunctionCall)) {
664
+ // The stream was cut after the answer finished: it ends the loop.
665
+ break;
666
+ }
667
+ if (replayed.cut) {
668
+ // Go on from the function calls the stream finished: run them, then ask
669
+ // the model again with their results in the conversation.
670
+ await this.runToolRound({
671
+ roundItems: replayed.items,
672
+ request,
673
+ prepared,
674
+ allItems,
675
+ conversationInput,
676
+ round,
677
+ spans,
678
+ modelSpan: null,
679
+ steers,
680
+ });
681
+ await recordRound(spend.keep());
682
+ }
589
683
  round += 1;
590
684
  const replayLimit = this.handleToolRoundLimit({
591
685
  round,
@@ -599,12 +693,7 @@ export class AgentHarnessModelCaller {
599
693
  continue;
600
694
  }
601
695
  if (marks.round !== round) {
602
- marks = {
603
- round,
604
- log: roundLedger?.mark() ?? 0,
605
- input: conversationInput.length,
606
- items: allItems.length,
607
- };
696
+ markRound();
608
697
  }
609
698
  // A graceful stop starts no new round: wait here until it cancels the call.
610
699
  await drains?.hold(request.ctx);
@@ -706,6 +795,10 @@ export class AgentHarnessModelCaller {
706
795
  // Output items the stream has finished, kept so a steer can stop the
707
796
  // round early without losing them.
708
797
  const finishedItems = [];
798
+ // Parsed for the round ledger; none once the stream has failed, since a call
799
+ // that has thrown must write nothing more.
800
+ const parsedItems = [];
801
+ let streaming = true;
709
802
  let steered = false;
710
803
  const pipePromise = pipeStreamEventsToBroadcaster({
711
804
  stream: callResult.getFullResponsesStream(),
@@ -724,6 +817,19 @@ export class AgentHarnessModelCaller {
724
817
  },
725
818
  onItemDone: async (item) => {
726
819
  finishedItems.push(item);
820
+ if (streaming && roundLedger) {
821
+ try {
822
+ parsedItems.push(...replaySchemas.parseMany(frameworkCast([
823
+ item,
824
+ ])));
825
+ checkpoint(parsedItems);
826
+ }
827
+ catch {
828
+ // The round fails on this item when it ends; nothing after it can be
829
+ // gone on from.
830
+ streaming = false;
831
+ }
832
+ }
727
833
  if (!steers?.hasQueued() || !(await steers.offer(SteerPoint.ItemDone))) {
728
834
  return;
729
835
  }
@@ -755,6 +861,8 @@ export class AgentHarnessModelCaller {
755
861
  await awaitWithAbort(pipePromise, roundSignal);
756
862
  }
757
863
  catch (err) {
864
+ streaming = false;
865
+ await checkpoints;
758
866
  if (dispatch && wasRefused(err, dispatch)) {
759
867
  await dispatch.settle();
760
868
  }
@@ -813,25 +921,25 @@ export class AgentHarnessModelCaller {
813
921
  }
814
922
  continue;
815
923
  }
816
- const recovery = this.handleModelRecovery({
924
+ const recovery = await rejectRound(() => this.handleModelRecovery({
817
925
  sdkResponse,
818
926
  round,
819
927
  invalidRecoveryContinuations,
820
928
  emitIfAllowed: prepared.emitIfAllowed,
821
- });
929
+ }));
822
930
  if (recovery.kind === 'continue') {
823
931
  invalidRecoveryContinuations = recovery.invalidRecoveryContinuations;
824
932
  useEphemeralContinue = true;
825
933
  continue;
826
934
  }
827
935
  const roundItems = this.parseRoundItems(request, extractOutputItems(sdkResponse));
828
- const outputRecovery = this.handleEmptyOutputRecovery({
936
+ const outputRecovery = await rejectRound(() => this.handleEmptyOutputRecovery({
829
937
  sdkResponse,
830
938
  roundItems,
831
939
  round,
832
940
  invalidRecoveryContinuations,
833
941
  emitIfAllowed: prepared.emitIfAllowed,
834
- });
942
+ }));
835
943
  if (outputRecovery.kind === 'continue') {
836
944
  invalidRecoveryContinuations = outputRecovery.invalidRecoveryContinuations;
837
945
  useEphemeralContinue = true;
@@ -859,6 +967,9 @@ export class AgentHarnessModelCaller {
859
967
  // A steer staged while the final answer streamed gets its own round, so
860
968
  // the model answers it inside this call rather than in the next turn.
861
969
  if (!ranTools && !steers?.hasStaged()) {
970
+ // The step's own record covers the round that ends the loop. A cut record
971
+ // left behind would hand a retry this answer after the step rejected it.
972
+ await dropCheckpoints();
862
973
  break;
863
974
  }
864
975
  if (!ranTools) {
@@ -14,6 +14,11 @@
14
14
  * belongs to the conversation the earlier recorded rounds built. When the step
15
15
  * finishes and records, the ledger prunes its rounds.
16
16
  *
17
+ * While a round streams, each output item it finishes is recorded at the same key as
18
+ * a `cut` round, so a host killed mid-stream resumes from those items rather than
19
+ * making them again. The round's own record replaces it. A cut round with neither a
20
+ * function call nor an answer has nothing to go on from, so replay stops there.
21
+ *
17
22
  * A call that fails charges its context with the rounds it recorded, so a failed run
18
23
  * reports what it paid. A retry in place replays those rounds on the same context,
19
24
  * so the ledger remembers which rounds were charged and the replay counts them no
@@ -28,6 +33,8 @@ export interface RoundRecord {
28
33
  input: unknown[];
29
34
  usage: RoundUsage;
30
35
  cost: number;
36
+ /** The stream had not finished: `items` holds the output items it had, tools not yet run. */
37
+ cut?: boolean;
31
38
  }
32
39
  /** A replayed round: its record plus the items it appended to the item log. */
33
40
  export interface ReplayedRound extends RoundRecord {
@@ -55,8 +62,17 @@ export declare class RoundLedger {
55
62
  take(round: number, schemas: ItemSchemaRegistry): ReplayedRound | undefined;
56
63
  /** Mark where the log stood when a round began, so its appends can be recorded. */
57
64
  mark(): number;
58
- /** Record a finished round. `logMark` is what `mark()` returned when it began. */
59
- record(round: number, logMark: number, record: RoundRecord): Promise<void>;
65
+ /**
66
+ * Record a round, finished or `cut`. `logMark` is what `mark()` returned when it
67
+ * began. Resolves whether the record was stored.
68
+ *
69
+ * Also drops the record of the round after it, left by an earlier attempt of the
70
+ * same step (a steering retry calls the model again at the same path). Replay
71
+ * stops at the first missing round, so the stale rounds past it are never read.
72
+ */
73
+ record(round: number, logMark: number, record: RoundRecord): Promise<boolean>;
74
+ /** Drop the record of round `round`: the loop threw that round away. */
75
+ drop(round: number): Promise<void>;
60
76
  /** Note that the rounds this loop recorded were charged to its context. */
61
77
  charged(): void;
62
78
  private key;
@@ -14,13 +14,19 @@
14
14
  * belongs to the conversation the earlier recorded rounds built. When the step
15
15
  * finishes and records, the ledger prunes its rounds.
16
16
  *
17
+ * While a round streams, each output item it finishes is recorded at the same key as
18
+ * a `cut` round, so a host killed mid-stream resumes from those items rather than
19
+ * making them again. The round's own record replaces it. A cut round with neither a
20
+ * function call nor an answer has nothing to go on from, so replay stops there.
21
+ *
17
22
  * A call that fails charges its context with the rounds it recorded, so a failed run
18
23
  * reports what it paid. A retry in place replays those rounds on the same context,
19
24
  * so the ledger remembers which rounds were charged and the replay counts them no
20
25
  * more.
21
26
  */
22
- import { frameworkCast } from '@noetic-tools/types';
27
+ import { frameworkCast, isAssistantMessage } from '@noetic-tools/types';
23
28
  import { z } from 'zod';
29
+ import { isFunctionCall } from '../interpreter/typeguards.js';
24
30
  import { ContextImpl } from './deps/runtime.js';
25
31
  //#region Types
26
32
  const ROUND_KIND = 'callModel:round';
@@ -34,6 +40,7 @@ const RoundOutputSchema = z.object({
34
40
  cacheWriteTokens: z.number().optional(),
35
41
  }),
36
42
  cost: z.number(),
43
+ cut: z.boolean().optional(),
37
44
  });
38
45
  /**
39
46
  * Keys of recorded rounds a failed call charged, per execution ledger. Kept in memory
@@ -52,7 +59,7 @@ export class RoundLedger {
52
59
  dispatch;
53
60
  replaying = true;
54
61
  /** Rounds this loop recorded. */
55
- recorded = [];
62
+ recorded = new Set();
56
63
  constructor(ctx, dispatch) {
57
64
  this.ctx = ctx;
58
65
  this.dispatch = dispatch;
@@ -85,12 +92,14 @@ export class RoundLedger {
85
92
  this.replaying = false;
86
93
  return undefined;
87
94
  }
95
+ let replayed;
88
96
  try {
89
- return {
97
+ replayed = {
90
98
  items: schemas.parseMany(parsed.data.items),
91
99
  input: parsed.data.input,
92
100
  usage: parsed.data.usage,
93
101
  cost: parsed.data.cost,
102
+ cut: parsed.data.cut,
94
103
  appended: schemas.parseMany(entry.items ?? []),
95
104
  charged: chargedRounds.get(ledger)?.has(this.key(round)) ?? false,
96
105
  };
@@ -99,17 +108,29 @@ export class RoundLedger {
99
108
  this.replaying = false;
100
109
  return undefined;
101
110
  }
111
+ if (replayed.cut && !replayed.items.some(goesOn)) {
112
+ this.replaying = false;
113
+ return undefined;
114
+ }
115
+ return replayed;
102
116
  }
103
117
  /** Mark where the log stood when a round began, so its appends can be recorded. */
104
118
  mark() {
105
119
  return this.ctx.appendedItems().length;
106
120
  }
107
- /** Record a finished round. `logMark` is what `mark()` returned when it began. */
121
+ /**
122
+ * Record a round, finished or `cut`. `logMark` is what `mark()` returned when it
123
+ * began. Resolves whether the record was stored.
124
+ *
125
+ * Also drops the record of the round after it, left by an earlier attempt of the
126
+ * same step (a steering retry calls the model again at the same path). Replay
127
+ * stops at the first missing round, so the stale rounds past it are never read.
128
+ */
108
129
  async record(round, logMark, record) {
109
130
  this.replaying = false;
110
131
  const ledger = this.ctx.ledger;
111
132
  if (!ledger) {
112
- return;
133
+ return false;
113
134
  }
114
135
  const appended = this.ctx.appendedItems().slice(logMark);
115
136
  const stored = await ledger.record({
@@ -126,16 +147,22 @@ export class RoundLedger {
126
147
  completedAt: new Date().toISOString(),
127
148
  });
128
149
  if (!stored) {
129
- return;
150
+ return false;
130
151
  }
131
- this.recorded.push(round);
152
+ this.recorded.add(round);
132
153
  // A new record holds a bill no context has been charged with yet.
133
154
  chargedRounds.get(ledger)?.delete(this.key(round));
155
+ await ledger.drop(this.key(round + 1));
156
+ return true;
157
+ }
158
+ /** Drop the record of round `round`: the loop threw that round away. */
159
+ async drop(round) {
160
+ await this.ctx.ledger?.drop(this.key(round));
134
161
  }
135
162
  /** Note that the rounds this loop recorded were charged to its context. */
136
163
  charged() {
137
164
  const ledger = this.ctx.ledger;
138
- if (!ledger || this.recorded.length === 0) {
165
+ if (!ledger || this.recorded.size === 0) {
139
166
  return;
140
167
  }
141
168
  const keys = chargedRounds.get(ledger) ?? new Set();
@@ -148,6 +175,10 @@ export class RoundLedger {
148
175
  return roundPath(this.dispatch.path, round);
149
176
  }
150
177
  }
178
+ /** A cut round holding a function call or an answer has something to go on from. */
179
+ function goesOn(item) {
180
+ return isFunctionCall(item) || isAssistantMessage(item);
181
+ }
151
182
  /** @internal The ledger key of round `round` of the model loop at step path `path`. */
152
183
  export function roundPath(path, round) {
153
184
  return `${path}/round#${round}`;
@@ -145,7 +145,7 @@ export declare function createStepLedgerStore(opts: {
145
145
  }): StepLedgerStore;
146
146
  /** @public What retention did to one execution's ledger. Observable for host logging. */
147
147
  export interface StepLedgerStats {
148
- /** Entries written. */
148
+ /** Paths recorded. A record that replaces the entry at its path counts no more. */
149
149
  recorded: number;
150
150
  /** Entries not written because their output exceeded `maxEntryBytes`. */
151
151
  droppedOversize: number;
@@ -216,6 +216,8 @@ export declare class StepLedger {
216
216
  * the entry was stored.
217
217
  */
218
218
  record(entry: StepLedgerEntry): Promise<boolean>;
219
+ /** Drop the entry recorded at `path`, when there is one. */
220
+ drop(path: string): Promise<void>;
219
221
  /**
220
222
  * Drop every positional entry. A host calls this once a run has finished and the
221
223
  * checkpoint holds its result: every later resume starts past them, so they are dead.
@@ -338,8 +338,10 @@ export class StepLedger {
338
338
  }
339
339
  const replaced = this.live.get(entry.path);
340
340
  this.live.set(entry.path, seq);
341
- this.counts.recorded += 1;
342
- if (replaced !== undefined) {
341
+ if (replaced === undefined) {
342
+ this.counts.recorded += 1;
343
+ }
344
+ else {
343
345
  await this.deleteSeq(replaced);
344
346
  }
345
347
  if (!entry.path.startsWith(REPLAY_KEY_PREFIX)) {
@@ -347,6 +349,12 @@ export class StepLedger {
347
349
  }
348
350
  return true;
349
351
  }
352
+ /** Drop the entry recorded at `path`, when there is one. */
353
+ async drop(path) {
354
+ await this.prune([
355
+ path,
356
+ ]);
357
+ }
350
358
  /**
351
359
  * Drop every positional entry. A host calls this once a run has finished and the
352
360
  * checkpoint holds its result: every later resume starts past them, so they are dead.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noetic-tools/core",
3
- "version": "5.19.0",
3
+ "version": "5.19.1",
4
4
  "type": "module",
5
5
  "description": "Step primitives, interpreter, runtime, and context layer contract for Noetic agents.",
6
6
  "license": "Apache-2.0",