Repository navigation
Expand file tree
/
Copy pathdispatch.ts
More file actions
449 lines (415 loc) · 27.4 KB
/
Copy pathdispatch.ts
File metadata and controls
449 lines (415 loc) · 27.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/**
* The one gate every paid action of this extension passes immediately before it is sent: a keep-warm refresh, and a
* summary request (compacting before expiry, when full, Pi's /compact through the cached path, the fallback compaction
* model). It is a pure function of what the caller read fresh at that moment: the model-data setting (in memory and on
* disk, latched), the route that will serve (its entry and the gateway's account marker), what the period rests on, the
* request's size and the lifetime its answer showed. It returns a priced quote, or why not.
*
* The quote is what every text says the request rests on: the entry, the account marker, the service tier, the price for
* the request's size (R3), the lifetime (R5), the four prices, the size. Any part unknown, no quote: the action is Pi's. What
* a call cost afterwards is the ledger's (`estimate`), display only, from its own reported usage.
*/
import { askedLifetime, type Dataset, type Route, type Situation } from "./reading.ts";
import { accountsRoute, namesOf, optionValue, priceSizes, retentionValues, shownValues, withoutAdds } from "./shown.ts";
export type PaidKind = "refresh" | "summary";
/**
* What an answer's write showed of the lifetime its request reached the provider with (lifetime-evidence.ts). Only a
* positive 1-hour count is evidence ("hour"); Pi's split never says five minutes (a zero is also a split left out).
*/
export type WriteEvidence = "hour" | "both" | "no breakdown" | "nothing" | undefined;
/** One account a gateway lists for the model, as pi-provimux tells it (model-upstreams `accounts`). */
export interface ListedAccount {
account?: string;
/** The gateway's priority of the account: the highest free one is tried first, accounts sharing it take turns. */
priority?: number;
subscription?: boolean;
answered: string[];
expected: string | null;
adds: Record<string, string>;
}
/** A model behind a gateway: every account it lists, and the latest real answer's account (its marker) and entry. */
export interface GatewayServing {
model: string;
rows: readonly ListedAccount[] | undefined;
answer: { marker: string | null; entry: string | null } | undefined;
}
export interface DispatchInput {
kind: PaidKind;
/** Model data on, as read in memory and on disk now, and not seen off since the session started (the latch). */
modelDataOn: boolean;
/** providers.dev's answers, as held now. */
data: Dataset;
/** The route that will serve the request, for a model of one of Pi's own providers. */
route: Route;
/** The account that will serve, by marker, for a model of Pi's own providers: none. */
marker: string | null;
/**
* A model behind a gateway: the accounts it lists and the latest answer. Given, the gate decides which account serves
* from them (and `route` and `marker` are not read): paid actions only where the answering account is the sole one at
* the top priority, and the latest real answer came from it, by its marker.
*/
gateway?: GatewayServing;
/** What the paid action rests on (a refresh: the period's answer): a change of entry or marker since then is a refusal. */
expected?: { entry: string; marker: string | null };
/** The request's input tokens, cached ones included: its own size (R3). */
size: number;
/**
* The model's provider was registered by an extension with a stream handler of its own for the model's API (Pi then
* sends through that handler, not its built-in adapter): the request may not reach the transport this extension checks.
*/
registeredHandler?: boolean;
/** The lifetime value the request carries, as sent (R5); null: none. */
carried: string | null;
/** The latest answer's write, all of it in one cache: the lifetime its request was on (R5, evidence first). */
evidence: WriteEvidence;
/** The service tier the request names; null: none. */
serviceTier: string | null;
/** The instant of the request (R4), ISO 8601. */
at: string;
/**
* A refresh's limit in its idle period, none of it in money: the refreshes sent so far and how many one cache miss pays
* for at the period's start quote (`refreshLimit`), and the cache-write tokens they reported against a tenth of the
* context (`writeLimit`).
*/
budget?: WarmLimit;
}
/** A refresh's limit in its idle period (see DispatchInput.budget). */
export interface WarmLimit {
refreshes: number;
refreshLimit: number;
written: number;
writeLimit: number;
}
/**
* How close under a published price-tier boundary (`input_tokens_above`, in the base schedule, its dated change, and the
* selected service tier's) a refresh's size may be: within it, the refresh is refused (the tokens a re-sent request adds
* could take it over). 1%: from 269,281 tokens under 272,000.
*/
export const TIER_MARGIN = 0.01;
/**
* A summary's size is an estimate (Pi's count of what was added since the last answer, reasoning tokens and trailing tool
* results included, can be far off): it is refused where a published boundary lies between these shares of its size.
*/
export const SUMMARY_SPAN = { below: 0.8, above: 1.25 } as const;
/** A priced quote: what the request costs, per million tokens, and what it rests on. */
export interface Quote {
kind: PaidKind;
entry: string;
marker: string | null;
/** The service tier the request names (null: none): the prices are that tier's. */
serviceTier: string | null;
/** The lifetime the request reached the provider with, and how long it lasts (null: not published; a summary needs none). */
lifetime: { value: string | null; seconds: number | null };
price: { input: number; output: number; cache_read: number; cache_write: number };
size: number;
window: number;
max_output: number;
/** A refresh: what it is expected to cost (the size read from the cache, one output token). */
expected: number;
}
/** Only mayDispatch makes one: a quote the gate approved. The send wrappers take nothing else. */
declare const APPROVED: unique symbol;
export type Approved = Quote & { readonly [APPROVED]: true };
export type Verdict =
| { ok: true; quote: Approved }
/** `halt`: paid actions end until the next real answer (every refusal but the budget, which ends the warming only). */
| { ok: false; reason: string; halt: boolean };
export const REFUSED = {
modelDataOff: "model data from providers.dev is off (or was turned off in this session), so this extension takes no paid action; it is left to Pi",
noEntry: "no providers.dev entry serves the request",
severalAccounts: "more than one account can serve the request, so its price is not known before it leaves",
severalEntries: "more than one providers.dev entry may serve the request, so its price is not known before it leaves",
routeChanged: "the route changed since the answer this rests on",
lifetime: "providers.dev publishes no cache lifetime for this request",
window: "the model's context window is unknown (providers.dev publishes none for it)",
output: "the model's output limit is unknown (providers.dev publishes none for it)",
price: "providers.dev publishes no complete price for this request (input, output, cache read, and the cache write for its lifetime)",
budget: "another refresh would pass the idle period's limit: as many refreshes as one cache miss pays for at the period's quote, or a tenth of the context written by refreshes",
lifetimeZero: "providers.dev publishes a cache lifetime of 0 seconds for this request, so there is no cache to keep warm",
nearTier: `the request's size is within ${TIER_MARGIN * 100}% under a published price tier boundary, so the price it is billed at is not known before it leaves`,
summaryTier: `a published price tier boundary lies between ${SUMMARY_SPAN.below} and ${SUMMARY_SPAN.above} times the summary's estimated size, so the price it is billed at is not known before it leaves`,
registeredHandler: "an extension registered this model's provider with a stream handler of its own for its API, so the request may not go through the transport this extension checks at its send",
retentionPrices: "providers.dev publishes no cache-write price for every option of this entry's cache-retention control, so a change of retention before the request leaves would send it at an unknown price",
hourOption: "the latest answer wrote all of it to the 1-hour cache, and providers.dev publishes no 1-hour option for this entry, so the write price of the lifetime the request reached the provider with is not known",
sentLifetime: "the request as built carries another cache lifetime than the one it was quoted at (the retention changed before it left)",
noAnswerEntry: "the latest answer named its account but no providers.dev entry, so its price is not known",
noRows: "the gateway lists no accounts for the model, so which account serves a request is not known",
priority: "the gateway gives no priority for an account of the model, so which account serves a request is not known",
noMarker: "the latest answer named no account (no marker), so which account serves a request is not known",
unlisted: "the account that answered is not among those the gateway lists for the model",
pool: "more than one account shares the top priority (a pool), so which one serves a request, and its price, is not known before it leaves",
fallback:
"through a gateway with a fallback account, at most one refresh or summary can be served by the fallback (for example a paid API key while your subscription is exhausted). It costs about one write of the whole context at that key's price, then pi-cache-keeper stops until your next message",
} as const;
/** The latest answer's account, where paid actions may rest on it (the sole one at the top priority); else why not. */
function topAccount(serving: GatewayServing): { reason: string } | { row: ListedAccount } {
const rows = serving.rows ?? [];
if (rows.length === 0) return { reason: REFUSED.noRows };
if (rows.some((row) => typeof row.priority !== "number" || !Number.isFinite(row.priority))) return { reason: REFUSED.priority };
const marker = serving.answer?.marker;
if (!marker) return { reason: REFUSED.noMarker };
const own = rows.filter((row) => row.account === marker);
if (own.length !== 1) return { reason: REFUSED.unlisted };
const top = Math.max(...rows.map((row) => row.priority as number));
const atTop = rows.filter((row) => row.priority === top);
if (atTop.length > 1) return { reason: REFUSED.pool };
if (atTop[0] !== own[0]) return { reason: `the latest answer came from a fallback account (${marker}), not the one at the top priority; ${REFUSED.fallback}` };
return { row: own[0] as ListedAccount };
}
/** The route of one listed account, priced at the entry the answer named on it (else the entries it names). */
function accountRoute(serving: GatewayServing, row: ListedAccount): Route {
const entry = serving.answer?.entry;
return accountsRoute({ id: serving.model }, [{ ...row, answered: entry ? [entry] : namesOf(row) }]);
}
const PER_MILLION = 1_000_000;
/**
* The lifetime a request reached the provider with (R5), one function for warming, compaction and booking: the
* answer's whole write in one cache first (its option's value, the gateway's additions then known to be in it), else
* the request's own value with what the gateway adds (the reader's R5), else the entry's default.
*/
export function requestLifetime(data: Dataset, route: Route, evidence: WriteEvidence, carried: string | null): { route: Route; lifetime: string | null; unknown?: true } {
// Only a positive 1-hour count is evidence; anything else is not told, and R5's next source applies. The hour told,
// with no 1-hour option published: the lifetime it reached the provider with has no published value, so none.
if (evidence === "hour") {
const shown = optionValue(data, route, "long");
return shown ? { route: withoutAdds(route), lifetime: shown } : { route, lifetime: carried, unknown: true };
}
return { route, lifetime: carried };
}
/**
* The lifetime a request as built reaches the provider with by its own value (R5 without evidence: the value it carries,
* what the answering account's gateway adds, else the entry's default), on the entry `entry`; undefined where not known.
*/
export function bodyLifetime(input: DispatchInput, entry: string): string | null | undefined {
const serving = servingOf(input, false);
if ("reason" in serving) return undefined;
const route = serving.route;
const summary = (input.data.summaries as Array<{ ref?: string }>).find((one) => one.ref === entry);
if (!summary) return undefined;
return askedLifetime(summary, { lifetime: input.carried }, route.kind === "provimux" && route.accounts.length === 1 ? route.accounts[0]?.adds : {}).value;
}
/** Whether Pi sends a model's requests through an extension's own handler: its provider registered with a `streamSimple` for the model's API. */
export const registeredHandlerServes = (config: { api?: string; streamSimple?: unknown } | undefined, api: string): boolean => typeof config?.streamSimple === "function" && config.api === api;
type Price = { input: number | null; output: number | null; cache_read: number | null; cache_write: number | null };
const completePrice = (p: Price): p is Quote["price"] => p.input !== null && p.output !== null && p.cache_read !== null && p.cache_write !== null;
const samePrice = (a: Price, b: Price): boolean => a.input === b.input && a.output === b.output && a.cache_read === b.cache_read && a.cache_write === b.cache_write;
/** The gate. Pure: the same input, the same verdict. */
export function mayDispatch(input: DispatchInput): Verdict {
return gate(input);
}
/**
* The route that serves a request and its account marker, as the gate decides it, else why not. Through a gateway, which
* account serves is decided from the listed rows and the latest answer, never from a route narrowed beforehand; a
* gateway's route without its listing (before pi-provimux sent it, or on a resume before it came) is refused.
* `anyAccount`: the answering account, whichever it is (pricing what was answered, not deciding what may be sent).
*/
function servingOf(input: DispatchInput, anyAccount: boolean): { reason: string } | { route: Route; marker: string | null } {
if (input.gateway) {
const rows = input.gateway.rows ?? [];
const answer = input.gateway.answer;
const own = rows.filter((row) => row.account !== undefined && row.account === answer?.marker);
const found = anyAccount ? (own.length === 1 ? { row: own[0] as ListedAccount } : { reason: REFUSED.unlisted }) : topAccount(input.gateway);
if ("reason" in found) return found;
// The answer named its account but no entry: never priced at the entry the row expects.
if (!answer?.entry) return { reason: REFUSED.noAnswerEntry };
return { route: accountRoute(input.gateway, found.row), marker: found.row.account ?? null };
}
// A gateway's route is priced only from its listing.
if (input.route.kind === "provimux") return { reason: REFUSED.noRows };
return { route: input.route, marker: input.marker };
}
function gate(input: DispatchInput): Verdict {
const no = (reason: string, halt = true): Verdict => ({ ok: false, reason, halt });
if (!input.modelDataOn) return no(REFUSED.modelDataOff);
// Only Pi's built-in adapter sends a paid request of this extension's: it hands the request to the transport checked
// at the send.
if (input.registeredHandler) return no(REFUSED.registeredHandler);
const serving = servingOf(input, false);
if ("reason" in serving) return no(serving.reason);
const { marker } = serving;
const { route, lifetime, unknown } = requestLifetime(input.data, serving.route, input.evidence, input.carried);
const situation = (size: number) => ({ input_tokens: size, lifetime, service_tier: input.serviceTier, at: input.at });
const values = shownValues(input.data, route, situation(input.size));
if (values.entries.length === 0) return no(REFUSED.noEntry);
if (values.entries.length > 1) return no(REFUSED.severalEntries);
// The hour told by the answer, with no 1-hour option published for the entry: no quote.
if (unknown) return no(REFUSED.hourOption);
const entry = values.entries[0] as string;
if (input.expected && (input.expected.entry !== entry || input.expected.marker !== marker)) {
const was = `${input.expected.entry}${input.expected.marker ? ` (account ${input.expected.marker})` : ""}`;
const now = `${entry}${marker ? ` (account ${marker})` : ""}`;
return no(`${REFUSED.routeChanged}: ${was}, now ${now}`);
}
// A refresh keeps a cache alive: its lifetime must be known, from providers.dev or from the answer's whole write in the
// 1-hour cache (R5, evidence first: Pi's split never says five minutes), and longer than nothing. A summary asks none.
const seconds = values.lifetime_s ?? (input.evidence === "hour" ? 3600 : null);
if (input.kind === "refresh" && seconds === null) return no(REFUSED.lifetime);
if (input.kind === "refresh" && !((seconds as number) > 0)) return no(REFUSED.lifetimeZero);
if (values.window === null || !(values.window > 0)) return no(REFUSED.window);
if (values.max_output === null || !(values.max_output > 0)) return no(REFUSED.output);
const price = values.price;
if (!completePrice(price)) return no(REFUSED.price);
// Every option of the entry's retention control has a published write price (a single lifetime passes): a retention
// changed before the request leaves never sends it at an unknown price.
for (const value of retentionValues(input.data, route)) {
const option = shownValues(input.data, withoutAdds(route), { ...situation(input.size), lifetime: value });
if (option.price.cache_write === null) return no(REFUSED.retentionPrices);
}
// The published price-tier boundaries, the base schedule's, its dated change's and the selected service tier's: a
// refresh within TIER_MARGIN under one, a summary with one between SUMMARY_SPAN of its estimated size, is refused.
const boundaries = priceSizes(input.data, route, input.serviceTier);
if (input.kind === "refresh" && boundaries.some((b) => b >= input.size && input.size > b * (1 - TIER_MARGIN))) return no(REFUSED.nearTier);
if (input.kind === "summary" && boundaries.some((b) => b >= input.size * SUMMARY_SPAN.below && b <= input.size * SUMMARY_SPAN.above)) return no(REFUSED.summaryTier);
const expected = (input.size * price.cache_read + price.output) / PER_MILLION;
const quote: Quote = {
kind: input.kind,
entry,
marker,
serviceTier: input.serviceTier,
// The value the request reaches the provider with (R5): what the account's gateway adds, else its own, else the default.
lifetime: { value: askedLifetime((input.data.summaries as Array<{ ref?: string }>).find((one) => one.ref === entry), { lifetime }, route.kind === "provimux" && route.accounts.length === 1 ? route.accounts[0]?.adds : {}).value, seconds },
price: { ...price },
size: input.size,
window: values.window,
max_output: values.max_output,
expected,
};
if (input.kind === "refresh" && input.budget) {
const { refreshes, refreshLimit, written, writeLimit } = input.budget;
if (refreshes >= refreshLimit || written >= writeLimit) return no(REFUSED.budget, false);
}
return { ok: true, quote: quote as Approved };
}
/**
* How many refreshes one cache miss pays for at a quote (miss cost ÷ expected refresh cost); 0 where none does (a miss
* that costs nothing more, at a published zero write price, say). `fit`: how many refreshes fit in the period (its time
* limit over the cache lifetime): at a published zero read price (a refresh that costs only its output token, or
* nothing) the count is that, finite, and the period's time limit is what ends it.
*/
export function refreshLimitOf(quote: Pick<Quote, "price" | "size" | "expected">, fit = Number.POSITIVE_INFINITY): number {
const miss = missCostOf(quote);
if (!(miss > 0)) return 0;
const paid = quote.expected > 0 ? (miss > quote.expected ? Math.floor(miss / quote.expected) : 0) : Number.POSITIVE_INFINITY;
// A published zero read price: a refresh costs at most its output token, so the miss would pay for a count with no
// meaning; the count is what fits in the period, and the period's time limit ends it (the token rule still holds).
return quote.price.cache_read > 0 ? paid : Math.min(paid, fit);
}
/**
* How many refreshes fit in a period of `minutes` after Pi goes idle, one every `intervalSeconds` (the cache lifetime less
* the lead a refresh leaves before expiry), and one more: never fewer than the time limit lets out, so it is the time
* limit that ends such a period.
*/
export const refreshesThatFit = (minutes: number, intervalSeconds: number): number =>
intervalSeconds > 0 ? Math.ceil((minutes * 60) / intervalSeconds) + 1 : 0;
/**
* Whether the reader's price for a request of `size` is the quote's, in the quote's situation, on the route the gate
* decides now: what a refresh's reported size is checked against once it settled. False where it is not known.
*/
export function samePriceAt(input: DispatchInput, quote: Pick<Quote, "price" | "entry">, size: number): boolean {
if (!input.modelDataOn) return false;
const serving = servingOf(input, true);
if ("reason" in serving) return false;
const { route, lifetime, unknown } = requestLifetime(input.data, serving.route, input.evidence, input.carried);
if (unknown) return false;
const there = shownValues(input.data, route, { input_tokens: size, lifetime, service_tier: input.serviceTier, at: input.at });
return there.entries.length === 1 && there.entries[0] === quote.entry && samePrice(there.price, quote.price);
}
/** The cache-write tokens an idle period's refreshes may report together: a tenth of the context. */
export const writeLimitOf = (size: number): number => size / 10;
/** A call's reported usage: Anthropic's `cacheWrite1h` is the part of the write in the 1-hour cache; none, no breakdown. */
export interface ReportedUsage {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
cacheWrite1h?: number;
}
/** What a call cost, estimated at providers.dev's published prices, by part. */
export interface Estimate {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
total: number;
}
/**
* The ledger (display only): what one call cost, estimated at providers.dev's published prices from its own reported
* usage: at the entry that answered it (through a gateway, the answering account's), in the price tier of its own size,
* its writes by the bucket they were reported in (5 minutes and 1 hour; a write without a breakdown at the lifetime
* the request reached the provider with). Null (unknown) where any part with tokens has no published price, the entry
* that answered is not known, or model data is off. Nothing here decides what is sent.
*/
export function estimate(input: DispatchInput, usage: ReportedUsage): Estimate | null {
if (!input.modelDataOn) return null;
const serving = servingOf(input, true);
if ("reason" in serving) return null;
const size = usage.input + usage.cacheRead + usage.cacheWrite;
const at = (route: Route, lifetime: string | null) => shownValues(input.data, route, { input_tokens: size, lifetime, service_tier: input.serviceTier, at: input.at });
const { route, lifetime, unknown } = requestLifetime(input.data, serving.route, input.evidence, input.carried);
if (unknown) return null;
const values = at(route, lifetime);
if (values.entries.length !== 1) return null;
const entry = values.entries[0];
const part = (tokens: number, price: number | null): number | null => (tokens > 0 ? (price === null ? null : (tokens * price) / PER_MILLION) : 0);
// The write price of one bucket: the long or the short option's value, read without what a gateway adds.
const bucket = (tokens: number, profile: "short" | "long"): number | null => {
if (!(tokens > 0)) return 0;
const value = optionValue(input.data, serving.route, profile);
if (!value) return null;
const shown = at(withoutAdds(serving.route), value);
return shown.entries.length === 1 && shown.entries[0] === entry ? part(tokens, shown.price.cache_write) : null;
};
// Only a positive 1-hour count is a breakdown (Pi reports a split left out as 0): else the whole write is priced at the
// lifetime the request reached the provider with.
const hour = usage.cacheWrite1h === undefined || !(usage.cacheWrite1h > 0) ? undefined : Math.min(usage.cacheWrite, usage.cacheWrite1h);
const write = hour === undefined ? part(usage.cacheWrite, values.price.cache_write) : sum([bucket(usage.cacheWrite - hour, "short"), bucket(hour, "long")]);
const parts = [part(usage.input, values.price.input), part(usage.output, values.price.output), part(usage.cacheRead, values.price.cache_read), write];
const total = sum(parts);
if (total === null) return null;
const [i, o, r, w] = parts as number[];
return { input: i as number, output: o as number, cacheRead: r as number, cacheWrite: w as number, total };
}
const sum = (parts: Array<number | null>): number | null => (parts.some((one) => one === null) ? null : (parts as number[]).reduce((a, b) => a + b, 0));
/**
* What a cache miss costs at a quote: the size written again at the published write price, less its cached read. A
* published zero write price is a miss that costs nothing more: 0 (never the input price in its place).
*/
export function missCostOf(quote: Pick<Quote, "price" | "size">): number {
return Math.max(0, (quote.size * quote.price.cache_write - quote.size * quote.price.cache_read) / PER_MILLION);
}
/** A quote in words, for the log and the texts: "anthropic/claude-opus-5-5, $4/$20 per M, cache read $0.2, write $5 (5 min)". */
export function quoteText(quote: Quote): string {
const dollars = (n: number) => `$${Number(n.toPrecision(4))}`;
const account = quote.marker ? ` via account ${quote.marker}` : "";
const tier = quote.serviceTier ? `, ${quote.serviceTier} service tier` : "";
return `${quote.entry}${account}: ${dollars(quote.price.input)}/${dollars(quote.price.output)} per M in/out at ${quote.size.toLocaleString("en-US")} tokens${tier}, cache read ${dollars(quote.price.cache_read)}, cache write ${dollars(quote.price.cache_write)} (${quote.lifetime.value ?? "default"} cache)`;
}
/** The situation the reader reads a quote's prices at (for a text that names them). */
export const situationOf = (quote: Quote, at: string): Situation => ({ input_tokens: quote.size, lifetime: quote.lifetime.value, service_tier: quote.serviceTier, at });
/**
* The Pi APIs whose adapters hand every HTTP request to the `fetch` a caller passes (pi-ai's StreamOptions.fetch), so the
* gate can quote a request again at the moment it is sent. A paid request on any other API can't be checked at its send,
* so this extension does not send one: Bedrock's SDK, Claude through pi-claude-bridge, an extension's own stream, and the
* WebSocket-first Codex adapters (`WEBSOCKET_APIS`), whose request leaves on a socket before any `fetch`.
*/
export const FETCH_APIS: ReadonlySet<string> = new Set([
"anthropic-messages",
"openai-completions",
"openai-responses",
"azure-openai-responses",
"google-generative-ai",
"google-vertex",
"mistral-conversations",
"pi-messages",
]);
/**
* The adapters that try a WebSocket first and fall back to `fetch` only after it fails: Pi's Codex adapter
* (`openai-codex-responses`) and pi-provimux's patched copy of it for Provimux's Codex format
* (`provimux-codex-responses`, extensions/codex-stream.ts). Never in FETCH_APIS.
*/
export const WEBSOCKET_APIS: ReadonlySet<string> = new Set(["openai-codex-responses", "provimux-codex-responses"]);
/** Why a summary request can't be sent on a model's API: it can't be quoted again at its send. */
export const unsentApi = (api: string): string =>
api === "claude-bridge"
? "a summary through pi-claude-bridge can't be checked by the gate at the moment it is sent, so this extension doesn't send one"
: `its requests (${api}) can't be checked by the gate at the moment they are sent, so this extension sends none`;