pi-free 2.2.2 → 2.2.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-free",
3
- "version": "2.2.2",
3
+ "version": "2.2.3",
4
4
  "type": "module",
5
5
  "description": "AI model providers for Pi with free model filtering and dynamic model fetching",
6
6
  "keywords": [
@@ -1,237 +1,237 @@
1
- /**
2
- * B.AI Provider Extension
3
- *
4
- * B.AI (https://b.ai) is an OpenAI-compatible LLM gateway providing access
5
- * to many models (OpenAI, Anthropic, Google, DeepSeek, Qwen, GLM, Kimi).
6
- *
7
- * API: https://api.b.ai/v1
8
- * Models: /v1/models
9
- * Chat: /v1/chat/completions
10
- *
11
- * Pricing is not exposed via the /v1/models endpoint, so all models
12
- * default to cost=0. The `isFreeModel` Route B detection (name contains
13
- * "free") is therefore used. As a result, with `free_only: true` no b.ai
14
- * models will be visible until you run `/toggle-bai` to enable paid models.
15
- *
16
- * A small set of known-promotional models are hardcoded as known-free so
17
- * they remain visible even when free-only mode is on (mirrors the
18
- * TokenRouter approach for `MiniMax-M3`).
19
- *
20
- * Setup:
21
- * BAI_API_KEY=sk-...
22
- * # or add bai_api_key to ~/.pi/free.json
23
- */
24
-
25
- import type {
26
- ExtensionAPI,
27
- ProviderModelConfig,
28
- } from "@earendil-works/pi-coding-agent";
29
- import { getBaiApiKey, getBaiShowPaid, applyHidden } from "../../config.ts";
30
- import {
31
- BASE_URL_BAI,
32
- DEFAULT_FETCH_TIMEOUT_MS,
33
- PROVIDER_BAI,
34
- } from "../../constants.ts";
35
- import { createLogger } from "../../lib/logger.ts";
36
- import { safeEnrichModelsWithModelsDev } from "../../lib/model-metadata.ts";
37
- import {
38
- getProxyModelCompat,
39
- isLikelyReasoningModel,
40
- } from "../../lib/provider-compat.ts";
41
- import { isFreeModel, registerWithGlobalToggle } from "../../lib/registry.ts";
42
- import { cleanModelName, fetchWithRetry } from "../../lib/util.ts";
43
- import { createReRegister, setupProvider } from "../../provider-helper.ts";
44
-
45
- const _logger = createLogger("bai");
46
-
47
- // =============================================================================
48
- // Known Free Models
49
- // B.AI doesn't expose pricing via /v1/models, so known-free models are
50
- // hardcoded. The site currently advertises `MiniMax-M3` as a limited-time
51
- // free promotional model; we hardcode that alias and any future `:free`
52
- // suffixed IDs (catches dynamic promotional additions).
53
- // =============================================================================
54
-
55
- const BAI_KNOWN_FREE_MODELS = new Set(["minimax-m3", "MiniMax-M3"]);
56
-
57
- function isBaiKnownFree(modelId: string): boolean {
58
- if (BAI_KNOWN_FREE_MODELS.has(modelId)) return true;
59
- // Catch any future `:free` suffixed model the gateway advertises
60
- return modelId.toLowerCase().endsWith(":free");
61
- }
62
-
63
- // =============================================================================
64
- // Types
65
- // =============================================================================
66
-
67
- interface BaiModel {
68
- id: string;
69
- object?: string;
70
- created?: number;
71
- owned_by?: string;
72
- supported_endpoint_types?: string[];
73
- }
74
-
75
- // =============================================================================
76
- // Helpers
77
- // =============================================================================
78
-
79
- /** Text-capable chat endpoints (excludes image/video/audio-only types) */
80
- const CHAT_ENDPOINT_TYPES = new Set([
81
- "openai",
82
- "openai-response",
83
- "anthropic",
84
- "anthropic-compatible",
85
- "gemini",
86
- ]);
87
-
88
- function isTextChatModel(model: BaiModel): boolean {
89
- const endpoints = model.supported_endpoint_types ?? [];
90
- if (endpoints.length === 0) {
91
- // No endpoint info — assume text chat (matches TokenRouter fallback)
92
- return true;
93
- }
94
- return endpoints.some((t) => CHAT_ENDPOINT_TYPES.has(t));
95
- }
96
-
97
- function mapBaiModel(model: BaiModel): ProviderModelConfig & {
98
- _pricingKnown?: boolean;
99
- _freeKnown?: boolean;
100
- _isFree?: boolean;
101
- } {
102
- const name = cleanModelName(model.id);
103
- const reasoning = isLikelyReasoningModel({ id: model.id, name });
104
- const isKnownFree = isBaiKnownFree(model.id);
105
-
106
- return {
107
- id: model.id,
108
- name,
109
- reasoning,
110
- input: ["text"],
111
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
112
- contextWindow: 128_000,
113
- maxTokens: 16_384,
114
- compat: getProxyModelCompat({ id: model.id, name }),
115
- // Known-free models bypass name-based detection entirely
116
- _freeKnown: isKnownFree,
117
- _isFree: isKnownFree,
118
- // Non-free models signal no pricing data (name-based detection only)
119
- _pricingKnown: false,
120
- } as ProviderModelConfig & {
121
- _pricingKnown?: boolean;
122
- _freeKnown?: boolean;
123
- _isFree?: boolean;
124
- };
125
- }
126
-
127
- // =============================================================================
128
- // Fetch Models
129
- // =============================================================================
130
-
131
- async function fetchBaiModels(apiKey: string): Promise<ProviderModelConfig[]> {
132
- _logger.info("[bai] Fetching models from B.AI API...");
133
-
134
- try {
135
- const response = await fetchWithRetry(
136
- `${BASE_URL_BAI}/models`,
137
- {
138
- headers: {
139
- Authorization: `Bearer ${apiKey}`,
140
- Accept: "application/json",
141
- "Content-Type": "application/json",
142
- },
143
- },
144
- 3,
145
- 1000,
146
- DEFAULT_FETCH_TIMEOUT_MS,
147
- );
148
-
149
- if (!response.ok) {
150
- throw new Error(`B.AI API error: ${response.status}`);
151
- }
152
-
153
- const json = (await response.json()) as { data?: BaiModel[] };
154
- const models = (json.data ?? []).filter(isTextChatModel);
155
-
156
- _logger.info(`[bai] Fetched ${models.length} text chat models`);
157
- const enriched = await safeEnrichModelsWithModelsDev(
158
- models.map(mapBaiModel),
159
- { providerId: PROVIDER_BAI },
160
- );
161
- return applyHidden(enriched, PROVIDER_BAI);
162
- } catch (error) {
163
- _logger.error("[bai] Failed to fetch models", {
164
- error: error instanceof Error ? error.message : String(error),
165
- });
166
- return [];
167
- }
168
- }
169
-
170
- // =============================================================================
171
- // Extension Entry Point
172
- // =============================================================================
173
-
174
- export default async function baiProvider(pi: ExtensionAPI) {
175
- const apiKey = getBaiApiKey();
176
-
177
- if (!apiKey) {
178
- _logger.info(
179
- "[bai] Skipping — BAI_API_KEY not set. Sign up at https://b.ai/",
180
- );
181
- return;
182
- }
183
-
184
- const allModels = await fetchBaiModels(apiKey);
185
-
186
- if (allModels.length === 0) {
187
- // Either the API failed (already logged inside fetchBaiModels) or
188
- // the API returned zero text chat models. We can't tell the user
189
- // which, but we can give a hint to check the log / their key.
190
- _logger.warn(
191
- "[bai] No text chat models available — verify BAI_API_KEY is valid and see ~/.pi/free.log for details",
192
- );
193
- return;
194
- }
195
-
196
- // Use isFreeModel with allModels for proper detection
197
- // B.AI doesn't expose pricing, so Route B (name-based) applies:
198
- // FREE if name contains "free" OR _isFree is true (known-free hardcoded).
199
- const freeModels = allModels.filter((m) =>
200
- isFreeModel({ ...m, provider: PROVIDER_BAI }, allModels),
201
- );
202
- const stored = { free: freeModels, all: allModels };
203
-
204
- _logger.info(
205
- `[bai] Registered ${allModels.length} models (${freeModels.length} free)`,
206
- );
207
-
208
- const reRegister = createReRegister(pi, {
209
- providerId: PROVIDER_BAI,
210
- baseUrl: BASE_URL_BAI,
211
- apiKey,
212
- });
213
-
214
- registerWithGlobalToggle(PROVIDER_BAI, stored, reRegister, true);
215
-
216
- setupProvider(
217
- pi,
218
- {
219
- providerId: PROVIDER_BAI,
220
- initialShowPaid: getBaiShowPaid(),
221
- tosUrl: "https://b.ai/",
222
- reRegister: (models, _stored) => {
223
- if (_stored) {
224
- stored.free = _stored.free;
225
- stored.all = _stored.all;
226
- }
227
- reRegister(models);
228
- },
229
- },
230
- stored,
231
- );
232
-
233
- const showPaid = getBaiShowPaid();
234
- const initialModels =
235
- showPaid && stored.all.length > 0 ? stored.all : freeModels;
236
- reRegister(initialModels);
237
- }
1
+ /**
2
+ * B.AI Provider Extension
3
+ *
4
+ * B.AI (https://b.ai) is an OpenAI-compatible LLM gateway providing access
5
+ * to many models (OpenAI, Anthropic, Google, DeepSeek, Qwen, GLM, Kimi).
6
+ *
7
+ * API: https://api.b.ai/v1
8
+ * Models: /v1/models
9
+ * Chat: /v1/chat/completions
10
+ *
11
+ * Pricing is not exposed via the /v1/models endpoint, so all models
12
+ * default to cost=0. The `isFreeModel` Route B detection (name contains
13
+ * "free") is therefore used. As a result, with `free_only: true` no b.ai
14
+ * models will be visible until you run `/toggle-bai` to enable paid models.
15
+ *
16
+ * A small set of known-promotional models are hardcoded as known-free so
17
+ * they remain visible even when free-only mode is on (mirrors the
18
+ * TokenRouter approach for `MiniMax-M3`).
19
+ *
20
+ * Setup:
21
+ * BAI_API_KEY=sk-...
22
+ * # or add bai_api_key to ~/.pi/free.json
23
+ */
24
+
25
+ import type {
26
+ ExtensionAPI,
27
+ ProviderModelConfig,
28
+ } from "@earendil-works/pi-coding-agent";
29
+ import { getBaiApiKey, getBaiShowPaid, applyHidden } from "../../config.ts";
30
+ import {
31
+ BASE_URL_BAI,
32
+ DEFAULT_FETCH_TIMEOUT_MS,
33
+ PROVIDER_BAI,
34
+ } from "../../constants.ts";
35
+ import { createLogger } from "../../lib/logger.ts";
36
+ import { safeEnrichModelsWithModelsDev } from "../../lib/model-metadata.ts";
37
+ import {
38
+ getProxyModelCompat,
39
+ isLikelyReasoningModel,
40
+ } from "../../lib/provider-compat.ts";
41
+ import { isFreeModel, registerWithGlobalToggle } from "../../lib/registry.ts";
42
+ import { cleanModelName, fetchWithRetry } from "../../lib/util.ts";
43
+ import { createReRegister, setupProvider } from "../../provider-helper.ts";
44
+
45
+ const _logger = createLogger("bai");
46
+
47
+ // =============================================================================
48
+ // Known Free Models
49
+ // B.AI doesn't expose pricing via /v1/models, so known-free models are
50
+ // hardcoded. The site currently advertises `MiniMax-M3` as a limited-time
51
+ // free promotional model; we hardcode that alias and any future `:free`
52
+ // suffixed IDs (catches dynamic promotional additions).
53
+ // =============================================================================
54
+
55
+ const BAI_KNOWN_FREE_MODELS = new Set(["minimax-m3", "MiniMax-M3"]);
56
+
57
+ function isBaiKnownFree(modelId: string): boolean {
58
+ if (BAI_KNOWN_FREE_MODELS.has(modelId)) return true;
59
+ // Catch any future `:free` suffixed model the gateway advertises
60
+ return modelId.toLowerCase().endsWith(":free");
61
+ }
62
+
63
+ // =============================================================================
64
+ // Types
65
+ // =============================================================================
66
+
67
+ interface BaiModel {
68
+ id: string;
69
+ object?: string;
70
+ created?: number;
71
+ owned_by?: string;
72
+ supported_endpoint_types?: string[];
73
+ }
74
+
75
+ // =============================================================================
76
+ // Helpers
77
+ // =============================================================================
78
+
79
+ /** Text-capable chat endpoints (excludes image/video/audio-only types) */
80
+ const CHAT_ENDPOINT_TYPES = new Set([
81
+ "openai",
82
+ "openai-response",
83
+ "anthropic",
84
+ "anthropic-compatible",
85
+ "gemini",
86
+ ]);
87
+
88
+ function isTextChatModel(model: BaiModel): boolean {
89
+ const endpoints = model.supported_endpoint_types ?? [];
90
+ if (endpoints.length === 0) {
91
+ // No endpoint info — assume text chat (matches TokenRouter fallback)
92
+ return true;
93
+ }
94
+ return endpoints.some((t) => CHAT_ENDPOINT_TYPES.has(t));
95
+ }
96
+
97
+ function mapBaiModel(model: BaiModel): ProviderModelConfig & {
98
+ _pricingKnown?: boolean;
99
+ _freeKnown?: boolean;
100
+ _isFree?: boolean;
101
+ } {
102
+ const name = cleanModelName(model.id);
103
+ const reasoning = isLikelyReasoningModel({ id: model.id, name });
104
+ const isKnownFree = isBaiKnownFree(model.id);
105
+
106
+ return {
107
+ id: model.id,
108
+ name,
109
+ reasoning,
110
+ input: ["text"],
111
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
112
+ contextWindow: 128_000,
113
+ maxTokens: 16_384,
114
+ compat: getProxyModelCompat({ id: model.id, name }),
115
+ // Known-free models bypass name-based detection entirely
116
+ _freeKnown: isKnownFree,
117
+ _isFree: isKnownFree,
118
+ // Non-free models signal no pricing data (name-based detection only)
119
+ _pricingKnown: false,
120
+ } as ProviderModelConfig & {
121
+ _pricingKnown?: boolean;
122
+ _freeKnown?: boolean;
123
+ _isFree?: boolean;
124
+ };
125
+ }
126
+
127
+ // =============================================================================
128
+ // Fetch Models
129
+ // =============================================================================
130
+
131
+ async function fetchBaiModels(apiKey: string): Promise<ProviderModelConfig[]> {
132
+ _logger.info("[bai] Fetching models from B.AI API...");
133
+
134
+ try {
135
+ const response = await fetchWithRetry(
136
+ `${BASE_URL_BAI}/models`,
137
+ {
138
+ headers: {
139
+ Authorization: `Bearer ${apiKey}`,
140
+ Accept: "application/json",
141
+ "Content-Type": "application/json",
142
+ },
143
+ },
144
+ 3,
145
+ 1000,
146
+ DEFAULT_FETCH_TIMEOUT_MS,
147
+ );
148
+
149
+ if (!response.ok) {
150
+ throw new Error(`B.AI API error: ${response.status}`);
151
+ }
152
+
153
+ const json = (await response.json()) as { data?: BaiModel[] };
154
+ const models = (json.data ?? []).filter(isTextChatModel);
155
+
156
+ _logger.info(`[bai] Fetched ${models.length} text chat models`);
157
+ const enriched = await safeEnrichModelsWithModelsDev(
158
+ models.map(mapBaiModel),
159
+ { providerId: PROVIDER_BAI },
160
+ );
161
+ return applyHidden(enriched, PROVIDER_BAI);
162
+ } catch (error) {
163
+ _logger.error("[bai] Failed to fetch models", {
164
+ error: error instanceof Error ? error.message : String(error),
165
+ });
166
+ return [];
167
+ }
168
+ }
169
+
170
+ // =============================================================================
171
+ // Extension Entry Point
172
+ // =============================================================================
173
+
174
+ export default async function baiProvider(pi: ExtensionAPI) {
175
+ const apiKey = getBaiApiKey();
176
+
177
+ if (!apiKey) {
178
+ _logger.info(
179
+ "[bai] Skipping — BAI_API_KEY not set. Sign up at https://b.ai/",
180
+ );
181
+ return;
182
+ }
183
+
184
+ const allModels = await fetchBaiModels(apiKey);
185
+
186
+ if (allModels.length === 0) {
187
+ // Either the API failed (already logged inside fetchBaiModels) or
188
+ // the API returned zero text chat models. We can't tell the user
189
+ // which, but we can give a hint to check the log / their key.
190
+ _logger.warn(
191
+ "[bai] No text chat models available — verify BAI_API_KEY is valid and see ~/.pi/free.log for details",
192
+ );
193
+ return;
194
+ }
195
+
196
+ // Use isFreeModel with allModels for proper detection
197
+ // B.AI doesn't expose pricing, so Route B (name-based) applies:
198
+ // FREE if name contains "free" OR _isFree is true (known-free hardcoded).
199
+ const freeModels = allModels.filter((m) =>
200
+ isFreeModel({ ...m, provider: PROVIDER_BAI }, allModels),
201
+ );
202
+ const stored = { free: freeModels, all: allModels };
203
+
204
+ _logger.info(
205
+ `[bai] Registered ${allModels.length} models (${freeModels.length} free)`,
206
+ );
207
+
208
+ const reRegister = createReRegister(pi, {
209
+ providerId: PROVIDER_BAI,
210
+ baseUrl: BASE_URL_BAI,
211
+ apiKey,
212
+ });
213
+
214
+ registerWithGlobalToggle(PROVIDER_BAI, stored, reRegister, true);
215
+
216
+ setupProvider(
217
+ pi,
218
+ {
219
+ providerId: PROVIDER_BAI,
220
+ initialShowPaid: getBaiShowPaid(),
221
+ tosUrl: "https://b.ai/",
222
+ reRegister: (models, _stored) => {
223
+ if (_stored) {
224
+ stored.free = _stored.free;
225
+ stored.all = _stored.all;
226
+ }
227
+ reRegister(models);
228
+ },
229
+ },
230
+ stored,
231
+ );
232
+
233
+ const showPaid = getBaiShowPaid();
234
+ const initialModels =
235
+ showPaid && stored.all.length > 0 ? stored.all : freeModels;
236
+ reRegister(initialModels);
237
+ }