@noetic-tools/core 5.18.0 → 5.19.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.
@@ -1,11 +1,13 @@
1
1
  import { frameworkCast, NoeticConfigError, SpendKind, SteerPoint, ToolChoiceMode, } from '@noetic-tools/types';
2
2
  import { serverTool } from '@openrouter/agent';
3
- import { convertTools, executeToolCall, extractOutputItems, extractSystemInstruction, extractUsage, itemsToInput, resolveWireJsonSchema, sanitizeToolNameForWire, } from '../adapters/openrouter.js';
3
+ import { convertTools, executeToolCall, extractOutputItems, extractSystemInstruction, extractUsage, itemsToInput, resolveWireJsonSchema, sanitizeToolNameForWire, toolsOnWire, } from '../adapters/openrouter.js';
4
4
  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 { drainsOf } from '../runtime/drain.js';
8
+ import { markSpent } from '../util/spent.js';
8
9
  import { isErrorStatus } from '../util/status-code.js';
10
+ import { CallSpend } from './call-spend.js';
9
11
  import { exportSpans } from './deps/context.js';
10
12
  import { RoundLedger } from './model-rounds.js';
11
13
  import { buildItemSchemaRegistry, createToolResultItem } from './model-schema.js';
@@ -474,8 +476,9 @@ export class AgentHarnessModelCaller {
474
476
  model: request.model,
475
477
  round: 0,
476
478
  });
479
+ let response;
477
480
  try {
478
- const response = await this.opts.callModelOverride(request);
481
+ response = await this.opts.callModelOverride(request);
479
482
  const itemSchemas = buildItemSchemaRegistry({
480
483
  base: this.opts.itemSchemas,
481
484
  layers: request.layers,
@@ -488,7 +491,10 @@ export class AgentHarnessModelCaller {
488
491
  };
489
492
  }
490
493
  finally {
491
- finished?.();
494
+ finished?.(response && {
495
+ cost: response.cost ?? 0,
496
+ usage: response.usage,
497
+ });
492
498
  await spans.flush();
493
499
  }
494
500
  }
@@ -504,28 +510,27 @@ export class AgentHarnessModelCaller {
504
510
  }
505
511
  const client = this.requireModelClient();
506
512
  const spans = this.newSpanCollector(request);
513
+ const spend = new CallSpend();
514
+ const roundLedger = RoundLedger.open(request.ctx);
507
515
  try {
508
- return await this.runModelLoop(request, client, spans);
516
+ return await this.runModelLoop({
517
+ request,
518
+ client,
519
+ spans,
520
+ spend,
521
+ roundLedger,
522
+ });
523
+ }
524
+ catch (error) {
525
+ throw markSpent(error, spend.charge(), () => roundLedger?.charged());
509
526
  }
510
527
  finally {
511
528
  await spans.flush();
512
529
  }
513
530
  }
514
- async runModelLoop(request, client, spans) {
531
+ async runModelLoop({ request, client, spans, spend, roundLedger, }) {
515
532
  const prepared = prepareModelRequest(request, this.opts.agentName);
516
533
  const allItems = [];
517
- const totalUsage = {
518
- inputTokens: 0,
519
- outputTokens: 0,
520
- cachedTokens: 0,
521
- };
522
- // Rounds after the first replay the same prefix and so hit the prompt cache
523
- // whatever the first round did. Keep them apart: only round 0 says whether
524
- // the assembled view was cached (see `noteCacheOutcome`).
525
- const rounds = [];
526
- let totalCost = 0;
527
- // What replayed rounds supplied, so the response can report what was paid now.
528
- let replayedCost;
529
534
  let servedTier;
530
535
  const conversationInput = itemsToInput(prepared.remaining);
531
536
  const textFormat = request.outputSchema
@@ -535,7 +540,6 @@ export class AgentHarnessModelCaller {
535
540
  let invalidRecoveryContinuations = 0;
536
541
  let toolLimitRecoveryContinuations = 0;
537
542
  let useEphemeralContinue = false;
538
- const roundLedger = RoundLedger.open(request.ctx);
539
543
  const drains = drainsOf(request.ctx);
540
544
  const replaySchemas = buildItemSchemaRegistry({
541
545
  base: this.opts.itemSchemas,
@@ -550,24 +554,16 @@ export class AgentHarnessModelCaller {
550
554
  items: 0,
551
555
  };
552
556
  // Record a round the loop goes on from, so a resumed loop can replay it.
553
- const recordRound = async (usage, cost) => {
554
- if (request.signal?.aborted) {
557
+ const recordRound = async (bill) => {
558
+ if (!roundLedger || request.signal?.aborted) {
555
559
  return;
556
560
  }
557
- await roundLedger?.record(round, marks.log, {
561
+ await roundLedger.record(round, marks.log, {
558
562
  items: allItems.slice(marks.items),
559
563
  input: conversationInput.slice(marks.input),
560
- usage,
561
- cost,
564
+ ...bill,
562
565
  });
563
566
  };
564
- const countRound = (usage, cost) => {
565
- rounds.push(usage);
566
- totalUsage.inputTokens += usage.inputTokens;
567
- totalUsage.outputTokens += usage.outputTokens;
568
- totalUsage.cachedTokens += usage.cachedTokens ?? 0;
569
- totalCost += cost;
570
- };
571
567
  let stoppedForRecall = false;
572
568
  const steers = openSteerInbox({
573
569
  ctx: request.ctx,
@@ -584,8 +580,9 @@ export class AgentHarnessModelCaller {
584
580
  for (const item of replayed.appended) {
585
581
  request.ctx?.itemLog.append(item);
586
582
  }
587
- countRound(replayed.usage, replayed.cost);
588
- replayedCost = (replayedCost ?? 0) + replayed.cost;
583
+ if (!replayed.charged) {
584
+ spend.replay(replayed);
585
+ }
589
586
  prepared.emitIfAllowed('model_round_replayed', {
590
587
  round,
591
588
  });
@@ -664,6 +661,8 @@ export class AgentHarnessModelCaller {
664
661
  model: request.model,
665
662
  instructions: prepared.instructions,
666
663
  input: modelInput,
664
+ tools: prepared.sdkTools && toolsOnWire(prepared.sdkTools),
665
+ text: textFormat,
667
666
  },
668
667
  maxOutputTokens: request.params?.maxTokens,
669
668
  round,
@@ -740,6 +739,18 @@ export class AgentHarnessModelCaller {
740
739
  try {
741
740
  sdkResponse = await awaitWithAbort(callResult.getResponse(), roundSignal);
742
741
  watchdog.stop();
742
+ // Counted before its record goes and before the recovery checks: a round
743
+ // rejected below and asked again was billed all the same. Once counted, the
744
+ // call charges its context with this bill however it ends, so a drain that
745
+ // reports from here on lists the round finished with it.
746
+ const roundUsage = extractUsage(sdkResponse.usage);
747
+ const roundCost = sdkResponse.usage?.cost ?? 0;
748
+ spend.count(roundUsage, roundCost);
749
+ roundFinished?.({
750
+ cost: roundCost,
751
+ usage: roundUsage,
752
+ });
753
+ spans.finishModelSpan(modelSpan, roundUsage, roundCost > 0 ? roundCost : undefined);
743
754
  await dispatch?.settle();
744
755
  await awaitWithAbort(pipePromise, roundSignal);
745
756
  }
@@ -759,19 +770,18 @@ export class AgentHarnessModelCaller {
759
770
  finally {
760
771
  watchdog.stop();
761
772
  dispatch?.end();
762
- roundFinished?.();
773
+ if (!sdkResponse) {
774
+ roundFinished?.();
775
+ }
763
776
  }
764
777
  if (request.signal?.aborted) {
765
- // A bill that arrived before the abort is counted here: its record is gone.
766
- if (sdkResponse) {
767
- countRound(extractUsage(sdkResponse.usage), sdkResponse.usage?.cost ?? 0);
768
- }
769
778
  break;
770
779
  }
771
780
  if (!sdkResponse) {
772
781
  // A steer stopped the stream before the response finished. The provider
773
782
  // never reports usage for a cut response, so this round adds none.
774
783
  modelSpan.end();
784
+ const bill = spend.keep();
775
785
  const roundItems = this.parseRoundItems(request, frameworkCast(finishedItems));
776
786
  prepared.emitIfAllowed('model_call_steered', {
777
787
  round,
@@ -790,10 +800,7 @@ export class AgentHarnessModelCaller {
790
800
  modelSpan,
791
801
  steers,
792
802
  });
793
- await recordRound({
794
- inputTokens: 0,
795
- outputTokens: 0,
796
- }, 0);
803
+ await recordRound(bill);
797
804
  round += 1;
798
805
  const cutLimitRecovery = this.handleToolRoundLimit({
799
806
  round,
@@ -813,7 +820,6 @@ export class AgentHarnessModelCaller {
813
820
  emitIfAllowed: prepared.emitIfAllowed,
814
821
  });
815
822
  if (recovery.kind === 'continue') {
816
- modelSpan.end();
817
823
  invalidRecoveryContinuations = recovery.invalidRecoveryContinuations;
818
824
  useEphemeralContinue = true;
819
825
  continue;
@@ -827,20 +833,16 @@ export class AgentHarnessModelCaller {
827
833
  emitIfAllowed: prepared.emitIfAllowed,
828
834
  });
829
835
  if (outputRecovery.kind === 'continue') {
830
- modelSpan.end();
831
836
  invalidRecoveryContinuations = outputRecovery.invalidRecoveryContinuations;
832
837
  useEphemeralContinue = true;
833
838
  continue;
834
839
  }
835
840
  invalidRecoveryContinuations = 0;
841
+ const bill = spend.keep();
836
842
  prepared.emitIfAllowed('model_call_completed', {
837
843
  round,
838
844
  itemCount: sdkResponse.output?.length ?? 0,
839
845
  });
840
- const roundUsage = extractUsage(sdkResponse.usage);
841
- const roundCost = sdkResponse.usage?.cost ?? 0;
842
- spans.finishModelSpan(modelSpan, roundUsage, roundCost > 0 ? roundCost : undefined);
843
- countRound(roundUsage, roundCost);
844
846
  servedTier = sdkResponse.serviceTier ?? undefined;
845
847
  allItems.push(...roundItems);
846
848
  const ranTools = await this.runToolRound({
@@ -862,7 +864,7 @@ export class AgentHarnessModelCaller {
862
864
  if (!ranTools) {
863
865
  replayOutput(conversationInput, roundItems);
864
866
  }
865
- await recordRound(roundUsage, roundCost);
867
+ await recordRound(bill);
866
868
  round += 1;
867
869
  const limitRecovery = this.handleToolRoundLimit({
868
870
  round,
@@ -876,27 +878,12 @@ export class AgentHarnessModelCaller {
876
878
  }
877
879
  return {
878
880
  items: allItems,
879
- usage: {
880
- inputTokens: totalUsage.inputTokens,
881
- outputTokens: totalUsage.outputTokens,
882
- // Stay `undefined` when no round reported a figure, so callers can tell
883
- // "this provider says nothing about caching" from "nothing was cached".
884
- cachedTokens: rounds.some((r) => r.cachedTokens !== undefined)
885
- ? totalUsage.cachedTokens
886
- : undefined,
887
- },
888
- rounds,
889
- cost: totalCost > 0 ? totalCost : undefined,
881
+ ...spend.totals(),
890
882
  ...(stoppedForRecall
891
883
  ? {
892
884
  recall: true,
893
885
  }
894
886
  : {}),
895
- ...(replayedCost !== undefined
896
- ? {
897
- billedCost: totalCost - replayedCost,
898
- }
899
- : {}),
900
887
  ...(servedTier
901
888
  ? {
902
889
  serviceTier: servedTier,
@@ -6,7 +6,7 @@ import type { OpenRouter } from '@openrouter/sdk';
6
6
  export declare const LOOKUP_TIMEOUT_MS = 10000;
7
7
  /** @internal The slice of the SDK client a price lookup uses. */
8
8
  export type PriceClient = Pick<OpenRouter, 'models'>;
9
- /** @internal USD per token, and the output cap the model publishes. */
9
+ /** @internal The most USD per token the model charges under any condition, and its caps. */
10
10
  export interface ModelPrice {
11
11
  input: number;
12
12
  output: number;
@@ -15,21 +15,37 @@ export interface ModelPrice {
15
15
  maxOutput?: number;
16
16
  contextLength?: number;
17
17
  }
18
- /** @internal What bounds one call: its prompt estimate and its own output cap. */
18
+ /** @internal What bounds one call: its prompt's token bound and its own output cap. */
19
19
  export interface TokenBound {
20
20
  inputTokens: number;
21
21
  maxOutputTokens?: number;
22
22
  }
23
+ /** @internal A request body as sent, and the most prompt tokens it can cost. */
24
+ export interface MeasuredRequest {
25
+ json: string;
26
+ inputTokens: number;
27
+ }
23
28
  /**
24
29
  * @internal
25
30
  * Price lookup, cached per model. A failed lookup is not cached. Resolves `undefined`
26
31
  * when the model publishes no price or the lookup failed.
27
32
  */
28
33
  export declare function createPriceBook(client: () => PriceClient | undefined): (model: string) => Promise<ModelPrice | undefined>;
34
+ /**
35
+ * @internal
36
+ * Serialize a request body and bound the prompt tokens it can cost.
37
+ *
38
+ * Byte-level BPE (GPT, Claude, Llama 3) and SentencePiece with byte fallback (Gemini,
39
+ * Mistral) spend at most one token per UTF-8 byte of text, and the JSON body holds
40
+ * every byte of the prompt's text, so its byte length bounds the text's tokens. The
41
+ * provider's own framing and each media part are not in those bytes: an image sent
42
+ * by URL is a few bytes that cost hundreds of tokens. Each gets a fixed allowance.
43
+ */
44
+ export declare function measureRequest(body: unknown): MeasuredRequest;
29
45
  /**
30
46
  * @internal
31
47
  * USD a call can have cost at most, or undefined when no output cap is known. The
32
- * output cap is the request's own, else the model's published max output, else what
33
- * its context leaves after the prompt.
48
+ * output cap is the request's own, else the model's published max output, else the
49
+ * model's context, which the prompt and output share.
34
50
  */
35
51
  export declare function ceilingOf(bound: TokenBound, price: ModelPrice): number | undefined;
@@ -4,6 +4,20 @@
4
4
  //#region Types
5
5
  /** @internal How long one provider lookup may take before it counts as failed. */
6
6
  export const LOOKUP_TIMEOUT_MS = 10e3;
7
+ /** Prompt tokens a provider may add around one request: chat template, tool-use preamble. */
8
+ const FRAMING_TOKENS = 1024;
9
+ /** Prompt tokens one image, file, audio, or video part may cost. */
10
+ const MEDIA_TOKENS = 4096;
11
+ /** Content part types that carry media rather than text, across the request shapes sent. */
12
+ const MEDIA_TYPES = new Set([
13
+ 'image_url',
14
+ 'input_image',
15
+ 'file',
16
+ 'input_file',
17
+ 'input_audio',
18
+ 'input_video',
19
+ 'video_url',
20
+ ]);
7
21
  //#endregion
8
22
  //#region Public API
9
23
  /**
@@ -28,25 +42,60 @@ export function createPriceBook(client) {
28
42
  return lookup;
29
43
  };
30
44
  }
45
+ /**
46
+ * @internal
47
+ * Serialize a request body and bound the prompt tokens it can cost.
48
+ *
49
+ * Byte-level BPE (GPT, Claude, Llama 3) and SentencePiece with byte fallback (Gemini,
50
+ * Mistral) spend at most one token per UTF-8 byte of text, and the JSON body holds
51
+ * every byte of the prompt's text, so its byte length bounds the text's tokens. The
52
+ * provider's own framing and each media part are not in those bytes: an image sent
53
+ * by URL is a few bytes that cost hundreds of tokens. Each gets a fixed allowance.
54
+ */
55
+ export function measureRequest(body) {
56
+ let media = 0;
57
+ const json = JSON.stringify(body, (_key, value) => {
58
+ if (isMediaPart(value)) {
59
+ media += 1;
60
+ }
61
+ return value;
62
+ }) ?? '';
63
+ return {
64
+ json,
65
+ inputTokens: new TextEncoder().encode(json).length + FRAMING_TOKENS + media * MEDIA_TOKENS,
66
+ };
67
+ }
31
68
  /**
32
69
  * @internal
33
70
  * USD a call can have cost at most, or undefined when no output cap is known. The
34
- * output cap is the request's own, else the model's published max output, else what
35
- * its context leaves after the prompt.
71
+ * output cap is the request's own, else the model's published max output, else the
72
+ * model's context, which the prompt and output share.
36
73
  */
37
74
  export function ceilingOf(bound, price) {
38
- const outputCap = bound.maxOutputTokens ??
39
- price.maxOutput ??
40
- (price.contextLength !== undefined
41
- ? Math.max(0, price.contextLength - bound.inputTokens)
42
- : undefined);
43
- if (outputCap === undefined) {
75
+ const context = price.contextLength;
76
+ // The provider refuses or trims a prompt longer than the context.
77
+ const prompt = context === undefined ? bound.inputTokens : Math.min(bound.inputTokens, context);
78
+ const outputCap = bound.maxOutputTokens ?? price.maxOutput;
79
+ if (outputCap !== undefined) {
80
+ return price.input * prompt + price.output * outputCap + price.request;
81
+ }
82
+ if (context === undefined) {
44
83
  return undefined;
45
84
  }
46
- return price.input * bound.inputTokens + price.output * outputCap + price.request;
85
+ // A shorter prompt leaves more room for output, so the cost peaks at one end of
86
+ // the prompt's range: no prompt at all, or the longest it can be.
87
+ const longest = price.input * prompt + price.output * (context - prompt);
88
+ return Math.max(longest, price.output * context) + price.request;
47
89
  }
48
90
  //#endregion
49
91
  //#region Helpers
92
+ function isMediaPart(value) {
93
+ return (typeof value === 'object' &&
94
+ value !== null &&
95
+ 'type' in value &&
96
+ typeof value.type === 'string' &&
97
+ MEDIA_TYPES.has(value.type));
98
+ }
50
99
  async function lookupPrice(model, client) {
51
100
  const slash = model.indexOf('/');
52
101
  if (!client || slash <= 0) {
@@ -59,18 +108,35 @@ async function lookupPrice(model, client) {
59
108
  }, {
60
109
  timeoutMs: LOOKUP_TIMEOUT_MS,
61
110
  });
62
- const input = Number(data.pricing.prompt);
63
- const output = Number(data.pricing.completion);
64
- if (!Number.isFinite(input) || !Number.isFinite(output) || input < 0 || output < 0) {
111
+ const { pricing } = data;
112
+ const base = Number(pricing.prompt);
113
+ const completion = Number(pricing.completion);
114
+ if (!Number.isFinite(base) || !Number.isFinite(completion) || base < 0 || completion < 0) {
65
115
  return undefined;
66
116
  }
67
- const request = Number(data.pricing.request ?? 0);
117
+ // Long prompts, cache writes, and reasoning can each bill above the base price,
118
+ // so a bound takes the dearest of every condition the model publishes.
119
+ const tiers = [
120
+ pricing,
121
+ ...(pricing.overrides ?? []),
122
+ ];
123
+ const context = Math.max(data.topProvider.contextLength ?? 0, data.contextLength ?? 0);
68
124
  return {
69
- input,
70
- output,
71
- request: Number.isFinite(request) && request > 0 ? request : 0,
125
+ input: dearest(tiers.flatMap((tier) => [
126
+ tier.prompt,
127
+ tier.inputCacheWrite,
128
+ tier.inputCacheWrite1h,
129
+ ])),
130
+ output: dearest([
131
+ ...tiers.map((tier) => tier.completion),
132
+ pricing.internalReasoning,
133
+ ]),
134
+ request: dearest([
135
+ pricing.request,
136
+ ]),
72
137
  maxOutput: data.topProvider.maxCompletionTokens ?? undefined,
73
- contextLength: data.topProvider.contextLength ?? data.contextLength ?? undefined,
138
+ // OpenRouter may route to any provider, so the widest context bounds the prompt.
139
+ contextLength: context > 0 ? context : undefined,
74
140
  };
75
141
  }
76
142
  catch {
@@ -78,4 +144,15 @@ async function lookupPrice(model, client) {
78
144
  return undefined;
79
145
  }
80
146
  }
147
+ /** The highest of some published USD prices; an absent or malformed one counts as free. */
148
+ function dearest(prices) {
149
+ let most = 0;
150
+ for (const price of prices) {
151
+ const value = Number(price);
152
+ if (Number.isFinite(value) && value > most) {
153
+ most = value;
154
+ }
155
+ }
156
+ return most;
157
+ }
81
158
  //#endregion
@@ -13,6 +13,11 @@
13
13
  * one it does not find; every round after that runs live, because a recorded round
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
+ *
17
+ * A call that fails charges its context with the rounds it recorded, so a failed run
18
+ * reports what it paid. A retry in place replays those rounds on the same context,
19
+ * so the ledger remembers which rounds were charged and the replay counts them no
20
+ * more.
16
21
  */
17
22
  import type { Item, ItemSchemaRegistry, RoundUsage } from '@noetic-tools/types';
18
23
  /** What one finished round added to the loop. */
@@ -27,6 +32,8 @@ export interface RoundRecord {
27
32
  /** A replayed round: its record plus the items it appended to the item log. */
28
33
  export interface ReplayedRound extends RoundRecord {
29
34
  appended: Item[];
35
+ /** A failed call already charged this round's bill to the context. */
36
+ charged: boolean;
30
37
  }
31
38
  /**
32
39
  * The round ledger for one model loop. `open` gives none when the call is not running
@@ -36,6 +43,8 @@ export declare class RoundLedger {
36
43
  private readonly ctx;
37
44
  private readonly dispatch;
38
45
  private replaying;
46
+ /** Rounds this loop recorded. */
47
+ private readonly recorded;
39
48
  private constructor();
40
49
  /** Undefined when the loop has nothing to record into. */
41
50
  static open(ctx: unknown): RoundLedger | undefined;
@@ -48,6 +57,8 @@ export declare class RoundLedger {
48
57
  mark(): number;
49
58
  /** Record a finished round. `logMark` is what `mark()` returned when it began. */
50
59
  record(round: number, logMark: number, record: RoundRecord): Promise<void>;
60
+ /** Note that the rounds this loop recorded were charged to its context. */
61
+ charged(): void;
51
62
  private key;
52
63
  }
53
64
  /** @internal The ledger key of round `round` of the model loop at step path `path`. */
@@ -13,6 +13,11 @@
13
13
  * one it does not find; every round after that runs live, because a recorded round
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
+ *
17
+ * A call that fails charges its context with the rounds it recorded, so a failed run
18
+ * reports what it paid. A retry in place replays those rounds on the same context,
19
+ * so the ledger remembers which rounds were charged and the replay counts them no
20
+ * more.
16
21
  */
17
22
  import { frameworkCast } from '@noetic-tools/types';
18
23
  import { z } from 'zod';
@@ -30,6 +35,12 @@ const RoundOutputSchema = z.object({
30
35
  }),
31
36
  cost: z.number(),
32
37
  });
38
+ /**
39
+ * Keys of recorded rounds a failed call charged, per execution ledger. Kept in memory
40
+ * only: a new harness resuming the execution starts from a restored context, which
41
+ * never saw that charge.
42
+ */
43
+ const chargedRounds = new WeakMap();
33
44
  //#endregion
34
45
  //#region Public API
35
46
  /**
@@ -40,6 +51,8 @@ export class RoundLedger {
40
51
  ctx;
41
52
  dispatch;
42
53
  replaying = true;
54
+ /** Rounds this loop recorded. */
55
+ recorded = [];
43
56
  constructor(ctx, dispatch) {
44
57
  this.ctx = ctx;
45
58
  this.dispatch = dispatch;
@@ -79,6 +92,7 @@ export class RoundLedger {
79
92
  usage: parsed.data.usage,
80
93
  cost: parsed.data.cost,
81
94
  appended: schemas.parseMany(entry.items ?? []),
95
+ charged: chargedRounds.get(ledger)?.has(this.key(round)) ?? false,
82
96
  };
83
97
  }
84
98
  catch {
@@ -93,8 +107,12 @@ export class RoundLedger {
93
107
  /** Record a finished round. `logMark` is what `mark()` returned when it began. */
94
108
  async record(round, logMark, record) {
95
109
  this.replaying = false;
110
+ const ledger = this.ctx.ledger;
111
+ if (!ledger) {
112
+ return;
113
+ }
96
114
  const appended = this.ctx.appendedItems().slice(logMark);
97
- await this.ctx.ledger?.record({
115
+ const stored = await ledger.record({
98
116
  path: this.key(round),
99
117
  stepId: this.dispatch.stepId,
100
118
  kind: ROUND_KIND,
@@ -107,6 +125,24 @@ export class RoundLedger {
107
125
  : {}),
108
126
  completedAt: new Date().toISOString(),
109
127
  });
128
+ if (!stored) {
129
+ return;
130
+ }
131
+ this.recorded.push(round);
132
+ // A new record holds a bill no context has been charged with yet.
133
+ chargedRounds.get(ledger)?.delete(this.key(round));
134
+ }
135
+ /** Note that the rounds this loop recorded were charged to its context. */
136
+ charged() {
137
+ const ledger = this.ctx.ledger;
138
+ if (!ledger || this.recorded.length === 0) {
139
+ return;
140
+ }
141
+ const keys = chargedRounds.get(ledger) ?? new Set();
142
+ for (const round of this.recorded) {
143
+ keys.add(this.key(round));
144
+ }
145
+ chargedRounds.set(ledger, keys);
110
146
  }
111
147
  key(round) {
112
148
  return roundPath(this.dispatch.path, round);
@@ -8,7 +8,8 @@
8
8
  * leaves the record behind. It is then *pending*: held at its ceiling, and priced
9
9
  * through the provider's generation lookup once the provider has billed it.
10
10
  */
11
- import type { Context, PendingSpend, ReconcileSpendOptions, SpendKind, SpendSettlement, UsageCharge, WriteOffSpendOptions } from '@noetic-tools/types';
11
+ import type { Context, PendingSpend, ReconcileSpendOptions, SpendSettlement, UsageCharge, WriteOffSpendOptions } from '@noetic-tools/types';
12
+ import { SpendKind } from '@noetic-tools/types';
12
13
  import type { OpenRouter } from '@openrouter/sdk';
13
14
  import type { DispatchRecord, SpendLog } from '../runtime/durable/spend-log.js';
14
15
  import type { EventBroadcaster } from './deps/runtime.js';
@@ -35,7 +36,7 @@ export interface DispatchParams {
35
36
  ctx?: Context;
36
37
  kind: SpendKind;
37
38
  model: string;
38
- /** The request body, hashed and sized for the record. */
39
+ /** The request body as sent, tools included: hashed, and sized to bound its prompt. */
39
40
  body: unknown;
40
41
  maxOutputTokens?: number;
41
42
  /** The model-loop round, for a `callModel` round's ledger key. */
@@ -62,7 +63,7 @@ export declare class Spend {
62
63
  open(params: DispatchParams): Promise<Dispatch>;
63
64
  /** Save a live dispatch's generation id. The client's response hook awaits it. */
64
65
  noteGeneration(dispatchId: string, generationId: string): Promise<void>;
65
- /** Unsettled dispatches, each with its ceiling. */
66
+ /** Unsettled dispatches, each with its ceiling. Unreadable ones have none. */
66
67
  pending(executionId?: string): Promise<PendingSpend[]>;
67
68
  /**
68
69
  * Hold the restored root context's pending dispatches on it, then reconcile them in
@@ -82,6 +83,10 @@ export declare class Spend {
82
83
  release(id: string): void;
83
84
  /** A dispatch ended without a bill: hold it and start looking for one. Called by `Dispatch` only. */
84
85
  leave(record: DispatchRecord, root: ContextImpl | undefined): void;
86
+ /**
87
+ * Stored dispatches not in flight here, all or one execution's. An unreadable record
88
+ * that names no execution may be any execution's, so it is listed with each of them.
89
+ */
85
90
  private unsettled;
86
91
  /**
87
92
  * Hold `record` at its ceiling, on `ctx` when given. A dispatch already held moves to
@@ -89,6 +94,7 @@ export declare class Spend {
89
94
  */
90
95
  private hold;
91
96
  private ceilingOf;
97
+ /** Unreadable records carry no generation id, so they are never priced. */
92
98
  private lookup;
93
99
  /**
94
100
  * Ask the provider for the call's bill until it has one. The provider prices a call