@noetic-tools/core 5.17.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.
Files changed (45) hide show
  1. package/dist/adapters/openrouter.d.ts +7 -0
  2. package/dist/adapters/openrouter.js +23 -0
  3. package/dist/conditions/conditions.js +3 -0
  4. package/dist/harness/agent-harness.d.ts +63 -9
  5. package/dist/harness/agent-harness.js +222 -22
  6. package/dist/harness/call-spend.d.ts +34 -0
  7. package/dist/harness/call-spend.js +125 -0
  8. package/dist/harness/decide-call.d.ts +3 -0
  9. package/dist/harness/decide-call.js +51 -12
  10. package/dist/harness/deps/adapters.d.ts +1 -1
  11. package/dist/harness/deps/adapters.js +1 -1
  12. package/dist/harness/deps/runtime.d.ts +3 -1
  13. package/dist/harness/deps/runtime.js +3 -1
  14. package/dist/harness/deps/types.d.ts +1 -1
  15. package/dist/harness/model-call.d.ts +3 -0
  16. package/dist/harness/model-call.js +123 -66
  17. package/dist/harness/model-price.d.ts +51 -0
  18. package/dist/harness/model-price.js +158 -0
  19. package/dist/harness/model-rounds.d.ts +13 -0
  20. package/dist/harness/model-rounds.js +42 -2
  21. package/dist/harness/spend.d.ts +144 -0
  22. package/dist/harness/spend.js +534 -0
  23. package/dist/index.d.ts +5 -1
  24. package/dist/index.js +2 -0
  25. package/dist/interpreter/execute-action.js +2 -0
  26. package/dist/interpreter/execute-control.js +1 -0
  27. package/dist/interpreter/execute-decide.js +43 -1
  28. package/dist/interpreter/execute.js +9 -0
  29. package/dist/runtime/context-impl.d.ts +1 -0
  30. package/dist/runtime/context-impl.js +1 -0
  31. package/dist/runtime/drain.d.ts +68 -0
  32. package/dist/runtime/drain.js +280 -0
  33. package/dist/runtime/durable/spend-log.d.ts +58 -0
  34. package/dist/runtime/durable/spend-log.js +133 -0
  35. package/dist/runtime/durable/step-ledger.d.ts +9 -2
  36. package/dist/runtime/durable/step-ledger.js +9 -6
  37. package/dist/runtime/session-runner.d.ts +5 -3
  38. package/dist/runtime/session-runner.js +9 -4
  39. package/dist/until/predicates.d.ts +5 -1
  40. package/dist/until/predicates.js +12 -7
  41. package/dist/util/spent.d.ts +14 -0
  42. package/dist/util/spent.js +67 -0
  43. package/dist/util/status-code.d.ts +5 -0
  44. package/dist/util/status-code.js +8 -0
  45. package/package.json +2 -2
@@ -1,9 +1,13 @@
1
- import { frameworkCast, NoeticConfigError, SteerPoint, ToolChoiceMode } from '@noetic-tools/types';
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
+ import { drainsOf } from '../runtime/drain.js';
8
+ import { markSpent } from '../util/spent.js';
9
+ import { isErrorStatus } from '../util/status-code.js';
10
+ import { CallSpend } from './call-spend.js';
7
11
  import { exportSpans } from './deps/context.js';
8
12
  import { RoundLedger } from './model-rounds.js';
9
13
  import { buildItemSchemaRegistry, createToolResultItem } from './model-schema.js';
@@ -66,6 +70,26 @@ function providerTerminalError(response) {
66
70
  function replayOutput(input, roundItems) {
67
71
  input.push(...itemsToInput(roundItems.filter((item) => !isFunctionCall(item))));
68
72
  }
73
+ /**
74
+ * Save the generation id a stream's `response.created` event carries, for a response
75
+ * whose headers did not. OpenRouter's ids start `gen-`; other ids price nothing.
76
+ */
77
+ function noteStreamGeneration(dispatch, event) {
78
+ if (!dispatch || !isStreamRecord(event) || event.type !== 'response.created') {
79
+ return;
80
+ }
81
+ const response = event.response;
82
+ if (!isStreamRecord(response) || typeof response.id !== 'string') {
83
+ return;
84
+ }
85
+ if (response.id.startsWith('gen-')) {
86
+ void dispatch.noteGeneration(response.id);
87
+ }
88
+ }
89
+ /** The provider refused the call before generating anything, so nothing was billed. */
90
+ function wasRefused(err, dispatch) {
91
+ return isErrorStatus(err) && dispatch.record.generationId === undefined;
92
+ }
69
93
  function hasItem(items, id) {
70
94
  return items.some((item) => 'id' in item && item.id === id);
71
95
  }
@@ -121,7 +145,7 @@ async function pipeStreamEventsToBroadcaster(opts) {
121
145
  if (signal?.aborted) {
122
146
  return;
123
147
  }
124
- onEvent?.();
148
+ onEvent?.(event);
125
149
  if (!isStreamRecord(event)) {
126
150
  continue;
127
151
  }
@@ -447,8 +471,14 @@ export class AgentHarnessModelCaller {
447
471
  }
448
472
  const spans = this.newSpanCollector(request);
449
473
  const modelSpan = spans.startModelSpan(request.model);
474
+ const finished = drainsOf(request.ctx)?.track(request.ctx, {
475
+ kind: 'model_round',
476
+ model: request.model,
477
+ round: 0,
478
+ });
479
+ let response;
450
480
  try {
451
- const response = await this.opts.callModelOverride(request);
481
+ response = await this.opts.callModelOverride(request);
452
482
  const itemSchemas = buildItemSchemaRegistry({
453
483
  base: this.opts.itemSchemas,
454
484
  layers: request.layers,
@@ -461,6 +491,10 @@ export class AgentHarnessModelCaller {
461
491
  };
462
492
  }
463
493
  finally {
494
+ finished?.(response && {
495
+ cost: response.cost ?? 0,
496
+ usage: response.usage,
497
+ });
464
498
  await spans.flush();
465
499
  }
466
500
  }
@@ -476,28 +510,27 @@ export class AgentHarnessModelCaller {
476
510
  }
477
511
  const client = this.requireModelClient();
478
512
  const spans = this.newSpanCollector(request);
513
+ const spend = new CallSpend();
514
+ const roundLedger = RoundLedger.open(request.ctx);
479
515
  try {
480
- 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());
481
526
  }
482
527
  finally {
483
528
  await spans.flush();
484
529
  }
485
530
  }
486
- async runModelLoop(request, client, spans) {
531
+ async runModelLoop({ request, client, spans, spend, roundLedger, }) {
487
532
  const prepared = prepareModelRequest(request, this.opts.agentName);
488
533
  const allItems = [];
489
- const totalUsage = {
490
- inputTokens: 0,
491
- outputTokens: 0,
492
- cachedTokens: 0,
493
- };
494
- // Rounds after the first replay the same prefix and so hit the prompt cache
495
- // whatever the first round did. Keep them apart: only round 0 says whether
496
- // the assembled view was cached (see `noteCacheOutcome`).
497
- const rounds = [];
498
- let totalCost = 0;
499
- // What replayed rounds supplied, so the response can report what was paid now.
500
- let replayedCost;
501
534
  let servedTier;
502
535
  const conversationInput = itemsToInput(prepared.remaining);
503
536
  const textFormat = request.outputSchema
@@ -507,7 +540,7 @@ export class AgentHarnessModelCaller {
507
540
  let invalidRecoveryContinuations = 0;
508
541
  let toolLimitRecoveryContinuations = 0;
509
542
  let useEphemeralContinue = false;
510
- const roundLedger = RoundLedger.open(request.ctx);
543
+ const drains = drainsOf(request.ctx);
511
544
  const replaySchemas = buildItemSchemaRegistry({
512
545
  base: this.opts.itemSchemas,
513
546
  layers: request.layers,
@@ -521,15 +554,14 @@ export class AgentHarnessModelCaller {
521
554
  items: 0,
522
555
  };
523
556
  // Record a round the loop goes on from, so a resumed loop can replay it.
524
- const recordRound = async (usage, cost) => {
525
- if (request.signal?.aborted) {
557
+ const recordRound = async (bill) => {
558
+ if (!roundLedger || request.signal?.aborted) {
526
559
  return;
527
560
  }
528
- await roundLedger?.record(round, marks.log, {
561
+ await roundLedger.record(round, marks.log, {
529
562
  items: allItems.slice(marks.items),
530
563
  input: conversationInput.slice(marks.input),
531
- usage,
532
- cost,
564
+ ...bill,
533
565
  });
534
566
  };
535
567
  let stoppedForRecall = false;
@@ -548,12 +580,9 @@ export class AgentHarnessModelCaller {
548
580
  for (const item of replayed.appended) {
549
581
  request.ctx?.itemLog.append(item);
550
582
  }
551
- rounds.push(replayed.usage);
552
- totalUsage.inputTokens += replayed.usage.inputTokens;
553
- totalUsage.outputTokens += replayed.usage.outputTokens;
554
- totalUsage.cachedTokens += replayed.usage.cachedTokens ?? 0;
555
- totalCost += replayed.cost;
556
- replayedCost = (replayedCost ?? 0) + replayed.cost;
583
+ if (!replayed.charged) {
584
+ spend.replay(replayed);
585
+ }
557
586
  prepared.emitIfAllowed('model_round_replayed', {
558
587
  round,
559
588
  });
@@ -577,6 +606,11 @@ export class AgentHarnessModelCaller {
577
606
  items: allItems.length,
578
607
  };
579
608
  }
609
+ // A graceful stop starts no new round: wait here until it cancels the call.
610
+ await drains?.hold(request.ctx);
611
+ if (request.signal?.aborted) {
612
+ break;
613
+ }
580
614
  const recoveryContinuation = useEphemeralContinue;
581
615
  useEphemeralContinue = false;
582
616
  if (steers) {
@@ -619,6 +653,31 @@ export class AgentHarnessModelCaller {
619
653
  recoveryContinuation,
620
654
  });
621
655
  const modelSpan = spans.startModelSpan(request.model);
656
+ const dispatch = await this.opts.spend?.open({
657
+ ctx: request.ctx ?? request._billTo,
658
+ kind: SpendKind.Model,
659
+ model: request.model,
660
+ body: {
661
+ model: request.model,
662
+ instructions: prepared.instructions,
663
+ input: modelInput,
664
+ tools: prepared.sdkTools && toolsOnWire(prepared.sdkTools),
665
+ text: textFormat,
666
+ },
667
+ maxOutputTokens: request.params?.maxTokens,
668
+ round,
669
+ });
670
+ if (request.signal?.aborted) {
671
+ // Aborted while the record was written: the call was never sent.
672
+ await dispatch?.settle();
673
+ modelSpan.end();
674
+ break;
675
+ }
676
+ const roundFinished = drains?.track(request.ctx, {
677
+ kind: 'model_round',
678
+ model: request.model,
679
+ round,
680
+ }, dispatch?.record);
622
681
  const callResult = client.callModel({
623
682
  model: request.model,
624
683
  input: modelInput,
@@ -638,6 +697,11 @@ export class AgentHarnessModelCaller {
638
697
  : {}),
639
698
  }, {
640
699
  signal: roundSignal,
700
+ ...(dispatch
701
+ ? {
702
+ headers: dispatch.headers,
703
+ }
704
+ : {}),
641
705
  });
642
706
  // Output items the stream has finished, kept so a steer can stop the
643
707
  // round early without losing them.
@@ -648,8 +712,9 @@ export class AgentHarnessModelCaller {
648
712
  broadcaster: prepared.broadcaster,
649
713
  agentName: this.opts.agentName,
650
714
  signal: roundSignal,
651
- onEvent: () => {
715
+ onEvent: (event) => {
652
716
  watchdog.reset();
717
+ noteStreamGeneration(dispatch, event);
653
718
  if (!firstEventSeen) {
654
719
  firstEventSeen = true;
655
720
  prepared.emitIfAllowed('model_call_first_event', {
@@ -674,23 +739,40 @@ export class AgentHarnessModelCaller {
674
739
  try {
675
740
  sdkResponse = await awaitWithAbort(callResult.getResponse(), roundSignal);
676
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);
754
+ await dispatch?.settle();
677
755
  await awaitWithAbort(pipePromise, roundSignal);
678
756
  }
679
757
  catch (err) {
758
+ if (dispatch && wasRefused(err, dispatch)) {
759
+ await dispatch.settle();
760
+ }
680
761
  if (idleStalled) {
681
762
  throw roundSignal.reason instanceof Error
682
763
  ? roundSignal.reason
683
764
  : new Error(`model stream idle timeout after ${this.opts.streamIdleTimeoutMs}ms`);
684
765
  }
685
- if (request.signal?.aborted) {
686
- break;
687
- }
688
- if (!steered) {
766
+ if (!steered && !request.signal?.aborted) {
689
767
  throw err;
690
768
  }
691
769
  }
692
770
  finally {
693
771
  watchdog.stop();
772
+ dispatch?.end();
773
+ if (!sdkResponse) {
774
+ roundFinished?.();
775
+ }
694
776
  }
695
777
  if (request.signal?.aborted) {
696
778
  break;
@@ -699,6 +781,7 @@ export class AgentHarnessModelCaller {
699
781
  // A steer stopped the stream before the response finished. The provider
700
782
  // never reports usage for a cut response, so this round adds none.
701
783
  modelSpan.end();
784
+ const bill = spend.keep();
702
785
  const roundItems = this.parseRoundItems(request, frameworkCast(finishedItems));
703
786
  prepared.emitIfAllowed('model_call_steered', {
704
787
  round,
@@ -717,10 +800,7 @@ export class AgentHarnessModelCaller {
717
800
  modelSpan,
718
801
  steers,
719
802
  });
720
- await recordRound({
721
- inputTokens: 0,
722
- outputTokens: 0,
723
- }, 0);
803
+ await recordRound(bill);
724
804
  round += 1;
725
805
  const cutLimitRecovery = this.handleToolRoundLimit({
726
806
  round,
@@ -740,7 +820,6 @@ export class AgentHarnessModelCaller {
740
820
  emitIfAllowed: prepared.emitIfAllowed,
741
821
  });
742
822
  if (recovery.kind === 'continue') {
743
- modelSpan.end();
744
823
  invalidRecoveryContinuations = recovery.invalidRecoveryContinuations;
745
824
  useEphemeralContinue = true;
746
825
  continue;
@@ -754,24 +833,16 @@ export class AgentHarnessModelCaller {
754
833
  emitIfAllowed: prepared.emitIfAllowed,
755
834
  });
756
835
  if (outputRecovery.kind === 'continue') {
757
- modelSpan.end();
758
836
  invalidRecoveryContinuations = outputRecovery.invalidRecoveryContinuations;
759
837
  useEphemeralContinue = true;
760
838
  continue;
761
839
  }
762
840
  invalidRecoveryContinuations = 0;
841
+ const bill = spend.keep();
763
842
  prepared.emitIfAllowed('model_call_completed', {
764
843
  round,
765
844
  itemCount: sdkResponse.output?.length ?? 0,
766
845
  });
767
- const roundUsage = extractUsage(sdkResponse.usage);
768
- const roundCost = sdkResponse.usage?.cost ?? 0;
769
- spans.finishModelSpan(modelSpan, roundUsage, roundCost > 0 ? roundCost : undefined);
770
- rounds.push(roundUsage);
771
- totalUsage.inputTokens += roundUsage.inputTokens;
772
- totalUsage.outputTokens += roundUsage.outputTokens;
773
- totalUsage.cachedTokens += roundUsage.cachedTokens ?? 0;
774
- totalCost += roundCost;
775
846
  servedTier = sdkResponse.serviceTier ?? undefined;
776
847
  allItems.push(...roundItems);
777
848
  const ranTools = await this.runToolRound({
@@ -793,7 +864,7 @@ export class AgentHarnessModelCaller {
793
864
  if (!ranTools) {
794
865
  replayOutput(conversationInput, roundItems);
795
866
  }
796
- await recordRound(roundUsage, roundCost);
867
+ await recordRound(bill);
797
868
  round += 1;
798
869
  const limitRecovery = this.handleToolRoundLimit({
799
870
  round,
@@ -807,27 +878,12 @@ export class AgentHarnessModelCaller {
807
878
  }
808
879
  return {
809
880
  items: allItems,
810
- usage: {
811
- inputTokens: totalUsage.inputTokens,
812
- outputTokens: totalUsage.outputTokens,
813
- // Stay `undefined` when no round reported a figure, so callers can tell
814
- // "this provider says nothing about caching" from "nothing was cached".
815
- cachedTokens: rounds.some((r) => r.cachedTokens !== undefined)
816
- ? totalUsage.cachedTokens
817
- : undefined,
818
- },
819
- rounds,
820
- cost: totalCost > 0 ? totalCost : undefined,
881
+ ...spend.totals(),
821
882
  ...(stoppedForRecall
822
883
  ? {
823
884
  recall: true,
824
885
  }
825
886
  : {}),
826
- ...(replayedCost !== undefined
827
- ? {
828
- billedCost: totalCost - replayedCost,
829
- }
830
- : {}),
831
887
  ...(servedTier
832
888
  ? {
833
889
  serviceTier: servedTier,
@@ -960,6 +1016,7 @@ export class AgentHarnessModelCaller {
960
1016
  });
961
1017
  }
962
1018
  for (const [index, fc] of functionCalls.entries()) {
1019
+ await drainsOf(request.ctx)?.hold(request.ctx);
963
1020
  if (request.signal?.aborted) {
964
1021
  break;
965
1022
  }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Published model prices, for bounding what a cut-off call can have cost.
3
+ */
4
+ import type { OpenRouter } from '@openrouter/sdk';
5
+ /** @internal How long one provider lookup may take before it counts as failed. */
6
+ export declare const LOOKUP_TIMEOUT_MS = 10000;
7
+ /** @internal The slice of the SDK client a price lookup uses. */
8
+ export type PriceClient = Pick<OpenRouter, 'models'>;
9
+ /** @internal The most USD per token the model charges under any condition, and its caps. */
10
+ export interface ModelPrice {
11
+ input: number;
12
+ output: number;
13
+ /** Flat USD per request. */
14
+ request: number;
15
+ maxOutput?: number;
16
+ contextLength?: number;
17
+ }
18
+ /** @internal What bounds one call: its prompt's token bound and its own output cap. */
19
+ export interface TokenBound {
20
+ inputTokens: number;
21
+ maxOutputTokens?: number;
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
+ }
28
+ /**
29
+ * @internal
30
+ * Price lookup, cached per model. A failed lookup is not cached. Resolves `undefined`
31
+ * when the model publishes no price or the lookup failed.
32
+ */
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;
45
+ /**
46
+ * @internal
47
+ * USD a call can have cost at most, or undefined when no output cap is known. The
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.
50
+ */
51
+ export declare function ceilingOf(bound: TokenBound, price: ModelPrice): number | undefined;
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Published model prices, for bounding what a cut-off call can have cost.
3
+ */
4
+ //#region Types
5
+ /** @internal How long one provider lookup may take before it counts as failed. */
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
+ ]);
21
+ //#endregion
22
+ //#region Public API
23
+ /**
24
+ * @internal
25
+ * Price lookup, cached per model. A failed lookup is not cached. Resolves `undefined`
26
+ * when the model publishes no price or the lookup failed.
27
+ */
28
+ export function createPriceBook(client) {
29
+ const prices = new Map();
30
+ return (model) => {
31
+ const known = prices.get(model);
32
+ if (known) {
33
+ return known;
34
+ }
35
+ const lookup = lookupPrice(model, client());
36
+ prices.set(model, lookup);
37
+ void lookup.then((price) => {
38
+ if (price === undefined) {
39
+ prices.delete(model);
40
+ }
41
+ });
42
+ return lookup;
43
+ };
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
+ }
68
+ /**
69
+ * @internal
70
+ * USD a call can have cost at most, or undefined when no output cap is known. The
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.
73
+ */
74
+ export function ceilingOf(bound, price) {
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) {
83
+ return undefined;
84
+ }
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;
89
+ }
90
+ //#endregion
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
+ }
99
+ async function lookupPrice(model, client) {
100
+ const slash = model.indexOf('/');
101
+ if (!client || slash <= 0) {
102
+ return undefined;
103
+ }
104
+ try {
105
+ const { data } = await client.models.get({
106
+ author: model.slice(0, slash),
107
+ slug: model.slice(slash + 1),
108
+ }, {
109
+ timeoutMs: LOOKUP_TIMEOUT_MS,
110
+ });
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) {
115
+ return undefined;
116
+ }
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);
124
+ return {
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
+ ]),
137
+ maxOutput: data.topProvider.maxCompletionTokens ?? undefined,
138
+ // OpenRouter may route to any provider, so the widest context bounds the prompt.
139
+ contextLength: context > 0 ? context : undefined,
140
+ };
141
+ }
142
+ catch {
143
+ // An unknown price leaves the hold unbounded, which `spend_pending` flags.
144
+ return undefined;
145
+ }
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
+ }
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,5 +57,9 @@ 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
  }
64
+ /** @internal The ledger key of round `round` of the model loop at step path `path`. */
65
+ export declare function roundPath(path: string, round: number): string;