@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.
@@ -0,0 +1,105 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "Pi currency-cost configuration",
4
+ "description": "Convert configured provider/model usage costs to USD for Pi sessions.",
5
+ "type": "object",
6
+ "additionalProperties": true,
7
+ "properties": {
8
+ "currencies": {
9
+ "type": "object",
10
+ "description": "USD rates keyed by 3-letter currency code.",
11
+ "propertyNames": {
12
+ "pattern": "^[A-Z]{3}$"
13
+ },
14
+ "additionalProperties": {
15
+ "type": "object",
16
+ "additionalProperties": true,
17
+ "properties": {
18
+ "usdRate": {
19
+ "type": "number",
20
+ "exclusiveMinimum": 0,
21
+ "description": "USD per one unit of the currency. Required for every configured non-USD currency; a fetched rate replaces it."
22
+ },
23
+ "updatedAt": {
24
+ "type": "number",
25
+ "description": "Epoch milliseconds when usdRate was last set or fetched."
26
+ }
27
+ }
28
+ }
29
+ },
30
+ "providers": {
31
+ "type": "object",
32
+ "description": "Provider IDs to convert. Providers not listed here are never converted.",
33
+ "propertyNames": {
34
+ "not": {
35
+ "pattern": "^(?:__proto__|constructor|prototype)$"
36
+ }
37
+ },
38
+ "additionalProperties": {
39
+ "type": "object",
40
+ "additionalProperties": true,
41
+ "properties": {
42
+ "currency": {
43
+ "type": "string",
44
+ "pattern": "^[A-Z]{3}$",
45
+ "description": "Currency Pi-reported usage costs are denominated in for this provider."
46
+ },
47
+ "models": {
48
+ "type": "object",
49
+ "description": "Exact per-model currency overrides; a model override wins over the provider currency.",
50
+ "propertyNames": {
51
+ "not": {
52
+ "pattern": "^(?:__proto__|constructor|prototype)$"
53
+ }
54
+ },
55
+ "additionalProperties": {
56
+ "type": "object",
57
+ "additionalProperties": true,
58
+ "properties": {
59
+ "currency": {
60
+ "type": "string",
61
+ "pattern": "^[A-Z]{3}$"
62
+ }
63
+ }
64
+ }
65
+ }
66
+ }
67
+ }
68
+ },
69
+ "rateSource": {
70
+ "description": "Source of current USD rates. Defaults to the fixed Frankfurter currency converter endpoint.",
71
+ "oneOf": [
72
+ {
73
+ "type": "string",
74
+ "enum": ["boc", "frankfurter"]
75
+ },
76
+ {
77
+ "type": "object",
78
+ "properties": {
79
+ "type": {
80
+ "const": "boc"
81
+ },
82
+ "timeoutMs": {
83
+ "type": "number",
84
+ "minimum": 1000,
85
+ "maximum": 60000
86
+ }
87
+ }
88
+ },
89
+ {
90
+ "type": "object",
91
+ "properties": {
92
+ "type": {
93
+ "const": "frankfurter"
94
+ },
95
+ "timeoutMs": {
96
+ "type": "number",
97
+ "minimum": 1000,
98
+ "maximum": 60000
99
+ }
100
+ }
101
+ }
102
+ ]
103
+ }
104
+ }
105
+ }
@@ -0,0 +1,44 @@
1
+ import { access } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+
4
+ // Extension ID, used to namespace the extension's config directory under
5
+ // `<agentDir>/extensions/`.
6
+ export const EXTENSION_ID = "pi-currency-cost";
7
+
8
+ /** Global config directory: `<agentDir>/extensions/pi-currency-cost/`. */
9
+ export function getGlobalConfigDir(agentDir: string): string {
10
+ return join(agentDir, "extensions", EXTENSION_ID);
11
+ }
12
+
13
+ /** Global config file: `<agentDir>/extensions/pi-currency-cost/config.json`. */
14
+ export function getGlobalConfigPath(agentDir: string): string {
15
+ return join(getGlobalConfigDir(agentDir), "config.json");
16
+ }
17
+
18
+ /** Project config file: `<cwd>/.pi/extensions/pi-currency-cost/config.json`. */
19
+ export function getProjectConfigPath(cwd: string): string {
20
+ return join(cwd, ".pi", "extensions", EXTENSION_ID, "config.json");
21
+ }
22
+
23
+ /**
24
+ * The config file the extension writes to. The project config is the writable
25
+ * effective config when a project config file exists; otherwise the global
26
+ * config path is used. Only an absent project config (ENOENT) redirects to
27
+ * the global scope: permission or other access failures throw so writes can
28
+ * never silently land in another scope.
29
+ */
30
+ export async function getWritableConfigPath(
31
+ agentDir: string,
32
+ cwd: string,
33
+ ): Promise<string> {
34
+ const project = getProjectConfigPath(cwd);
35
+ try {
36
+ await access(project);
37
+ return project;
38
+ } catch (error) {
39
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
40
+ return getGlobalConfigPath(agentDir);
41
+ }
42
+ throw error;
43
+ }
44
+ }
package/src/config.ts ADDED
@@ -0,0 +1,418 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+
4
+ /**
5
+ * One currency entry. `usdRate` is the sole conversion rate (USD per one
6
+ * unit of this currency), required for every configured non-USD currency.
7
+ * It is configured by the user and replaced in place (along with
8
+ * `updatedAt`) when a fresh rate is fetched.
9
+ */
10
+ export interface CurrencyRateConfig {
11
+ /** USD per one unit of this currency. Required for every configured non-USD currency. */
12
+ usdRate: number;
13
+ /** Epoch milliseconds when `usdRate` was last set or fetched. */
14
+ updatedAt?: number;
15
+ }
16
+
17
+ /** Per-model currency override inside a provider mapping. */
18
+ export interface ProviderModelCurrency {
19
+ currency?: string;
20
+ }
21
+
22
+ /**
23
+ * Provider mapping: the currency Pi-reported usage costs are denominated in.
24
+ * A per-model override wins over the provider-level currency.
25
+ */
26
+ export interface ProviderCurrencyConfig {
27
+ currency?: string;
28
+ models?: Record<string, ProviderModelCurrency>;
29
+ }
30
+
31
+ /** Bank of China official spot-rate table (mainland-China reachable). */
32
+ export interface BocRateSourceConfig {
33
+ type: "boc";
34
+ timeoutMs?: number;
35
+ }
36
+
37
+ /**
38
+ * Fixed Frankfurter currency converter endpoint: this extension reads
39
+ * `rates.USD` for `base=<CURRENCY>&symbols=USD` (USD per one source unit).
40
+ * The source is built in and cannot be redirected; only the timeout is
41
+ * configurable.
42
+ */
43
+ export interface FrankfurterRateSourceConfig {
44
+ type: "frankfurter";
45
+ timeoutMs?: number;
46
+ }
47
+
48
+ export type RateSourceConfig =
49
+ | BocRateSourceConfig
50
+ | FrankfurterRateSourceConfig;
51
+
52
+ export interface CurrencyCostConfig {
53
+ /** Rates keyed by normalized 3-letter currency code. */
54
+ currencies: Record<string, CurrencyRateConfig>;
55
+ /** Provider → currency mapping. Providers not listed here are never converted. */
56
+ providers: Record<string, ProviderCurrencyConfig>;
57
+ rateSource: RateSourceConfig;
58
+ }
59
+
60
+ export const DEFAULT_CONFIG: CurrencyCostConfig = {
61
+ currencies: {},
62
+ providers: {},
63
+ rateSource: { type: "frankfurter" },
64
+ };
65
+
66
+ export type ConfigWarnings = string[];
67
+
68
+ export const DEFAULT_TIMEOUT_MS = 8000;
69
+ export const MIN_TIMEOUT_MS = 1000;
70
+ export const MAX_TIMEOUT_MS = 60000;
71
+ export const USD_CODE = "USD";
72
+
73
+ const CURRENCY_CODE_RE = /^[A-Z]{3}$/;
74
+
75
+ /**
76
+ * Object keys that must never be used as config map keys (currency codes,
77
+ * provider IDs, model IDs). Assigning or reading them on a normal object
78
+ * can set or inherit from the prototype chain.
79
+ */
80
+ const UNSAFE_CONFIG_KEYS = new Set(["__proto__", "constructor", "prototype"]);
81
+
82
+ function isSafeConfigKey(key: string): boolean {
83
+ return !UNSAFE_CONFIG_KEYS.has(key);
84
+ }
85
+
86
+ function isRecord(value: unknown): value is Record<string, unknown> {
87
+ return typeof value === "object" && value !== null && !Array.isArray(value);
88
+ }
89
+
90
+ /** Uppercase a raw currency code and validate the normalized 3-letter form. */
91
+ export function normalizeCurrencyCode(value: unknown): string | undefined {
92
+ if (typeof value !== "string") return undefined;
93
+ const normalized = value.trim().toUpperCase();
94
+ return CURRENCY_CODE_RE.test(normalized) ? normalized : undefined;
95
+ }
96
+
97
+ function isPositiveFinite(value: unknown): value is number {
98
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
99
+ }
100
+
101
+ function applyTimeoutMs(
102
+ raw: Record<string, unknown>,
103
+ base: number | undefined,
104
+ warnings: ConfigWarnings,
105
+ ): number | undefined {
106
+ const value = raw.timeoutMs;
107
+ if (value === undefined) return base;
108
+ if (isPositiveFinite(value)) {
109
+ return Math.min(
110
+ MAX_TIMEOUT_MS,
111
+ Math.max(MIN_TIMEOUT_MS, Math.trunc(value)),
112
+ );
113
+ }
114
+ warnings.push("rateSource.timeoutMs must be a positive number; ignoring");
115
+ return base;
116
+ }
117
+
118
+ /**
119
+ * Derive the single `usdRate` from a raw currency entry. There is no
120
+ * separate fallback/current rate: only `usdRate` is honored. A positive
121
+ * finite number is returned, or undefined when the entry carries no usable
122
+ * rate (a newer config with only a legacy field no longer migrates).
123
+ */
124
+ function pickUsdRate(
125
+ raw: Record<string, unknown>,
126
+ warnings: ConfigWarnings,
127
+ ): number | undefined {
128
+ if (raw.usdRate !== undefined) {
129
+ if (isPositiveFinite(raw.usdRate)) {
130
+ return raw.usdRate;
131
+ }
132
+ warnings.push("usdRate must be a positive number; ignoring");
133
+ return undefined;
134
+ }
135
+ return undefined;
136
+ }
137
+
138
+ function normalizeCurrencyEntry(
139
+ raw: unknown,
140
+ base: CurrencyRateConfig | undefined,
141
+ warnings: ConfigWarnings,
142
+ ): CurrencyRateConfig {
143
+ const entry: CurrencyRateConfig = base ? { ...base } : { usdRate: NaN };
144
+ if (!isRecord(raw)) {
145
+ warnings.push("currency entries must be objects; ignoring entry");
146
+ return entry;
147
+ }
148
+ const usdRate = pickUsdRate(raw, warnings);
149
+ if (usdRate !== undefined) {
150
+ entry.usdRate = usdRate;
151
+ }
152
+ if (raw.updatedAt !== undefined) {
153
+ if (typeof raw.updatedAt === "number" && Number.isFinite(raw.updatedAt)) {
154
+ entry.updatedAt = raw.updatedAt;
155
+ } else {
156
+ warnings.push("updatedAt must be a finite number; ignoring");
157
+ }
158
+ }
159
+ return entry;
160
+ }
161
+
162
+ function normalizeCurrencies(
163
+ raw: unknown,
164
+ base: Record<string, CurrencyRateConfig>,
165
+ warnings: ConfigWarnings,
166
+ ): Record<string, CurrencyRateConfig> {
167
+ if (raw === undefined || raw === null) return { ...base };
168
+ if (!isRecord(raw)) {
169
+ warnings.push("currencies must be an object of currency codes; ignoring");
170
+ return { ...base };
171
+ }
172
+ const result: Record<string, CurrencyRateConfig> = { ...base };
173
+ for (const [rawKey, value] of Object.entries(raw)) {
174
+ const code = normalizeCurrencyCode(rawKey);
175
+ if (!code) {
176
+ warnings.push(
177
+ `currency key "${rawKey}" is not a 3-letter code; ignoring`,
178
+ );
179
+ continue;
180
+ }
181
+ result[code] = normalizeCurrencyEntry(value, result[code], warnings);
182
+ if (!isPositiveFinite(result[code].usdRate) && code !== USD_CODE) {
183
+ warnings.push(
184
+ `currency ${code}: a positive usdRate is required; conversions for ${code} will be skipped until one is set`,
185
+ );
186
+ }
187
+ }
188
+ return result;
189
+ }
190
+
191
+ function normalizeProviderEntry(
192
+ raw: unknown,
193
+ base: ProviderCurrencyConfig | undefined,
194
+ warnings: ConfigWarnings,
195
+ ): ProviderCurrencyConfig {
196
+ const entry: ProviderCurrencyConfig = base ? { ...base } : {};
197
+ if (!isRecord(raw)) {
198
+ warnings.push("provider entries must be objects; ignoring entry");
199
+ return entry;
200
+ }
201
+ if (raw.currency !== undefined) {
202
+ const code = normalizeCurrencyCode(raw.currency);
203
+ if (code) {
204
+ entry.currency = code;
205
+ } else {
206
+ warnings.push("provider currency must be a 3-letter code; ignoring");
207
+ }
208
+ }
209
+ if (raw.models !== undefined) {
210
+ if (isRecord(raw.models)) {
211
+ const models: Record<string, ProviderModelCurrency> = {
212
+ ...(entry.models ?? {}),
213
+ };
214
+ for (const [modelId, modelRaw] of Object.entries(raw.models)) {
215
+ if (!isSafeConfigKey(modelId)) {
216
+ warnings.push(
217
+ `model "${modelId}" ID is a reserved object key; ignoring`,
218
+ );
219
+ continue;
220
+ }
221
+ if (!isRecord(modelRaw)) {
222
+ warnings.push(
223
+ `model "${modelId}" override must be an object; ignoring`,
224
+ );
225
+ continue;
226
+ }
227
+ const merged = { ...(models[modelId] ?? {}) };
228
+ if (modelRaw.currency !== undefined) {
229
+ const code = normalizeCurrencyCode(modelRaw.currency);
230
+ if (code) {
231
+ merged.currency = code;
232
+ } else {
233
+ warnings.push(
234
+ `model "${modelId}" currency must be a 3-letter code; ignoring`,
235
+ );
236
+ }
237
+ }
238
+ models[modelId] = merged;
239
+ }
240
+ entry.models = models;
241
+ } else {
242
+ warnings.push("provider models must be an object of model IDs; ignoring");
243
+ }
244
+ }
245
+ return entry;
246
+ }
247
+
248
+ function normalizeProviders(
249
+ raw: unknown,
250
+ base: Record<string, ProviderCurrencyConfig>,
251
+ warnings: ConfigWarnings,
252
+ ): Record<string, ProviderCurrencyConfig> {
253
+ if (raw === undefined || raw === null) return { ...base };
254
+ if (!isRecord(raw)) {
255
+ warnings.push("providers must be an object of provider IDs; ignoring");
256
+ return { ...base };
257
+ }
258
+ const result: Record<string, ProviderCurrencyConfig> = { ...base };
259
+ for (const [providerId, value] of Object.entries(raw)) {
260
+ if (providerId.trim() === "") {
261
+ warnings.push("provider IDs must be non-empty strings; ignoring");
262
+ continue;
263
+ }
264
+ if (!isSafeConfigKey(providerId)) {
265
+ warnings.push(
266
+ `provider ID "${providerId}" is a reserved object key; ignoring`,
267
+ );
268
+ continue;
269
+ }
270
+ const entry = normalizeProviderEntry(value, result[providerId], warnings);
271
+ if (entry.currency === undefined && !entry.models) {
272
+ warnings.push(
273
+ `provider "${providerId}": configure a currency or a models map; ignoring`,
274
+ );
275
+ continue;
276
+ }
277
+ result[providerId] = entry;
278
+ }
279
+ return result;
280
+ }
281
+
282
+ function normalizeRateSource(
283
+ raw: unknown,
284
+ base: RateSourceConfig,
285
+ warnings: ConfigWarnings,
286
+ ): RateSourceConfig {
287
+ if (raw === undefined || raw === null) return base;
288
+ if (raw === "boc") return { ...base, type: "boc" };
289
+ if (raw === "frankfurter") return { ...base, type: "frankfurter" };
290
+ if (!isRecord(raw)) {
291
+ warnings.push(
292
+ 'rateSource must be "boc", "frankfurter", or an object with a "type"; keeping previous',
293
+ );
294
+ return base;
295
+ }
296
+ if (raw.type === "boc") {
297
+ return {
298
+ type: "boc",
299
+ timeoutMs: applyTimeoutMs(
300
+ raw,
301
+ base.type === "boc" ? base.timeoutMs : undefined,
302
+ warnings,
303
+ ),
304
+ };
305
+ }
306
+ if (raw.type === "frankfurter") {
307
+ return {
308
+ type: "frankfurter",
309
+ timeoutMs: applyTimeoutMs(
310
+ raw,
311
+ base.type === "frankfurter" ? base.timeoutMs : undefined,
312
+ warnings,
313
+ ),
314
+ };
315
+ }
316
+ if (raw.type === "json") {
317
+ // Custom JSON endpoints were removed; a legacy "json" source warns and
318
+ // falls back to the built-in Frankfurter source.
319
+ warnings.push(
320
+ 'rateSource.type "json" is no longer supported (custom JSON endpoints were removed); using "frankfurter"',
321
+ );
322
+ return {
323
+ type: "frankfurter",
324
+ timeoutMs: applyTimeoutMs(
325
+ raw,
326
+ base.type === "frankfurter" ? base.timeoutMs : undefined,
327
+ warnings,
328
+ ),
329
+ };
330
+ }
331
+ warnings.push(
332
+ 'rateSource.type must be "boc" or "frankfurter"; keeping previous',
333
+ );
334
+ return base;
335
+ }
336
+
337
+ /**
338
+ * Normalize one raw config object (global or project) onto a base config.
339
+ * Project currency/provider entries merge field-by-field over the global base,
340
+ * so a project may refine a global currency entry without repeating it.
341
+ * Invalid values are skipped and reported as warnings.
342
+ */
343
+ export function normalizeConfig(
344
+ raw: unknown,
345
+ base: CurrencyCostConfig = DEFAULT_CONFIG,
346
+ ): { config: CurrencyCostConfig; warnings: ConfigWarnings } {
347
+ const warnings: ConfigWarnings = [];
348
+ if (raw === undefined || raw === null) {
349
+ return { config: cloneConfig(base), warnings };
350
+ }
351
+ if (!isRecord(raw)) {
352
+ warnings.push("config must be a JSON object; ignoring");
353
+ return { config: cloneConfig(base), warnings };
354
+ }
355
+ const config: CurrencyCostConfig = {
356
+ currencies: normalizeCurrencies(raw.currencies, base.currencies, warnings),
357
+ providers: normalizeProviders(raw.providers, base.providers, warnings),
358
+ rateSource: normalizeRateSource(raw.rateSource, base.rateSource, warnings),
359
+ };
360
+ return { config, warnings };
361
+ }
362
+
363
+ function cloneConfig(config: CurrencyCostConfig): CurrencyCostConfig {
364
+ const currencies: Record<string, CurrencyRateConfig> = {};
365
+ for (const [code, entry] of Object.entries(config.currencies)) {
366
+ currencies[code] = { ...entry };
367
+ }
368
+ const providers: Record<string, ProviderCurrencyConfig> = {};
369
+ for (const [id, entry] of Object.entries(config.providers)) {
370
+ providers[id] = {
371
+ ...entry,
372
+ models: entry.models
373
+ ? Object.fromEntries(
374
+ Object.entries(entry.models).map(([model, override]) => [
375
+ model,
376
+ { ...override },
377
+ ]),
378
+ )
379
+ : undefined,
380
+ };
381
+ }
382
+ return {
383
+ currencies,
384
+ providers,
385
+ rateSource: { ...config.rateSource },
386
+ };
387
+ }
388
+
389
+ async function readJson(path: string): Promise<unknown> {
390
+ try {
391
+ return JSON.parse(await readFile(path, "utf8")) as unknown;
392
+ } catch (error) {
393
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
394
+ throw error;
395
+ }
396
+ }
397
+
398
+ /**
399
+ * Load and merge the global config (`<agentDir>/extensions/pi-currency-cost/config.json`)
400
+ * and the project config (`<cwd>/.pi/extensions/pi-currency-cost/config.json`).
401
+ * Project values override global values; currency entries and provider
402
+ * mappings are merged per field/key.
403
+ */
404
+ export async function loadConfig(
405
+ agentDir: string,
406
+ cwd: string,
407
+ ): Promise<{ config: CurrencyCostConfig; warnings: ConfigWarnings }> {
408
+ const [globalRaw, projectRaw] = await Promise.all([
409
+ readJson(join(agentDir, "extensions", "pi-currency-cost", "config.json")),
410
+ readJson(join(cwd, ".pi", "extensions", "pi-currency-cost", "config.json")),
411
+ ]);
412
+ const global = normalizeConfig(globalRaw);
413
+ const project = normalizeConfig(projectRaw, global.config);
414
+ return {
415
+ config: project.config,
416
+ warnings: [...global.warnings, ...project.warnings],
417
+ };
418
+ }