@noetic-tools/core 5.17.0 → 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.
- package/dist/conditions/conditions.js +1 -0
- package/dist/harness/agent-harness.d.ts +54 -9
- package/dist/harness/agent-harness.js +179 -22
- package/dist/harness/decide-call.d.ts +3 -0
- package/dist/harness/decide-call.js +45 -12
- package/dist/harness/deps/adapters.d.ts +1 -1
- package/dist/harness/deps/adapters.js +1 -1
- package/dist/harness/deps/runtime.d.ts +3 -1
- package/dist/harness/deps/runtime.js +3 -1
- package/dist/harness/deps/types.d.ts +1 -1
- package/dist/harness/model-call.d.ts +3 -0
- package/dist/harness/model-call.js +87 -17
- package/dist/harness/model-price.d.ts +35 -0
- package/dist/harness/model-price.js +81 -0
- package/dist/harness/model-rounds.d.ts +2 -0
- package/dist/harness/model-rounds.js +5 -1
- package/dist/harness/spend.d.ts +138 -0
- package/dist/harness/spend.js +494 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +2 -0
- package/dist/interpreter/execute-control.js +1 -0
- package/dist/interpreter/execute-decide.js +18 -0
- package/dist/interpreter/execute.js +9 -0
- package/dist/runtime/context-impl.d.ts +1 -0
- package/dist/runtime/context-impl.js +1 -0
- package/dist/runtime/drain.d.ts +77 -0
- package/dist/runtime/drain.js +268 -0
- package/dist/runtime/durable/spend-log.d.ts +38 -0
- package/dist/runtime/durable/spend-log.js +65 -0
- package/dist/runtime/durable/step-ledger.d.ts +6 -0
- package/dist/runtime/durable/step-ledger.js +3 -2
- package/dist/runtime/session-runner.d.ts +5 -3
- package/dist/runtime/session-runner.js +9 -4
- package/dist/until/predicates.d.ts +5 -1
- package/dist/until/predicates.js +12 -7
- package/dist/util/status-code.d.ts +5 -0
- package/dist/util/status-code.js +8 -0
- package/package.json +2 -2
|
@@ -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,26 @@ 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
|
+
}
|
|
69
91
|
function hasItem(items, id) {
|
|
70
92
|
return items.some((item) => 'id' in item && item.id === id);
|
|
71
93
|
}
|
|
@@ -121,7 +143,7 @@ async function pipeStreamEventsToBroadcaster(opts) {
|
|
|
121
143
|
if (signal?.aborted) {
|
|
122
144
|
return;
|
|
123
145
|
}
|
|
124
|
-
onEvent?.();
|
|
146
|
+
onEvent?.(event);
|
|
125
147
|
if (!isStreamRecord(event)) {
|
|
126
148
|
continue;
|
|
127
149
|
}
|
|
@@ -447,6 +469,11 @@ export class AgentHarnessModelCaller {
|
|
|
447
469
|
}
|
|
448
470
|
const spans = this.newSpanCollector(request);
|
|
449
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
|
+
});
|
|
450
477
|
try {
|
|
451
478
|
const response = await this.opts.callModelOverride(request);
|
|
452
479
|
const itemSchemas = buildItemSchemaRegistry({
|
|
@@ -461,6 +488,7 @@ export class AgentHarnessModelCaller {
|
|
|
461
488
|
};
|
|
462
489
|
}
|
|
463
490
|
finally {
|
|
491
|
+
finished?.();
|
|
464
492
|
await spans.flush();
|
|
465
493
|
}
|
|
466
494
|
}
|
|
@@ -508,6 +536,7 @@ export class AgentHarnessModelCaller {
|
|
|
508
536
|
let toolLimitRecoveryContinuations = 0;
|
|
509
537
|
let useEphemeralContinue = false;
|
|
510
538
|
const roundLedger = RoundLedger.open(request.ctx);
|
|
539
|
+
const drains = drainsOf(request.ctx);
|
|
511
540
|
const replaySchemas = buildItemSchemaRegistry({
|
|
512
541
|
base: this.opts.itemSchemas,
|
|
513
542
|
layers: request.layers,
|
|
@@ -532,6 +561,13 @@ export class AgentHarnessModelCaller {
|
|
|
532
561
|
cost,
|
|
533
562
|
});
|
|
534
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
|
+
};
|
|
535
571
|
let stoppedForRecall = false;
|
|
536
572
|
const steers = openSteerInbox({
|
|
537
573
|
ctx: request.ctx,
|
|
@@ -548,11 +584,7 @@ export class AgentHarnessModelCaller {
|
|
|
548
584
|
for (const item of replayed.appended) {
|
|
549
585
|
request.ctx?.itemLog.append(item);
|
|
550
586
|
}
|
|
551
|
-
|
|
552
|
-
totalUsage.inputTokens += replayed.usage.inputTokens;
|
|
553
|
-
totalUsage.outputTokens += replayed.usage.outputTokens;
|
|
554
|
-
totalUsage.cachedTokens += replayed.usage.cachedTokens ?? 0;
|
|
555
|
-
totalCost += replayed.cost;
|
|
587
|
+
countRound(replayed.usage, replayed.cost);
|
|
556
588
|
replayedCost = (replayedCost ?? 0) + replayed.cost;
|
|
557
589
|
prepared.emitIfAllowed('model_round_replayed', {
|
|
558
590
|
round,
|
|
@@ -577,6 +609,11 @@ export class AgentHarnessModelCaller {
|
|
|
577
609
|
items: allItems.length,
|
|
578
610
|
};
|
|
579
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
|
+
}
|
|
580
617
|
const recoveryContinuation = useEphemeralContinue;
|
|
581
618
|
useEphemeralContinue = false;
|
|
582
619
|
if (steers) {
|
|
@@ -619,6 +656,29 @@ export class AgentHarnessModelCaller {
|
|
|
619
656
|
recoveryContinuation,
|
|
620
657
|
});
|
|
621
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);
|
|
622
682
|
const callResult = client.callModel({
|
|
623
683
|
model: request.model,
|
|
624
684
|
input: modelInput,
|
|
@@ -638,6 +698,11 @@ export class AgentHarnessModelCaller {
|
|
|
638
698
|
: {}),
|
|
639
699
|
}, {
|
|
640
700
|
signal: roundSignal,
|
|
701
|
+
...(dispatch
|
|
702
|
+
? {
|
|
703
|
+
headers: dispatch.headers,
|
|
704
|
+
}
|
|
705
|
+
: {}),
|
|
641
706
|
});
|
|
642
707
|
// Output items the stream has finished, kept so a steer can stop the
|
|
643
708
|
// round early without losing them.
|
|
@@ -648,8 +713,9 @@ export class AgentHarnessModelCaller {
|
|
|
648
713
|
broadcaster: prepared.broadcaster,
|
|
649
714
|
agentName: this.opts.agentName,
|
|
650
715
|
signal: roundSignal,
|
|
651
|
-
onEvent: () => {
|
|
716
|
+
onEvent: (event) => {
|
|
652
717
|
watchdog.reset();
|
|
718
|
+
noteStreamGeneration(dispatch, event);
|
|
653
719
|
if (!firstEventSeen) {
|
|
654
720
|
firstEventSeen = true;
|
|
655
721
|
prepared.emitIfAllowed('model_call_first_event', {
|
|
@@ -674,25 +740,32 @@ export class AgentHarnessModelCaller {
|
|
|
674
740
|
try {
|
|
675
741
|
sdkResponse = await awaitWithAbort(callResult.getResponse(), roundSignal);
|
|
676
742
|
watchdog.stop();
|
|
743
|
+
await dispatch?.settle();
|
|
677
744
|
await awaitWithAbort(pipePromise, roundSignal);
|
|
678
745
|
}
|
|
679
746
|
catch (err) {
|
|
747
|
+
if (dispatch && wasRefused(err, dispatch)) {
|
|
748
|
+
await dispatch.settle();
|
|
749
|
+
}
|
|
680
750
|
if (idleStalled) {
|
|
681
751
|
throw roundSignal.reason instanceof Error
|
|
682
752
|
? roundSignal.reason
|
|
683
753
|
: new Error(`model stream idle timeout after ${this.opts.streamIdleTimeoutMs}ms`);
|
|
684
754
|
}
|
|
685
|
-
if (request.signal?.aborted) {
|
|
686
|
-
break;
|
|
687
|
-
}
|
|
688
|
-
if (!steered) {
|
|
755
|
+
if (!steered && !request.signal?.aborted) {
|
|
689
756
|
throw err;
|
|
690
757
|
}
|
|
691
758
|
}
|
|
692
759
|
finally {
|
|
693
760
|
watchdog.stop();
|
|
761
|
+
dispatch?.end();
|
|
762
|
+
roundFinished?.();
|
|
694
763
|
}
|
|
695
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
|
+
}
|
|
696
769
|
break;
|
|
697
770
|
}
|
|
698
771
|
if (!sdkResponse) {
|
|
@@ -767,11 +840,7 @@ export class AgentHarnessModelCaller {
|
|
|
767
840
|
const roundUsage = extractUsage(sdkResponse.usage);
|
|
768
841
|
const roundCost = sdkResponse.usage?.cost ?? 0;
|
|
769
842
|
spans.finishModelSpan(modelSpan, roundUsage, roundCost > 0 ? roundCost : undefined);
|
|
770
|
-
|
|
771
|
-
totalUsage.inputTokens += roundUsage.inputTokens;
|
|
772
|
-
totalUsage.outputTokens += roundUsage.outputTokens;
|
|
773
|
-
totalUsage.cachedTokens += roundUsage.cachedTokens ?? 0;
|
|
774
|
-
totalCost += roundCost;
|
|
843
|
+
countRound(roundUsage, roundCost);
|
|
775
844
|
servedTier = sdkResponse.serviceTier ?? undefined;
|
|
776
845
|
allItems.push(...roundItems);
|
|
777
846
|
const ranTools = await this.runToolRound({
|
|
@@ -960,6 +1029,7 @@ export class AgentHarnessModelCaller {
|
|
|
960
1029
|
});
|
|
961
1030
|
}
|
|
962
1031
|
for (const [index, fc] of functionCalls.entries()) {
|
|
1032
|
+
await drainsOf(request.ctx)?.hold(request.ctx);
|
|
963
1033
|
if (request.signal?.aborted) {
|
|
964
1034
|
break;
|
|
965
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
|
|
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
|
+
}
|