@brglng/pi-currency-cost 0.1.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/LICENSE +5 -0
- package/README.md +151 -0
- package/README.zh.md +140 -0
- package/config/config.example.json +34 -0
- package/dist/public.d.ts +255 -0
- package/package.json +77 -0
- package/schemas/config.schema.json +105 -0
- package/src/config-paths.ts +44 -0
- package/src/config.ts +418 -0
- package/src/index.ts +449 -0
- package/src/rates.ts +324 -0
- package/src/store.ts +87 -0
- package/src/usage-cost.ts +111 -0
package/src/rates.ts
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
import type { CurrencyRateConfig, RateSourceConfig } from "./config";
|
|
2
|
+
import { DEFAULT_TIMEOUT_MS, USD_CODE } from "./config";
|
|
3
|
+
|
|
4
|
+
/** Bank of China official spot-rate page (中行外汇牌价). */
|
|
5
|
+
export const BOC_PAGE_URL = "https://www.boc.cn/sourcedb/whpj/";
|
|
6
|
+
|
|
7
|
+
/** Frankfurter currency converter base endpoint (fixed, built in). */
|
|
8
|
+
export const FRANKFURTER_BASE_URL = "https://api.frankfurter.dev/v1/latest";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Chinese currency names as published in the 货币名称 column of the Bank of
|
|
12
|
+
* China rate table. The table publishes 中行折算价 per 100 units of the
|
|
13
|
+
* foreign currency; CNY itself is the base currency and has no row.
|
|
14
|
+
*/
|
|
15
|
+
export const BOC_CURRENCY_NAMES: Record<string, string> = {
|
|
16
|
+
AED: "阿联酋迪拉姆",
|
|
17
|
+
AUD: "澳大利亚元",
|
|
18
|
+
BND: "文莱元",
|
|
19
|
+
BRL: "巴西雷亚尔",
|
|
20
|
+
CAD: "加拿大元",
|
|
21
|
+
CHF: "瑞士法郎",
|
|
22
|
+
CZK: "捷克克朗",
|
|
23
|
+
DKK: "丹麦克朗",
|
|
24
|
+
EUR: "欧元",
|
|
25
|
+
GBP: "英镑",
|
|
26
|
+
HKD: "港币",
|
|
27
|
+
HUF: "匈牙利福林",
|
|
28
|
+
IDR: "印尼卢比",
|
|
29
|
+
ILS: "以色列谢克尔",
|
|
30
|
+
INR: "印度卢比",
|
|
31
|
+
JPY: "日元",
|
|
32
|
+
KHR: "柬埔寨瑞尔",
|
|
33
|
+
KRW: "韩国元",
|
|
34
|
+
KWD: "科威特第纳尔",
|
|
35
|
+
MNT: "蒙古图格里克",
|
|
36
|
+
MOP: "澳门元",
|
|
37
|
+
MXN: "墨西哥比索",
|
|
38
|
+
MYR: "林吉特",
|
|
39
|
+
NOK: "挪威克朗",
|
|
40
|
+
NPR: "尼泊尔卢比",
|
|
41
|
+
NZD: "新西兰元",
|
|
42
|
+
PHP: "菲律宾比索",
|
|
43
|
+
PKR: "巴基斯坦卢比",
|
|
44
|
+
QAR: "卡塔尔里亚尔",
|
|
45
|
+
RSD: "塞尔维亚第纳尔",
|
|
46
|
+
RUB: "卢布",
|
|
47
|
+
SAR: "沙特里亚尔",
|
|
48
|
+
SEK: "瑞典克朗",
|
|
49
|
+
SGD: "新加坡元",
|
|
50
|
+
THB: "泰国铢",
|
|
51
|
+
TRY: "土耳其里拉",
|
|
52
|
+
TWD: "新台币",
|
|
53
|
+
USD: "美元",
|
|
54
|
+
VND: "越南盾",
|
|
55
|
+
ZAR: "南非兰特",
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
/** Column index of 中行折算价 (BOC calculation price) in each table row. */
|
|
59
|
+
const BOC_MID_COLUMN = 5;
|
|
60
|
+
|
|
61
|
+
const NAME_TO_CODE: ReadonlyMap<string, string> = new Map(
|
|
62
|
+
Object.entries(BOC_CURRENCY_NAMES).map(([code, name]) => [name, code]),
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
const DOT_PATH_SEGMENT_RE = /^[A-Za-z_$][A-Za-z0-9_$-]*$/;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Parse the Bank of China HTML table into `Map<code, 中行折算价>` where the
|
|
69
|
+
* value is CNY per 100 units of the currency. Rows whose name is not in the
|
|
70
|
+
* known name map are ignored (including the disclaimer footer row).
|
|
71
|
+
*/
|
|
72
|
+
export function parseBocTable(html: string): Map<string, number> {
|
|
73
|
+
const result = new Map<string, number>();
|
|
74
|
+
const rowPattern = /<tr[^>]*>([\s\S]*?)<\/tr>/g;
|
|
75
|
+
for (const rowMatch of html.matchAll(rowPattern)) {
|
|
76
|
+
const rowHtml = rowMatch[1];
|
|
77
|
+
const cells: string[] = [];
|
|
78
|
+
const cellPattern = /<td[^>]*>([\s\S]*?)<\/td>/g;
|
|
79
|
+
for (const cellMatch of rowHtml.matchAll(cellPattern)) {
|
|
80
|
+
cells.push(cellMatch[1].replace(/<[^>]+>/g, "").trim());
|
|
81
|
+
}
|
|
82
|
+
if (cells.length <= BOC_MID_COLUMN) continue;
|
|
83
|
+
const code = NAME_TO_CODE.get(cells[0]);
|
|
84
|
+
if (!code) continue;
|
|
85
|
+
const mid = Number(cells[BOC_MID_COLUMN]);
|
|
86
|
+
if (Number.isFinite(mid) && mid > 0) {
|
|
87
|
+
result.set(code, mid);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return result;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* USD per one unit of `currency` derived from a parsed BOC table
|
|
95
|
+
* (cross-rate via the USD row, CNY handled as the base currency).
|
|
96
|
+
*/
|
|
97
|
+
export function bocUsdPerUnit(
|
|
98
|
+
parsed: Map<string, number>,
|
|
99
|
+
currency: string,
|
|
100
|
+
): number | undefined {
|
|
101
|
+
if (currency === USD_CODE) return 1;
|
|
102
|
+
const usdMid = parsed.get(USD_CODE);
|
|
103
|
+
if (usdMid === undefined || usdMid <= 0) return undefined;
|
|
104
|
+
if (currency === "CNY") return 100 / usdMid;
|
|
105
|
+
const mid = parsed.get(currency);
|
|
106
|
+
if (mid === undefined || mid <= 0) return undefined;
|
|
107
|
+
// Both values are CNY per 100 units, so the per-100 factor cancels out.
|
|
108
|
+
return mid / usdMid;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Fetch and decode the BOC page. The page is UTF-8 today but was historically
|
|
113
|
+
* GB2312/GBK; when the UTF-8 parse yields no rows the bytes are re-decoded
|
|
114
|
+
* as gb18030 and re-parsed.
|
|
115
|
+
*/
|
|
116
|
+
export async function fetchBocTable(
|
|
117
|
+
timeoutMs: number,
|
|
118
|
+
signal: AbortSignal | undefined,
|
|
119
|
+
fetchImpl: typeof fetch = fetch,
|
|
120
|
+
): Promise<Map<string, number>> {
|
|
121
|
+
const response = await fetchWithTimeout(
|
|
122
|
+
BOC_PAGE_URL,
|
|
123
|
+
timeoutMs,
|
|
124
|
+
signal,
|
|
125
|
+
fetchImpl,
|
|
126
|
+
);
|
|
127
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
128
|
+
let parsed = parseBocTable(
|
|
129
|
+
new TextDecoder("utf-8", { fatal: true }).decode(bytes),
|
|
130
|
+
);
|
|
131
|
+
if (parsed.size === 0) {
|
|
132
|
+
parsed = parseBocTable(new TextDecoder("gb18030").decode(bytes));
|
|
133
|
+
}
|
|
134
|
+
if (parsed.size === 0) {
|
|
135
|
+
throw new Error("Could not parse the Bank of China rate table");
|
|
136
|
+
}
|
|
137
|
+
return parsed;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Conservative dot-path read: segments are plain object keys (no array
|
|
142
|
+
* indices, no wildcards, no prototype/inherited keys). Returns undefined
|
|
143
|
+
* for missing or unsafe paths.
|
|
144
|
+
*/
|
|
145
|
+
export function readDotPath(root: unknown, dotPath: string): unknown {
|
|
146
|
+
let current: unknown = root;
|
|
147
|
+
for (const segment of dotPath.split(".")) {
|
|
148
|
+
if (!DOT_PATH_SEGMENT_RE.test(segment)) return undefined;
|
|
149
|
+
if (
|
|
150
|
+
current === null ||
|
|
151
|
+
typeof current !== "object" ||
|
|
152
|
+
Array.isArray(current)
|
|
153
|
+
) {
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
// Own properties only: prototype keys such as `constructor`, `__proto__`
|
|
157
|
+
// or `toString` must never resolve to inherited values.
|
|
158
|
+
if (!Object.hasOwn(current, segment)) {
|
|
159
|
+
return undefined;
|
|
160
|
+
}
|
|
161
|
+
current = (current as Record<string, unknown>)[segment];
|
|
162
|
+
}
|
|
163
|
+
return current;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export async function fetchWithTimeout(
|
|
167
|
+
url: string,
|
|
168
|
+
timeoutMs: number,
|
|
169
|
+
signal: AbortSignal | undefined,
|
|
170
|
+
fetchImpl: typeof fetch = fetch,
|
|
171
|
+
): Promise<Response> {
|
|
172
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
173
|
+
const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
174
|
+
const response = await fetchImpl(url, {
|
|
175
|
+
signal: combined,
|
|
176
|
+
headers: { accept: "text/html,application/json" },
|
|
177
|
+
});
|
|
178
|
+
if (!response.ok) {
|
|
179
|
+
throw new Error(`HTTP ${response.status} from ${url}`);
|
|
180
|
+
}
|
|
181
|
+
return response;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Fetch USD per one unit of `currency` from the fixed Frankfurter endpoint
|
|
186
|
+
* `?base=<currency>&symbols=USD`. The response's `rates.USD` is USD per one
|
|
187
|
+
* source unit, which is exactly the conversion the extension applies.
|
|
188
|
+
*/
|
|
189
|
+
export async function fetchFrankfurterUsdRate(
|
|
190
|
+
currency: string,
|
|
191
|
+
timeoutMs: number,
|
|
192
|
+
signal: AbortSignal | undefined,
|
|
193
|
+
fetchImpl: typeof fetch = fetch,
|
|
194
|
+
): Promise<number> {
|
|
195
|
+
const url = `${FRANKFURTER_BASE_URL}?base=${encodeURIComponent(currency)}&symbols=USD`;
|
|
196
|
+
const response = await fetchWithTimeout(url, timeoutMs, signal, fetchImpl);
|
|
197
|
+
const json: unknown = await response.json();
|
|
198
|
+
const raw = readDotPath(json, "rates.USD");
|
|
199
|
+
const value =
|
|
200
|
+
typeof raw === "number"
|
|
201
|
+
? raw
|
|
202
|
+
: typeof raw === "string" && raw.trim() !== ""
|
|
203
|
+
? Number(raw)
|
|
204
|
+
: Number.NaN;
|
|
205
|
+
if (!Number.isFinite(value) || value <= 0) {
|
|
206
|
+
throw new Error(
|
|
207
|
+
`No positive USD rate found at "rates.USD" in the response from ${url}`,
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
return value;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export interface RateFetchError {
|
|
214
|
+
currency: string;
|
|
215
|
+
message: string;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export interface RateFetchResult {
|
|
219
|
+
/** currency -> USD per one unit, for every currency that could be resolved. */
|
|
220
|
+
rates: Map<string, number>;
|
|
221
|
+
errors: RateFetchError[];
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Fetch current USD rates for all requested currencies. Frankfurter is queried
|
|
226
|
+
* once per currency; BOC uses one table request for all currencies.
|
|
227
|
+
* Transport-level failures of the whole source throw; per-currency failures
|
|
228
|
+
* are reported in `errors` so the caller can keep the configured `usdRate`
|
|
229
|
+
* and warn.
|
|
230
|
+
*/
|
|
231
|
+
export async function fetchUsdRates(
|
|
232
|
+
rateSource: RateSourceConfig,
|
|
233
|
+
currencies: string[],
|
|
234
|
+
signal: AbortSignal | undefined,
|
|
235
|
+
fetchImpl: typeof fetch = fetch,
|
|
236
|
+
): Promise<RateFetchResult> {
|
|
237
|
+
const codes = [...new Set(currencies.map((code) => code.toUpperCase()))];
|
|
238
|
+
const errors: RateFetchError[] = [];
|
|
239
|
+
if (rateSource.type === "frankfurter") {
|
|
240
|
+
const settled = await Promise.allSettled(
|
|
241
|
+
codes.map((code) =>
|
|
242
|
+
fetchFrankfurterUsdRate(
|
|
243
|
+
code,
|
|
244
|
+
rateSource.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
245
|
+
signal,
|
|
246
|
+
fetchImpl,
|
|
247
|
+
),
|
|
248
|
+
),
|
|
249
|
+
);
|
|
250
|
+
const rates = new Map<string, number>();
|
|
251
|
+
settled.forEach((outcome, index) => {
|
|
252
|
+
const code = codes[index];
|
|
253
|
+
if (outcome.status === "fulfilled") {
|
|
254
|
+
rates.set(code, outcome.value);
|
|
255
|
+
} else {
|
|
256
|
+
errors.push({
|
|
257
|
+
currency: code,
|
|
258
|
+
message:
|
|
259
|
+
outcome.reason instanceof Error
|
|
260
|
+
? outcome.reason.message
|
|
261
|
+
: String(outcome.reason),
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
return { rates, errors };
|
|
266
|
+
}
|
|
267
|
+
const parsed = await fetchBocTable(
|
|
268
|
+
rateSource.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
|
269
|
+
signal,
|
|
270
|
+
fetchImpl,
|
|
271
|
+
);
|
|
272
|
+
const rates = new Map<string, number>();
|
|
273
|
+
for (const code of codes) {
|
|
274
|
+
const rate = bocUsdPerUnit(parsed, code);
|
|
275
|
+
if (rate === undefined) {
|
|
276
|
+
errors.push({
|
|
277
|
+
currency: code,
|
|
278
|
+
message: `No 中行折算价 row found for ${code} in the Bank of China table`,
|
|
279
|
+
});
|
|
280
|
+
} else {
|
|
281
|
+
rates.set(code, rate);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return { rates, errors };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* True when a currency entry has a usable positive configured rate.
|
|
289
|
+
* Conversion never happens without one. There is no fallback/current split:
|
|
290
|
+
* the single `usdRate` is both what the user sets and what a fetch replaces.
|
|
291
|
+
*/
|
|
292
|
+
export function hasValidUsdRate(
|
|
293
|
+
entry: CurrencyRateConfig | undefined,
|
|
294
|
+
): boolean {
|
|
295
|
+
return (
|
|
296
|
+
entry !== undefined &&
|
|
297
|
+
typeof entry.usdRate === "number" &&
|
|
298
|
+
Number.isFinite(entry.usdRate) &&
|
|
299
|
+
entry.usdRate > 0
|
|
300
|
+
);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Pick the configured rate to convert with (the single `usdRate`). */
|
|
304
|
+
export function selectUsdRate(
|
|
305
|
+
entry: CurrencyRateConfig | undefined,
|
|
306
|
+
): number | undefined {
|
|
307
|
+
if (
|
|
308
|
+
entry &&
|
|
309
|
+
typeof entry.usdRate === "number" &&
|
|
310
|
+
Number.isFinite(entry.usdRate) &&
|
|
311
|
+
entry.usdRate > 0
|
|
312
|
+
) {
|
|
313
|
+
return entry.usdRate;
|
|
314
|
+
}
|
|
315
|
+
return undefined;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** Human-readable description of the configured rate source. */
|
|
319
|
+
export function rateSourceDescription(rateSource: RateSourceConfig): string {
|
|
320
|
+
if (rateSource.type === "boc") {
|
|
321
|
+
return `Bank of China spot-rate table (${BOC_PAGE_URL})`;
|
|
322
|
+
}
|
|
323
|
+
return `Frankfurter currency converter (${FRANKFURTER_BASE_URL}?base=<CURRENCY>&symbols=USD)`;
|
|
324
|
+
}
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
|
|
4
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
5
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Read a raw config JSON file. Returns undefined when the file does not
|
|
10
|
+
* exist; throws when it exists but is not valid JSON (so callers never
|
|
11
|
+
* silently clobber a corrupt user config).
|
|
12
|
+
*/
|
|
13
|
+
export async function readRawConfig(
|
|
14
|
+
path: string,
|
|
15
|
+
): Promise<Record<string, unknown> | undefined> {
|
|
16
|
+
let text: string;
|
|
17
|
+
try {
|
|
18
|
+
text = await readFile(path, "utf8");
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
const parsed: unknown = JSON.parse(text) as unknown;
|
|
24
|
+
return isRecord(parsed) ? parsed : undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Write a config JSON file atomically: write to a sibling temp file, then
|
|
29
|
+
* rename over the target. A failed write leaves the previous file intact and
|
|
30
|
+
* cleans up the temp file.
|
|
31
|
+
*/
|
|
32
|
+
export async function writeConfigAtomic(
|
|
33
|
+
path: string,
|
|
34
|
+
raw: Record<string, unknown>,
|
|
35
|
+
): Promise<void> {
|
|
36
|
+
const tmpPath = `${path}.tmp-${process.pid}-${Date.now()}`;
|
|
37
|
+
await mkdir(dirname(path), { recursive: true });
|
|
38
|
+
try {
|
|
39
|
+
await writeFile(tmpPath, `${JSON.stringify(raw, null, 2)}\n`, "utf8");
|
|
40
|
+
await rename(tmpPath, path);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
await unlink(tmpPath).catch(() => undefined);
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Serialize config writes so concurrent refreshes cannot interleave and
|
|
48
|
+
// corrupt the file (last writer wins, but every write is complete).
|
|
49
|
+
let writeQueue: Promise<unknown> = Promise.resolve();
|
|
50
|
+
|
|
51
|
+
function enqueueWrite<T>(task: () => Promise<T>): Promise<T> {
|
|
52
|
+
const run = writeQueue.then(task, task);
|
|
53
|
+
writeQueue = run.catch(() => undefined);
|
|
54
|
+
return run;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface CurrencyUpdate {
|
|
58
|
+
/** USD per one unit of the currency; replaces the stored `usdRate`. */
|
|
59
|
+
usdRate: number;
|
|
60
|
+
updatedAt: number;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Merge a currency update into the config file at `path`, preserving all
|
|
65
|
+
* unknown root fields, other currency entries, and unknown fields inside the
|
|
66
|
+
* updated currency entry. Returns the updated root object.
|
|
67
|
+
*/
|
|
68
|
+
export async function updateWritableConfig(
|
|
69
|
+
path: string,
|
|
70
|
+
currency: string,
|
|
71
|
+
update: CurrencyUpdate,
|
|
72
|
+
): Promise<Record<string, unknown>> {
|
|
73
|
+
return enqueueWrite(async () => {
|
|
74
|
+
const existing = (await readRawConfig(path)) ?? {};
|
|
75
|
+
const currencies = isRecord(existing.currencies) ? existing.currencies : {};
|
|
76
|
+
const entry = isRecord(currencies[currency]) ? currencies[currency] : {};
|
|
77
|
+
const nextRoot: Record<string, unknown> = {
|
|
78
|
+
...existing,
|
|
79
|
+
currencies: {
|
|
80
|
+
...currencies,
|
|
81
|
+
[currency]: { ...entry, ...update },
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
await writeConfigAtomic(path, nextRoot);
|
|
85
|
+
return nextRoot;
|
|
86
|
+
});
|
|
87
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import type { MessageEndEvent } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { CurrencyCostConfig, ProviderCurrencyConfig } from "./config";
|
|
3
|
+
import { USD_CODE } from "./config";
|
|
4
|
+
import { hasValidUsdRate, selectUsdRate } from "./rates";
|
|
5
|
+
|
|
6
|
+
const COST_COMPONENTS = ["input", "output", "cacheRead", "cacheWrite"] as const;
|
|
7
|
+
|
|
8
|
+
export type ConversionWarn = (message: string) => void;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Resolve the source currency for a provider/model pair: the per-model
|
|
12
|
+
* override wins over the provider-level currency; providers that are not
|
|
13
|
+
* mapped at all yield undefined (never converted). Only own keys are read,
|
|
14
|
+
* so inherited prototype entries can never act as providers or models.
|
|
15
|
+
*/
|
|
16
|
+
export function selectCurrency(
|
|
17
|
+
providers: Record<string, ProviderCurrencyConfig>,
|
|
18
|
+
provider: string,
|
|
19
|
+
model: string,
|
|
20
|
+
): string | undefined {
|
|
21
|
+
if (!Object.hasOwn(providers, provider)) return undefined;
|
|
22
|
+
const providerConfig = providers[provider];
|
|
23
|
+
if (!providerConfig) return undefined;
|
|
24
|
+
if (providerConfig.models) {
|
|
25
|
+
if (Object.hasOwn(providerConfig.models, model)) {
|
|
26
|
+
const modelOverride = providerConfig.models[model];
|
|
27
|
+
if (modelOverride?.currency) {
|
|
28
|
+
return modelOverride.currency;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return providerConfig.currency;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Convert an assistant message's `usage.cost` fields from the configured
|
|
37
|
+
* source currency to USD. Returns a replacement message (same role, same
|
|
38
|
+
* shape) when a conversion applies, or undefined when the message is not
|
|
39
|
+
* covered by the config (unmapped/untouched providers, USD, missing rates).
|
|
40
|
+
*
|
|
41
|
+
* Only the five `usage.cost` fields are touched; the rest of the message and
|
|
42
|
+
* usage objects are preserved by reference. `total` is recomputed as the sum
|
|
43
|
+
* of the converted components, which is how Pi itself derives `cost.total`.
|
|
44
|
+
*/
|
|
45
|
+
export function convertUsageCost(
|
|
46
|
+
message: MessageEndEvent["message"],
|
|
47
|
+
config: CurrencyCostConfig,
|
|
48
|
+
warn: ConversionWarn | undefined = undefined,
|
|
49
|
+
): MessageEndEvent["message"] | undefined {
|
|
50
|
+
if (message?.role !== "assistant") return undefined;
|
|
51
|
+
const cost = message.usage?.cost;
|
|
52
|
+
if (!cost || typeof cost !== "object" || Array.isArray(cost)) {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
const provider = String(message.provider ?? "");
|
|
56
|
+
const model = message.responseModel ?? message.model;
|
|
57
|
+
const currency = selectCurrency(config.providers, provider, model);
|
|
58
|
+
if (!currency || currency === USD_CODE) return undefined;
|
|
59
|
+
|
|
60
|
+
if (!Object.hasOwn(config.currencies, currency)) {
|
|
61
|
+
warn?.(
|
|
62
|
+
`pi-currency-cost: no currency rate entry for ${currency} (provider "${provider}"${model ? `, model "${model}"` : ""}); usage left in ${currency}`,
|
|
63
|
+
);
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
const entry = config.currencies[currency];
|
|
67
|
+
// The single configured `usdRate` must be a positive finite number.
|
|
68
|
+
// Without one conversion stays off so the rate is always traceable to
|
|
69
|
+
// user configuration.
|
|
70
|
+
if (!hasValidUsdRate(entry)) {
|
|
71
|
+
warn?.(
|
|
72
|
+
`pi-currency-cost: no positive usdRate for ${currency} (provider "${provider}"${model ? `, model "${model}"` : ""}); set one in config; usage left in ${currency}`,
|
|
73
|
+
);
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
const rate = selectUsdRate(entry);
|
|
77
|
+
if (!rate) {
|
|
78
|
+
warn?.(
|
|
79
|
+
`pi-currency-cost: no usable USD rate for ${currency} (provider "${provider}"${model ? `, model "${model}"` : ""}); set one in config; usage left in ${currency}`,
|
|
80
|
+
);
|
|
81
|
+
return undefined;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const nextCost = { ...cost };
|
|
85
|
+
let allComponents = true;
|
|
86
|
+
for (const key of COST_COMPONENTS) {
|
|
87
|
+
const value = cost[key];
|
|
88
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
89
|
+
nextCost[key] = value * rate;
|
|
90
|
+
} else {
|
|
91
|
+
allComponents = false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (allComponents) {
|
|
95
|
+
nextCost.total =
|
|
96
|
+
nextCost.input +
|
|
97
|
+
nextCost.output +
|
|
98
|
+
nextCost.cacheRead +
|
|
99
|
+
nextCost.cacheWrite;
|
|
100
|
+
} else if (typeof cost.total === "number" && Number.isFinite(cost.total)) {
|
|
101
|
+
nextCost.total = cost.total * rate;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return {
|
|
105
|
+
...message,
|
|
106
|
+
usage: {
|
|
107
|
+
...message.usage,
|
|
108
|
+
cost: nextCost,
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
}
|