pi-free 2.0.2 → 2.0.4

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.
@@ -1,101 +1,101 @@
1
- /**
2
- * Qwen OAuth model definitions.
3
- *
4
- * @deprecated The 1,000 req/day free tier is no longer available. Auth is broken.
5
- * This provider remains for backward compatibility but should not be used.
6
- */
7
-
8
- import type { ProviderModelConfig } from "@mariozechner/pi-coding-agent";
9
- import { createLogger } from "../../lib/logger.ts";
10
-
11
- const _logger = createLogger("qwen-models");
12
-
13
- /**
14
- * portal.qwen.ai compatibility settings.
15
- *
16
- * portal.qwen.ai's OpenAI-compatible API does not support several parameters
17
- * that the pi framework sends by default.
18
- */
19
- export const PORTAL_COMPAT: NonNullable<ProviderModelConfig["compat"]> = {
20
- supportsStore: false,
21
- supportsDeveloperRole: false,
22
- supportsReasoningEffort: false,
23
- supportsUsageInStreaming: false,
24
- supportsStrictMode: false,
25
- maxTokensField: "max_tokens",
26
- };
27
-
28
- /**
29
- * Fallback model used before OAuth completes or if model discovery fails.
30
- * The real model ID is resolved dynamically via fetchQwenLiveModels() after auth.
31
- */
32
- export const QWEN_FREE_MODELS: ProviderModelConfig[] = [
33
- {
34
- id: "coder-model",
35
- name: "Qwen Coder — DEPRECATED (free tier discontinued)",
36
- reasoning: false,
37
- input: ["text"],
38
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
39
- contextWindow: 131_072,
40
- maxTokens: 16_384,
41
- compat: PORTAL_COMPAT,
42
- },
43
- ];
44
-
45
- /**
46
- * Fetch Qwen models. Returns static model list for backward compatibility.
47
- * @deprecated Qwen free tier is discontinued.
48
- */
49
- export async function fetchQwenModels(): Promise<ProviderModelConfig[]> {
50
- _logger.info("Qwen provider is deprecated, returning placeholder models");
51
- return QWEN_FREE_MODELS;
52
- }
53
-
54
- /**
55
- * Fetch live model list from the Qwen API using the OAuth access token.
56
- * Returns updated models with real IDs from the server, or the original
57
- * models unchanged if the request fails.
58
- */
59
- export async function fetchQwenLiveModels(
60
- baseUrl: string,
61
- accessToken: string,
62
- templateModels: ProviderModelConfig[],
63
- ): Promise<ProviderModelConfig[]> {
64
- try {
65
- const response = await fetch(`${baseUrl}/models`, {
66
- headers: {
67
- Authorization: `Bearer ${accessToken}`,
68
- Accept: "application/json",
69
- },
70
- });
71
-
72
- if (!response.ok) {
73
- _logger.info("Qwen /v1/models fetch failed, keeping current model IDs", {
74
- status: response.status,
75
- });
76
- return templateModels;
77
- }
78
-
79
- interface ModelEntry {
80
- id: string;
81
- }
82
- const data = (await response.json()) as { data?: ModelEntry[] };
83
- const ids: string[] = (data.data ?? [])
84
- .map((m: ModelEntry) => m.id)
85
- .filter(Boolean);
86
-
87
- _logger.info("Qwen live models discovered", { ids });
88
-
89
- if (ids.length === 0) return templateModels;
90
-
91
- // Prefer a coder model if available, otherwise use the first model
92
- const preferred = ids.find((id) => /coder/i.test(id)) ?? ids[0];
93
-
94
- return templateModels.map((m) => ({ ...m, id: preferred }));
95
- } catch (err) {
96
- _logger.info("Qwen live model fetch error, keeping current model IDs", {
97
- error: String(err),
98
- });
99
- return templateModels;
100
- }
101
- }
1
+ /**
2
+ * Qwen OAuth model definitions.
3
+ *
4
+ * @deprecated The 1,000 req/day free tier is no longer available. Auth is broken.
5
+ * This provider remains for backward compatibility but should not be used.
6
+ */
7
+
8
+ import type { ProviderModelConfig } from "@mariozechner/pi-coding-agent";
9
+ import { createLogger } from "../../lib/logger.ts";
10
+
11
+ const _logger = createLogger("qwen-models");
12
+
13
+ /**
14
+ * portal.qwen.ai compatibility settings.
15
+ *
16
+ * portal.qwen.ai's OpenAI-compatible API does not support several parameters
17
+ * that the pi framework sends by default.
18
+ */
19
+ export const PORTAL_COMPAT: NonNullable<ProviderModelConfig["compat"]> = {
20
+ supportsStore: false,
21
+ supportsDeveloperRole: false,
22
+ supportsReasoningEffort: false,
23
+ supportsUsageInStreaming: false,
24
+ supportsStrictMode: false,
25
+ maxTokensField: "max_tokens",
26
+ };
27
+
28
+ /**
29
+ * Fallback model used before OAuth completes or if model discovery fails.
30
+ * The real model ID is resolved dynamically via fetchQwenLiveModels() after auth.
31
+ */
32
+ export const QWEN_FREE_MODELS: ProviderModelConfig[] = [
33
+ {
34
+ id: "coder-model",
35
+ name: "Qwen Coder — DEPRECATED (free tier discontinued)",
36
+ reasoning: false,
37
+ input: ["text"],
38
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
39
+ contextWindow: 131_072,
40
+ maxTokens: 16_384,
41
+ compat: PORTAL_COMPAT,
42
+ },
43
+ ];
44
+
45
+ /**
46
+ * Fetch Qwen models. Returns static model list for backward compatibility.
47
+ * @deprecated Qwen free tier is discontinued.
48
+ */
49
+ export async function fetchQwenModels(): Promise<ProviderModelConfig[]> {
50
+ _logger.info("Qwen provider is deprecated, returning placeholder models");
51
+ return QWEN_FREE_MODELS;
52
+ }
53
+
54
+ /**
55
+ * Fetch live model list from the Qwen API using the OAuth access token.
56
+ * Returns updated models with real IDs from the server, or the original
57
+ * models unchanged if the request fails.
58
+ */
59
+ export async function fetchQwenLiveModels(
60
+ baseUrl: string,
61
+ accessToken: string,
62
+ templateModels: ProviderModelConfig[],
63
+ ): Promise<ProviderModelConfig[]> {
64
+ try {
65
+ const response = await fetch(`${baseUrl}/models`, {
66
+ headers: {
67
+ Authorization: `Bearer ${accessToken}`,
68
+ Accept: "application/json",
69
+ },
70
+ });
71
+
72
+ if (!response.ok) {
73
+ _logger.info("Qwen /v1/models fetch failed, keeping current model IDs", {
74
+ status: response.status,
75
+ });
76
+ return templateModels;
77
+ }
78
+
79
+ interface ModelEntry {
80
+ id: string;
81
+ }
82
+ const data = (await response.json()) as { data?: ModelEntry[] };
83
+ const ids: string[] = (data.data ?? [])
84
+ .map((m: ModelEntry) => m.id)
85
+ .filter(Boolean);
86
+
87
+ _logger.info("Qwen live models discovered", { ids });
88
+
89
+ if (ids.length === 0) return templateModels;
90
+
91
+ // Prefer a coder model if available, otherwise use the first model
92
+ const preferred = ids.find((id) => /coder/i.test(id)) ?? ids[0];
93
+
94
+ return templateModels.map((m) => ({ ...m, id: preferred }));
95
+ } catch (err) {
96
+ _logger.info("Qwen live model fetch error, keeping current model IDs", {
97
+ error: String(err),
98
+ });
99
+ return templateModels;
100
+ }
101
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * ZenMux Provider Extension
3
+ *
4
+ * Provides access to ZenMux AI gateway - unified API for 200+ models from
5
+ * OpenAI, Anthropic, Google, and other providers.
6
+ *
7
+ * Setup:
8
+ * 1. Get API key from https://zenmux.ai
9
+ * 2. Set ZENMUX_API_KEY env var or add to ~/.pi/free.json
10
+ *
11
+ * Responds to global free-only filter.
12
+ *
13
+ * Usage:
14
+ * pi install git:github.com/apmantza/pi-free
15
+ * # Set ZENMUX_API_KEY env var
16
+ * # Models appear in /model selector
17
+ */
18
+
19
+ import type {
20
+ ExtensionAPI,
21
+ ProviderModelConfig,
22
+ } from "@mariozechner/pi-coding-agent";
23
+ import { getZenmuxApiKey, getZenmuxShowPaid } from "../../config.ts";
24
+ import {
25
+ BASE_URL_ZENMUX,
26
+ DEFAULT_FETCH_TIMEOUT_MS,
27
+ PROVIDER_ZENMUX,
28
+ } from "../../constants.ts";
29
+ import { createLogger } from "../../lib/logger.ts";
30
+ import {
31
+ getProxyModelCompat,
32
+ isLikelyReasoningModel,
33
+ } from "../../lib/provider-compat.ts";
34
+ import { isFreeModel, registerWithGlobalToggle } from "../../lib/registry.ts";
35
+ import { fetchWithRetry } from "../../lib/util.ts";
36
+ import { createReRegister, setupProvider } from "../../provider-helper.ts";
37
+
38
+ const _logger = createLogger("zenmux");
39
+
40
+ // =============================================================================
41
+ // Fetch ZenMux models
42
+ // =============================================================================
43
+
44
+ interface ZenMuxModel {
45
+ id: string;
46
+ name?: string;
47
+ context_length?: number;
48
+ pricing?: {
49
+ prompt?: number;
50
+ completion?: number;
51
+ };
52
+ }
53
+
54
+ function isZenmuxReasoningModel(model: Pick<ZenMuxModel, "id" | "name">) {
55
+ const haystack = `${model.id} ${model.name ?? ""}`.toLowerCase();
56
+ return isLikelyReasoningModel(model) || haystack.includes("claude");
57
+ }
58
+
59
+ async function fetchZenmuxModels(
60
+ apiKey: string,
61
+ ): Promise<ProviderModelConfig[]> {
62
+ _logger.info("[zenmux] Fetching models from ZenMux API...");
63
+
64
+ try {
65
+ const response = await fetchWithRetry(
66
+ `${BASE_URL_ZENMUX}/models`,
67
+ {
68
+ headers: {
69
+ Authorization: `Bearer ${apiKey}`,
70
+ "Content-Type": "application/json",
71
+ },
72
+ },
73
+ 3,
74
+ 1000,
75
+ DEFAULT_FETCH_TIMEOUT_MS,
76
+ );
77
+
78
+ if (!response.ok) {
79
+ throw new Error(`ZenMux API error: ${response.status}`);
80
+ }
81
+
82
+ const data = (await response.json()) as { data?: ZenMuxModel[] };
83
+ const models = data.data ?? [];
84
+
85
+ _logger.info(`[zenmux] Fetched ${models.length} models`);
86
+
87
+ return models.map(
88
+ (m): ProviderModelConfig => ({
89
+ id: m.id,
90
+ name: m.name || m.id,
91
+ reasoning: isZenmuxReasoningModel(m),
92
+ input: ["text"],
93
+ cost: {
94
+ input: m.pricing?.prompt || 0,
95
+ output: m.pricing?.completion || 0,
96
+ cacheRead: 0,
97
+ cacheWrite: 0,
98
+ },
99
+ contextWindow: m.context_length || 128000,
100
+ maxTokens: m.context_length ? Math.floor(m.context_length / 2) : 4096,
101
+ compat: getProxyModelCompat(m),
102
+ }),
103
+ );
104
+ } catch (error) {
105
+ _logger.error("[zenmux] Failed to fetch models:", {
106
+ error: error instanceof Error ? error.message : String(error),
107
+ });
108
+ return [];
109
+ }
110
+ }
111
+
112
+ // =============================================================================
113
+ // Extension Entry Point
114
+ // =============================================================================
115
+
116
+ export default async function zenmuxProvider(pi: ExtensionAPI) {
117
+ const apiKey = getZenmuxApiKey();
118
+
119
+ if (!apiKey) {
120
+ _logger.info(
121
+ "[zenmux] Skipping - ZENMUX_API_KEY not set (env var or ~/.pi/free.json)",
122
+ );
123
+ return;
124
+ }
125
+
126
+ // Fetch models
127
+ const allModels = await fetchZenmuxModels(apiKey);
128
+
129
+ if (allModels.length === 0) {
130
+ _logger.warn("[zenmux] No models available");
131
+ return;
132
+ }
133
+
134
+ // Use isFreeModel with allModels for proper detection
135
+ // ZenMux exposes pricing, so Route A (OR logic) will be used:
136
+ // FREE if cost=0 OR "free" in name
137
+ const freeModels = allModels.filter((m) =>
138
+ isFreeModel({ ...m, provider: PROVIDER_ZENMUX }, allModels),
139
+ );
140
+
141
+ const stored = { free: freeModels, all: allModels };
142
+
143
+ _logger.info(
144
+ `[zenmux] Registered ${allModels.length} models (${freeModels.length} free)`,
145
+ );
146
+
147
+ // Create re-register function
148
+ const reRegister = createReRegister(pi, {
149
+ providerId: PROVIDER_ZENMUX,
150
+ baseUrl: BASE_URL_ZENMUX,
151
+ apiKey,
152
+ });
153
+
154
+ // Register with global toggle
155
+ registerWithGlobalToggle(PROVIDER_ZENMUX, stored, reRegister, true);
156
+
157
+ // Setup provider with toggle command
158
+ setupProvider(
159
+ pi,
160
+ {
161
+ providerId: PROVIDER_ZENMUX,
162
+ initialShowPaid: getZenmuxShowPaid(),
163
+ reRegister: (models, _stored) => {
164
+ if (_stored) {
165
+ stored.free = _stored.free;
166
+ stored.all = _stored.all;
167
+ }
168
+ reRegister(models);
169
+ },
170
+ },
171
+ stored,
172
+ );
173
+
174
+ // Initial registration
175
+ reRegister(freeModels);
176
+ }
@@ -7,48 +7,51 @@
7
7
  * node scripts/check-extensions.mjs <dir> # from installed location
8
8
  */
9
9
 
10
- import { readFileSync, readdirSync, statSync } from "node:fs";
11
- import { join, resolve, dirname } from "node:path";
12
10
  import { execSync } from "node:child_process";
11
+ import { readdirSync, readFileSync, statSync } from "node:fs";
12
+ import { dirname, join, resolve } from "node:path";
13
13
 
14
14
  const installDir = resolve(process.argv[2] ?? ".");
15
15
  const fromSource = process.argv[2] == null;
16
16
 
17
17
  function getFiles() {
18
- if (fromSource) {
19
- // Use npm pack --dry-run to get exactly the files that would be published
20
- const out = execSync("npm pack --dry-run 2>&1", { encoding: "utf8" });
21
- return out
22
- .split("\n")
23
- .map(l => l.match(/npm notice [\d.]+\w+\s+(.+)/)?.[1]?.trim())
24
- .filter(f => f && (f.endsWith(".ts") || f.endsWith(".mjs")))
25
- .map(f => join(installDir, f));
26
- }
27
- // Installed location: walk all .ts/.mjs files
28
- const files = [];
29
- function walk(dir) {
30
- for (const entry of readdirSync(dir)) {
31
- const full = join(dir, entry);
32
- if (entry === "node_modules") continue;
33
- if (statSync(full).isDirectory()) walk(full);
34
- else if (entry.endsWith(".ts") || entry.endsWith(".mjs")) files.push(full);
35
- }
36
- }
37
- walk(installDir);
38
- return files;
18
+ if (fromSource) {
19
+ // Use npm pack --dry-run to get exactly the files that would be published
20
+ const out = execSync("npm pack --dry-run 2>&1", { encoding: "utf8" });
21
+ return out
22
+ .split("\n")
23
+ .map((l) => l.match(/npm notice \S+\s+(.+)/)?.[1]?.trim())
24
+ .filter((f) => f && (f.endsWith(".ts") || f.endsWith(".mjs")))
25
+ .map((f) => join(installDir, f));
26
+ }
27
+ // Installed location: walk all .ts/.mjs files
28
+ const files = [];
29
+ function walk(dir) {
30
+ for (const entry of readdirSync(dir)) {
31
+ const full = join(dir, entry);
32
+ if (entry === "node_modules") continue;
33
+ if (statSync(full).isDirectory()) walk(full);
34
+ else if (entry.endsWith(".ts") || entry.endsWith(".mjs"))
35
+ files.push(full);
36
+ }
37
+ }
38
+ walk(installDir);
39
+ return files;
39
40
  }
40
41
 
41
42
  function resolveImport(fromFile, importPath) {
42
- const base = join(dirname(fromFile), importPath);
43
- for (const candidate of [
44
- base,
45
- base.replace(/\.js$/, ".ts"), // .js → .ts (TypeScript ESM convention)
46
- base + ".ts",
47
- join(base, "index.ts"),
48
- ]) {
49
- try { if (statSync(candidate).isFile()) return candidate; } catch {}
50
- }
51
- return null;
43
+ const base = join(dirname(fromFile), importPath);
44
+ for (const candidate of [
45
+ base,
46
+ base.replace(/\.js$/, ".ts"), // .js → .ts (TypeScript ESM convention)
47
+ base + ".ts",
48
+ join(base, "index.ts"),
49
+ ]) {
50
+ try {
51
+ if (statSync(candidate).isFile()) return candidate;
52
+ } catch {}
53
+ }
54
+ return null;
52
55
  }
53
56
 
54
57
  const files = getFiles();
@@ -59,29 +62,35 @@ let failed = 0;
59
62
  const seen = new Set();
60
63
 
61
64
  for (const file of files) {
62
- const src = readFileSync(file, "utf8");
63
- const relFile = file.slice(installDir.length + 1).replace(/\\/g, "/");
64
- // Strip comments before matching imports
65
- const stripped = src.replace(/\/\/[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
66
- const importRe = /from\s+['"](\.[^'"]+)['"]/g;
67
- let match;
68
- while ((match = importRe.exec(stripped)) !== null) {
69
- const importPath = match[1];
70
- const key = `${relFile}:${importPath}`;
71
- if (seen.has(key)) continue;
72
- seen.add(key);
73
- totalImports++;
74
- if (!resolveImport(file, importPath)) {
75
- console.error(` ✗ ${relFile}`);
76
- console.error(` imports '${importPath}' → NOT FOUND`);
77
- failed++;
78
- }
79
- }
65
+ const src = readFileSync(file, "utf8");
66
+ const relFile = file.slice(installDir.length + 1).replace(/\\/g, "/");
67
+ // Strip comments before matching imports
68
+ const stripped = src
69
+ .replace(/\/\/[^\n]*/g, "")
70
+ .replace(/\/\*[\s\S]*?\*\//g, "");
71
+ const importRe = /from\s+['"](\.[^'"]+)['"]/g;
72
+ let match;
73
+ while ((match = importRe.exec(stripped)) !== null) {
74
+ const importPath = match[1];
75
+ const key = `${relFile}:${importPath}`;
76
+ if (seen.has(key)) continue;
77
+ seen.add(key);
78
+ totalImports++;
79
+ if (!resolveImport(file, importPath)) {
80
+ console.error(` ✗ ${relFile}`);
81
+ console.error(` imports '${importPath}' → NOT FOUND`);
82
+ failed++;
83
+ }
84
+ }
80
85
  }
81
86
 
82
- console.log(`Checked ${totalImports} relative import(s) across ${files.length} file(s).`);
83
- console.log(failed === 0
84
- ? `\nAll imports resolve OK ✓`
85
- : `\n${failed} import(s) could not be resolved ✗`);
87
+ console.log(
88
+ `Checked ${totalImports} relative import(s) across ${files.length} file(s).`,
89
+ );
90
+ console.log(
91
+ failed === 0
92
+ ? `\nAll imports resolve OK ✓`
93
+ : `\n${failed} import(s) could not be resolved ✗`,
94
+ );
86
95
 
87
96
  process.exit(failed > 0 ? 1 : 0);