@noetic-tools/core 5.16.1 → 5.18.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/conditions/conditions.js +1 -0
  2. package/dist/harness/agent-harness.d.ts +54 -9
  3. package/dist/harness/agent-harness.js +192 -23
  4. package/dist/harness/decide-call.d.ts +3 -0
  5. package/dist/harness/decide-call.js +45 -12
  6. package/dist/harness/deps/adapters.d.ts +1 -1
  7. package/dist/harness/deps/adapters.js +1 -1
  8. package/dist/harness/deps/runtime.d.ts +4 -2
  9. package/dist/harness/deps/runtime.js +4 -2
  10. package/dist/harness/deps/types.d.ts +1 -1
  11. package/dist/harness/model-call.d.ts +5 -1
  12. package/dist/harness/model-call.js +107 -21
  13. package/dist/harness/model-price.d.ts +35 -0
  14. package/dist/harness/model-price.js +81 -0
  15. package/dist/harness/model-rounds.d.ts +2 -0
  16. package/dist/harness/model-rounds.js +5 -1
  17. package/dist/harness/spend.d.ts +138 -0
  18. package/dist/harness/spend.js +494 -0
  19. package/dist/harness/steer-inbox.d.ts +5 -0
  20. package/dist/harness/steer-inbox.js +45 -5
  21. package/dist/harness/thread-record.d.ts +17 -5
  22. package/dist/harness/thread-record.js +54 -4
  23. package/dist/index.d.ts +5 -1
  24. package/dist/index.js +2 -0
  25. package/dist/interpreter/execute-action.js +60 -11
  26. package/dist/interpreter/execute-control.js +1 -0
  27. package/dist/interpreter/execute-decide.js +18 -0
  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 +77 -0
  32. package/dist/runtime/drain.js +268 -0
  33. package/dist/runtime/durable/session-store.d.ts +12 -0
  34. package/dist/runtime/durable/session-store.js +16 -0
  35. package/dist/runtime/durable/spend-log.d.ts +38 -0
  36. package/dist/runtime/durable/spend-log.js +65 -0
  37. package/dist/runtime/durable/step-ledger.d.ts +6 -0
  38. package/dist/runtime/durable/step-ledger.js +3 -2
  39. package/dist/runtime/session-runner.d.ts +5 -3
  40. package/dist/runtime/session-runner.js +9 -4
  41. package/dist/until/predicates.d.ts +5 -1
  42. package/dist/until/predicates.js +12 -7
  43. package/dist/util/status-code.d.ts +5 -0
  44. package/dist/util/status-code.js +8 -0
  45. package/package.json +3 -3
@@ -1,6 +1,7 @@
1
1
  import type { AgentHarnessContract, CallModelRequest, ItemSchemaRegistry, LLMResponse, TraceExporter } from '@noetic-tools/types';
2
2
  import { NoeticConfigError } from '@noetic-tools/types';
3
3
  import type { OpenRouter } from '@openrouter/agent';
4
+ import type { Spend } from './spend.js';
4
5
  interface StreamIdleWatchdog {
5
6
  /** Bump the deadline because a stream event just arrived. */
6
7
  reset: () => void;
@@ -24,6 +25,8 @@ interface AgentHarnessModelCallerOpts {
24
25
  streamIdleTimeoutMs: number;
25
26
  harness: AgentHarnessContract;
26
27
  traceExporter: TraceExporter;
28
+ /** Records each paid round before it is sent. Absent without durable storage. */
29
+ spend?: Spend;
27
30
  }
28
31
  export declare class AgentHarnessModelCaller {
29
32
  private readonly opts;
@@ -43,7 +46,8 @@ export declare class AgentHarnessModelCaller {
43
46
  /**
44
47
  * Offer queued steers before a model call and add the applied ones to the
45
48
  * conversation. They join `allItems` rather than the log so the log keeps
46
- * them in the order the model saw them.
49
+ * them in the order the model saw them. Returns whether a layer asked for
50
+ * recall to run again before the call goes on.
47
51
  */
48
52
  private applySteers;
49
53
  private parseRoundItems;
@@ -1,9 +1,11 @@
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
3
  import { convertTools, executeToolCall, extractOutputItems, extractSystemInstruction, extractUsage, itemsToInput, resolveWireJsonSchema, sanitizeToolNameForWire, } 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 { isErrorStatus } from '../util/status-code.js';
7
9
  import { exportSpans } from './deps/context.js';
8
10
  import { RoundLedger } from './model-rounds.js';
9
11
  import { buildItemSchemaRegistry, createToolResultItem } from './model-schema.js';
@@ -66,6 +68,29 @@ function providerTerminalError(response) {
66
68
  function replayOutput(input, roundItems) {
67
69
  input.push(...itemsToInput(roundItems.filter((item) => !isFunctionCall(item))));
68
70
  }
71
+ /**
72
+ * Save the generation id a stream's `response.created` event carries, for a response
73
+ * whose headers did not. OpenRouter's ids start `gen-`; other ids price nothing.
74
+ */
75
+ function noteStreamGeneration(dispatch, event) {
76
+ if (!dispatch || !isStreamRecord(event) || event.type !== 'response.created') {
77
+ return;
78
+ }
79
+ const response = event.response;
80
+ if (!isStreamRecord(response) || typeof response.id !== 'string') {
81
+ return;
82
+ }
83
+ if (response.id.startsWith('gen-')) {
84
+ void dispatch.noteGeneration(response.id);
85
+ }
86
+ }
87
+ /** The provider refused the call before generating anything, so nothing was billed. */
88
+ function wasRefused(err, dispatch) {
89
+ return isErrorStatus(err) && dispatch.record.generationId === undefined;
90
+ }
91
+ function hasItem(items, id) {
92
+ return items.some((item) => 'id' in item && item.id === id);
93
+ }
69
94
  function hasUsableResponseOutput(response, items) {
70
95
  if (items.length > 0) {
71
96
  return true;
@@ -118,7 +143,7 @@ async function pipeStreamEventsToBroadcaster(opts) {
118
143
  if (signal?.aborted) {
119
144
  return;
120
145
  }
121
- onEvent?.();
146
+ onEvent?.(event);
122
147
  if (!isStreamRecord(event)) {
123
148
  continue;
124
149
  }
@@ -444,6 +469,11 @@ export class AgentHarnessModelCaller {
444
469
  }
445
470
  const spans = this.newSpanCollector(request);
446
471
  const modelSpan = spans.startModelSpan(request.model);
472
+ const finished = drainsOf(request.ctx)?.track(request.ctx, {
473
+ kind: 'model_round',
474
+ model: request.model,
475
+ round: 0,
476
+ });
447
477
  try {
448
478
  const response = await this.opts.callModelOverride(request);
449
479
  const itemSchemas = buildItemSchemaRegistry({
@@ -458,6 +488,7 @@ export class AgentHarnessModelCaller {
458
488
  };
459
489
  }
460
490
  finally {
491
+ finished?.();
461
492
  await spans.flush();
462
493
  }
463
494
  }
@@ -505,6 +536,7 @@ export class AgentHarnessModelCaller {
505
536
  let toolLimitRecoveryContinuations = 0;
506
537
  let useEphemeralContinue = false;
507
538
  const roundLedger = RoundLedger.open(request.ctx);
539
+ const drains = drainsOf(request.ctx);
508
540
  const replaySchemas = buildItemSchemaRegistry({
509
541
  base: this.opts.itemSchemas,
510
542
  layers: request.layers,
@@ -529,11 +561,20 @@ export class AgentHarnessModelCaller {
529
561
  cost,
530
562
  });
531
563
  };
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
+ let stoppedForRecall = false;
532
572
  const steers = openSteerInbox({
533
573
  ctx: request.ctx,
534
574
  layers: request.layers ?? [],
535
575
  harness: this.opts.harness,
536
576
  emit: prepared.emitIfAllowed,
577
+ inConversation: (itemId) => hasItem(allItems, itemId) || hasItem(request.ctx?.itemLog.items ?? [], itemId),
537
578
  });
538
579
  while (!request.signal?.aborted) {
539
580
  const replayed = roundLedger?.take(round, replaySchemas);
@@ -543,11 +584,7 @@ export class AgentHarnessModelCaller {
543
584
  for (const item of replayed.appended) {
544
585
  request.ctx?.itemLog.append(item);
545
586
  }
546
- rounds.push(replayed.usage);
547
- totalUsage.inputTokens += replayed.usage.inputTokens;
548
- totalUsage.outputTokens += replayed.usage.outputTokens;
549
- totalUsage.cachedTokens += replayed.usage.cachedTokens ?? 0;
550
- totalCost += replayed.cost;
587
+ countRound(replayed.usage, replayed.cost);
551
588
  replayedCost = (replayedCost ?? 0) + replayed.cost;
552
589
  prepared.emitIfAllowed('model_round_replayed', {
553
590
  round,
@@ -572,10 +609,15 @@ export class AgentHarnessModelCaller {
572
609
  items: allItems.length,
573
610
  };
574
611
  }
612
+ // A graceful stop starts no new round: wait here until it cancels the call.
613
+ await drains?.hold(request.ctx);
614
+ if (request.signal?.aborted) {
615
+ break;
616
+ }
575
617
  const recoveryContinuation = useEphemeralContinue;
576
618
  useEphemeralContinue = false;
577
619
  if (steers) {
578
- await this.applySteers({
620
+ const recall = await this.applySteers({
579
621
  steers,
580
622
  ctx: request.ctx,
581
623
  conversationInput,
@@ -583,6 +625,10 @@ export class AgentHarnessModelCaller {
583
625
  round,
584
626
  emitIfAllowed: prepared.emitIfAllowed,
585
627
  });
628
+ if (recall) {
629
+ stoppedForRecall = true;
630
+ break;
631
+ }
586
632
  }
587
633
  const roundController = new AbortController();
588
634
  const roundSignal = request.signal
@@ -610,6 +656,29 @@ export class AgentHarnessModelCaller {
610
656
  recoveryContinuation,
611
657
  });
612
658
  const modelSpan = spans.startModelSpan(request.model);
659
+ const dispatch = await this.opts.spend?.open({
660
+ ctx: request.ctx ?? request._billTo,
661
+ kind: SpendKind.Model,
662
+ model: request.model,
663
+ body: {
664
+ model: request.model,
665
+ instructions: prepared.instructions,
666
+ input: modelInput,
667
+ },
668
+ maxOutputTokens: request.params?.maxTokens,
669
+ round,
670
+ });
671
+ if (request.signal?.aborted) {
672
+ // Aborted while the record was written: the call was never sent.
673
+ await dispatch?.settle();
674
+ modelSpan.end();
675
+ break;
676
+ }
677
+ const roundFinished = drains?.track(request.ctx, {
678
+ kind: 'model_round',
679
+ model: request.model,
680
+ round,
681
+ }, dispatch?.record);
613
682
  const callResult = client.callModel({
614
683
  model: request.model,
615
684
  input: modelInput,
@@ -629,6 +698,11 @@ export class AgentHarnessModelCaller {
629
698
  : {}),
630
699
  }, {
631
700
  signal: roundSignal,
701
+ ...(dispatch
702
+ ? {
703
+ headers: dispatch.headers,
704
+ }
705
+ : {}),
632
706
  });
633
707
  // Output items the stream has finished, kept so a steer can stop the
634
708
  // round early without losing them.
@@ -639,8 +713,9 @@ export class AgentHarnessModelCaller {
639
713
  broadcaster: prepared.broadcaster,
640
714
  agentName: this.opts.agentName,
641
715
  signal: roundSignal,
642
- onEvent: () => {
716
+ onEvent: (event) => {
643
717
  watchdog.reset();
718
+ noteStreamGeneration(dispatch, event);
644
719
  if (!firstEventSeen) {
645
720
  firstEventSeen = true;
646
721
  prepared.emitIfAllowed('model_call_first_event', {
@@ -665,25 +740,32 @@ export class AgentHarnessModelCaller {
665
740
  try {
666
741
  sdkResponse = await awaitWithAbort(callResult.getResponse(), roundSignal);
667
742
  watchdog.stop();
743
+ await dispatch?.settle();
668
744
  await awaitWithAbort(pipePromise, roundSignal);
669
745
  }
670
746
  catch (err) {
747
+ if (dispatch && wasRefused(err, dispatch)) {
748
+ await dispatch.settle();
749
+ }
671
750
  if (idleStalled) {
672
751
  throw roundSignal.reason instanceof Error
673
752
  ? roundSignal.reason
674
753
  : new Error(`model stream idle timeout after ${this.opts.streamIdleTimeoutMs}ms`);
675
754
  }
676
- if (request.signal?.aborted) {
677
- break;
678
- }
679
- if (!steered) {
755
+ if (!steered && !request.signal?.aborted) {
680
756
  throw err;
681
757
  }
682
758
  }
683
759
  finally {
684
760
  watchdog.stop();
761
+ dispatch?.end();
762
+ roundFinished?.();
685
763
  }
686
764
  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
+ }
687
769
  break;
688
770
  }
689
771
  if (!sdkResponse) {
@@ -758,11 +840,7 @@ export class AgentHarnessModelCaller {
758
840
  const roundUsage = extractUsage(sdkResponse.usage);
759
841
  const roundCost = sdkResponse.usage?.cost ?? 0;
760
842
  spans.finishModelSpan(modelSpan, roundUsage, roundCost > 0 ? roundCost : undefined);
761
- rounds.push(roundUsage);
762
- totalUsage.inputTokens += roundUsage.inputTokens;
763
- totalUsage.outputTokens += roundUsage.outputTokens;
764
- totalUsage.cachedTokens += roundUsage.cachedTokens ?? 0;
765
- totalCost += roundCost;
843
+ countRound(roundUsage, roundCost);
766
844
  servedTier = sdkResponse.serviceTier ?? undefined;
767
845
  allItems.push(...roundItems);
768
846
  const ranTools = await this.runToolRound({
@@ -809,6 +887,11 @@ export class AgentHarnessModelCaller {
809
887
  },
810
888
  rounds,
811
889
  cost: totalCost > 0 ? totalCost : undefined,
890
+ ...(stoppedForRecall
891
+ ? {
892
+ recall: true,
893
+ }
894
+ : {}),
812
895
  ...(replayedCost !== undefined
813
896
  ? {
814
897
  billedCost: totalCost - replayedCost,
@@ -824,14 +907,15 @@ export class AgentHarnessModelCaller {
824
907
  /**
825
908
  * Offer queued steers before a model call and add the applied ones to the
826
909
  * conversation. They join `allItems` rather than the log so the log keeps
827
- * them in the order the model saw them.
910
+ * them in the order the model saw them. Returns whether a layer asked for
911
+ * recall to run again before the call goes on.
828
912
  */
829
913
  async applySteers(params) {
830
914
  const { steers, ctx, conversationInput, allItems } = params;
831
915
  await steers.offer(SteerPoint.BeforeRound);
832
- const { messageIds, items } = steers.takeStaged();
916
+ const { messageIds, items, recall } = steers.takeStaged();
833
917
  if (messageIds.length === 0) {
834
- return;
918
+ return false;
835
919
  }
836
920
  conversationInput.push(...itemsToInput(items));
837
921
  for (const item of items) {
@@ -843,6 +927,7 @@ export class AgentHarnessModelCaller {
843
927
  count: messageIds.length,
844
928
  messageIds,
845
929
  });
930
+ return recall;
846
931
  }
847
932
  parseRoundItems(request, items) {
848
933
  const roundItemSchemas = buildItemSchemaRegistry({
@@ -944,6 +1029,7 @@ export class AgentHarnessModelCaller {
944
1029
  });
945
1030
  }
946
1031
  for (const [index, fc] of functionCalls.entries()) {
1032
+ await drainsOf(request.ctx)?.hold(request.ctx);
947
1033
  if (request.signal?.aborted) {
948
1034
  break;
949
1035
  }
@@ -0,0 +1,35 @@
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 USD per token, and the output cap the model publishes. */
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 estimate and its own output cap. */
19
+ export interface TokenBound {
20
+ inputTokens: number;
21
+ maxOutputTokens?: number;
22
+ }
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 declare function createPriceBook(client: () => PriceClient | undefined): (model: string) => Promise<ModelPrice | undefined>;
29
+ /**
30
+ * @internal
31
+ * 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.
34
+ */
35
+ export declare function ceilingOf(bound: TokenBound, price: ModelPrice): number | undefined;
@@ -0,0 +1,81 @@
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
+ //#endregion
8
+ //#region Public API
9
+ /**
10
+ * @internal
11
+ * Price lookup, cached per model. A failed lookup is not cached. Resolves `undefined`
12
+ * when the model publishes no price or the lookup failed.
13
+ */
14
+ export function createPriceBook(client) {
15
+ const prices = new Map();
16
+ return (model) => {
17
+ const known = prices.get(model);
18
+ if (known) {
19
+ return known;
20
+ }
21
+ const lookup = lookupPrice(model, client());
22
+ prices.set(model, lookup);
23
+ void lookup.then((price) => {
24
+ if (price === undefined) {
25
+ prices.delete(model);
26
+ }
27
+ });
28
+ return lookup;
29
+ };
30
+ }
31
+ /**
32
+ * @internal
33
+ * 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.
36
+ */
37
+ 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) {
44
+ return undefined;
45
+ }
46
+ return price.input * bound.inputTokens + price.output * outputCap + price.request;
47
+ }
48
+ //#endregion
49
+ //#region Helpers
50
+ async function lookupPrice(model, client) {
51
+ const slash = model.indexOf('/');
52
+ if (!client || slash <= 0) {
53
+ return undefined;
54
+ }
55
+ try {
56
+ const { data } = await client.models.get({
57
+ author: model.slice(0, slash),
58
+ slug: model.slice(slash + 1),
59
+ }, {
60
+ timeoutMs: LOOKUP_TIMEOUT_MS,
61
+ });
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) {
65
+ return undefined;
66
+ }
67
+ const request = Number(data.pricing.request ?? 0);
68
+ return {
69
+ input,
70
+ output,
71
+ request: Number.isFinite(request) && request > 0 ? request : 0,
72
+ maxOutput: data.topProvider.maxCompletionTokens ?? undefined,
73
+ contextLength: data.topProvider.contextLength ?? data.contextLength ?? undefined,
74
+ };
75
+ }
76
+ catch {
77
+ // An unknown price leaves the hold unbounded, which `spend_pending` flags.
78
+ return undefined;
79
+ }
80
+ }
81
+ //#endregion
@@ -50,3 +50,5 @@ export declare class RoundLedger {
50
50
  record(round: number, logMark: number, record: RoundRecord): Promise<void>;
51
51
  private key;
52
52
  }
53
+ /** @internal The ledger key of round `round` of the model loop at step path `path`. */
54
+ export declare function roundPath(path: string, round: number): string;
@@ -109,7 +109,11 @@ export class RoundLedger {
109
109
  });
110
110
  }
111
111
  key(round) {
112
- return `${this.dispatch.path}/round#${round}`;
112
+ return roundPath(this.dispatch.path, round);
113
113
  }
114
114
  }
115
+ /** @internal The ledger key of round `round` of the model loop at step path `path`. */
116
+ export function roundPath(path, round) {
117
+ return `${path}/round#${round}`;
118
+ }
115
119
  //#endregion
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Paid dispatches: a record before every paid provider call, and the bill settled
3
+ * afterwards even when the call was cut off (spec 23 § Paid dispatches).
4
+ *
5
+ * A call's record is written before it is sent, gains the provider's generation id
6
+ * when its response headers arrive, and is deleted when its bill reaches the run.
7
+ * A call that ends any other way — cancelled, steered, timed out, its host killed —
8
+ * leaves the record behind. It is then *pending*: held at its ceiling, and priced
9
+ * through the provider's generation lookup once the provider has billed it.
10
+ */
11
+ import type { Context, PendingSpend, ReconcileSpendOptions, SpendKind, SpendSettlement, UsageCharge, WriteOffSpendOptions } from '@noetic-tools/types';
12
+ import type { OpenRouter } from '@openrouter/sdk';
13
+ import type { DispatchRecord, SpendLog } from '../runtime/durable/spend-log.js';
14
+ import type { EventBroadcaster } from './deps/runtime.js';
15
+ import { ContextImpl } from './deps/runtime.js';
16
+ /** @internal Request header that ties a response back to its dispatch. */
17
+ export declare const DISPATCH_HEADER = "x-noetic-dispatch";
18
+ /** @internal Response header carrying OpenRouter's id for the call. */
19
+ export declare const GENERATION_HEADER = "x-generation-id";
20
+ /** @internal The slice of the SDK client spend needs: prices and generation lookups. */
21
+ export type SpendClient = Pick<OpenRouter, 'models' | 'generations'>;
22
+ /** @internal What the harness gives `Spend`. */
23
+ export interface SpendHost {
24
+ readonly agentName: string;
25
+ readonly log: SpendLog;
26
+ client(): SpendClient | undefined;
27
+ /** The root context with a run in flight under `executionId`, if any. */
28
+ liveRoot(executionId: string): Context | undefined;
29
+ /** Add `charge` to the thread's stored session. False when the thread has none. */
30
+ chargeSession(threadId: string, charge: UsageCharge): Promise<boolean>;
31
+ sessionBroadcaster(threadId: string): EventBroadcaster | undefined;
32
+ }
33
+ /** @internal One paid call about to be sent. */
34
+ export interface DispatchParams {
35
+ ctx?: Context;
36
+ kind: SpendKind;
37
+ model: string;
38
+ /** The request body, hashed and sized for the record. */
39
+ body: unknown;
40
+ maxOutputTokens?: number;
41
+ /** The model-loop round, for a `callModel` round's ledger key. */
42
+ round?: number;
43
+ }
44
+ /**
45
+ * @internal
46
+ * One harness's paid dispatches: the live ones it is sending and the pending ones it
47
+ * holds. Pending records come from storage, so any harness over the same storage can
48
+ * settle a call another harness made.
49
+ */
50
+ export declare class Spend {
51
+ private readonly host;
52
+ private readonly live;
53
+ private readonly holds;
54
+ /**
55
+ * Generation lookups in flight, so two callers never settle one dispatch twice and
56
+ * a reconcile waits for the ones already running.
57
+ */
58
+ private readonly lookups;
59
+ private readonly price;
60
+ constructor(host: SpendHost);
61
+ /** Write the record for a call about to be sent. A failed write never blocks the call. */
62
+ open(params: DispatchParams): Promise<Dispatch>;
63
+ /** Save a live dispatch's generation id. The client's response hook awaits it. */
64
+ noteGeneration(dispatchId: string, generationId: string): Promise<void>;
65
+ /** Unsettled dispatches, each with its ceiling. */
66
+ pending(executionId?: string): Promise<PendingSpend[]>;
67
+ /**
68
+ * Hold the restored root context's pending dispatches on it, then reconcile them in
69
+ * the background. `ctx.heldCost` is set when this resolves.
70
+ */
71
+ adopt(ctx: Context): Promise<void>;
72
+ /**
73
+ * Price every pending dispatch that has a generation id, polling until the provider
74
+ * has, and wait for lookups already running for the same dispatches.
75
+ */
76
+ reconcile(opts?: ReconcileSpendOptions): Promise<SpendSettlement[]>;
77
+ /** Settle one pending dispatch at an amount the host asserts. */
78
+ writeOff(id: string, opts: WriteOffSpendOptions): Promise<SpendSettlement | undefined>;
79
+ /** USD held for a thread's pending dispatches. */
80
+ heldFor(threadId: string): number;
81
+ /** A live dispatch ended. Called by `Dispatch` only. */
82
+ release(id: string): void;
83
+ /** A dispatch ended without a bill: hold it and start looking for one. Called by `Dispatch` only. */
84
+ leave(record: DispatchRecord, root: ContextImpl | undefined): void;
85
+ private unsettled;
86
+ /**
87
+ * Hold `record` at its ceiling, on `ctx` when given. A dispatch already held moves to
88
+ * `ctx`, so an execution restored in this process takes over its cut-off calls.
89
+ */
90
+ private hold;
91
+ private ceilingOf;
92
+ private lookup;
93
+ /**
94
+ * Ask the provider for the call's bill until it has one. The provider prices a call
95
+ * some seconds after it ends — 7 to 32 s observed — so a lookup that gave up after a
96
+ * few seconds would leave ordinary calls unknown.
97
+ */
98
+ private poll;
99
+ /**
100
+ * Settle a held dispatch: drop its record, release its hold, and charge its bill
101
+ * once. The record goes first, so a crash part-way loses a settlement rather than
102
+ * counting one twice. A record already gone was settled by another harness over the
103
+ * same storage, which charged it; one that could not be deleted stays held, to be
104
+ * settled by a later reconcile.
105
+ */
106
+ private settle;
107
+ /**
108
+ * Charge a bill to one place: the run in flight on its execution, else its thread's
109
+ * session, else the context this harness held it on. A run in flight passes the
110
+ * charge on to its turn's usage, so charging the session too would count it twice.
111
+ */
112
+ private charge;
113
+ /** Delete a held dispatch's record, unless it is already gone. */
114
+ private take;
115
+ private emit;
116
+ }
117
+ /**
118
+ * @internal
119
+ * One paid call in flight. Record writes run one at a time, so a generation id saved
120
+ * late never brings back a record that was already deleted.
121
+ */
122
+ export declare class Dispatch {
123
+ private readonly spend;
124
+ private readonly log;
125
+ readonly record: DispatchRecord;
126
+ private readonly root;
127
+ private writes;
128
+ private ended;
129
+ constructor(spend: Spend, log: SpendLog, record: DispatchRecord, root: ContextImpl | undefined);
130
+ /** Request headers that tie the response back to this dispatch. */
131
+ get headers(): Record<string, string>;
132
+ noteGeneration(generationId: string): Promise<void>;
133
+ /** The call's bill reached the run, or the provider refused it: drop the record. */
134
+ settle(): Promise<void>;
135
+ /** The call is over. Without a settled bill its record stays, pending. */
136
+ end(): void;
137
+ private queue;
138
+ }