@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/index.ts
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ExtensionAPI,
|
|
3
|
+
ExtensionCommandContext,
|
|
4
|
+
ExtensionContext,
|
|
5
|
+
} from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import {
|
|
8
|
+
type ConfigWarnings,
|
|
9
|
+
type CurrencyCostConfig,
|
|
10
|
+
type CurrencyRateConfig,
|
|
11
|
+
loadConfig,
|
|
12
|
+
} from "./config";
|
|
13
|
+
import {
|
|
14
|
+
getGlobalConfigPath,
|
|
15
|
+
getProjectConfigPath,
|
|
16
|
+
getWritableConfigPath,
|
|
17
|
+
} from "./config-paths";
|
|
18
|
+
import {
|
|
19
|
+
fetchUsdRates,
|
|
20
|
+
hasValidUsdRate,
|
|
21
|
+
type RateFetchResult,
|
|
22
|
+
rateSourceDescription,
|
|
23
|
+
selectUsdRate,
|
|
24
|
+
} from "./rates";
|
|
25
|
+
import { updateWritableConfig } from "./store";
|
|
26
|
+
import { convertUsageCost } from "./usage-cost";
|
|
27
|
+
|
|
28
|
+
const COMMAND_NAME = "currency-cost";
|
|
29
|
+
|
|
30
|
+
/** Outer timeout for the whole start-of-session rate fetch. Per-source
|
|
31
|
+
* request timeouts already bound every request; this caps the complete
|
|
32
|
+
* fetch+persist so startup can never stall the session lifecycle. */
|
|
33
|
+
const STARTUP_FETCH_TIMEOUT_MS = 30_000;
|
|
34
|
+
|
|
35
|
+
function usageText(): string {
|
|
36
|
+
return [
|
|
37
|
+
"Usage: /currency-cost <subcommand>",
|
|
38
|
+
"",
|
|
39
|
+
" status Show config paths, currency rates, and provider mappings",
|
|
40
|
+
" refresh Fetch current USD rates for all configured currencies",
|
|
41
|
+
" help Show this help",
|
|
42
|
+
].join("\n");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
interface Note {
|
|
46
|
+
text: string;
|
|
47
|
+
type: "info" | "warning";
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
class CurrencyCostRuntime {
|
|
51
|
+
readonly convertedMessages = new WeakSet<object>();
|
|
52
|
+
private readonly warned = new Set<string>();
|
|
53
|
+
private pendingNotes: Note[] = [];
|
|
54
|
+
/** Config load warnings (not yet reported over a session context). */
|
|
55
|
+
constructor(public config: CurrencyCostConfig) {}
|
|
56
|
+
|
|
57
|
+
enqueueNote(text: string, type: Note["type"]): void {
|
|
58
|
+
this.pendingNotes.push({ text, type });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Flush pending startup notes through the first session context. */
|
|
62
|
+
flushNotes(ctx: ExtensionContext): void {
|
|
63
|
+
for (const note of this.pendingNotes) {
|
|
64
|
+
ctx.ui.notify(note.text, note.type);
|
|
65
|
+
}
|
|
66
|
+
this.pendingNotes = [];
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
warnOnce(ctx: ExtensionContext, key: string, text: string): void {
|
|
70
|
+
if (this.warned.has(key)) return;
|
|
71
|
+
this.warned.add(key);
|
|
72
|
+
ctx.ui.notify(text, "warning");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Fetch a fresh rate for every configured non-USD currency that has a
|
|
77
|
+
* valid `usdRate`, persist each result back to that same field, and update
|
|
78
|
+
* the in-memory config. Per-currency failures keep the configured `usdRate`
|
|
79
|
+
* (selection uses it unchanged) and are reported; a source-level failure is
|
|
80
|
+
* reported as a warning and never crashes startup. `signal` bounds the
|
|
81
|
+
* whole fetch.
|
|
82
|
+
*/
|
|
83
|
+
async refreshConfiguredRates(
|
|
84
|
+
agentDir: string,
|
|
85
|
+
cwd: string,
|
|
86
|
+
signal: AbortSignal | undefined,
|
|
87
|
+
fetchImpl: typeof fetch = fetch,
|
|
88
|
+
): Promise<void> {
|
|
89
|
+
const configured = Object.entries(this.config.currencies)
|
|
90
|
+
.filter(([code, entry]) => code !== "USD" && hasValidUsdRate(entry))
|
|
91
|
+
.map(([code]) => code);
|
|
92
|
+
if (configured.length === 0) return;
|
|
93
|
+
|
|
94
|
+
let result: RateFetchResult;
|
|
95
|
+
try {
|
|
96
|
+
result = await fetchUsdRates(
|
|
97
|
+
this.config.rateSource,
|
|
98
|
+
configured,
|
|
99
|
+
signal,
|
|
100
|
+
fetchImpl,
|
|
101
|
+
);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
this.enqueueNote(
|
|
104
|
+
`pi-currency-cost: could not fetch fresh rates (${error instanceof Error ? error.message : String(error)}). Keeping the configured usdRate values.`,
|
|
105
|
+
"warning",
|
|
106
|
+
);
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
const note = await this.persistFetchedRates(agentDir, cwd, result);
|
|
110
|
+
if (result.errors.length > 0) {
|
|
111
|
+
this.enqueueNote(note, "warning");
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Start-of-session fetch of missing current rates, awaited inside
|
|
117
|
+
* `session_start` so its notes are flushed in that lifecycle and the
|
|
118
|
+
* persisted rates update the in-memory config before any message_end.
|
|
119
|
+
* Every failure is caught and reported; startup can never crash here.
|
|
120
|
+
*/
|
|
121
|
+
async startupFetch(
|
|
122
|
+
agentDir: string,
|
|
123
|
+
cwd: string,
|
|
124
|
+
fetchImpl: typeof fetch,
|
|
125
|
+
timeoutSignal: AbortSignal,
|
|
126
|
+
): Promise<void> {
|
|
127
|
+
try {
|
|
128
|
+
await this.refreshConfiguredRates(
|
|
129
|
+
agentDir,
|
|
130
|
+
cwd,
|
|
131
|
+
timeoutSignal,
|
|
132
|
+
fetchImpl,
|
|
133
|
+
);
|
|
134
|
+
} catch (error) {
|
|
135
|
+
this.enqueueNote(
|
|
136
|
+
`pi-currency-cost: unexpected startup rate-fetch error (${error instanceof Error ? error.message : String(error)}); keeping the configured usdRate values.`,
|
|
137
|
+
"warning",
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Refresh every configured non-USD currency and persist fresh rates. */
|
|
143
|
+
async refreshRates(
|
|
144
|
+
agentDir: string,
|
|
145
|
+
cwd: string,
|
|
146
|
+
ctx: ExtensionCommandContext,
|
|
147
|
+
fetchImpl: typeof fetch = fetch,
|
|
148
|
+
): Promise<void> {
|
|
149
|
+
const codes = Object.keys(this.config.currencies).filter(
|
|
150
|
+
(code) => code !== "USD",
|
|
151
|
+
);
|
|
152
|
+
if (codes.length === 0) {
|
|
153
|
+
ctx.ui.notify(
|
|
154
|
+
"pi-currency-cost: no non-USD currencies configured; nothing to refresh.",
|
|
155
|
+
"info",
|
|
156
|
+
);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
let result: RateFetchResult;
|
|
160
|
+
try {
|
|
161
|
+
result = await fetchUsdRates(
|
|
162
|
+
this.config.rateSource,
|
|
163
|
+
codes,
|
|
164
|
+
ctx.signal,
|
|
165
|
+
fetchImpl,
|
|
166
|
+
);
|
|
167
|
+
} catch (error) {
|
|
168
|
+
ctx.ui.notify(
|
|
169
|
+
`pi-currency-cost: refresh failed (${error instanceof Error ? error.message : String(error)}). Configured usdRate values are unchanged.`,
|
|
170
|
+
"error",
|
|
171
|
+
);
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
const note = await this.persistFetchedRates(agentDir, cwd, result);
|
|
175
|
+
ctx.ui.notify(note, result.errors.length > 0 ? "warning" : "info");
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
private async persistFetchedRates(
|
|
179
|
+
agentDir: string,
|
|
180
|
+
cwd: string,
|
|
181
|
+
result: RateFetchResult,
|
|
182
|
+
): Promise<string> {
|
|
183
|
+
const writable = await getWritableConfigPath(agentDir, cwd);
|
|
184
|
+
const updatedAt = Date.now();
|
|
185
|
+
for (const [code, rate] of result.rates) {
|
|
186
|
+
try {
|
|
187
|
+
await updateWritableConfig(writable, code, {
|
|
188
|
+
usdRate: rate,
|
|
189
|
+
updatedAt,
|
|
190
|
+
});
|
|
191
|
+
this.config.currencies[code] = {
|
|
192
|
+
...this.config.currencies[code],
|
|
193
|
+
usdRate: rate,
|
|
194
|
+
updatedAt,
|
|
195
|
+
};
|
|
196
|
+
} catch (error) {
|
|
197
|
+
result.errors.push({
|
|
198
|
+
currency: code,
|
|
199
|
+
message: `could not persist rate: ${error instanceof Error ? error.message : String(error)}`,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
const lines = [
|
|
204
|
+
`pi-currency-cost: updated USD rates (source: ${rateSourceDescription(this.config.rateSource)})`,
|
|
205
|
+
];
|
|
206
|
+
for (const [code, rate] of result.rates) {
|
|
207
|
+
lines.push(` ${code}: 1 ${code} = ${rate.toFixed(6)} USD`);
|
|
208
|
+
}
|
|
209
|
+
if (result.errors.length > 0) {
|
|
210
|
+
lines.push("");
|
|
211
|
+
lines.push(
|
|
212
|
+
`Keeping the configured usdRate for: ${result.errors.map((error) => error.currency).join(", ")}`,
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
return lines.join("\n");
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* `/currency-cost status`: show config paths, the rate source, the single
|
|
220
|
+
* configured `usdRate` per currency, and provider mappings.
|
|
221
|
+
*/
|
|
222
|
+
async statusCommand(
|
|
223
|
+
args: string[],
|
|
224
|
+
agentDir: string,
|
|
225
|
+
cwd: string,
|
|
226
|
+
ctx: ExtensionCommandContext,
|
|
227
|
+
): Promise<void> {
|
|
228
|
+
if (args.length > 1 && args[1] !== "help") {
|
|
229
|
+
ctx.ui.notify(usageText(), "info");
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const lines = [
|
|
233
|
+
`pi-currency-cost status`,
|
|
234
|
+
``,
|
|
235
|
+
`Global config : ${getGlobalConfigPath(agentDir)}`,
|
|
236
|
+
`Project config: ${getProjectConfigPath(cwd)}`,
|
|
237
|
+
`Writable path : ${await getWritableConfigPath(agentDir, cwd)}`,
|
|
238
|
+
`Rate source : ${rateSourceDescription(this.config.rateSource)}`,
|
|
239
|
+
``,
|
|
240
|
+
];
|
|
241
|
+
const currencies = Object.keys(this.config.currencies);
|
|
242
|
+
if (currencies.length === 0) {
|
|
243
|
+
lines.push("Currencies: none configured");
|
|
244
|
+
} else {
|
|
245
|
+
lines.push("Currencies:");
|
|
246
|
+
for (const code of currencies.sort()) {
|
|
247
|
+
const entry = this.config.currencies[code];
|
|
248
|
+
if (code === "USD") {
|
|
249
|
+
lines.push(` ${code}: USD is always 1 (no conversion)`);
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
const rate = selectUsdRate(entry);
|
|
253
|
+
lines.push(
|
|
254
|
+
` ${code}: ${rate === undefined ? "no rate" : `${rate} USD per unit`}${entry.updatedAt ? `, updated ${new Date(entry.updatedAt).toISOString()}` : ""}`,
|
|
255
|
+
);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
const providerIds = Object.keys(this.config.providers);
|
|
259
|
+
if (providerIds.length === 0) {
|
|
260
|
+
lines.push("Providers: none mapped (no conversions will happen)");
|
|
261
|
+
} else {
|
|
262
|
+
lines.push("Providers:");
|
|
263
|
+
for (const id of providerIds.sort()) {
|
|
264
|
+
const provider = this.config.providers[id];
|
|
265
|
+
const currency = provider.currency ?? "(none)";
|
|
266
|
+
const modelOverrides = Object.entries(provider.models ?? {})
|
|
267
|
+
.filter(([, override]) => override.currency)
|
|
268
|
+
.map(([model, override]) => `${model} → ${override.currency}`);
|
|
269
|
+
lines.push(
|
|
270
|
+
` ${id}: ${currency}${modelOverrides.length > 0 ? ` (${modelOverrides.join(", ")})` : ""}`,
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function describeConfigWarnings(warnings: ConfigWarnings): Note[] {
|
|
279
|
+
if (warnings.length === 0) return [];
|
|
280
|
+
return [
|
|
281
|
+
{
|
|
282
|
+
text: `pi-currency-cost configuration warnings:\n${warnings.map((warning) => `- ${warning}`).join("\n")}`,
|
|
283
|
+
type: "warning",
|
|
284
|
+
},
|
|
285
|
+
];
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* Build the extension runtime. Async: the merged global + project config
|
|
290
|
+
* is loaded before any handler is registered so message_end and the
|
|
291
|
+
* /currency-cost command always observe the effective config — startup never
|
|
292
|
+
* races with config loading.
|
|
293
|
+
*/
|
|
294
|
+
export async function createCurrencyCostExtension(
|
|
295
|
+
pi: ExtensionAPI,
|
|
296
|
+
options: {
|
|
297
|
+
agentDir?: string;
|
|
298
|
+
cwd?: string;
|
|
299
|
+
/** Skip the start-of-session rate fetch (used by tests). */
|
|
300
|
+
skipStartupFetch?: boolean;
|
|
301
|
+
fetchImpl?: typeof fetch;
|
|
302
|
+
} = {},
|
|
303
|
+
): Promise<{ runtime: CurrencyCostRuntime; reload: () => Promise<void> }> {
|
|
304
|
+
const agentDir = options.agentDir ?? getAgentDir();
|
|
305
|
+
const cwd = options.cwd ?? process.cwd();
|
|
306
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
307
|
+
|
|
308
|
+
// Load config before registering any hooks/commands so startup never
|
|
309
|
+
// races config loading against message_end handling.
|
|
310
|
+
const loaded = await loadConfig(agentDir, cwd);
|
|
311
|
+
const state = { config: loaded.config, warnings: loaded.warnings };
|
|
312
|
+
const runtime = new CurrencyCostRuntime(loaded.config);
|
|
313
|
+
|
|
314
|
+
let startupFetchDone = false;
|
|
315
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
316
|
+
for (const note of describeConfigWarnings(state.warnings)) {
|
|
317
|
+
runtime.enqueueNote(note.text, note.type);
|
|
318
|
+
}
|
|
319
|
+
runtime.flushNotes(ctx);
|
|
320
|
+
if (!options.skipStartupFetch && !startupFetchDone) {
|
|
321
|
+
startupFetchDone = true;
|
|
322
|
+
// Awaited inside session_start (pi awaits session_start handlers), so
|
|
323
|
+
// every warning is guaranteed to be flushed before the session banner
|
|
324
|
+
// finishes and the persisted rates update the in-memory config before
|
|
325
|
+
// any message_end. AbortSignal.timeout bounds the whole fetch and its
|
|
326
|
+
// timer auto-cleans (it never keeps the process alive).
|
|
327
|
+
await runtime.startupFetch(
|
|
328
|
+
agentDir,
|
|
329
|
+
cwd,
|
|
330
|
+
fetchImpl,
|
|
331
|
+
AbortSignal.timeout(STARTUP_FETCH_TIMEOUT_MS),
|
|
332
|
+
);
|
|
333
|
+
runtime.flushNotes(ctx);
|
|
334
|
+
}
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
pi.on("message_end", (event, ctx) => {
|
|
338
|
+
if (event.message.role !== "assistant") return undefined;
|
|
339
|
+
if (runtime.convertedMessages.has(event.message)) return undefined;
|
|
340
|
+
const replacement = convertUsageCost(
|
|
341
|
+
event.message,
|
|
342
|
+
runtime.config,
|
|
343
|
+
(text) => runtime.warnOnce(ctx, text, text),
|
|
344
|
+
);
|
|
345
|
+
if (!replacement) return undefined;
|
|
346
|
+
runtime.convertedMessages.add(event.message);
|
|
347
|
+
// Mark the replacement too so a re-emitted event for the same logical
|
|
348
|
+
// message cannot be converted twice within this runtime instance.
|
|
349
|
+
runtime.convertedMessages.add(replacement);
|
|
350
|
+
return { message: replacement };
|
|
351
|
+
});
|
|
352
|
+
|
|
353
|
+
pi.registerCommand(COMMAND_NAME, {
|
|
354
|
+
description:
|
|
355
|
+
"Convert configured provider/model usage costs to USD. Subcommands: status, refresh, help.",
|
|
356
|
+
getArgumentCompletions: (prefix) =>
|
|
357
|
+
["status", "refresh", "help"]
|
|
358
|
+
.filter((value) => value.startsWith(prefix))
|
|
359
|
+
.map((value) => ({ value, label: value })),
|
|
360
|
+
handler: async (args, ctx) => {
|
|
361
|
+
const [subcommand, ...rest] = args.trim().split(/\s+/);
|
|
362
|
+
const run = async (): Promise<void> => {
|
|
363
|
+
if (!subcommand || subcommand === "help") {
|
|
364
|
+
ctx.ui.notify(usageText(), "info");
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
if (subcommand === "status") {
|
|
368
|
+
await runtime.statusCommand(rest, agentDir, cwd, ctx);
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
if (subcommand === "refresh") {
|
|
372
|
+
await runtime.refreshRates(agentDir, cwd, ctx, fetchImpl);
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
ctx.ui.notify(usageText(), "warning");
|
|
376
|
+
};
|
|
377
|
+
await run();
|
|
378
|
+
},
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
return {
|
|
382
|
+
runtime,
|
|
383
|
+
reload: async () => {
|
|
384
|
+
const reloaded = await loadConfig(agentDir, cwd);
|
|
385
|
+
state.config = reloaded.config;
|
|
386
|
+
state.warnings = reloaded.warnings;
|
|
387
|
+
runtime.config = reloaded.config;
|
|
388
|
+
},
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* @brglng/pi-currency-cost extension factory.
|
|
394
|
+
* Loads global + project config, converts mapped provider/model usage costs
|
|
395
|
+
* to USD on every finalized assistant message, and registers the
|
|
396
|
+
* /currency-cost command.
|
|
397
|
+
*/
|
|
398
|
+
export default async function piCurrencyCostExtension(
|
|
399
|
+
pi: ExtensionAPI,
|
|
400
|
+
): Promise<void> {
|
|
401
|
+
await createCurrencyCostExtension(pi);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
export {
|
|
405
|
+
type BocRateSourceConfig,
|
|
406
|
+
type ConfigWarnings,
|
|
407
|
+
type CurrencyCostConfig,
|
|
408
|
+
type CurrencyRateConfig,
|
|
409
|
+
DEFAULT_CONFIG,
|
|
410
|
+
DEFAULT_TIMEOUT_MS,
|
|
411
|
+
loadConfig,
|
|
412
|
+
normalizeConfig,
|
|
413
|
+
normalizeCurrencyCode,
|
|
414
|
+
type ProviderCurrencyConfig,
|
|
415
|
+
type ProviderModelCurrency,
|
|
416
|
+
type RateSourceConfig,
|
|
417
|
+
USD_CODE,
|
|
418
|
+
} from "./config";
|
|
419
|
+
export {
|
|
420
|
+
EXTENSION_ID,
|
|
421
|
+
getGlobalConfigDir,
|
|
422
|
+
getGlobalConfigPath,
|
|
423
|
+
getProjectConfigPath,
|
|
424
|
+
getWritableConfigPath,
|
|
425
|
+
} from "./config-paths";
|
|
426
|
+
export {
|
|
427
|
+
BOC_CURRENCY_NAMES,
|
|
428
|
+
BOC_PAGE_URL,
|
|
429
|
+
bocUsdPerUnit,
|
|
430
|
+
fetchUsdRates,
|
|
431
|
+
hasValidUsdRate,
|
|
432
|
+
parseBocTable,
|
|
433
|
+
type RateFetchError,
|
|
434
|
+
type RateFetchResult,
|
|
435
|
+
rateSourceDescription,
|
|
436
|
+
readDotPath,
|
|
437
|
+
selectUsdRate,
|
|
438
|
+
} from "./rates";
|
|
439
|
+
export {
|
|
440
|
+
type CurrencyUpdate,
|
|
441
|
+
readRawConfig,
|
|
442
|
+
updateWritableConfig,
|
|
443
|
+
writeConfigAtomic,
|
|
444
|
+
} from "./store";
|
|
445
|
+
export {
|
|
446
|
+
type ConversionWarn,
|
|
447
|
+
convertUsageCost,
|
|
448
|
+
selectCurrency,
|
|
449
|
+
} from "./usage-cost";
|