pi-dynamic-providers 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 cybershape
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,82 @@
1
+ # pi-dynamic-providers
2
+
3
+ [![CI](https://github.com/cybershape/pi-dynamic-models/actions/workflows/ci.yml/badge.svg)](https://github.com/cybershape/pi-dynamic-models/actions/workflows/ci.yml)
4
+ [![npm version](https://img.shields.io/npm/v/pi-dynamic-providers.svg)](https://www.npmjs.com/package/pi-dynamic-providers)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ A [Pi coding agent](https://pi.dev) extension to automatically discover and register models from OpenAI-compatible endpoints (`/models`).
8
+
9
+ ## Features
10
+
11
+ - **Dynamic Model Discovery**: Queries the `/models` endpoint at startup and dynamically registers available models with the Pi provider registry.
12
+ - **Reasoning Model Support**: Automatically detects reasoning/thinking models (via `reasoning_efforts` metadata or naming heuristics) and sets up appropriate thinking levels.
13
+ - **Manual Hot-Reload**: Provides a `/refresh-models` command to reload the remote model catalog without restarting Pi.
14
+ - **Flexible Configuration**: Reads configuration from `~/.pi/agent/dynamic-models/config.json`.
15
+
16
+ ## Configuration
17
+
18
+ Create configuration in `~/.pi/agent/dynamic-models/config.json` (or `~/.pi/agents/dynamic-models/config.json`):
19
+
20
+ ```json
21
+ {
22
+ "baseUrl": "https://your-llm-proxy.example.com/v1",
23
+ "apiKey": "your-api-key-optional",
24
+ "providerId": "my-proxy",
25
+ "providerName": "Custom Proxy",
26
+ "defaultContextWindow": 400000,
27
+ "defaultMaxTokens": 8192
28
+ }
29
+ ```
30
+
31
+ ### Configuration Options
32
+
33
+ | Option | Type | Default | Description |
34
+ | --- | --- | --- | --- |
35
+ | `baseUrl` | `string` | *(required)* | Base URL for the OpenAI-compatible API endpoint |
36
+ | `apiKey` | `string` | `"dummy-key"` | Authorization token sent as Bearer header |
37
+ | `providerId` | `string` | `"dynamic-models"` | Unique ID for the registered provider in Pi |
38
+ | `providerName` | `string` | `"Dynamic Models"` | Friendly name for the provider displayed in Pi |
39
+ | `defaultContextWindow` | `number` | `400000` | Fallback context window when not reported by `/models` |
40
+ | `defaultMaxTokens` | `number` | `8192` | Fallback max tokens when not reported by `/models` |
41
+
42
+ ## Commands
43
+
44
+ - `/refresh-models`: Re-fetches the remote `/models` endpoint and updates registered models.
45
+
46
+ ## Installation
47
+
48
+ ### Via Pi Package Catalog / npm
49
+
50
+ ```bash
51
+ pi install npm:pi-dynamic-providers
52
+ ```
53
+
54
+ ### Via Git Repository
55
+
56
+ ```bash
57
+ pi install git:github.com/cybershape/pi-dynamic-models
58
+ ```
59
+
60
+ ### Try Without Installing
61
+
62
+ ```bash
63
+ pi -e git:github.com/cybershape/pi-dynamic-models
64
+ ```
65
+
66
+ ## Requirements
67
+
68
+ - Pi Coding Agent (`@earendil-works/pi-coding-agent`) `>= 0.80.0`
69
+ - Node.js `>= 20.0.0`
70
+
71
+ ## Development
72
+
73
+ Install dependencies and run checks:
74
+
75
+ ```bash
76
+ npm install
77
+ npm run check
78
+ ```
79
+
80
+ ## License
81
+
82
+ [MIT](LICENSE) © cybershape
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "pi-dynamic-providers",
3
+ "version": "0.0.1",
4
+ "description": "Pi extension to dynamically discover and register models from OpenAI-compatible endpoints",
5
+ "author": "cybershape",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/cybershape/pi-dynamic-models.git"
10
+ },
11
+ "homepage": "https://github.com/cybershape/pi-dynamic-models#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/cybershape/pi-dynamic-models/issues"
14
+ },
15
+ "type": "module",
16
+ "main": "./src/dynamic-models.ts",
17
+ "keywords": [
18
+ "pi-package",
19
+ "pi-extension",
20
+ "pi",
21
+ "models",
22
+ "dynamic-models",
23
+ "provider",
24
+ "openai-compatible",
25
+ "pi-coding-agent"
26
+ ],
27
+ "files": [
28
+ "LICENSE",
29
+ "README.md",
30
+ "src"
31
+ ],
32
+ "publishConfig": {
33
+ "access": "public",
34
+ "provenance": true
35
+ },
36
+ "scripts": {
37
+ "typecheck": "tsc --noEmit",
38
+ "check": "npm run typecheck",
39
+ "prepublishOnly": "npm run check"
40
+ },
41
+ "pi": {
42
+ "extensions": [
43
+ "./src/dynamic-models.ts"
44
+ ]
45
+ },
46
+ "peerDependencies": {
47
+ "@earendil-works/pi-coding-agent": "*"
48
+ },
49
+ "devDependencies": {
50
+ "@earendil-works/pi-coding-agent": "^0.80.3",
51
+ "@types/node": "^22.13.9",
52
+ "typescript": "^5.8.2"
53
+ }
54
+ }
@@ -0,0 +1,144 @@
1
+ import * as fs from "fs";
2
+ import * as os from "os";
3
+ import * as path from "path";
4
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
+
6
+ interface Config {
7
+ baseUrl: string;
8
+ apiKey?: string;
9
+ providerId?: string;
10
+ providerName?: string;
11
+ defaultContextWindow?: number;
12
+ defaultMaxTokens?: number;
13
+ }
14
+
15
+ interface RemoteModelItem {
16
+ id: string;
17
+ name?: string;
18
+ context_window?: number;
19
+ context_length?: number;
20
+ reasoning_efforts?: Array<{ value: string }>;
21
+ supported_in_api?: boolean;
22
+ }
23
+
24
+ /**
25
+ * Load configuration from ~/.pi/agent/dynamic-models/config.json or ~/.pi/agents/dynamic-models/config.json
26
+ */
27
+ function loadConfig(): Config | null {
28
+ const possiblePaths = [
29
+ path.join(os.homedir(), ".pi", "agent", "dynamic-models", "config.json"),
30
+ path.join(os.homedir(), ".pi", "agents", "dynamic-models", "config.json"),
31
+ ];
32
+
33
+ for (const p of possiblePaths) {
34
+ if (fs.existsSync(p)) {
35
+ try {
36
+ const raw = fs.readFileSync(p, "utf-8");
37
+ return JSON.parse(raw) as Config;
38
+ } catch (err: any) {
39
+ console.error(`[dynamic-models] Failed to parse config file (${p}): ${err?.message}`);
40
+ return null;
41
+ }
42
+ }
43
+ }
44
+
45
+ console.warn(`[dynamic-models] Config file not found: ${possiblePaths[0]}`);
46
+ return null;
47
+ }
48
+
49
+ /**
50
+ * Fetch and register models from remote /models endpoint
51
+ */
52
+ async function syncModels(pi: ExtensionAPI): Promise<number> {
53
+ const config = loadConfig();
54
+ if (!config?.baseUrl) return 0;
55
+
56
+ const providerId = config.providerId || "dynamic-models";
57
+ const providerName = config.providerName || "Dynamic Models";
58
+ const apiKey = config.apiKey || "dummy-key";
59
+ const endpoint = `${config.baseUrl.replace(/\/+$/, "")}/models`;
60
+ const defaultContextWindow = config.defaultContextWindow || 400000;
61
+ const defaultMaxTokens = config.defaultMaxTokens || 8192;
62
+
63
+ try {
64
+ const res = await fetch(endpoint, {
65
+ headers: {
66
+ Authorization: `Bearer ${apiKey}`,
67
+ },
68
+ });
69
+
70
+ if (!res.ok) {
71
+ throw new Error(`HTTP ${res.status}: ${res.statusText}`);
72
+ }
73
+
74
+ const payload = (await res.json()) as { data?: RemoteModelItem[] };
75
+ const rawList = Array.isArray(payload?.data) ? payload.data : [];
76
+
77
+ const models = rawList
78
+ .filter((m) => m.supported_in_api !== false)
79
+ .map((m) => {
80
+ const isReasoning =
81
+ (Array.isArray(m.reasoning_efforts) && m.reasoning_efforts.length > 0) ||
82
+ m.id.toLowerCase().includes("thinking") ||
83
+ (m.name ? m.name.toLowerCase().includes("thinking") : false);
84
+
85
+ const contextWindow = m.context_window || m.context_length || defaultContextWindow;
86
+
87
+ return {
88
+ id: m.id,
89
+ name: m.name || m.id,
90
+ reasoning: isReasoning,
91
+ ...(isReasoning && {
92
+ thinkingLevelMap: {
93
+ xhigh: "xhigh",
94
+ max: "max",
95
+ },
96
+ }),
97
+ input: ["text", "image"] as ("text" | "image")[],
98
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
99
+ contextWindow,
100
+ maxTokens: Math.min(contextWindow, defaultMaxTokens),
101
+ // compat must be placed on each model: registerProvider provider-level config has no compat field,
102
+ // and applyExtension does not merge provider-level configs into models.
103
+ // Without this, reasoning models may send system prompts with developer role and be rejected upstream.
104
+ compat: {
105
+ supportsDeveloperRole: false,
106
+ },
107
+ };
108
+ });
109
+
110
+ if (models.length > 0) {
111
+ pi.registerProvider(providerId, {
112
+ name: providerName,
113
+ baseUrl: config.baseUrl,
114
+ apiKey: apiKey,
115
+ api: "openai-completions",
116
+ models,
117
+ });
118
+ }
119
+
120
+ return models.length;
121
+ } catch (err: any) {
122
+ console.warn(`[dynamic-models] Failed to sync models: ${err?.message}`);
123
+ return 0;
124
+ }
125
+ }
126
+
127
+ export default async function (pi: ExtensionAPI) {
128
+ // Automatically fetch and register models at startup
129
+ await syncModels(pi);
130
+
131
+ // Register slash command for runtime manual refresh
132
+ pi.registerCommand("refresh-models", {
133
+ description: "Re-sync models from ~/.pi/agent/dynamic-models/config.json",
134
+ handler: async (_args, ctx) => {
135
+ ctx.ui.notify("Fetching latest models...", "info");
136
+ const count = await syncModels(pi);
137
+ if (count > 0) {
138
+ ctx.ui.notify(`Sync successful! Registered ${count} model(s).`, "info");
139
+ } else {
140
+ ctx.ui.notify("Failed to fetch models or no valid models found. Please check configuration and network.", "warning");
141
+ }
142
+ },
143
+ });
144
+ }