pi-free 2.1.1 → 2.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/config.ts CHANGED
@@ -1,629 +1,644 @@
1
- /**
2
- * Shared config for pi-free-providers.
3
- *
4
- * Keys and flags are resolved in this order (first wins):
5
- * 1. Environment variable
6
- * 2. ~/.pi/free.json
7
- *
8
- * All exported values are getter functions so that runtime changes
9
- * (e.g. after toggle-{provider}) are visible immediately.
10
- */
11
-
12
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
13
- import { join } from "node:path";
14
- export {
15
- PROVIDER_CLINE,
16
- PROVIDER_KILO,
17
- PROVIDER_MODAL,
18
- PROVIDER_QWEN,
19
- PROVIDER_ROUTEWAY,
20
- PROVIDER_TOKENROUTER,
21
- } from "./constants.ts";
22
- import { createLogger } from "./lib/logger.ts";
23
- import { ensureDir, PI_DATA_DIR } from "./lib/paths.ts";
24
-
25
- /**
26
- * JSON.parse reviver that strips prototype-pollution payloads.
27
- */
28
- function safeJsonReviver(_key: string, value: unknown): unknown {
29
- if (_key === "__proto__" || _key === "constructor") {
30
- return undefined;
31
- }
32
- return value;
33
- }
34
-
35
- const _logger = createLogger("config");
36
-
37
- interface PiFreeConfig {
38
- nvidia_api_key?: string;
39
- ollama_api_key?: string;
40
- zenmux_api_key?: string;
41
- crofai_api_key?: string;
42
- codestral_api_key?: string;
43
- llm7_api_key?: string;
44
- deepinfra_api_key?: string;
45
- sambanova_api_key?: string;
46
- together_api_key?: string;
47
- novita_api_key?: string;
48
- routeway_api_key?: string;
49
- fastrouter_api_key?: string;
50
- tokenrouter_api_key?: string;
51
- kilo_free_only?: boolean;
52
- hidden_models?: string[];
53
- free_only?: boolean;
54
- kilo_show_paid?: boolean;
55
- ollama_show_paid?: boolean;
56
- cline_show_paid?: boolean;
57
- zenmux_show_paid?: boolean;
58
- crofai_show_paid?: boolean;
59
- codestral_show_paid?: boolean;
60
- llm7_show_paid?: boolean;
61
- deepinfra_show_paid?: boolean;
62
- sambanova_show_paid?: boolean;
63
- together_show_paid?: boolean;
64
- novita_show_paid?: boolean;
65
- routeway_show_paid?: boolean;
66
- fastrouter_show_paid?: boolean;
67
- tokenrouter_show_paid?: boolean;
68
- openrouter_show_paid?: boolean;
69
- opencode_show_paid?: boolean;
70
- }
71
-
72
- const CONFIG_TEMPLATE: PiFreeConfig = {
73
- nvidia_api_key: "",
74
- ollama_api_key: "",
75
- zenmux_api_key: "",
76
- crofai_api_key: "",
77
- codestral_api_key: "",
78
- llm7_api_key: "",
79
- deepinfra_api_key: "",
80
- sambanova_api_key: "",
81
- together_api_key: "",
82
- novita_api_key: "",
83
- routeway_api_key: "",
84
- fastrouter_api_key: "",
85
- tokenrouter_api_key: "",
86
-
87
- kilo_free_only: false,
88
- hidden_models: [],
89
- free_only: true,
90
- kilo_show_paid: false,
91
- ollama_show_paid: false,
92
- cline_show_paid: false,
93
- zenmux_show_paid: false,
94
- crofai_show_paid: false,
95
- codestral_show_paid: false,
96
- llm7_show_paid: false,
97
- deepinfra_show_paid: false,
98
- sambanova_show_paid: false,
99
- together_show_paid: false,
100
- novita_show_paid: false,
101
- routeway_show_paid: false,
102
- fastrouter_show_paid: false,
103
- tokenrouter_show_paid: false,
104
- openrouter_show_paid: false,
105
- opencode_show_paid: false,
106
- };
107
-
108
- const CONFIG_PATH = join(PI_DATA_DIR, "free.json");
109
-
110
- function ensureConfigFile(): void {
111
- try {
112
- ensureDir(PI_DATA_DIR);
113
- if (existsSync(CONFIG_PATH)) {
114
- let existing: PiFreeConfig;
115
- try {
116
- existing = JSON.parse(
117
- readFileSync(CONFIG_PATH, "utf8"),
118
- ) as PiFreeConfig;
119
- } catch (_parseErr) {
120
- // File exists but is corrupt — DO NOT overwrite it.
121
- // The user needs to fix or delete it manually.
122
- _logger.error(
123
- "Config file exists but is corrupt — refusing to overwrite. Fix or delete ~/.pi/free.json.",
124
- { path: CONFIG_PATH },
125
- );
126
- return;
127
- }
128
- // Merge with template to add any missing keys, preserving existing values
129
- const merged = { ...CONFIG_TEMPLATE, ...existing };
130
- if (JSON.stringify(merged) !== JSON.stringify(existing)) {
131
- writeFileSync(
132
- CONFIG_PATH,
133
- `${JSON.stringify(merged, null, 2)}\n`,
134
- "utf8",
135
- );
136
- }
137
- } else {
138
- writeFileSync(
139
- CONFIG_PATH,
140
- `${JSON.stringify(CONFIG_TEMPLATE, null, 2)}\n`,
141
- "utf8",
142
- );
143
- }
144
- } catch (err) {
145
- _logger.warn("Could not create config file", {
146
- path: CONFIG_PATH,
147
- error: err instanceof Error ? err.message : String(err),
148
- });
149
- }
150
- }
151
-
152
- export function loadConfigFile(): PiFreeConfig {
153
- try {
154
- return JSON.parse(
155
- readFileSync(CONFIG_PATH, "utf8"),
156
- safeJsonReviver,
157
- ) as PiFreeConfig;
158
- } catch (err) {
159
- _logger.error("Could not parse config file — returning empty config", {
160
- path: CONFIG_PATH,
161
- error: err instanceof Error ? err.message : String(err),
162
- });
163
- return {};
164
- }
165
- }
166
-
167
- /**
168
- * Read the raw config file content without merging with template.
169
- * Returns the file content as string, or undefined if unreadable.
170
- */
171
- function readRawConfigFile(): string | undefined {
172
- try {
173
- return readFileSync(CONFIG_PATH, "utf8");
174
- } catch {
175
- return undefined;
176
- }
177
- }
178
-
179
- ensureConfigFile();
180
-
181
- // Resolve each value: env var takes priority over config file.
182
- function resolve(envKey: string, fileVal?: string): string | undefined {
183
- return process.env[envKey] || (fileVal?.trim() ? fileVal : undefined);
184
- }
185
-
186
- // Resolve boolean flag: env var takes priority, then config file.
187
- function resolveBool(envKey: string, fileVal?: boolean): boolean {
188
- const envValue = process.env[envKey];
189
- if (envValue === "true") return true;
190
- if (envValue === "false") return false;
191
- return fileVal === true;
192
- }
193
-
194
- // =============================================================================
195
- // Per-provider paid-model flags (getters so toggles reflect immediately)
196
- // =============================================================================
197
-
198
- export function getKiloShowPaid(): boolean {
199
- return resolveBool("KILO_SHOW_PAID", loadConfigFile().kilo_show_paid);
200
- }
201
-
202
- export function getClineShowPaid(): boolean {
203
- return resolveBool("CLINE_SHOW_PAID", loadConfigFile().cline_show_paid);
204
- }
205
-
206
- export function getZenmuxShowPaid(): boolean {
207
- return resolveBool("ZENMUX_SHOW_PAID", loadConfigFile().zenmux_show_paid);
208
- }
209
-
210
- export function getCrofaiShowPaid(): boolean {
211
- return resolveBool("CROFAI_SHOW_PAID", loadConfigFile().crofai_show_paid);
212
- }
213
-
214
- export function getCodestralShowPaid(): boolean {
215
- return resolveBool(
216
- "CODESTRAL_SHOW_PAID",
217
- loadConfigFile().codestral_show_paid,
218
- );
219
- }
220
-
221
- export function getLlm7ShowPaid(): boolean {
222
- return resolveBool("LLM7_SHOW_PAID", loadConfigFile().llm7_show_paid);
223
- }
224
-
225
- export function getDeepinfraShowPaid(): boolean {
226
- return resolveBool(
227
- "DEEPINFRA_SHOW_PAID",
228
- loadConfigFile().deepinfra_show_paid,
229
- );
230
- }
231
-
232
- export function getSambanovaShowPaid(): boolean {
233
- return resolveBool(
234
- "SAMBANOVA_SHOW_PAID",
235
- loadConfigFile().sambanova_show_paid,
236
- );
237
- }
238
-
239
- export function getTogetherShowPaid(): boolean {
240
- return resolveBool("TOGETHER_SHOW_PAID", loadConfigFile().together_show_paid);
241
- }
242
-
243
- export function getNovitaShowPaid(): boolean {
244
- return resolveBool("NOVITA_SHOW_PAID", loadConfigFile().novita_show_paid);
245
- }
246
-
247
- export function getRoutewayShowPaid(): boolean {
248
- return resolveBool("ROUTEWAY_SHOW_PAID", loadConfigFile().routeway_show_paid);
249
- }
250
-
251
- export function getTokenrouterShowPaid(): boolean {
252
- return resolveBool(
253
- "TOKENROUTER_SHOW_PAID",
254
- loadConfigFile().tokenrouter_show_paid,
255
- );
256
- }
257
-
258
- export function getFastrouterShowPaid(): boolean {
259
- return resolveBool(
260
- "FASTROUTER_SHOW_PAID",
261
- loadConfigFile().fastrouter_show_paid,
262
- );
263
- }
264
-
265
- export function getOllamaShowPaid(): boolean {
266
- return resolveBool("OLLAMA_SHOW_PAID", loadConfigFile().ollama_show_paid);
267
- }
268
-
269
- export function getOpenrouterShowPaid(): boolean {
270
- return resolveBool(
271
- "OPENROUTER_SHOW_PAID",
272
- loadConfigFile().openrouter_show_paid,
273
- );
274
- }
275
-
276
- export function getOpencodeShowPaid(): boolean {
277
- return resolveBool("OPENCODE_SHOW_PAID", loadConfigFile().opencode_show_paid);
278
- }
279
-
280
- export function getProviderShowPaid(providerId: string): boolean {
281
- switch (providerId) {
282
- case "kilo":
283
- return getKiloShowPaid();
284
- case "cline":
285
- return getClineShowPaid();
286
- case "zenmux":
287
- return getZenmuxShowPaid();
288
- case "crofai":
289
- return getCrofaiShowPaid();
290
- case "codestral":
291
- return getCodestralShowPaid();
292
- case "llm7":
293
- return getLlm7ShowPaid();
294
- case "deepinfra":
295
- return getDeepinfraShowPaid();
296
- case "sambanova":
297
- return getSambanovaShowPaid();
298
- case "together":
299
- return getTogetherShowPaid();
300
- case "novita":
301
- return getNovitaShowPaid();
302
- case "routeway":
303
- return getRoutewayShowPaid();
304
- case "tokenrouter":
305
- return getTokenrouterShowPaid();
306
- case "fastrouter":
307
- return getFastrouterShowPaid();
308
- case "ollama-cloud":
309
- return getOllamaShowPaid();
310
- case "openrouter":
311
- return getOpenrouterShowPaid();
312
- case "opencode":
313
- return getOpencodeShowPaid();
314
- default:
315
- return false;
316
- }
317
- }
318
-
319
- // =============================================================================
320
- // Global free-only mode
321
- // =============================================================================
322
-
323
- export function getFreeOnly(): boolean {
324
- return resolveBool("PI_FREE_ONLY", loadConfigFile().free_only);
325
- }
326
-
327
- export function getKiloFreeOnly(): boolean {
328
- return resolveBool("PI_FREE_KILO_FREE_ONLY", loadConfigFile().kilo_free_only);
329
- }
330
-
331
- // =============================================================================
332
- // API Keys (getters so runtime config changes are visible)
333
- // =============================================================================
334
-
335
- export function getNvidiaApiKey(): string | undefined {
336
- return resolve("NVIDIA_API_KEY", loadConfigFile().nvidia_api_key);
337
- }
338
-
339
- export function getZenmuxApiKey(): string | undefined {
340
- return resolve("ZENMUX_API_KEY", loadConfigFile().zenmux_api_key);
341
- }
342
-
343
- export function getCrofaiApiKey(): string | undefined {
344
- return resolve("CROFAI_API_KEY", loadConfigFile().crofai_api_key);
345
- }
346
-
347
- export function getCodestralApiKey(): string | undefined {
348
- return resolve("CODESTRAL_API_KEY", loadConfigFile().codestral_api_key);
349
- }
350
-
351
- export function getLlm7ApiKey(): string | undefined {
352
- return resolve("LLM7_API_KEY", loadConfigFile().llm7_api_key);
353
- }
354
-
355
- export function getDeepinfraApiKey(): string | undefined {
356
- return resolve("DEEPINFRA_TOKEN", loadConfigFile().deepinfra_api_key);
357
- }
358
-
359
- export function getSambanovaApiKey(): string | undefined {
360
- return resolve("SAMBANOVA_API_KEY", loadConfigFile().sambanova_api_key);
361
- }
362
-
363
- export function getTogetherApiKey(): string | undefined {
364
- return resolve("TOGETHER_AI_API_KEY", loadConfigFile().together_api_key);
365
- }
366
-
367
- export function getNovitaApiKey(): string | undefined {
368
- return resolve("NOVITA_API_KEY", loadConfigFile().novita_api_key);
369
- }
370
-
371
- export function getRoutewayApiKey(): string | undefined {
372
- return resolve("ROUTEWAY_API_KEY", loadConfigFile().routeway_api_key);
373
- }
374
-
375
- export function getFastrouterApiKey(): string | undefined {
376
- return resolve("FASTROUTER_API_KEY", loadConfigFile().fastrouter_api_key);
377
- }
378
-
379
- export function getTokenrouterApiKey(): string | undefined {
380
- return resolve("TOKENROUTER_API_KEY", loadConfigFile().tokenrouter_api_key);
381
- }
382
-
383
- export function getOllamaApiKey(): string | undefined {
384
- return resolve("OLLAMA_API_KEY", loadConfigFile().ollama_api_key);
385
- }
386
-
387
- /** Mistral is pi's built-in provider — key comes from env var only. */
388
- export function getMistralApiKey(): string | undefined {
389
- return process.env.MISTRAL_API_KEY;
390
- }
391
-
392
- /** Groq is pi's built-in provider — key comes from env var only. */
393
- export function getGroqApiKey(): string | undefined {
394
- return process.env.GROQ_API_KEY;
395
- }
396
-
397
- /** Cerebras is pi's built-in provider — key comes from env var only. */
398
- export function getCerebrasApiKey(): string | undefined {
399
- return process.env.CEREBRAS_API_KEY;
400
- }
401
-
402
- /** xAI is pi's built-in provider — key comes from env var only. */
403
- export function getXaiApiKey(): string | undefined {
404
- return process.env.XAI_API_KEY;
405
- }
406
-
407
- /** HuggingFace is pi's built-in provider — token comes from env var only. */
408
- export function getHfToken(): string | undefined {
409
- return process.env.HF_TOKEN;
410
- }
411
-
412
- /**
413
- * Read an API key from ~/.pi/agent/auth.json.
414
- * Pi stores built-in provider keys there (opencode, openrouter, etc.).
415
- * Falls back to env var if auth.json is missing or key not found.
416
- */
417
- function readAuthJsonKey(
418
- providerId: string,
419
- envVar: string,
420
- ): string | undefined {
421
- // Check env var first (fast path)
422
- const envVal = process.env[envVar];
423
- if (envVal) return envVal;
424
-
425
- // Check auth.json
426
- try {
427
- const authPath = join(PI_DATA_DIR, "agent", "auth.json");
428
- if (!existsSync(authPath)) return undefined;
429
- const raw = readFileSync(authPath, "utf8");
430
- const auth = JSON.parse(raw, safeJsonReviver) as Record<
431
- string,
432
- { type?: string; key?: string }
433
- >;
434
- const entry = auth[providerId];
435
- if (entry?.key?.trim()) return entry.key;
436
- } catch {
437
- // auth.json missing or corrupt — silently skip
438
- }
439
- return undefined;
440
- }
441
-
442
- /**
443
- * OpenRouter key — pi's built-in provider reads from ~/.pi/agent/auth.json.
444
- * pi-free checks env var first, then auth.json.
445
- */
446
- export function getOpenrouterApiKey(): string | undefined {
447
- return readAuthJsonKey("openrouter", "OPENROUTER_API_KEY");
448
- }
449
-
450
- /** OpenCode key pi's built-in provider. Read from env or auth.json. */
451
- export function getOpencodeApiKey(): string | undefined {
452
- return readAuthJsonKey("opencode", "OPENCODE_API_KEY");
453
- }
454
-
455
- // =============================================================================
456
- // Hidden models (re-reads config on every call)
457
- // =============================================================================
458
-
459
- /**
460
- * Apply hidden models filter with provider scoping.
461
- * Hidden models can be specified as:
462
- * - "model-id" (global, applies to all providers - deprecated)
463
- * - "provider/model-id" (provider-specific, preferred)
464
- */
465
- export function applyHidden<T extends { id: string }>(
466
- models: T[],
467
- providerId?: string,
468
- ): T[] {
469
- const hidden = new Set(loadConfigFile().hidden_models ?? []);
470
- if (hidden.size === 0) return models;
471
-
472
- return models.filter((m) => {
473
- // Check provider-scoped ID (preferred format: "provider/model-id")
474
- if (providerId && hidden.has(`${providerId}/${m.id}`)) {
475
- return false;
476
- }
477
- // Check global ID (legacy format, still supported for backward compat)
478
- if (hidden.has(m.id)) {
479
- return false;
480
- }
481
- return true;
482
- });
483
- }
484
-
485
- // =============================================================================
486
- // Persistence
487
- // =============================================================================
488
-
489
- export function saveConfig(updates: Partial<PiFreeConfig>): void {
490
- try {
491
- // Read the raw file content — never use loadConfigFile() here because
492
- // if the file is unparseable, loadConfigFile() returns {} which would
493
- // cause us to write a partial config and WIPE all existing keys.
494
- const raw = readRawConfigFile();
495
- if (raw === undefined) {
496
- // File doesn't exist or can't be read — start from template
497
- const merged = { ...CONFIG_TEMPLATE, ...updates };
498
- writeFileSync(
499
- CONFIG_PATH,
500
- `${JSON.stringify(merged, null, 2)}\n`,
501
- "utf8",
502
- );
503
- _logger.info("Config saved (new file)", {
504
- path: CONFIG_PATH,
505
- keys: Object.keys(updates),
506
- });
507
- return;
508
- }
509
-
510
- let existing: PiFreeConfig;
511
- try {
512
- existing = JSON.parse(raw, safeJsonReviver) as PiFreeConfig;
513
- } catch (parseErr) {
514
- // File exists but is corrupt. REFUSE to overwrite it with a partial
515
- // config — that would permanently destroy the user's keys.
516
- _logger.error(
517
- "REFUSING to save config — existing file is corrupt. Fix or delete ~/.pi/free.json manually.",
518
- {
519
- path: CONFIG_PATH,
520
- error:
521
- parseErr instanceof Error ? parseErr.message : String(parseErr),
522
- },
523
- );
524
- return;
525
- }
526
-
527
- const merged = { ...existing, ...updates };
528
- writeFileSync(CONFIG_PATH, `${JSON.stringify(merged, null, 2)}\n`, "utf8");
529
- _logger.info("Config saved", {
530
- path: CONFIG_PATH,
531
- keys: Object.keys(updates),
532
- });
533
- } catch (err) {
534
- _logger.error("Failed to save config", {
535
- path: CONFIG_PATH,
536
- error: err instanceof Error ? err.message : String(err),
537
- });
538
- }
539
- }
540
-
541
- /**
542
- * Serialise all config RMW operations to prevent concurrent updates
543
- * from clobbering each other (e.g. two provider probes finishing at the
544
- * same time both writing hidden_models and losing the other's update).
545
- */
546
- class ConfigLock {
547
- private promise: Promise<void> = Promise.resolve();
548
-
549
- async acquire(): Promise<() => void> {
550
- let release: () => void;
551
- const newPromise = new Promise<void>((resolve) => {
552
- release = resolve;
553
- });
554
- const previous = this.promise;
555
- this.promise = previous.then(() => newPromise);
556
- await previous;
557
- return release!;
558
- }
559
- }
560
-
561
- const _configLock = new ConfigLock();
562
-
563
- /**
564
- * Atomically read-modify-write the config file. The updater function
565
- * receives the current parsed config and returns the partial updates to
566
- * merge. Concurrent calls are serialised by an internal lock.
567
- *
568
- * If the config file is corrupt, the updater is NOT called and the file
569
- * is left untouched (matches saveConfig's safety behaviour).
570
- */
571
- export async function updateConfig(
572
- updater: (current: PiFreeConfig) => Partial<PiFreeConfig>,
573
- ): Promise<void> {
574
- const release = await _configLock.acquire();
575
- try {
576
- const raw = readRawConfigFile();
577
- if (raw === undefined) {
578
- // File doesn't exist — start from template, apply updater once
579
- const updated = updater({ ...CONFIG_TEMPLATE });
580
- const merged = { ...CONFIG_TEMPLATE, ...updated };
581
- writeFileSync(
582
- CONFIG_PATH,
583
- `${JSON.stringify(merged, null, 2)}\n`,
584
- "utf8",
585
- );
586
- _logger.info("Config updated (new file)", {
587
- path: CONFIG_PATH,
588
- keys: Object.keys(updated),
589
- });
590
- return;
591
- }
592
-
593
- let existing: PiFreeConfig;
594
- try {
595
- existing = JSON.parse(raw, safeJsonReviver) as PiFreeConfig;
596
- } catch (parseErr) {
597
- _logger.error(
598
- "REFUSING to update config — existing file is corrupt. Fix or delete ~/.pi/free.json manually.",
599
- {
600
- path: CONFIG_PATH,
601
- error:
602
- parseErr instanceof Error ? parseErr.message : String(parseErr),
603
- },
604
- );
605
- return;
606
- }
607
-
608
- const updated = updater(existing);
609
- const merged = { ...existing, ...updated };
610
- writeFileSync(CONFIG_PATH, `${JSON.stringify(merged, null, 2)}\n`, "utf8");
611
- _logger.info("Config updated", {
612
- path: CONFIG_PATH,
613
- keys: Object.keys(updated),
614
- });
615
- } catch (err) {
616
- _logger.error("Failed to update config", {
617
- path: CONFIG_PATH,
618
- error: err instanceof Error ? err.message : String(err),
619
- });
620
- } finally {
621
- release();
622
- }
623
- }
624
-
625
- export function getConfig(): PiFreeConfig {
626
- return loadConfigFile();
627
- }
628
-
629
- // =============================================================================
1
+ /**
2
+ * Shared config for pi-free-providers.
3
+ *
4
+ * Keys and flags are resolved in this order (first wins):
5
+ * 1. Environment variable
6
+ * 2. ~/.pi/free.json
7
+ *
8
+ * All exported values are getter functions so that runtime changes
9
+ * (e.g. after toggle-{provider}) are visible immediately.
10
+ */
11
+
12
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ export {
15
+ PROVIDER_BAI,
16
+ PROVIDER_CLINE,
17
+ PROVIDER_KILO,
18
+ PROVIDER_MODAL,
19
+ PROVIDER_QWEN,
20
+ PROVIDER_ROUTEWAY,
21
+ PROVIDER_TOKENROUTER,
22
+ } from "./constants.ts";
23
+ import { createLogger } from "./lib/logger.ts";
24
+ import { ensureDir, PI_DATA_DIR } from "./lib/paths.ts";
25
+
26
+ /**
27
+ * JSON.parse reviver that strips prototype-pollution payloads.
28
+ */
29
+ function safeJsonReviver(_key: string, value: unknown): unknown {
30
+ if (_key === "__proto__" || _key === "constructor") {
31
+ return undefined;
32
+ }
33
+ return value;
34
+ }
35
+
36
+ const _logger = createLogger("config");
37
+
38
+ interface PiFreeConfig {
39
+ nvidia_api_key?: string;
40
+ ollama_api_key?: string;
41
+ zenmux_api_key?: string;
42
+ crofai_api_key?: string;
43
+ codestral_api_key?: string;
44
+ llm7_api_key?: string;
45
+ deepinfra_api_key?: string;
46
+ sambanova_api_key?: string;
47
+ together_api_key?: string;
48
+ novita_api_key?: string;
49
+ routeway_api_key?: string;
50
+ fastrouter_api_key?: string;
51
+ tokenrouter_api_key?: string;
52
+ bai_api_key?: string;
53
+ kilo_free_only?: boolean;
54
+ hidden_models?: string[];
55
+ free_only?: boolean;
56
+ kilo_show_paid?: boolean;
57
+ ollama_show_paid?: boolean;
58
+ cline_show_paid?: boolean;
59
+ zenmux_show_paid?: boolean;
60
+ crofai_show_paid?: boolean;
61
+ codestral_show_paid?: boolean;
62
+ llm7_show_paid?: boolean;
63
+ deepinfra_show_paid?: boolean;
64
+ sambanova_show_paid?: boolean;
65
+ together_show_paid?: boolean;
66
+ novita_show_paid?: boolean;
67
+ routeway_show_paid?: boolean;
68
+ fastrouter_show_paid?: boolean;
69
+ tokenrouter_show_paid?: boolean;
70
+ bai_show_paid?: boolean;
71
+ openrouter_show_paid?: boolean;
72
+ opencode_show_paid?: boolean;
73
+ }
74
+
75
+ const CONFIG_TEMPLATE: PiFreeConfig = {
76
+ nvidia_api_key: "",
77
+ ollama_api_key: "",
78
+ zenmux_api_key: "",
79
+ crofai_api_key: "",
80
+ codestral_api_key: "",
81
+ llm7_api_key: "",
82
+ deepinfra_api_key: "",
83
+ sambanova_api_key: "",
84
+ together_api_key: "",
85
+ novita_api_key: "",
86
+ routeway_api_key: "",
87
+ fastrouter_api_key: "",
88
+ tokenrouter_api_key: "",
89
+ bai_api_key: "",
90
+
91
+ kilo_free_only: false,
92
+ hidden_models: [],
93
+ free_only: true,
94
+ kilo_show_paid: false,
95
+ ollama_show_paid: false,
96
+ cline_show_paid: false,
97
+ zenmux_show_paid: false,
98
+ crofai_show_paid: false,
99
+ codestral_show_paid: false,
100
+ llm7_show_paid: false,
101
+ deepinfra_show_paid: false,
102
+ sambanova_show_paid: false,
103
+ together_show_paid: false,
104
+ novita_show_paid: false,
105
+ routeway_show_paid: false,
106
+ fastrouter_show_paid: false,
107
+ tokenrouter_show_paid: false,
108
+ bai_show_paid: false,
109
+ openrouter_show_paid: false,
110
+ opencode_show_paid: false,
111
+ };
112
+
113
+ const CONFIG_PATH = join(PI_DATA_DIR, "free.json");
114
+
115
+ function ensureConfigFile(): void {
116
+ try {
117
+ ensureDir(PI_DATA_DIR);
118
+ if (existsSync(CONFIG_PATH)) {
119
+ let existing: PiFreeConfig;
120
+ try {
121
+ existing = JSON.parse(
122
+ readFileSync(CONFIG_PATH, "utf8"),
123
+ ) as PiFreeConfig;
124
+ } catch (_parseErr) {
125
+ // File exists but is corrupt — DO NOT overwrite it.
126
+ // The user needs to fix or delete it manually.
127
+ _logger.error(
128
+ "Config file exists but is corrupt refusing to overwrite. Fix or delete ~/.pi/free.json.",
129
+ { path: CONFIG_PATH },
130
+ );
131
+ return;
132
+ }
133
+ // Merge with template to add any missing keys, preserving existing values
134
+ const merged = { ...CONFIG_TEMPLATE, ...existing };
135
+ if (JSON.stringify(merged) !== JSON.stringify(existing)) {
136
+ writeFileSync(
137
+ CONFIG_PATH,
138
+ `${JSON.stringify(merged, null, 2)}\n`,
139
+ "utf8",
140
+ );
141
+ }
142
+ } else {
143
+ writeFileSync(
144
+ CONFIG_PATH,
145
+ `${JSON.stringify(CONFIG_TEMPLATE, null, 2)}\n`,
146
+ "utf8",
147
+ );
148
+ }
149
+ } catch (err) {
150
+ _logger.warn("Could not create config file", {
151
+ path: CONFIG_PATH,
152
+ error: err instanceof Error ? err.message : String(err),
153
+ });
154
+ }
155
+ }
156
+
157
+ export function loadConfigFile(): PiFreeConfig {
158
+ try {
159
+ return JSON.parse(
160
+ readFileSync(CONFIG_PATH, "utf8"),
161
+ safeJsonReviver,
162
+ ) as PiFreeConfig;
163
+ } catch (err) {
164
+ _logger.error("Could not parse config file — returning empty config", {
165
+ path: CONFIG_PATH,
166
+ error: err instanceof Error ? err.message : String(err),
167
+ });
168
+ return {};
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Read the raw config file content without merging with template.
174
+ * Returns the file content as string, or undefined if unreadable.
175
+ */
176
+ function readRawConfigFile(): string | undefined {
177
+ try {
178
+ return readFileSync(CONFIG_PATH, "utf8");
179
+ } catch {
180
+ return undefined;
181
+ }
182
+ }
183
+
184
+ ensureConfigFile();
185
+
186
+ // Resolve each value: env var takes priority over config file.
187
+ function resolve(envKey: string, fileVal?: string): string | undefined {
188
+ return process.env[envKey] || (fileVal?.trim() ? fileVal : undefined);
189
+ }
190
+
191
+ // Resolve boolean flag: env var takes priority, then config file.
192
+ function resolveBool(envKey: string, fileVal?: boolean): boolean {
193
+ const envValue = process.env[envKey];
194
+ if (envValue === "true") return true;
195
+ if (envValue === "false") return false;
196
+ return fileVal === true;
197
+ }
198
+
199
+ // =============================================================================
200
+ // Per-provider paid-model flags (getters so toggles reflect immediately)
201
+ // =============================================================================
202
+
203
+ export function getKiloShowPaid(): boolean {
204
+ return resolveBool("KILO_SHOW_PAID", loadConfigFile().kilo_show_paid);
205
+ }
206
+
207
+ export function getClineShowPaid(): boolean {
208
+ return resolveBool("CLINE_SHOW_PAID", loadConfigFile().cline_show_paid);
209
+ }
210
+
211
+ export function getZenmuxShowPaid(): boolean {
212
+ return resolveBool("ZENMUX_SHOW_PAID", loadConfigFile().zenmux_show_paid);
213
+ }
214
+
215
+ export function getCrofaiShowPaid(): boolean {
216
+ return resolveBool("CROFAI_SHOW_PAID", loadConfigFile().crofai_show_paid);
217
+ }
218
+
219
+ export function getCodestralShowPaid(): boolean {
220
+ return resolveBool(
221
+ "CODESTRAL_SHOW_PAID",
222
+ loadConfigFile().codestral_show_paid,
223
+ );
224
+ }
225
+
226
+ export function getLlm7ShowPaid(): boolean {
227
+ return resolveBool("LLM7_SHOW_PAID", loadConfigFile().llm7_show_paid);
228
+ }
229
+
230
+ export function getDeepinfraShowPaid(): boolean {
231
+ return resolveBool(
232
+ "DEEPINFRA_SHOW_PAID",
233
+ loadConfigFile().deepinfra_show_paid,
234
+ );
235
+ }
236
+
237
+ export function getSambanovaShowPaid(): boolean {
238
+ return resolveBool(
239
+ "SAMBANOVA_SHOW_PAID",
240
+ loadConfigFile().sambanova_show_paid,
241
+ );
242
+ }
243
+
244
+ export function getTogetherShowPaid(): boolean {
245
+ return resolveBool("TOGETHER_SHOW_PAID", loadConfigFile().together_show_paid);
246
+ }
247
+
248
+ export function getNovitaShowPaid(): boolean {
249
+ return resolveBool("NOVITA_SHOW_PAID", loadConfigFile().novita_show_paid);
250
+ }
251
+
252
+ export function getRoutewayShowPaid(): boolean {
253
+ return resolveBool("ROUTEWAY_SHOW_PAID", loadConfigFile().routeway_show_paid);
254
+ }
255
+
256
+ export function getTokenrouterShowPaid(): boolean {
257
+ return resolveBool(
258
+ "TOKENROUTER_SHOW_PAID",
259
+ loadConfigFile().tokenrouter_show_paid,
260
+ );
261
+ }
262
+
263
+ export function getBaiShowPaid(): boolean {
264
+ return resolveBool("BAI_SHOW_PAID", loadConfigFile().bai_show_paid);
265
+ }
266
+
267
+ export function getFastrouterShowPaid(): boolean {
268
+ return resolveBool(
269
+ "FASTROUTER_SHOW_PAID",
270
+ loadConfigFile().fastrouter_show_paid,
271
+ );
272
+ }
273
+
274
+ export function getOllamaShowPaid(): boolean {
275
+ return resolveBool("OLLAMA_SHOW_PAID", loadConfigFile().ollama_show_paid);
276
+ }
277
+
278
+ export function getOpenrouterShowPaid(): boolean {
279
+ return resolveBool(
280
+ "OPENROUTER_SHOW_PAID",
281
+ loadConfigFile().openrouter_show_paid,
282
+ );
283
+ }
284
+
285
+ export function getOpencodeShowPaid(): boolean {
286
+ return resolveBool("OPENCODE_SHOW_PAID", loadConfigFile().opencode_show_paid);
287
+ }
288
+
289
+ export function getProviderShowPaid(providerId: string): boolean {
290
+ switch (providerId) {
291
+ case "kilo":
292
+ return getKiloShowPaid();
293
+ case "cline":
294
+ return getClineShowPaid();
295
+ case "zenmux":
296
+ return getZenmuxShowPaid();
297
+ case "crofai":
298
+ return getCrofaiShowPaid();
299
+ case "codestral":
300
+ return getCodestralShowPaid();
301
+ case "llm7":
302
+ return getLlm7ShowPaid();
303
+ case "deepinfra":
304
+ return getDeepinfraShowPaid();
305
+ case "sambanova":
306
+ return getSambanovaShowPaid();
307
+ case "together":
308
+ return getTogetherShowPaid();
309
+ case "novita":
310
+ return getNovitaShowPaid();
311
+ case "routeway":
312
+ return getRoutewayShowPaid();
313
+ case "tokenrouter":
314
+ return getTokenrouterShowPaid();
315
+ case "bai":
316
+ return getBaiShowPaid();
317
+ case "fastrouter":
318
+ return getFastrouterShowPaid();
319
+ case "ollama-cloud":
320
+ return getOllamaShowPaid();
321
+ case "openrouter":
322
+ return getOpenrouterShowPaid();
323
+ case "opencode":
324
+ return getOpencodeShowPaid();
325
+ default:
326
+ return false;
327
+ }
328
+ }
329
+
330
+ // =============================================================================
331
+ // Global free-only mode
332
+ // =============================================================================
333
+
334
+ export function getFreeOnly(): boolean {
335
+ return resolveBool("PI_FREE_ONLY", loadConfigFile().free_only);
336
+ }
337
+
338
+ export function getKiloFreeOnly(): boolean {
339
+ return resolveBool("PI_FREE_KILO_FREE_ONLY", loadConfigFile().kilo_free_only);
340
+ }
341
+
342
+ // =============================================================================
343
+ // API Keys (getters so runtime config changes are visible)
344
+ // =============================================================================
345
+
346
+ export function getNvidiaApiKey(): string | undefined {
347
+ return resolve("NVIDIA_API_KEY", loadConfigFile().nvidia_api_key);
348
+ }
349
+
350
+ export function getZenmuxApiKey(): string | undefined {
351
+ return resolve("ZENMUX_API_KEY", loadConfigFile().zenmux_api_key);
352
+ }
353
+
354
+ export function getCrofaiApiKey(): string | undefined {
355
+ return resolve("CROFAI_API_KEY", loadConfigFile().crofai_api_key);
356
+ }
357
+
358
+ export function getCodestralApiKey(): string | undefined {
359
+ return resolve("CODESTRAL_API_KEY", loadConfigFile().codestral_api_key);
360
+ }
361
+
362
+ export function getLlm7ApiKey(): string | undefined {
363
+ return resolve("LLM7_API_KEY", loadConfigFile().llm7_api_key);
364
+ }
365
+
366
+ export function getDeepinfraApiKey(): string | undefined {
367
+ return resolve("DEEPINFRA_TOKEN", loadConfigFile().deepinfra_api_key);
368
+ }
369
+
370
+ export function getSambanovaApiKey(): string | undefined {
371
+ return resolve("SAMBANOVA_API_KEY", loadConfigFile().sambanova_api_key);
372
+ }
373
+
374
+ export function getTogetherApiKey(): string | undefined {
375
+ return resolve("TOGETHER_AI_API_KEY", loadConfigFile().together_api_key);
376
+ }
377
+
378
+ export function getNovitaApiKey(): string | undefined {
379
+ return resolve("NOVITA_API_KEY", loadConfigFile().novita_api_key);
380
+ }
381
+
382
+ export function getRoutewayApiKey(): string | undefined {
383
+ return resolve("ROUTEWAY_API_KEY", loadConfigFile().routeway_api_key);
384
+ }
385
+
386
+ export function getFastrouterApiKey(): string | undefined {
387
+ return resolve("FASTROUTER_API_KEY", loadConfigFile().fastrouter_api_key);
388
+ }
389
+
390
+ export function getTokenrouterApiKey(): string | undefined {
391
+ return resolve("TOKENROUTER_API_KEY", loadConfigFile().tokenrouter_api_key);
392
+ }
393
+
394
+ export function getBaiApiKey(): string | undefined {
395
+ return resolve("BAI_API_KEY", loadConfigFile().bai_api_key);
396
+ }
397
+
398
+ export function getOllamaApiKey(): string | undefined {
399
+ return resolve("OLLAMA_API_KEY", loadConfigFile().ollama_api_key);
400
+ }
401
+
402
+ /** Mistral is pi's built-in provider — key comes from env var only. */
403
+ export function getMistralApiKey(): string | undefined {
404
+ return process.env.MISTRAL_API_KEY;
405
+ }
406
+
407
+ /** Groq is pi's built-in provider — key comes from env var only. */
408
+ export function getGroqApiKey(): string | undefined {
409
+ return process.env.GROQ_API_KEY;
410
+ }
411
+
412
+ /** Cerebras is pi's built-in provider — key comes from env var only. */
413
+ export function getCerebrasApiKey(): string | undefined {
414
+ return process.env.CEREBRAS_API_KEY;
415
+ }
416
+
417
+ /** xAI is pi's built-in provider — key comes from env var only. */
418
+ export function getXaiApiKey(): string | undefined {
419
+ return process.env.XAI_API_KEY;
420
+ }
421
+
422
+ /** HuggingFace is pi's built-in provider — token comes from env var only. */
423
+ export function getHfToken(): string | undefined {
424
+ return process.env.HF_TOKEN;
425
+ }
426
+
427
+ /**
428
+ * Read an API key from ~/.pi/agent/auth.json.
429
+ * Pi stores built-in provider keys there (opencode, openrouter, etc.).
430
+ * Falls back to env var if auth.json is missing or key not found.
431
+ */
432
+ function readAuthJsonKey(
433
+ providerId: string,
434
+ envVar: string,
435
+ ): string | undefined {
436
+ // Check env var first (fast path)
437
+ const envVal = process.env[envVar];
438
+ if (envVal) return envVal;
439
+
440
+ // Check auth.json
441
+ try {
442
+ const authPath = join(PI_DATA_DIR, "agent", "auth.json");
443
+ if (!existsSync(authPath)) return undefined;
444
+ const raw = readFileSync(authPath, "utf8");
445
+ const auth = JSON.parse(raw, safeJsonReviver) as Record<
446
+ string,
447
+ { type?: string; key?: string }
448
+ >;
449
+ const entry = auth[providerId];
450
+ if (entry?.key?.trim()) return entry.key;
451
+ } catch {
452
+ // auth.json missing or corrupt — silently skip
453
+ }
454
+ return undefined;
455
+ }
456
+
457
+ /**
458
+ * OpenRouter key — pi's built-in provider reads from ~/.pi/agent/auth.json.
459
+ * pi-free checks env var first, then auth.json.
460
+ */
461
+ export function getOpenrouterApiKey(): string | undefined {
462
+ return readAuthJsonKey("openrouter", "OPENROUTER_API_KEY");
463
+ }
464
+
465
+ /** OpenCode key pi's built-in provider. Read from env or auth.json. */
466
+ export function getOpencodeApiKey(): string | undefined {
467
+ return readAuthJsonKey("opencode", "OPENCODE_API_KEY");
468
+ }
469
+
470
+ // =============================================================================
471
+ // Hidden models (re-reads config on every call)
472
+ // =============================================================================
473
+
474
+ /**
475
+ * Apply hidden models filter with provider scoping.
476
+ * Hidden models can be specified as:
477
+ * - "model-id" (global, applies to all providers - deprecated)
478
+ * - "provider/model-id" (provider-specific, preferred)
479
+ */
480
+ export function applyHidden<T extends { id: string }>(
481
+ models: T[],
482
+ providerId?: string,
483
+ ): T[] {
484
+ const hidden = new Set(loadConfigFile().hidden_models ?? []);
485
+ if (hidden.size === 0) return models;
486
+
487
+ return models.filter((m) => {
488
+ // Check provider-scoped ID (preferred format: "provider/model-id")
489
+ if (providerId && hidden.has(`${providerId}/${m.id}`)) {
490
+ return false;
491
+ }
492
+ // Check global ID (legacy format, still supported for backward compat)
493
+ if (hidden.has(m.id)) {
494
+ return false;
495
+ }
496
+ return true;
497
+ });
498
+ }
499
+
500
+ // =============================================================================
501
+ // Persistence
502
+ // =============================================================================
503
+
504
+ export function saveConfig(updates: Partial<PiFreeConfig>): void {
505
+ try {
506
+ // Read the raw file content — never use loadConfigFile() here because
507
+ // if the file is unparseable, loadConfigFile() returns {} which would
508
+ // cause us to write a partial config and WIPE all existing keys.
509
+ const raw = readRawConfigFile();
510
+ if (raw === undefined) {
511
+ // File doesn't exist or can't be read — start from template
512
+ const merged = { ...CONFIG_TEMPLATE, ...updates };
513
+ writeFileSync(
514
+ CONFIG_PATH,
515
+ `${JSON.stringify(merged, null, 2)}\n`,
516
+ "utf8",
517
+ );
518
+ _logger.info("Config saved (new file)", {
519
+ path: CONFIG_PATH,
520
+ keys: Object.keys(updates),
521
+ });
522
+ return;
523
+ }
524
+
525
+ let existing: PiFreeConfig;
526
+ try {
527
+ existing = JSON.parse(raw, safeJsonReviver) as PiFreeConfig;
528
+ } catch (parseErr) {
529
+ // File exists but is corrupt. REFUSE to overwrite it with a partial
530
+ // config — that would permanently destroy the user's keys.
531
+ _logger.error(
532
+ "REFUSING to save config — existing file is corrupt. Fix or delete ~/.pi/free.json manually.",
533
+ {
534
+ path: CONFIG_PATH,
535
+ error:
536
+ parseErr instanceof Error ? parseErr.message : String(parseErr),
537
+ },
538
+ );
539
+ return;
540
+ }
541
+
542
+ const merged = { ...existing, ...updates };
543
+ writeFileSync(CONFIG_PATH, `${JSON.stringify(merged, null, 2)}\n`, "utf8");
544
+ _logger.info("Config saved", {
545
+ path: CONFIG_PATH,
546
+ keys: Object.keys(updates),
547
+ });
548
+ } catch (err) {
549
+ _logger.error("Failed to save config", {
550
+ path: CONFIG_PATH,
551
+ error: err instanceof Error ? err.message : String(err),
552
+ });
553
+ }
554
+ }
555
+
556
+ /**
557
+ * Serialise all config RMW operations to prevent concurrent updates
558
+ * from clobbering each other (e.g. two provider probes finishing at the
559
+ * same time both writing hidden_models and losing the other's update).
560
+ */
561
+ class ConfigLock {
562
+ private promise: Promise<void> = Promise.resolve();
563
+
564
+ async acquire(): Promise<() => void> {
565
+ let release: () => void;
566
+ const newPromise = new Promise<void>((resolve) => {
567
+ release = resolve;
568
+ });
569
+ const previous = this.promise;
570
+ this.promise = previous.then(() => newPromise);
571
+ await previous;
572
+ return release!;
573
+ }
574
+ }
575
+
576
+ const _configLock = new ConfigLock();
577
+
578
+ /**
579
+ * Atomically read-modify-write the config file. The updater function
580
+ * receives the current parsed config and returns the partial updates to
581
+ * merge. Concurrent calls are serialised by an internal lock.
582
+ *
583
+ * If the config file is corrupt, the updater is NOT called and the file
584
+ * is left untouched (matches saveConfig's safety behaviour).
585
+ */
586
+ export async function updateConfig(
587
+ updater: (current: PiFreeConfig) => Partial<PiFreeConfig>,
588
+ ): Promise<void> {
589
+ const release = await _configLock.acquire();
590
+ try {
591
+ const raw = readRawConfigFile();
592
+ if (raw === undefined) {
593
+ // File doesn't exist — start from template, apply updater once
594
+ const updated = updater({ ...CONFIG_TEMPLATE });
595
+ const merged = { ...CONFIG_TEMPLATE, ...updated };
596
+ writeFileSync(
597
+ CONFIG_PATH,
598
+ `${JSON.stringify(merged, null, 2)}\n`,
599
+ "utf8",
600
+ );
601
+ _logger.info("Config updated (new file)", {
602
+ path: CONFIG_PATH,
603
+ keys: Object.keys(updated),
604
+ });
605
+ return;
606
+ }
607
+
608
+ let existing: PiFreeConfig;
609
+ try {
610
+ existing = JSON.parse(raw, safeJsonReviver) as PiFreeConfig;
611
+ } catch (parseErr) {
612
+ _logger.error(
613
+ "REFUSING to update config — existing file is corrupt. Fix or delete ~/.pi/free.json manually.",
614
+ {
615
+ path: CONFIG_PATH,
616
+ error:
617
+ parseErr instanceof Error ? parseErr.message : String(parseErr),
618
+ },
619
+ );
620
+ return;
621
+ }
622
+
623
+ const updated = updater(existing);
624
+ const merged = { ...existing, ...updated };
625
+ writeFileSync(CONFIG_PATH, `${JSON.stringify(merged, null, 2)}\n`, "utf8");
626
+ _logger.info("Config updated", {
627
+ path: CONFIG_PATH,
628
+ keys: Object.keys(updated),
629
+ });
630
+ } catch (err) {
631
+ _logger.error("Failed to update config", {
632
+ path: CONFIG_PATH,
633
+ error: err instanceof Error ? err.message : String(err),
634
+ });
635
+ } finally {
636
+ release();
637
+ }
638
+ }
639
+
640
+ export function getConfig(): PiFreeConfig {
641
+ return loadConfigFile();
642
+ }
643
+
644
+ // =============================================================================