pi-free 2.0.10 → 2.0.12

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,349 +1,500 @@
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, mkdirSync, readFileSync, writeFileSync } from "node:fs";
13
- import { join } from "node:path";
14
- export {
15
- PROVIDER_CLINE,
16
- PROVIDER_KILO,
17
- PROVIDER_MODAL,
18
- PROVIDER_NVIDIA,
19
- PROVIDER_QWEN,
20
- } from "./constants.ts";
21
- import { createLogger } from "./lib/logger.ts";
22
-
23
- const _logger = createLogger("config");
24
-
25
- interface PiFreeConfig {
26
- nvidia_api_key?: string;
27
- ollama_api_key?: string;
28
- zenmux_api_key?: string;
29
- crofai_api_key?: string;
30
- codestral_api_key?: string;
31
- mistral_api_key?: string;
32
- llm7_api_key?: string;
33
- deepinfra_api_key?: string;
34
- sambanova_api_key?: string;
35
- together_api_key?: string;
36
- groq_api_key?: string;
37
- cerebras_api_key?: string;
38
- xai_api_key?: string;
39
- hf_token?: string;
40
- kilo_free_only?: boolean;
41
- hidden_models?: string[];
42
- free_only?: boolean;
43
- kilo_show_paid?: boolean;
44
- ollama_show_paid?: boolean;
45
- cline_show_paid?: boolean;
46
- zenmux_show_paid?: boolean;
47
- crofai_show_paid?: boolean;
48
- codestral_show_paid?: boolean;
49
- llm7_show_paid?: boolean;
50
- deepinfra_show_paid?: boolean;
51
- sambanova_show_paid?: boolean;
52
- together_show_paid?: boolean;
53
- openrouter_show_paid?: boolean;
54
- opencode_show_paid?: boolean;
55
- }
56
-
57
- const CONFIG_TEMPLATE: PiFreeConfig = {
58
- nvidia_api_key: "",
59
- ollama_api_key: "",
60
- zenmux_api_key: "",
61
- crofai_api_key: "",
62
- codestral_api_key: "",
63
- mistral_api_key: "",
64
- llm7_api_key: "",
65
- deepinfra_api_key: "",
66
- sambanova_api_key: "",
67
- together_api_key: "",
68
- groq_api_key: "",
69
- cerebras_api_key: "",
70
- xai_api_key: "",
71
- hf_token: "",
72
-
73
- kilo_free_only: false,
74
- hidden_models: [],
75
- free_only: true,
76
- kilo_show_paid: false,
77
- ollama_show_paid: false,
78
- cline_show_paid: false,
79
- zenmux_show_paid: false,
80
- crofai_show_paid: false,
81
- codestral_show_paid: false,
82
- llm7_show_paid: false,
83
- deepinfra_show_paid: false,
84
- sambanova_show_paid: false,
85
- together_show_paid: false,
86
- openrouter_show_paid: false,
87
- opencode_show_paid: false,
88
- };
89
-
90
- const PI_DIR = join(process.env.HOME || process.env.USERPROFILE || "", ".pi");
91
- const CONFIG_PATH = join(PI_DIR, "free.json");
92
-
93
- function ensureConfigFile(): void {
94
- try {
95
- mkdirSync(PI_DIR, { recursive: true });
96
- if (existsSync(CONFIG_PATH)) {
97
- const existing = JSON.parse(
98
- readFileSync(CONFIG_PATH, "utf8"),
99
- ) as PiFreeConfig;
100
- const merged = { ...CONFIG_TEMPLATE, ...existing };
101
- if (JSON.stringify(merged) !== JSON.stringify(existing)) {
102
- writeFileSync(
103
- CONFIG_PATH,
104
- `${JSON.stringify(merged, null, 2)}\n`,
105
- "utf8",
106
- );
107
- }
108
- } else {
109
- writeFileSync(
110
- CONFIG_PATH,
111
- `${JSON.stringify(CONFIG_TEMPLATE, null, 2)}\n`,
112
- "utf8",
113
- );
114
- }
115
- } catch (err) {
116
- _logger.warn("Could not create config file", {
117
- path: CONFIG_PATH,
118
- error: err instanceof Error ? err.message : String(err),
119
- });
120
- }
121
- }
122
-
123
- export function loadConfigFile(): PiFreeConfig {
124
- try {
125
- return JSON.parse(readFileSync(CONFIG_PATH, "utf8")) as PiFreeConfig;
126
- } catch (err) {
127
- _logger.warn("Could not parse config file — returning empty config", {
128
- path: CONFIG_PATH,
129
- error: err instanceof Error ? err.message : String(err),
130
- });
131
- return {};
132
- }
133
- }
134
-
135
- ensureConfigFile();
136
-
137
- // Resolve each value: env var takes priority over config file.
138
- function resolve(envKey: string, fileVal?: string): string | undefined {
139
- return process.env[envKey] || (fileVal?.trim() ? fileVal : undefined);
140
- }
141
-
142
- // Resolve boolean flag: env var takes priority, then config file.
143
- function resolveBool(envKey: string, fileVal?: boolean): boolean {
144
- const envValue = process.env[envKey];
145
- if (envValue === "true") return true;
146
- if (envValue === "false") return false;
147
- return fileVal === true;
148
- }
149
-
150
- // =============================================================================
151
- // Per-provider paid-model flags (getters so toggles reflect immediately)
152
- // =============================================================================
153
-
154
- export function getKiloShowPaid(): boolean {
155
- return resolveBool("KILO_SHOW_PAID", loadConfigFile().kilo_show_paid);
156
- }
157
-
158
- export function getClineShowPaid(): boolean {
159
- return resolveBool("CLINE_SHOW_PAID", loadConfigFile().cline_show_paid);
160
- }
161
-
162
- export function getZenmuxShowPaid(): boolean {
163
- return resolveBool("ZENMUX_SHOW_PAID", loadConfigFile().zenmux_show_paid);
164
- }
165
-
166
- export function getCrofaiShowPaid(): boolean {
167
- return resolveBool("CROFAI_SHOW_PAID", loadConfigFile().crofai_show_paid);
168
- }
169
-
170
- export function getCodestralShowPaid(): boolean {
171
- return resolveBool(
172
- "CODESTRAL_SHOW_PAID",
173
- loadConfigFile().codestral_show_paid,
174
- );
175
- }
176
-
177
- export function getLlm7ShowPaid(): boolean {
178
- return resolveBool("LLM7_SHOW_PAID", loadConfigFile().llm7_show_paid);
179
- }
180
-
181
- export function getDeepinfraShowPaid(): boolean {
182
- return resolveBool(
183
- "DEEPINFRA_SHOW_PAID",
184
- loadConfigFile().deepinfra_show_paid,
185
- );
186
- }
187
-
188
- export function getSambanovaShowPaid(): boolean {
189
- return resolveBool(
190
- "SAMBANOVA_SHOW_PAID",
191
- loadConfigFile().sambanova_show_paid,
192
- );
193
- }
194
-
195
- export function getTogetherShowPaid(): boolean {
196
- return resolveBool("TOGETHER_SHOW_PAID", loadConfigFile().together_show_paid);
197
- }
198
-
199
- export function getOllamaShowPaid(): boolean {
200
- return resolveBool("OLLAMA_SHOW_PAID", loadConfigFile().ollama_show_paid);
201
- }
202
-
203
- export function getOpenrouterShowPaid(): boolean {
204
- return resolveBool(
205
- "OPENROUTER_SHOW_PAID",
206
- loadConfigFile().openrouter_show_paid,
207
- );
208
- }
209
-
210
- export function getOpencodeShowPaid(): boolean {
211
- return resolveBool("OPENCODE_SHOW_PAID", loadConfigFile().opencode_show_paid);
212
- }
213
-
214
- // =============================================================================
215
- // Global free-only mode
216
- // =============================================================================
217
-
218
- export function getFreeOnly(): boolean {
219
- return resolveBool("PI_FREE_ONLY", loadConfigFile().free_only);
220
- }
221
-
222
- export function getKiloFreeOnly(): boolean {
223
- return resolveBool("PI_FREE_KILO_FREE_ONLY", loadConfigFile().kilo_free_only);
224
- }
225
-
226
- // =============================================================================
227
- // API Keys (getters so runtime config changes are visible)
228
- // =============================================================================
229
-
230
- export function getNvidiaApiKey(): string | undefined {
231
- return resolve("NVIDIA_API_KEY", loadConfigFile().nvidia_api_key);
232
- }
233
-
234
- export function getZenmuxApiKey(): string | undefined {
235
- return resolve("ZENMUX_API_KEY", loadConfigFile().zenmux_api_key);
236
- }
237
-
238
- export function getCrofaiApiKey(): string | undefined {
239
- return resolve("CROFAI_API_KEY", loadConfigFile().crofai_api_key);
240
- }
241
-
242
- export function getCodestralApiKey(): string | undefined {
243
- return resolve("CODESTRAL_API_KEY", loadConfigFile().codestral_api_key);
244
- }
245
-
246
- export function getLlm7ApiKey(): string | undefined {
247
- return resolve("LLM7_API_KEY", loadConfigFile().llm7_api_key);
248
- }
249
-
250
- export function getDeepinfraApiKey(): string | undefined {
251
- return resolve("DEEPINFRA_TOKEN", loadConfigFile().deepinfra_api_key);
252
- }
253
-
254
- export function getSambanovaApiKey(): string | undefined {
255
- return resolve("SAMBANOVA_API_KEY", loadConfigFile().sambanova_api_key);
256
- }
257
-
258
- export function getTogetherApiKey(): string | undefined {
259
- return resolve("TOGETHER_AI_API_KEY", loadConfigFile().together_api_key);
260
- }
261
-
262
- export function getOllamaApiKey(): string | undefined {
263
- return resolve("OLLAMA_API_KEY", loadConfigFile().ollama_api_key);
264
- }
265
-
266
- export function getMistralApiKey(): string | undefined {
267
- return resolve("MISTRAL_API_KEY", loadConfigFile().mistral_api_key);
268
- }
269
-
270
- export function getGroqApiKey(): string | undefined {
271
- return resolve("GROQ_API_KEY", loadConfigFile().groq_api_key);
272
- }
273
-
274
- export function getCerebrasApiKey(): string | undefined {
275
- return resolve("CEREBRAS_API_KEY", loadConfigFile().cerebras_api_key);
276
- }
277
-
278
- export function getXaiApiKey(): string | undefined {
279
- return resolve("XAI_API_KEY", loadConfigFile().xai_api_key);
280
- }
281
-
282
- export function getHfToken(): string | undefined {
283
- return resolve("HF_TOKEN", loadConfigFile().hf_token);
284
- }
285
-
286
- /**
287
- * OpenRouter key — pi's built-in provider reads from ~/.pi/agent/auth.json.
288
- * pi-free only checks the env var to avoid stale keys from free.json.
289
- */
290
- export function getOpenrouterApiKey(): string | undefined {
291
- return process.env.OPENROUTER_API_KEY;
292
- }
293
-
294
- // =============================================================================
295
- // Hidden models (re-reads config on every call)
296
- // =============================================================================
297
-
298
- /**
299
- * Apply hidden models filter with provider scoping.
300
- * Hidden models can be specified as:
301
- * - "model-id" (global, applies to all providers - deprecated)
302
- * - "provider/model-id" (provider-specific, preferred)
303
- */
304
- export function applyHidden<T extends { id: string }>(
305
- models: T[],
306
- providerId?: string,
307
- ): T[] {
308
- const hidden = new Set(loadConfigFile().hidden_models ?? []);
309
- if (hidden.size === 0) return models;
310
-
311
- return models.filter((m) => {
312
- // Check provider-scoped ID (preferred format: "provider/model-id")
313
- if (providerId && hidden.has(`${providerId}/${m.id}`)) {
314
- return false;
315
- }
316
- // Check global ID (legacy format, still supported for backward compat)
317
- if (hidden.has(m.id)) {
318
- return false;
319
- }
320
- return true;
321
- });
322
- }
323
-
324
- // =============================================================================
325
- // Persistence
326
- // =============================================================================
327
-
328
- export function saveConfig(updates: Partial<PiFreeConfig>): void {
329
- try {
330
- const existing = loadConfigFile();
331
- const merged = { ...existing, ...updates };
332
- writeFileSync(CONFIG_PATH, `${JSON.stringify(merged, null, 2)}\n`, "utf8");
333
- _logger.info("Config saved", {
334
- path: CONFIG_PATH,
335
- keys: Object.keys(updates),
336
- });
337
- } catch (err) {
338
- _logger.error("Failed to save config", {
339
- path: CONFIG_PATH,
340
- error: err instanceof Error ? err.message : String(err),
341
- });
342
- }
343
- }
344
-
345
- export function getConfig(): PiFreeConfig {
346
- return loadConfigFile();
347
- }
348
-
349
- // =============================================================================
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, mkdirSync, readFileSync, writeFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ export {
15
+ PROVIDER_CLINE,
16
+ PROVIDER_KILO,
17
+ PROVIDER_MODAL,
18
+ PROVIDER_NVIDIA,
19
+ PROVIDER_QWEN,
20
+ } from "./constants.ts";
21
+ import { createLogger } from "./lib/logger.ts";
22
+
23
+ const _logger = createLogger("config");
24
+
25
+ interface PiFreeConfig {
26
+ nvidia_api_key?: string;
27
+ ollama_api_key?: string;
28
+ zenmux_api_key?: string;
29
+ crofai_api_key?: string;
30
+ codestral_api_key?: string;
31
+ llm7_api_key?: string;
32
+ deepinfra_api_key?: string;
33
+ sambanova_api_key?: string;
34
+ together_api_key?: string;
35
+ novita_api_key?: string;
36
+ fastrouter_api_key?: string;
37
+ kilo_free_only?: boolean;
38
+ hidden_models?: string[];
39
+ free_only?: boolean;
40
+ kilo_show_paid?: boolean;
41
+ ollama_show_paid?: boolean;
42
+ cline_show_paid?: boolean;
43
+ zenmux_show_paid?: boolean;
44
+ crofai_show_paid?: boolean;
45
+ codestral_show_paid?: boolean;
46
+ llm7_show_paid?: boolean;
47
+ deepinfra_show_paid?: boolean;
48
+ sambanova_show_paid?: boolean;
49
+ together_show_paid?: boolean;
50
+ novita_show_paid?: boolean;
51
+ fastrouter_show_paid?: boolean;
52
+ openrouter_show_paid?: boolean;
53
+ opencode_show_paid?: boolean;
54
+ }
55
+
56
+ const CONFIG_TEMPLATE: PiFreeConfig = {
57
+ nvidia_api_key: "",
58
+ ollama_api_key: "",
59
+ zenmux_api_key: "",
60
+ crofai_api_key: "",
61
+ codestral_api_key: "",
62
+ llm7_api_key: "",
63
+ deepinfra_api_key: "",
64
+ sambanova_api_key: "",
65
+ together_api_key: "",
66
+ novita_api_key: "",
67
+ fastrouter_api_key: "",
68
+
69
+ kilo_free_only: false,
70
+ hidden_models: [],
71
+ free_only: true,
72
+ kilo_show_paid: false,
73
+ ollama_show_paid: false,
74
+ cline_show_paid: false,
75
+ zenmux_show_paid: false,
76
+ crofai_show_paid: false,
77
+ codestral_show_paid: false,
78
+ llm7_show_paid: false,
79
+ deepinfra_show_paid: false,
80
+ sambanova_show_paid: false,
81
+ together_show_paid: false,
82
+ novita_show_paid: false,
83
+ fastrouter_show_paid: false,
84
+ openrouter_show_paid: false,
85
+ opencode_show_paid: false,
86
+ };
87
+
88
+ const PI_DIR = join(process.env.HOME || process.env.USERPROFILE || "", ".pi");
89
+ const CONFIG_PATH = join(PI_DIR, "free.json");
90
+
91
+ function ensureConfigFile(): void {
92
+ try {
93
+ mkdirSync(PI_DIR, { recursive: true });
94
+ if (existsSync(CONFIG_PATH)) {
95
+ let existing: PiFreeConfig;
96
+ try {
97
+ existing = JSON.parse(
98
+ readFileSync(CONFIG_PATH, "utf8"),
99
+ ) as PiFreeConfig;
100
+ } catch (_parseErr) {
101
+ // File exists but is corrupt — DO NOT overwrite it.
102
+ // The user needs to fix or delete it manually.
103
+ _logger.error(
104
+ "Config file exists but is corrupt — refusing to overwrite. Fix or delete ~/.pi/free.json.",
105
+ { path: CONFIG_PATH },
106
+ );
107
+ return;
108
+ }
109
+ // Merge with template to add any missing keys, preserving existing values
110
+ const merged = { ...CONFIG_TEMPLATE, ...existing };
111
+ if (JSON.stringify(merged) !== JSON.stringify(existing)) {
112
+ writeFileSync(
113
+ CONFIG_PATH,
114
+ `${JSON.stringify(merged, null, 2)}\n`,
115
+ "utf8",
116
+ );
117
+ }
118
+ } else {
119
+ writeFileSync(
120
+ CONFIG_PATH,
121
+ `${JSON.stringify(CONFIG_TEMPLATE, null, 2)}\n`,
122
+ "utf8",
123
+ );
124
+ }
125
+ } catch (err) {
126
+ _logger.warn("Could not create config file", {
127
+ path: CONFIG_PATH,
128
+ error: err instanceof Error ? err.message : String(err),
129
+ });
130
+ }
131
+ }
132
+
133
+ export function loadConfigFile(): PiFreeConfig {
134
+ try {
135
+ return JSON.parse(readFileSync(CONFIG_PATH, "utf8")) as PiFreeConfig;
136
+ } catch (err) {
137
+ _logger.error("Could not parse config file returning empty config", {
138
+ path: CONFIG_PATH,
139
+ error: err instanceof Error ? err.message : String(err),
140
+ });
141
+ return {};
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Read the raw config file content without merging with template.
147
+ * Returns the file content as string, or undefined if unreadable.
148
+ */
149
+ function readRawConfigFile(): string | undefined {
150
+ try {
151
+ return readFileSync(CONFIG_PATH, "utf8");
152
+ } catch {
153
+ return undefined;
154
+ }
155
+ }
156
+
157
+ ensureConfigFile();
158
+
159
+ // Resolve each value: env var takes priority over config file.
160
+ function resolve(envKey: string, fileVal?: string): string | undefined {
161
+ return process.env[envKey] || (fileVal?.trim() ? fileVal : undefined);
162
+ }
163
+
164
+ // Resolve boolean flag: env var takes priority, then config file.
165
+ function resolveBool(envKey: string, fileVal?: boolean): boolean {
166
+ const envValue = process.env[envKey];
167
+ if (envValue === "true") return true;
168
+ if (envValue === "false") return false;
169
+ return fileVal === true;
170
+ }
171
+
172
+ // =============================================================================
173
+ // Per-provider paid-model flags (getters so toggles reflect immediately)
174
+ // =============================================================================
175
+
176
+ export function getKiloShowPaid(): boolean {
177
+ return resolveBool("KILO_SHOW_PAID", loadConfigFile().kilo_show_paid);
178
+ }
179
+
180
+ export function getClineShowPaid(): boolean {
181
+ return resolveBool("CLINE_SHOW_PAID", loadConfigFile().cline_show_paid);
182
+ }
183
+
184
+ export function getZenmuxShowPaid(): boolean {
185
+ return resolveBool("ZENMUX_SHOW_PAID", loadConfigFile().zenmux_show_paid);
186
+ }
187
+
188
+ export function getCrofaiShowPaid(): boolean {
189
+ return resolveBool("CROFAI_SHOW_PAID", loadConfigFile().crofai_show_paid);
190
+ }
191
+
192
+ export function getCodestralShowPaid(): boolean {
193
+ return resolveBool(
194
+ "CODESTRAL_SHOW_PAID",
195
+ loadConfigFile().codestral_show_paid,
196
+ );
197
+ }
198
+
199
+ export function getLlm7ShowPaid(): boolean {
200
+ return resolveBool("LLM7_SHOW_PAID", loadConfigFile().llm7_show_paid);
201
+ }
202
+
203
+ export function getDeepinfraShowPaid(): boolean {
204
+ return resolveBool(
205
+ "DEEPINFRA_SHOW_PAID",
206
+ loadConfigFile().deepinfra_show_paid,
207
+ );
208
+ }
209
+
210
+ export function getSambanovaShowPaid(): boolean {
211
+ return resolveBool(
212
+ "SAMBANOVA_SHOW_PAID",
213
+ loadConfigFile().sambanova_show_paid,
214
+ );
215
+ }
216
+
217
+ export function getTogetherShowPaid(): boolean {
218
+ return resolveBool("TOGETHER_SHOW_PAID", loadConfigFile().together_show_paid);
219
+ }
220
+
221
+ export function getNovitaShowPaid(): boolean {
222
+ return resolveBool("NOVITA_SHOW_PAID", loadConfigFile().novita_show_paid);
223
+ }
224
+
225
+ export function getFastrouterShowPaid(): boolean {
226
+ return resolveBool(
227
+ "FASTROUTER_SHOW_PAID",
228
+ loadConfigFile().fastrouter_show_paid,
229
+ );
230
+ }
231
+
232
+ export function getOllamaShowPaid(): boolean {
233
+ return resolveBool("OLLAMA_SHOW_PAID", loadConfigFile().ollama_show_paid);
234
+ }
235
+
236
+ export function getOpenrouterShowPaid(): boolean {
237
+ return resolveBool(
238
+ "OPENROUTER_SHOW_PAID",
239
+ loadConfigFile().openrouter_show_paid,
240
+ );
241
+ }
242
+
243
+ export function getOpencodeShowPaid(): boolean {
244
+ return resolveBool("OPENCODE_SHOW_PAID", loadConfigFile().opencode_show_paid);
245
+ }
246
+
247
+ export function getProviderShowPaid(providerId: string): boolean {
248
+ switch (providerId) {
249
+ case "kilo":
250
+ return getKiloShowPaid();
251
+ case "cline":
252
+ return getClineShowPaid();
253
+ case "zenmux":
254
+ return getZenmuxShowPaid();
255
+ case "crofai":
256
+ return getCrofaiShowPaid();
257
+ case "codestral":
258
+ return getCodestralShowPaid();
259
+ case "llm7":
260
+ return getLlm7ShowPaid();
261
+ case "deepinfra":
262
+ return getDeepinfraShowPaid();
263
+ case "sambanova":
264
+ return getSambanovaShowPaid();
265
+ case "together":
266
+ return getTogetherShowPaid();
267
+ case "novita":
268
+ return getNovitaShowPaid();
269
+ case "fastrouter":
270
+ return getFastrouterShowPaid();
271
+ case "ollama-cloud":
272
+ return getOllamaShowPaid();
273
+ case "openrouter":
274
+ return getOpenrouterShowPaid();
275
+ case "opencode":
276
+ return getOpencodeShowPaid();
277
+ default:
278
+ return false;
279
+ }
280
+ }
281
+
282
+ // =============================================================================
283
+ // Global free-only mode
284
+ // =============================================================================
285
+
286
+ export function getFreeOnly(): boolean {
287
+ return resolveBool("PI_FREE_ONLY", loadConfigFile().free_only);
288
+ }
289
+
290
+ export function getKiloFreeOnly(): boolean {
291
+ return resolveBool("PI_FREE_KILO_FREE_ONLY", loadConfigFile().kilo_free_only);
292
+ }
293
+
294
+ // =============================================================================
295
+ // API Keys (getters so runtime config changes are visible)
296
+ // =============================================================================
297
+
298
+ export function getNvidiaApiKey(): string | undefined {
299
+ return resolve("NVIDIA_API_KEY", loadConfigFile().nvidia_api_key);
300
+ }
301
+
302
+ export function getZenmuxApiKey(): string | undefined {
303
+ return resolve("ZENMUX_API_KEY", loadConfigFile().zenmux_api_key);
304
+ }
305
+
306
+ export function getCrofaiApiKey(): string | undefined {
307
+ return resolve("CROFAI_API_KEY", loadConfigFile().crofai_api_key);
308
+ }
309
+
310
+ export function getCodestralApiKey(): string | undefined {
311
+ return resolve("CODESTRAL_API_KEY", loadConfigFile().codestral_api_key);
312
+ }
313
+
314
+ export function getLlm7ApiKey(): string | undefined {
315
+ return resolve("LLM7_API_KEY", loadConfigFile().llm7_api_key);
316
+ }
317
+
318
+ export function getDeepinfraApiKey(): string | undefined {
319
+ return resolve("DEEPINFRA_TOKEN", loadConfigFile().deepinfra_api_key);
320
+ }
321
+
322
+ export function getSambanovaApiKey(): string | undefined {
323
+ return resolve("SAMBANOVA_API_KEY", loadConfigFile().sambanova_api_key);
324
+ }
325
+
326
+ export function getTogetherApiKey(): string | undefined {
327
+ return resolve("TOGETHER_AI_API_KEY", loadConfigFile().together_api_key);
328
+ }
329
+
330
+ export function getNovitaApiKey(): string | undefined {
331
+ return resolve("NOVITA_API_KEY", loadConfigFile().novita_api_key);
332
+ }
333
+
334
+ export function getFastrouterApiKey(): string | undefined {
335
+ return resolve("FASTROUTER_API_KEY", loadConfigFile().fastrouter_api_key);
336
+ }
337
+
338
+ export function getOllamaApiKey(): string | undefined {
339
+ return resolve("OLLAMA_API_KEY", loadConfigFile().ollama_api_key);
340
+ }
341
+
342
+ /** Mistral is pi's built-in provider — key comes from env var only. */
343
+ export function getMistralApiKey(): string | undefined {
344
+ return process.env.MISTRAL_API_KEY;
345
+ }
346
+
347
+ /** Groq is pi's built-in provider — key comes from env var only. */
348
+ export function getGroqApiKey(): string | undefined {
349
+ return process.env.GROQ_API_KEY;
350
+ }
351
+
352
+ /** Cerebras is pi's built-in provider — key comes from env var only. */
353
+ export function getCerebrasApiKey(): string | undefined {
354
+ return process.env.CEREBRAS_API_KEY;
355
+ }
356
+
357
+ /** xAI is pi's built-in provider — key comes from env var only. */
358
+ export function getXaiApiKey(): string | undefined {
359
+ return process.env.XAI_API_KEY;
360
+ }
361
+
362
+ /** HuggingFace is pi's built-in provider — token comes from env var only. */
363
+ export function getHfToken(): string | undefined {
364
+ return process.env.HF_TOKEN;
365
+ }
366
+
367
+ /**
368
+ * Read an API key from ~/.pi/agent/auth.json.
369
+ * Pi stores built-in provider keys there (opencode, openrouter, etc.).
370
+ * Falls back to env var if auth.json is missing or key not found.
371
+ */
372
+ function readAuthJsonKey(
373
+ providerId: string,
374
+ envVar: string,
375
+ ): string | undefined {
376
+ // Check env var first (fast path)
377
+ const envVal = process.env[envVar];
378
+ if (envVal) return envVal;
379
+
380
+ // Check auth.json
381
+ try {
382
+ const authPath = join(PI_DIR, "agent", "auth.json");
383
+ if (!existsSync(authPath)) return undefined;
384
+ const raw = readFileSync(authPath, "utf8");
385
+ const auth = JSON.parse(raw) as Record<
386
+ string,
387
+ { type?: string; key?: string }
388
+ >;
389
+ const entry = auth[providerId];
390
+ if (entry?.key?.trim()) return entry.key;
391
+ } catch {
392
+ // auth.json missing or corrupt — silently skip
393
+ }
394
+ return undefined;
395
+ }
396
+
397
+ /**
398
+ * OpenRouter key — pi's built-in provider reads from ~/.pi/agent/auth.json.
399
+ * pi-free checks env var first, then auth.json.
400
+ */
401
+ export function getOpenrouterApiKey(): string | undefined {
402
+ return readAuthJsonKey("openrouter", "OPENROUTER_API_KEY");
403
+ }
404
+
405
+ /** OpenCode key — pi's built-in provider. Read from env or auth.json. */
406
+ export function getOpencodeApiKey(): string | undefined {
407
+ return readAuthJsonKey("opencode", "OPENCODE_API_KEY");
408
+ }
409
+
410
+ // =============================================================================
411
+ // Hidden models (re-reads config on every call)
412
+ // =============================================================================
413
+
414
+ /**
415
+ * Apply hidden models filter with provider scoping.
416
+ * Hidden models can be specified as:
417
+ * - "model-id" (global, applies to all providers - deprecated)
418
+ * - "provider/model-id" (provider-specific, preferred)
419
+ */
420
+ export function applyHidden<T extends { id: string }>(
421
+ models: T[],
422
+ providerId?: string,
423
+ ): T[] {
424
+ const hidden = new Set(loadConfigFile().hidden_models ?? []);
425
+ if (hidden.size === 0) return models;
426
+
427
+ return models.filter((m) => {
428
+ // Check provider-scoped ID (preferred format: "provider/model-id")
429
+ if (providerId && hidden.has(`${providerId}/${m.id}`)) {
430
+ return false;
431
+ }
432
+ // Check global ID (legacy format, still supported for backward compat)
433
+ if (hidden.has(m.id)) {
434
+ return false;
435
+ }
436
+ return true;
437
+ });
438
+ }
439
+
440
+ // =============================================================================
441
+ // Persistence
442
+ // =============================================================================
443
+
444
+ export function saveConfig(updates: Partial<PiFreeConfig>): void {
445
+ try {
446
+ // Read the raw file content — never use loadConfigFile() here because
447
+ // if the file is unparseable, loadConfigFile() returns {} which would
448
+ // cause us to write a partial config and WIPE all existing keys.
449
+ const raw = readRawConfigFile();
450
+ if (raw === undefined) {
451
+ // File doesn't exist or can't be read — start from template
452
+ const merged = { ...CONFIG_TEMPLATE, ...updates };
453
+ writeFileSync(
454
+ CONFIG_PATH,
455
+ `${JSON.stringify(merged, null, 2)}\n`,
456
+ "utf8",
457
+ );
458
+ _logger.info("Config saved (new file)", {
459
+ path: CONFIG_PATH,
460
+ keys: Object.keys(updates),
461
+ });
462
+ return;
463
+ }
464
+
465
+ let existing: PiFreeConfig;
466
+ try {
467
+ existing = JSON.parse(raw) as PiFreeConfig;
468
+ } catch (parseErr) {
469
+ // File exists but is corrupt. REFUSE to overwrite it with a partial
470
+ // config — that would permanently destroy the user's keys.
471
+ _logger.error(
472
+ "REFUSING to save config — existing file is corrupt. Fix or delete ~/.pi/free.json manually.",
473
+ {
474
+ path: CONFIG_PATH,
475
+ error:
476
+ parseErr instanceof Error ? parseErr.message : String(parseErr),
477
+ },
478
+ );
479
+ return;
480
+ }
481
+
482
+ const merged = { ...existing, ...updates };
483
+ writeFileSync(CONFIG_PATH, `${JSON.stringify(merged, null, 2)}\n`, "utf8");
484
+ _logger.info("Config saved", {
485
+ path: CONFIG_PATH,
486
+ keys: Object.keys(updates),
487
+ });
488
+ } catch (err) {
489
+ _logger.error("Failed to save config", {
490
+ path: CONFIG_PATH,
491
+ error: err instanceof Error ? err.message : String(err),
492
+ });
493
+ }
494
+ }
495
+
496
+ export function getConfig(): PiFreeConfig {
497
+ return loadConfigFile();
498
+ }
499
+
500
+ // =============================================================================