@brglng/pi-currency-cost 0.1.2 → 0.2.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/README.md CHANGED
@@ -15,7 +15,60 @@ pi install npm:@brglng/pi-currency-cost
15
15
 
16
16
  ## Configuration
17
17
 
18
- The extension reads two optional JSON files and merges them, with the project
18
+ ### Rates in Pi's settings.json
19
+
20
+ Add the `pi-currency-cost` namespace to Pi's global `<agentDir>/settings.json`
21
+ (default: `~/.pi/agent/settings.json`). Use strict JSON (no comments or
22
+ trailing commas). The extension ignores this namespace in project settings
23
+ and in `models.json`.
24
+
25
+ ```json
26
+ {
27
+ "pi-currency-cost": {
28
+ "currencies": {
29
+ "CNY": { "usdRate": 0.147 }
30
+ },
31
+ "currencyExchangeRateSource": { "type": "frankfurter" }
32
+ }
33
+ }
34
+ ```
35
+
36
+ Valid rates and rate-source settings here take precedence over the merged
37
+ legacy configuration.
38
+
39
+ ### Provider and model currencies in Pi's models.json
40
+
41
+ Declare `currency` beside the provider or model definition in Pi's global
42
+ `<agentDir>/models.json`. Merge these fields into your existing configuration;
43
+ this excerpt omits the other fields Pi needs for custom models.
44
+
45
+ ```json
46
+ {
47
+ "providers": {
48
+ "bailian": {
49
+ "currency": "CNY",
50
+ "models": [
51
+ { "id": "custom-usd-model", "currency": "USD" }
52
+ ]
53
+ },
54
+ "openrouter": {
55
+ "modelOverrides": {
56
+ "some-model-id": { "currency": "CNY" }
57
+ }
58
+ }
59
+ }
60
+ }
61
+ ```
62
+
63
+ Currency precedence is **inline model → inline provider → legacy model →
64
+ legacy provider**. Within an inline provider, a valid `modelOverrides`
65
+ currency wins over a `models` entry with the same ID. Use `USD` to leave a
66
+ model's costs unchanged. Missing or invalid inline values fall back to the
67
+ next applicable setting.
68
+
69
+ ### Legacy configuration files
70
+
71
+ The extension also reads two optional JSON files and merges them, with the project
19
72
  file taking precedence over the global file:
20
73
 
21
74
  - Global: `~/.pi/agent/extensions/pi-currency-cost/config.json`
@@ -132,6 +185,11 @@ configured non-USD currency and saves it back to the same `usdRate` field, so
132
185
  conversion always uses the most recent rate the extension can obtain. You can
133
186
  also trigger this manually at any time with `/currency-cost refresh`.
134
187
 
188
+ If the effective `usdRate` came from global `settings.json`, updates go back to
189
+ that entry without rewriting unrelated settings. Other rates
190
+ are saved to the legacy project file if it exists, or the legacy global file
191
+ otherwise.
192
+
135
193
  ## Network and fallback
136
194
 
137
195
  Rate fetches require network access, which cannot be guaranteed in every
package/README.zh.md CHANGED
@@ -14,7 +14,56 @@ pi install npm:@brglng/pi-currency-cost
14
14
 
15
15
  ## 配置
16
16
 
17
- 扩展读取两份可选的 JSON 配置文件并把它们合并,其中项目配置优先于全局配置:
17
+ ### 在 Pi 的 settings.json 中配置汇率
18
+
19
+ 将 `pi-currency-cost` 命名空间添加到 Pi 的全局 `<agentDir>/settings.json`
20
+ (默认为 `~/.pi/agent/settings.json`)。请使用严格的 JSON,不要添加注释或
21
+ 尾随逗号。扩展会忽略项目设置和 `models.json` 中的此命名空间。
22
+
23
+ ```json
24
+ {
25
+ "pi-currency-cost": {
26
+ "currencies": {
27
+ "CNY": { "usdRate": 0.147 }
28
+ },
29
+ "currencyExchangeRateSource": { "type": "frankfurter" }
30
+ }
31
+ }
32
+ ```
33
+
34
+ 此处有效的汇率及汇率来源设置优先于合并后的旧版配置。
35
+
36
+ ### 在 Pi 的 models.json 中声明 Provider 和模型的币种
37
+
38
+ 在 Pi 的全局 `<agentDir>/models.json` 中,将 `currency` 写在对应的 Provider
39
+ 或模型定义中。请将以下字段合并到现有配置中;示例省略了 Pi 为自定义模型
40
+ 所需的其他字段。
41
+
42
+ ```json
43
+ {
44
+ "providers": {
45
+ "bailian": {
46
+ "currency": "CNY",
47
+ "models": [
48
+ { "id": "custom-usd-model", "currency": "USD" }
49
+ ]
50
+ },
51
+ "openrouter": {
52
+ "modelOverrides": {
53
+ "some-model-id": { "currency": "CNY" }
54
+ }
55
+ }
56
+ }
57
+ }
58
+ ```
59
+
60
+ 币种优先级为**内联模型 → 内联 Provider → 旧版模型 → 旧版 Provider**。
61
+ 对同一模型 ID,`modelOverrides` 中有效的币种优先于 `models` 中的币种。
62
+ 使用 `USD` 可让模型费用保持原样。内联值缺失或无效时,使用下一级适用设置。
63
+
64
+ ### 旧版配置文件
65
+
66
+ 扩展仍读取两份可选的 JSON 配置文件并把它们合并,其中项目配置优先于全局配置:
18
67
 
19
68
  - 全局:`~/.pi/agent/extensions/pi-currency-cost/config.json`
20
69
  - 项目:`<cwd>/.pi/extensions/pi-currency-cost/config.json`
@@ -123,6 +172,9 @@ Pi 报告该 Provider 用量费用所用的币种,也可以在此基础上叠
123
172
  `usdRate` 字段,这样换算始终使用扩展能取得的最新汇率。你也可以随时用
124
173
  `/currency-cost refresh` 手动触发。
125
174
 
175
+ 如果生效的 `usdRate` 来自全局 `settings.json`,更新会写回该条目,不改动其他设置。
176
+ 其他汇率仍写入旧版配置:有项目配置文件时写入该文件,否则写入全局配置文件。
177
+
126
178
  ## 网络与回退
127
179
 
128
180
  取汇率需要网络访问,而网络访问无法保证在所有环境中都可用。如果汇率来源
package/dist/public.d.ts CHANGED
@@ -63,12 +63,7 @@ declare function normalizeConfig(raw: unknown, base?: CurrencyCostConfig): {
63
63
  config: CurrencyCostConfig;
64
64
  warnings: ConfigWarnings;
65
65
  };
66
- /**
67
- * Load and merge the global config (`<agentDir>/extensions/pi-currency-cost/config.json`)
68
- * and the project config (`<cwd>/.pi/extensions/pi-currency-cost/config.json`).
69
- * Project values override global values; currency entries and provider
70
- * mappings are merged per field/key.
71
- */
66
+ /** Load the effective config without exposing internal rate write locations. */
72
67
  declare function loadConfig(agentDir: string, cwd: string): Promise<{
73
68
  config: CurrencyCostConfig;
74
69
  warnings: ConfigWarnings;
@@ -193,11 +188,11 @@ interface Note {
193
188
  }
194
189
  declare class CurrencyCostRuntime {
195
190
  config: CurrencyCostConfig;
191
+ inlineRateKeys: ReadonlyMap<string, string>;
196
192
  readonly convertedMessages: WeakSet<object>;
197
193
  private readonly warned;
198
194
  private pendingNotes;
199
- /** Config load warnings (not yet reported over a session context). */
200
- constructor(config: CurrencyCostConfig);
195
+ constructor(config: CurrencyCostConfig, inlineRateKeys: ReadonlyMap<string, string>);
201
196
  enqueueNote(text: string, type: Note["type"]): void;
202
197
  /** Flush pending startup notes through the first session context. */
203
198
  flushNotes(ctx: ExtensionContext): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brglng/pi-currency-cost",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "Convert configured provider/model usage costs to USD for Pi sessions",
5
5
  "type": "module",
6
6
  "exports": {
@@ -18,6 +18,14 @@
18
18
  "README.zh.md",
19
19
  "LICENSE"
20
20
  ],
21
+ "scripts": {
22
+ "check": "tsc --noEmit",
23
+ "build:types": "rollup -c rollup.dts.config.mjs",
24
+ "prepack": "pnpm run build:types",
25
+ "test": "vitest run",
26
+ "lint:md": "rumdl check *.md",
27
+ "lint": "biome check . && pnpm run lint:md"
28
+ },
21
29
  "keywords": [
22
30
  "pi-package",
23
31
  "pi",
@@ -66,11 +74,7 @@
66
74
  "typescript": "^6.0.3",
67
75
  "vitest": "^4.1.8"
68
76
  },
69
- "scripts": {
70
- "check": "tsc --noEmit",
71
- "build:types": "rollup -c rollup.dts.config.mjs",
72
- "test": "vitest run",
73
- "lint:md": "rumdl check *.md",
74
- "lint": "biome check . && pnpm run lint:md"
77
+ "dependencies": {
78
+ "jsonc-parser": "^3.3.1"
75
79
  }
76
- }
80
+ }
package/src/config.ts CHANGED
@@ -1,5 +1,13 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
+ import { EXTENSION_ID } from "./config-paths";
4
+ import {
5
+ getModelsConfigPath,
6
+ isPositiveFinite,
7
+ isRecord,
8
+ readModelsConfig,
9
+ } from "./models-config";
10
+ import { readSettingsConfig } from "./settings-config";
3
11
 
4
12
  /**
5
13
  * One currency entry. `usdRate` is the sole conversion rate (USD per one
@@ -83,10 +91,6 @@ function isSafeConfigKey(key: string): boolean {
83
91
  return !UNSAFE_CONFIG_KEYS.has(key);
84
92
  }
85
93
 
86
- function isRecord(value: unknown): value is Record<string, unknown> {
87
- return typeof value === "object" && value !== null && !Array.isArray(value);
88
- }
89
-
90
94
  /** Uppercase a raw currency code and validate the normalized 3-letter form. */
91
95
  export function normalizeCurrencyCode(value: unknown): string | undefined {
92
96
  if (typeof value !== "string") return undefined;
@@ -94,14 +98,11 @@ export function normalizeCurrencyCode(value: unknown): string | undefined {
94
98
  return CURRENCY_CODE_RE.test(normalized) ? normalized : undefined;
95
99
  }
96
100
 
97
- function isPositiveFinite(value: unknown): value is number {
98
- return typeof value === "number" && Number.isFinite(value) && value > 0;
99
- }
100
-
101
101
  function applyTimeoutMs(
102
102
  raw: Record<string, unknown>,
103
103
  base: number | undefined,
104
104
  warnings: ConfigWarnings,
105
+ sourceLabel = "rateSource",
105
106
  ): number | undefined {
106
107
  const value = raw.timeoutMs;
107
108
  if (value === undefined) return base;
@@ -111,7 +112,7 @@ function applyTimeoutMs(
111
112
  Math.max(MIN_TIMEOUT_MS, Math.trunc(value)),
112
113
  );
113
114
  }
114
- warnings.push("rateSource.timeoutMs must be a positive number; ignoring");
115
+ warnings.push(`${sourceLabel}.timeoutMs must be a positive number; ignoring`);
115
116
  return base;
116
117
  }
117
118
 
@@ -395,24 +396,159 @@ async function readJson(path: string): Promise<unknown> {
395
396
  }
396
397
  }
397
398
 
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([
399
+ /** Never include raw model-file values or keys in configuration warnings. */
400
+ function inlineCurrency(value: unknown, warnings: ConfigWarnings) {
401
+ if (value === undefined) return undefined;
402
+ const code = normalizeCurrencyCode(value);
403
+ if (!code)
404
+ warnings.push("models.json: currency must be a 3-letter code; ignoring");
405
+ return code;
406
+ }
407
+
408
+ function applyInlineProviders(
409
+ raw: unknown,
410
+ providers: CurrencyCostConfig["providers"],
411
+ warnings: ConfigWarnings,
412
+ ): void {
413
+ if (!isRecord(raw)) return;
414
+ for (const [id, provider] of Object.entries(raw)) {
415
+ if (!id.trim() || !isSafeConfigKey(id) || !isRecord(provider)) continue;
416
+ const currency = inlineCurrency(provider.currency, warnings);
417
+ const models: Record<string, ProviderModelCurrency> = {};
418
+ const addModel = (modelId: unknown, value: unknown) => {
419
+ if (
420
+ typeof modelId !== "string" ||
421
+ !modelId.trim() ||
422
+ !isSafeConfigKey(modelId)
423
+ )
424
+ return;
425
+ const code = inlineCurrency(value, warnings);
426
+ if (code) models[modelId] = { currency: code };
427
+ };
428
+
429
+ if (Array.isArray(provider.models)) {
430
+ for (const model of provider.models) {
431
+ if (isRecord(model)) addModel(model.id, model.currency);
432
+ }
433
+ }
434
+ if (isRecord(provider.modelOverrides)) {
435
+ for (const [modelId, override] of Object.entries(
436
+ provider.modelOverrides,
437
+ )) {
438
+ if (isRecord(override)) addModel(modelId, override.currency);
439
+ }
440
+ }
441
+
442
+ const legacy = Object.hasOwn(providers, id) ? providers[id] : undefined;
443
+ if (currency) {
444
+ // An inline provider default wins even over legacy model mappings.
445
+ providers[id] = { currency, models };
446
+ } else if (Object.keys(models).length > 0) {
447
+ providers[id] = { ...legacy, models: { ...legacy?.models, ...models } };
448
+ }
449
+ }
450
+ }
451
+
452
+ export async function loadConfigWithSources(agentDir: string, cwd: string) {
453
+ const inlineWarnings: ConfigWarnings = [];
454
+ const [globalRaw, projectRaw, models, settingsRaw] = await Promise.all([
409
455
  readJson(join(agentDir, "extensions", "pi-currency-cost", "config.json")),
410
456
  readJson(join(cwd, ".pi", "extensions", "pi-currency-cost", "config.json")),
457
+ readModelsConfig(getModelsConfigPath(agentDir)).catch(() => {
458
+ inlineWarnings.push(
459
+ "Could not read a valid models.json; ignoring provider/model currency declarations",
460
+ );
461
+ return undefined;
462
+ }),
463
+ readSettingsConfig(agentDir).catch(() => {
464
+ inlineWarnings.push(
465
+ "Could not read a valid settings.json; ignoring pi-currency-cost settings",
466
+ );
467
+ return undefined;
468
+ }),
411
469
  ]);
412
470
  const global = normalizeConfig(globalRaw);
413
- const project = normalizeConfig(projectRaw, global.config);
471
+ const { config, warnings: projectWarnings } = normalizeConfig(
472
+ projectRaw,
473
+ global.config,
474
+ );
475
+ const inlineRateKeys = new Map<string, string>();
476
+ const settings = settingsRaw?.[EXTENSION_ID];
477
+
478
+ if (isRecord(settings)) {
479
+ if (isRecord(settings.currencies)) {
480
+ for (const [key, value] of Object.entries(settings.currencies)) {
481
+ const code = normalizeCurrencyCode(key);
482
+ if (!code || !isRecord(value) || !isPositiveFinite(value.usdRate)) {
483
+ inlineWarnings.push(
484
+ "settings.json: inline currency rates require a 3-letter code and positive usdRate; ignoring entry",
485
+ );
486
+ continue;
487
+ }
488
+ const warnings: ConfigWarnings = [];
489
+ const entry = normalizeCurrencyEntry(value, undefined, warnings);
490
+ inlineWarnings.push(
491
+ ...warnings.map((warning) => `settings.json: ${warning}`),
492
+ );
493
+ config.currencies[code] = entry;
494
+ inlineRateKeys.set(code, key);
495
+ }
496
+ } else if (settings.currencies !== undefined) {
497
+ inlineWarnings.push(
498
+ "settings.json: currencies must be an object; ignoring",
499
+ );
500
+ }
501
+
502
+ const source = settings.currencyExchangeRateSource;
503
+ if (isRecord(source)) {
504
+ const type = source.type;
505
+ if (type !== undefined && type !== "boc" && type !== "frankfurter") {
506
+ inlineWarnings.push(
507
+ 'settings.json: currencyExchangeRateSource.type must be "boc" or "frankfurter"; keeping previous',
508
+ );
509
+ }
510
+ config.rateSource = {
511
+ type:
512
+ type === "boc" || type === "frankfurter"
513
+ ? type
514
+ : config.rateSource.type,
515
+ timeoutMs: applyTimeoutMs(
516
+ source,
517
+ config.rateSource.timeoutMs,
518
+ inlineWarnings,
519
+ "settings.json: currencyExchangeRateSource",
520
+ ),
521
+ };
522
+ } else if (source === "boc" || source === "frankfurter") {
523
+ config.rateSource = { ...config.rateSource, type: source };
524
+ } else if (source !== undefined) {
525
+ inlineWarnings.push(
526
+ "settings.json: invalid currencyExchangeRateSource; keeping previous",
527
+ );
528
+ }
529
+ } else if (settings !== undefined) {
530
+ inlineWarnings.push(
531
+ "settings.json: pi-currency-cost must be an object; ignoring",
532
+ );
533
+ }
534
+
535
+ applyInlineProviders(models?.providers, config.providers, inlineWarnings);
414
536
  return {
415
- config: project.config,
416
- warnings: [...global.warnings, ...project.warnings],
537
+ config,
538
+ warnings: [
539
+ ...global.warnings,
540
+ ...projectWarnings,
541
+ ...new Set(inlineWarnings),
542
+ ],
543
+ inlineRateKeys,
417
544
  };
418
545
  }
546
+
547
+ /** Load the effective config without exposing internal rate write locations. */
548
+ export async function loadConfig(
549
+ agentDir: string,
550
+ cwd: string,
551
+ ): Promise<{ config: CurrencyCostConfig; warnings: ConfigWarnings }> {
552
+ const { config, warnings } = await loadConfigWithSources(agentDir, cwd);
553
+ return { config, warnings };
554
+ }
package/src/index.ts CHANGED
@@ -7,14 +7,14 @@ import { getAgentDir } from "@earendil-works/pi-coding-agent";
7
7
  import {
8
8
  type ConfigWarnings,
9
9
  type CurrencyCostConfig,
10
- type CurrencyRateConfig,
11
- loadConfig,
10
+ loadConfigWithSources,
12
11
  } from "./config";
13
12
  import {
14
13
  getGlobalConfigPath,
15
14
  getProjectConfigPath,
16
15
  getWritableConfigPath,
17
16
  } from "./config-paths";
17
+ import { getModelsConfigPath } from "./models-config";
18
18
  import {
19
19
  fetchUsdRates,
20
20
  hasValidUsdRate,
@@ -22,7 +22,8 @@ import {
22
22
  rateSourceDescription,
23
23
  selectUsdRate,
24
24
  } from "./rates";
25
- import { updateWritableConfig } from "./store";
25
+ import { getSettingsConfigPath } from "./settings-config";
26
+ import { updateInlineRate, updateWritableConfig } from "./store";
26
27
  import { convertUsageCost } from "./usage-cost";
27
28
 
28
29
  const COMMAND_NAME = "currency-cost";
@@ -51,8 +52,10 @@ class CurrencyCostRuntime {
51
52
  readonly convertedMessages = new WeakSet<object>();
52
53
  private readonly warned = new Set<string>();
53
54
  private pendingNotes: Note[] = [];
54
- /** Config load warnings (not yet reported over a session context). */
55
- constructor(public config: CurrencyCostConfig) {}
55
+ constructor(
56
+ public config: CurrencyCostConfig,
57
+ public inlineRateKeys: ReadonlyMap<string, string>,
58
+ ) {}
56
59
 
57
60
  enqueueNote(text: string, type: Note["type"]): void {
58
61
  this.pendingNotes.push({ text, type });
@@ -108,7 +111,7 @@ class CurrencyCostRuntime {
108
111
  }
109
112
  const note = await this.persistFetchedRates(agentDir, cwd, result);
110
113
  if (result.errors.length > 0) {
111
- this.enqueueNote(note, "warning");
114
+ this.enqueueNote(note, "info");
112
115
  }
113
116
  }
114
117
 
@@ -180,14 +183,25 @@ class CurrencyCostRuntime {
180
183
  cwd: string,
181
184
  result: RateFetchResult,
182
185
  ): Promise<string> {
183
- const writable = await getWritableConfigPath(agentDir, cwd);
186
+ let writable: string | undefined;
184
187
  const updatedAt = Date.now();
188
+ const persisted = new Map<string, number>();
185
189
  for (const [code, rate] of result.rates) {
186
190
  try {
187
- await updateWritableConfig(writable, code, {
188
- usdRate: rate,
189
- updatedAt,
190
- });
191
+ const inlineKey = this.inlineRateKeys.get(code);
192
+ const update = { usdRate: rate, updatedAt };
193
+ if (inlineKey !== undefined) {
194
+ await updateInlineRate(
195
+ getSettingsConfigPath(agentDir),
196
+ code,
197
+ inlineKey,
198
+ update,
199
+ );
200
+ } else {
201
+ writable ??= await getWritableConfigPath(agentDir, cwd);
202
+ await updateWritableConfig(writable, code, update);
203
+ }
204
+ persisted.set(code, rate);
191
205
  this.config.currencies[code] = {
192
206
  ...this.config.currencies[code],
193
207
  usdRate: rate,
@@ -203,7 +217,7 @@ class CurrencyCostRuntime {
203
217
  const lines = [
204
218
  `pi-currency-cost: updated USD rates (source: ${rateSourceDescription(this.config.rateSource)})`,
205
219
  ];
206
- for (const [code, rate] of result.rates) {
220
+ for (const [code, rate] of persisted) {
207
221
  lines.push(` ${code}: 1 ${code} = ${rate.toFixed(6)} USD`);
208
222
  }
209
223
  if (result.errors.length > 0) {
@@ -232,9 +246,11 @@ class CurrencyCostRuntime {
232
246
  const lines = [
233
247
  `pi-currency-cost status`,
234
248
  ``,
249
+ `Pi settings : ${getSettingsConfigPath(agentDir)}`,
250
+ `Pi models : ${getModelsConfigPath(agentDir)}`,
235
251
  `Global config : ${getGlobalConfigPath(agentDir)}`,
236
252
  `Project config: ${getProjectConfigPath(cwd)}`,
237
- `Writable path : ${await getWritableConfigPath(agentDir, cwd)}`,
253
+ `Legacy writable path: ${await getWritableConfigPath(agentDir, cwd)}`,
238
254
  `Rate source : ${rateSourceDescription(this.config.rateSource)}`,
239
255
  ``,
240
256
  ];
@@ -307,13 +323,13 @@ export async function createCurrencyCostExtension(
307
323
 
308
324
  // Load config before registering any hooks/commands so startup never
309
325
  // 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);
326
+ const loaded = await loadConfigWithSources(agentDir, cwd);
327
+ let warnings = loaded.warnings;
328
+ const runtime = new CurrencyCostRuntime(loaded.config, loaded.inlineRateKeys);
313
329
 
314
330
  let startupFetchDone = false;
315
331
  pi.on("session_start", async (_event, ctx) => {
316
- for (const note of describeConfigWarnings(state.warnings)) {
332
+ for (const note of describeConfigWarnings(warnings)) {
317
333
  runtime.enqueueNote(note.text, note.type);
318
334
  }
319
335
  runtime.flushNotes(ctx);
@@ -381,10 +397,10 @@ export async function createCurrencyCostExtension(
381
397
  return {
382
398
  runtime,
383
399
  reload: async () => {
384
- const reloaded = await loadConfig(agentDir, cwd);
385
- state.config = reloaded.config;
386
- state.warnings = reloaded.warnings;
400
+ const reloaded = await loadConfigWithSources(agentDir, cwd);
401
+ warnings = reloaded.warnings;
387
402
  runtime.config = reloaded.config;
403
+ runtime.inlineRateKeys = reloaded.inlineRateKeys;
388
404
  },
389
405
  };
390
406
  }
@@ -0,0 +1,44 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { type ParseError, parseTree, stripComments } from "jsonc-parser";
4
+
5
+ export function getModelsConfigPath(agentDir: string): string {
6
+ return join(agentDir, "models.json");
7
+ }
8
+
9
+ export function isRecord(value: unknown): value is Record<string, unknown> {
10
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11
+ }
12
+
13
+ export function isPositiveFinite(value: unknown): value is number {
14
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
15
+ }
16
+
17
+ export function parseModelsConfig(text: string): Record<string, unknown> {
18
+ const source = text.replace(/^\uFEFF/, "");
19
+ const errors: ParseError[] = [];
20
+ const tree = parseTree(source, errors, { allowTrailingComma: true });
21
+ if (errors.length > 0 || tree?.type !== "object") {
22
+ throw new Error("models.json must contain a valid JSON object");
23
+ }
24
+ // Match Pi's support for trailing commas without touching string literals.
25
+ // Use JSON.parse for data so object keys such as __proto__ stay own keys.
26
+ const json = stripComments(source, " ").replace(
27
+ /"(?:\\.|[^"\\])*"|,(\s*[}\]])/g,
28
+ (match, tail: string | undefined) => tail ?? match,
29
+ );
30
+ return JSON.parse(json) as Record<string, unknown>;
31
+ }
32
+
33
+ export async function readModelsConfig(
34
+ path: string,
35
+ ): Promise<Record<string, unknown> | undefined> {
36
+ let text: string;
37
+ try {
38
+ text = await readFile(path, "utf8");
39
+ } catch (error) {
40
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
41
+ throw error;
42
+ }
43
+ return parseModelsConfig(text);
44
+ }
@@ -0,0 +1,28 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { isRecord } from "./models-config";
4
+
5
+ export function getSettingsConfigPath(agentDir: string): string {
6
+ return join(agentDir, "settings.json");
7
+ }
8
+
9
+ export function parseSettingsConfig(text: string): Record<string, unknown> {
10
+ // Pi settings use JSON.parse, unlike models.json. Current Pi also strips a BOM.
11
+ const raw: unknown = JSON.parse(text.replace(/^\uFEFF/, ""));
12
+ if (!isRecord(raw))
13
+ throw new Error("settings.json must contain a JSON object");
14
+ return raw;
15
+ }
16
+
17
+ export async function readSettingsConfig(
18
+ agentDir: string,
19
+ ): Promise<Record<string, unknown> | undefined> {
20
+ try {
21
+ return parseSettingsConfig(
22
+ await readFile(getSettingsConfigPath(agentDir), "utf8"),
23
+ );
24
+ } catch (error) {
25
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
26
+ throw error;
27
+ }
28
+ }
package/src/store.ts CHANGED
@@ -1,9 +1,22 @@
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
- }
1
+ import {
2
+ chmod,
3
+ mkdir,
4
+ mkdtemp,
5
+ readFile,
6
+ realpath,
7
+ rename,
8
+ rm,
9
+ rmdir,
10
+ stat,
11
+ unlink,
12
+ writeFile,
13
+ } from "node:fs/promises";
14
+ import { dirname, join } from "node:path";
15
+ import { applyEdits, modify, type Node, parseTree } from "jsonc-parser";
16
+ import { normalizeCurrencyCode } from "./config";
17
+ import { EXTENSION_ID } from "./config-paths";
18
+ import { isPositiveFinite, isRecord } from "./models-config";
19
+ import { parseSettingsConfig } from "./settings-config";
7
20
 
8
21
  /**
9
22
  * Read a raw config JSON file. Returns undefined when the file does not
@@ -85,3 +98,106 @@ export async function updateWritableConfig(
85
98
  return nextRoot;
86
99
  });
87
100
  }
101
+
102
+ // Match JSON.parse's last-wins semantics for duplicate properties.
103
+ function propertyValue(node: Node | undefined, key: string): Node | undefined {
104
+ return node?.children?.findLast(
105
+ (child) => child.type === "property" && child.children?.[0]?.value === key,
106
+ )?.children?.[1];
107
+ }
108
+
109
+ /** Update only an existing, effective inline rate. Never create settings.json. */
110
+ export async function updateInlineRate(
111
+ path: string,
112
+ code: string,
113
+ key: string,
114
+ update: CurrencyUpdate,
115
+ ): Promise<void> {
116
+ return enqueueWrite(async () => {
117
+ const lock = `${path}.lock`;
118
+ try {
119
+ // Pi uses a sibling lock directory at the configured (unresolved) path.
120
+ // If another writer holds it, leave the configured rate in effect.
121
+ await mkdir(lock);
122
+ } catch {
123
+ throw new Error("Could not lock settings.json to update inline rate");
124
+ }
125
+ try {
126
+ const target = await realpath(path);
127
+ const info = await stat(target);
128
+ if (!info.isFile()) throw new Error();
129
+ const text = await readFile(target, "utf8");
130
+ const raw = parseSettingsConfig(text);
131
+ const settings = raw[EXTENSION_ID];
132
+ const currencies = isRecord(settings) ? settings.currencies : undefined;
133
+ if (!isRecord(currencies)) throw new Error();
134
+ const effective = Object.entries(currencies).findLast(
135
+ ([name, entry]) =>
136
+ normalizeCurrencyCode(name) === code &&
137
+ isRecord(entry) &&
138
+ isPositiveFinite(entry.usdRate),
139
+ );
140
+ if (effective?.[0] !== key) throw new Error();
141
+
142
+ const bomLength = text.startsWith("\uFEFF") ? 1 : 0;
143
+ const source = text.slice(bomLength);
144
+ const tree = parseTree(source);
145
+ const entry = propertyValue(
146
+ propertyValue(propertyValue(tree, EXTENSION_ID), "currencies"),
147
+ key,
148
+ );
149
+ const rate = propertyValue(entry, "usdRate");
150
+ if (!entry || !rate) throw new Error();
151
+ const timestamp = propertyValue(entry, "updatedAt");
152
+ const entryText = source.slice(entry.offset, entry.offset + entry.length);
153
+ const edits = [
154
+ {
155
+ offset: rate.offset - entry.offset,
156
+ length: rate.length,
157
+ content: JSON.stringify(update.usdRate),
158
+ },
159
+ ...(timestamp
160
+ ? [
161
+ {
162
+ offset: timestamp.offset - entry.offset,
163
+ length: timestamp.length,
164
+ content: JSON.stringify(update.updatedAt),
165
+ },
166
+ ]
167
+ : modify(entryText, ["updatedAt"], update.updatedAt, {})),
168
+ ];
169
+ const edited =
170
+ text.slice(0, bomLength + entry.offset) +
171
+ applyEdits(entryText, edits) +
172
+ source.slice(entry.offset + entry.length);
173
+ parseSettingsConfig(edited);
174
+
175
+ // Stage privately: settings.json may contain sensitive data. Apply the
176
+ // original mode before replacing the file, without changing symlinks.
177
+ const directory = await mkdtemp(
178
+ join(dirname(target), ".pi-currency-cost-"),
179
+ );
180
+ try {
181
+ const tmp = join(directory, "settings.json");
182
+ await writeFile(tmp, edited, { mode: 0o600 });
183
+ await chmod(tmp, info.mode & 0o777);
184
+ if (
185
+ (await realpath(path)) !== target ||
186
+ (await readFile(target, "utf8")) !== text
187
+ ) {
188
+ throw new Error();
189
+ }
190
+ await rename(tmp, target);
191
+ } finally {
192
+ await rm(directory, { recursive: true, force: true }).catch(
193
+ () => undefined,
194
+ );
195
+ }
196
+ } catch {
197
+ // Parse and filesystem errors may contain sensitive text or paths.
198
+ throw new Error("Could not safely update inline rate in settings.json");
199
+ } finally {
200
+ await rmdir(lock).catch(() => undefined);
201
+ }
202
+ });
203
+ }