@2tle/pi-provider-manager 0.1.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.
Files changed (4) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +148 -0
  3. package/index.ts +673 -0
  4. package/package.json +16 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,148 @@
1
+ # Pi Provider Manager
2
+
3
+ An extension for registering and managing OpenAI-compatible API providers in Pi Agent.
4
+
5
+ When working with local LLM servers, private gateways, proxies, or hosted APIs, managing each provider through `models.json` and restarting Pi can be cumbersome. This extension keeps managed providers and their model catalogs in one place.
6
+
7
+ ## Features
8
+
9
+ - Add OpenAI-compatible providers from the Pi TUI
10
+ - List managed providers without exposing API keys
11
+ - Edit a provider's display name, Base URL, or API key
12
+ - Refresh one provider's model catalog or every managed catalog
13
+ - Delete a managed provider and its stored API key
14
+ - Keep provider metadata and credentials in separate files
15
+
16
+ ## Commands
17
+
18
+ ### Add a provider
19
+
20
+ ```text
21
+ /provider add
22
+ ```
23
+
24
+ The interactive flow requests:
25
+
26
+ 1. Provider ID — lowercase letters, numbers, `.`, `_`, and `-` only
27
+ 2. Provider display name
28
+ 3. OpenAI-compatible Base URL — for example, `http://localhost:1234/v1`
29
+ 4. API key — local servers can use a placeholder such as `local`
30
+
31
+ After the provider is added, its `/models` endpoint is queried immediately.
32
+
33
+ ### List managed providers
34
+
35
+ ```text
36
+ /provider list
37
+ ```
38
+
39
+ Displays each provider's ID, display name, Base URL, API key status, and the number of currently loaded models. API key values are never displayed.
40
+
41
+ ### Edit a provider
42
+
43
+ ```text
44
+ /provider edit <provider_name>
45
+ ```
46
+
47
+ Use a provider ID (recommended) or a unique display name. Select the fields to change, then choose **Save changes**. The extension refreshes the provider's model catalog after saving.
48
+
49
+ In TUI mode, API key input is masked with `*` characters. In RPC mode, the connected client is responsible for secret masking.
50
+
51
+ ### Refresh model catalogs
52
+
53
+ ```text
54
+ /provider reload <provider_name>
55
+ /provider reload --all
56
+ ```
57
+
58
+ The extension sends a request to `<baseUrl>/models` and accepts the OpenAI-style response shape:
59
+
60
+ ```json
61
+ {
62
+ "data": [{ "id": "model-name" }]
63
+ }
64
+ ```
65
+
66
+ This is different from Pi's `/reload`, which reloads extension code and resources.
67
+
68
+ ### Delete a provider
69
+
70
+ ```text
71
+ /provider delete <provider_name>
72
+ ```
73
+
74
+ After confirmation, the extension removes the managed provider and its stored API key. Built-in providers and providers owned by other extensions cannot be deleted.
75
+
76
+ ## Supported APIs
77
+
78
+ The extension targets OpenAI Chat Completions-compatible services that provide a model-listing endpoint and support Pi's OpenAI-compatible transport, including:
79
+
80
+ - OpenAI-compatible gateways and proxies
81
+ - vLLM
82
+ - LM Studio
83
+ - llama.cpp server
84
+ - Ollama's OpenAI-compatible endpoint
85
+ - Private or internal LLM gateways
86
+
87
+ Provider implementations differ in support for developer roles, reasoning options, token fields, and streaming usage. This extension currently uses Pi's standard `openai-completions` transport.
88
+
89
+ ## Stored configuration
90
+
91
+ Provider metadata and API keys are stored separately:
92
+
93
+ ```text
94
+ ~/.pi/agent/pi-provider-manager.json
95
+ ~/.pi/agent/pi-provider-manager-secrets.json
96
+ ```
97
+
98
+ The first file contains provider IDs, display names, and Base URLs. The second contains API keys. The extension creates its directory with `0700` permissions and the secrets file with `0600` permissions. API keys are not included in model-list output or notifications.
99
+
100
+ ## Operational behavior
101
+
102
+ - Provider IDs are stable identifiers. `/provider edit` changes the display name, Base URL, and API key, but does not rename the provider ID.
103
+ - Cancelling the edit menu discards all unsaved changes.
104
+ - Saving an edit persists the new settings first, then refreshes that provider's model catalog. A failed catalog refresh does not discard an otherwise valid saved edit.
105
+ - `/provider list` reports the model count currently loaded in Pi. It can be `0` before a successful refresh.
106
+ - The extension starts by refreshing every managed provider with a 30-second timeout per refresh operation.
107
+
108
+ ## Development
109
+
110
+ Install dependencies from the repository root:
111
+
112
+ ```bash
113
+ npm install
114
+ ```
115
+
116
+ Run only this local extension during development:
117
+
118
+ ```bash
119
+ pi -ne -e .
120
+ ```
121
+
122
+ For a single-file load:
123
+
124
+ ```bash
125
+ pi -ne -e ./index.ts
126
+ ```
127
+
128
+ After changing code, run `/reload` in Pi or restart Pi. To refresh model catalogs without reloading the extension, use:
129
+
130
+ ```text
131
+ /provider reload --all
132
+ ```
133
+
134
+ To register the package in Pi's user settings instead of passing `-e` every time:
135
+
136
+ ```bash
137
+ pi install "$PWD"
138
+ ```
139
+
140
+ ## Security
141
+
142
+ Pi extensions can run with full system permissions. Review source code and packages before installing them.
143
+
144
+ Protect API keys, refresh tokens, custom authorization headers, and sensitive endpoint query parameters. The extension avoids printing raw API keys and sends only the credential required for model-list requests.
145
+
146
+ ## License
147
+
148
+ Licensed under the [Apache License 2.0](LICENSE).
package/index.ts ADDED
@@ -0,0 +1,673 @@
1
+ import { homedir } from "node:os";
2
+ import { dirname, join } from "node:path";
3
+ import { chmod, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
4
+ import type { RefreshModelsContext } from "@earendil-works/pi-ai";
5
+ import { DynamicBorder, keyHint, type ExtensionAPI, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
6
+ import { Container, CURSOR_MARKER, getKeybindings, Input, Spacer, Text, truncateToWidth } from "@earendil-works/pi-tui";
7
+
8
+ const CONFIG_PATH = join(homedir(), ".pi", "agent", "pi-provider-manager.json");
9
+ const SECRETS_PATH = join(homedir(), ".pi", "agent", "pi-provider-manager-secrets.json");
10
+ const API = "openai-completions" as const;
11
+ const DEFAULT_CONTEXT_WINDOW = 128_000;
12
+ const DEFAULT_MAX_TOKENS = 16_384;
13
+ const REFRESH_TIMEOUT_MS = 30_000;
14
+
15
+ interface StoredProvider {
16
+ id: string;
17
+ name: string;
18
+ baseUrl: string;
19
+ }
20
+
21
+ interface StoredState {
22
+ providers: StoredProvider[];
23
+ }
24
+
25
+ interface StoredSecrets {
26
+ apiKeys: Record<string, string>;
27
+ }
28
+
29
+ interface ProviderModelConfig {
30
+ id: string;
31
+ name: string;
32
+ api: typeof API;
33
+ reasoning: boolean;
34
+ input: ("text" | "image")[];
35
+ cost: {
36
+ input: number;
37
+ output: number;
38
+ cacheRead: number;
39
+ cacheWrite: number;
40
+ };
41
+ contextWindow: number;
42
+ maxTokens: number;
43
+ }
44
+
45
+ interface ManagedProviderConfig {
46
+ name: string;
47
+ baseUrl: string;
48
+ api: typeof API;
49
+ apiKey: string;
50
+ models: ProviderModelConfig[];
51
+ refreshModels(context: RefreshModelsContext): Promise<ProviderModelConfig[]>;
52
+ }
53
+
54
+ interface OpenAIModelPayload {
55
+ id?: unknown;
56
+ name?: unknown;
57
+ context_window?: unknown;
58
+ contextWindow?: unknown;
59
+ max_tokens?: unknown;
60
+ maxTokens?: unknown;
61
+ reasoning?: unknown;
62
+ supports_reasoning?: unknown;
63
+ input?: unknown;
64
+ cost?: unknown;
65
+ }
66
+
67
+ interface OpenAIModelsPayload {
68
+ data?: unknown;
69
+ }
70
+
71
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
72
+ return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : undefined;
73
+ }
74
+
75
+ function asNonEmptyString(value: unknown): string | undefined {
76
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
77
+ }
78
+
79
+ function asPositiveNumber(value: unknown, fallback: number): number {
80
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
81
+ }
82
+
83
+ function normalizeBaseUrl(value: string): string {
84
+ return value.trim().replace(/\/+$/, "");
85
+ }
86
+
87
+ function validateProviderId(id: string): void {
88
+ if (!/^[a-z0-9][a-z0-9._-]*$/.test(id)) {
89
+ throw new Error("Provider ID may contain only lowercase letters, numbers, '.', '_' or '-'.");
90
+ }
91
+ }
92
+
93
+ function validateBaseUrl(value: string): string {
94
+ const baseUrl = normalizeBaseUrl(value);
95
+ let parsed: URL;
96
+ try {
97
+ parsed = new URL(baseUrl);
98
+ } catch {
99
+ throw new Error("Base URL is not a valid URL.");
100
+ }
101
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
102
+ throw new Error("Base URL must use the http or https protocol.");
103
+ }
104
+ return baseUrl;
105
+ }
106
+
107
+ function modelsUrl(baseUrl: string): string {
108
+ return new URL("models", `${normalizeBaseUrl(baseUrl)}/`).toString();
109
+ }
110
+
111
+ async function loadState(): Promise<StoredState> {
112
+ try {
113
+ const raw = await readFile(CONFIG_PATH, "utf8");
114
+ const parsed = asRecord(JSON.parse(raw));
115
+ const providers = Array.isArray(parsed?.providers) ? parsed.providers : [];
116
+ const normalized: StoredProvider[] = [];
117
+ for (const item of providers) {
118
+ const record = asRecord(item);
119
+ const id = asNonEmptyString(record?.id);
120
+ const name = asNonEmptyString(record?.name);
121
+ const baseUrl = asNonEmptyString(record?.baseUrl);
122
+ if (!id || !name || !baseUrl) continue;
123
+ try {
124
+ validateProviderId(id);
125
+ normalized.push({ id, name, baseUrl: validateBaseUrl(baseUrl) });
126
+ } catch {
127
+ // Ignore malformed entries so one broken provider does not prevent startup.
128
+ }
129
+ }
130
+ return { providers: normalized };
131
+ } catch (error) {
132
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
133
+ return { providers: [] };
134
+ }
135
+ throw new Error(`Unable to read provider configuration: ${error instanceof Error ? error.message : String(error)}`);
136
+ }
137
+ }
138
+
139
+ async function loadSecrets(): Promise<StoredSecrets> {
140
+ try {
141
+ const raw = await readFile(SECRETS_PATH, "utf8");
142
+ const parsed = asRecord(JSON.parse(raw));
143
+ const apiKeys: Record<string, string> = {};
144
+ const rawApiKeys = asRecord(parsed?.apiKeys);
145
+ for (const [id, value] of Object.entries(rawApiKeys ?? {})) {
146
+ if (typeof value === "string" && value.trim()) apiKeys[id] = value;
147
+ }
148
+ return { apiKeys };
149
+ } catch (error) {
150
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
151
+ return { apiKeys: {} };
152
+ }
153
+ throw new Error(`Unable to read provider API keys: ${error instanceof Error ? error.message : String(error)}`);
154
+ }
155
+ }
156
+
157
+ async function saveJsonFile(path: string, value: object): Promise<void> {
158
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
159
+ const temporaryPath = `${path}.${process.pid}.${Date.now()}.tmp`;
160
+ const content = `${JSON.stringify(value, null, 2)}\n`;
161
+ try {
162
+ await writeFile(temporaryPath, content, { encoding: "utf8", mode: 0o600 });
163
+ await chmod(temporaryPath, 0o600);
164
+ await rename(temporaryPath, path);
165
+ } finally {
166
+ await unlink(temporaryPath).catch(() => undefined);
167
+ }
168
+ }
169
+
170
+ async function saveState(state: StoredState): Promise<void> {
171
+ await saveJsonFile(CONFIG_PATH, state);
172
+ }
173
+
174
+ async function saveSecrets(secrets: StoredSecrets): Promise<void> {
175
+ await saveJsonFile(SECRETS_PATH, secrets);
176
+ }
177
+
178
+ function modelFromPayload(
179
+ provider: StoredProvider,
180
+ payload: OpenAIModelPayload,
181
+ ): ProviderModelConfig | undefined {
182
+ const id = asNonEmptyString(payload.id);
183
+ if (!id) return undefined;
184
+
185
+ const cost = asRecord(payload.cost);
186
+ const input: ("text" | "image")[] =
187
+ Array.isArray(payload.input) && payload.input.includes("image") ? ["text", "image"] : ["text"];
188
+
189
+ return {
190
+ id,
191
+ name: asNonEmptyString(payload.name) ?? id,
192
+ api: API,
193
+ reasoning: payload.reasoning === true || payload.supports_reasoning === true,
194
+ input,
195
+ cost: {
196
+ input: asPositiveNumber(cost?.input, 0),
197
+ output: asPositiveNumber(cost?.output, 0),
198
+ cacheRead: asPositiveNumber(cost?.cacheRead, 0),
199
+ cacheWrite: asPositiveNumber(cost?.cacheWrite, 0),
200
+ },
201
+ contextWindow: asPositiveNumber(payload.context_window ?? payload.contextWindow, DEFAULT_CONTEXT_WINDOW),
202
+ maxTokens: asPositiveNumber(payload.max_tokens ?? payload.maxTokens, DEFAULT_MAX_TOKENS),
203
+ };
204
+ }
205
+
206
+ async function fetchProviderModels(
207
+ provider: StoredProvider,
208
+ context: RefreshModelsContext,
209
+ getApiKey: () => string | undefined,
210
+ ): Promise<ProviderModelConfig[]> {
211
+ const apiKey = getApiKey();
212
+ if (!apiKey) {
213
+ throw new Error(`API key for provider '${provider.id}' is not configured.`);
214
+ }
215
+
216
+ const response = await fetch(modelsUrl(provider.baseUrl), {
217
+ signal: context.signal,
218
+ headers: {
219
+ Accept: "application/json",
220
+ Authorization: `Bearer ${apiKey}`,
221
+ },
222
+ });
223
+
224
+ if (!response.ok) {
225
+ throw new Error(`Failed to fetch model list (${response.status} ${response.statusText})`);
226
+ }
227
+
228
+ const payload = (await response.json()) as OpenAIModelsPayload | unknown[];
229
+ const data = Array.isArray(payload) ? payload : asRecord(payload)?.data;
230
+ if (!Array.isArray(data)) {
231
+ throw new Error("Model list response does not contain a data array.");
232
+ }
233
+
234
+ return data
235
+ .map((item) => {
236
+ const record = asRecord(item);
237
+ return record ? modelFromPayload(provider, record as OpenAIModelPayload) : undefined;
238
+ })
239
+ .filter((model): model is ProviderModelConfig => model !== undefined);
240
+ }
241
+
242
+ function createManagedProvider(
243
+ config: StoredProvider,
244
+ getApiKey: () => string | undefined,
245
+ ): ManagedProviderConfig {
246
+ return {
247
+ name: config.name,
248
+ baseUrl: config.baseUrl,
249
+ api: API,
250
+ // The API key is held outside the regular provider config and is only
251
+ // read when the provider is registered or refreshed.
252
+ apiKey: getApiKey() ?? "local",
253
+ models: [],
254
+ refreshModels: (context) => fetchProviderModels(config, context, getApiKey),
255
+ };
256
+ }
257
+
258
+ export function maskInputLine(line: string): string {
259
+ const prompt = line.startsWith("> ") ? "> " : "";
260
+ let result = "";
261
+ for (let index = prompt.length; index < line.length; ) {
262
+ // Keep Input's zero-width APC cursor marker intact. Masking only CSI/SGR
263
+ // codes previously turned the marker bytes into visible bullets.
264
+ if (line.startsWith(CURSOR_MARKER, index)) {
265
+ result += CURSOR_MARKER;
266
+ index += CURSOR_MARKER.length;
267
+ continue;
268
+ }
269
+
270
+ if (line[index] === "\x1b") {
271
+ const ansi = line.slice(index).match(/^\x1b\[[0-9;?]*[ -/]*[@-~]/)?.[0];
272
+ if (ansi) {
273
+ result += ansi;
274
+ index += ansi.length;
275
+ continue;
276
+ }
277
+ }
278
+
279
+ const character = line[index++];
280
+ result += /\s/u.test(character) ? character : "*";
281
+ }
282
+ return prompt + result;
283
+ }
284
+
285
+ class MaskedInput extends Input {
286
+ override render(width: number): string[] {
287
+ const terminalWidth = process.stdout.columns;
288
+ const safeWidth = Math.max(1, Number.isFinite(terminalWidth) ? Math.min(width, terminalWidth) : width);
289
+ return super.render(safeWidth).map((line) => truncateToWidth(maskInputLine(line), safeWidth, "", false));
290
+ }
291
+ }
292
+
293
+ class SecretInputDialog extends Container {
294
+ private readonly input = new MaskedInput();
295
+ private _focused = false;
296
+
297
+ constructor(
298
+ done: (value: string | undefined) => void,
299
+ title: string,
300
+ helpText: string,
301
+ border: (text: string) => string,
302
+ ) {
303
+ super();
304
+ // Match Pi's built-in ctx.ui.input() layout while keeping the secret masked.
305
+ this.addChild(new DynamicBorder(border));
306
+ this.addChild(new Spacer(1));
307
+ this.addChild(new Text(title, 1, 0));
308
+ this.addChild(new Spacer(1));
309
+ this.addChild(this.input);
310
+ this.addChild(new Spacer(1));
311
+ this.addChild(new Text(helpText, 1, 0));
312
+ this.addChild(new Spacer(1));
313
+ this.addChild(new DynamicBorder(border));
314
+ this.done = done;
315
+ }
316
+
317
+ private readonly done: (value: string | undefined) => void;
318
+
319
+ get focused(): boolean {
320
+ return this._focused;
321
+ }
322
+
323
+ set focused(value: boolean) {
324
+ this._focused = value;
325
+ this.input.focused = value;
326
+ }
327
+
328
+ handleInput(data: string): void {
329
+ const keybindings = getKeybindings();
330
+ if (keybindings.matches(data, "tui.select.confirm") || data === "\n") {
331
+ this.done(this.input.getValue());
332
+ } else if (keybindings.matches(data, "tui.select.cancel")) {
333
+ this.done(undefined);
334
+ } else {
335
+ this.input.handleInput(data);
336
+ }
337
+ }
338
+ }
339
+
340
+ function parseArgs(args: string): string[] {
341
+ return args.trim().split(/\s+/).filter(Boolean);
342
+ }
343
+
344
+ function usage(): string {
345
+ return [
346
+ "Usage:",
347
+ " /provider add",
348
+ " /provider list",
349
+ " /provider edit <provider_name>",
350
+ " /provider reload --all",
351
+ " /provider reload <provider_name>",
352
+ " /provider delete <provider_name>",
353
+ ].join("\n");
354
+ }
355
+
356
+ function commandNotify(ctx: ExtensionCommandContext, message: string, type: "info" | "warning" | "error" = "info"): void {
357
+ if (ctx.hasUI) ctx.ui.notify(message, type);
358
+ }
359
+
360
+ async function refreshProviders(
361
+ ctx: ExtensionCommandContext,
362
+ providerIds: readonly string[],
363
+ ): Promise<void> {
364
+ if (providerIds.length === 0) {
365
+ commandNotify(ctx, "No providers to refresh.", "warning");
366
+ return;
367
+ }
368
+
369
+ const signal = AbortSignal.timeout(REFRESH_TIMEOUT_MS);
370
+ const result = await ctx.modelRegistry.refresh({
371
+ providers: providerIds,
372
+ allowNetwork: true,
373
+ force: true,
374
+ signal,
375
+ });
376
+
377
+ if (result.aborted) {
378
+ throw new Error("Model list refresh was cancelled or timed out.");
379
+ }
380
+
381
+ const messages: string[] = [];
382
+ for (const providerId of providerIds) {
383
+ const error = result.errors.get(providerId);
384
+ if (error) {
385
+ messages.push(`${providerId}: failed — ${error.message}`);
386
+ continue;
387
+ }
388
+ const provider = ctx.modelRegistry.getProvider(providerId);
389
+ const count = provider?.getModels().length ?? 0;
390
+ messages.push(`${providerId}: ${count} model${count === 1 ? "" : "s"}`);
391
+ }
392
+
393
+ const failed = result.errors.size > 0;
394
+ commandNotify(ctx, `Model list refresh complete\n${messages.join("\n")}`, failed ? "warning" : "info");
395
+ }
396
+
397
+ async function promptForProvider(ctx: ExtensionCommandContext): Promise<StoredProvider | undefined> {
398
+ if (!ctx.hasUI) throw new Error("/provider add requires an interactive UI.");
399
+
400
+ const id = (await ctx.ui.input("Provider ID", "e.g. lmstudio"))?.trim();
401
+ if (!id) return undefined;
402
+ validateProviderId(id);
403
+
404
+ const name = (await ctx.ui.input("Provider display name", id))?.trim() || id;
405
+ const baseUrlInput = await ctx.ui.input("OpenAI-compatible Base URL", "e.g. http://localhost:1234/v1");
406
+ if (!baseUrlInput?.trim()) return undefined;
407
+
408
+ return { id, name, baseUrl: validateBaseUrl(baseUrlInput) };
409
+ }
410
+
411
+ async function promptForApiKey(ctx: ExtensionCommandContext): Promise<string | undefined> {
412
+ if (!ctx.hasUI) throw new Error("API key entry requires an interactive UI.");
413
+
414
+ const apiKey =
415
+ ctx.mode === "tui"
416
+ ? await ctx.ui.custom<string | undefined>((_tui, theme, _keybindings, done) =>
417
+ new SecretInputDialog(
418
+ done,
419
+ theme.fg("accent", "API key"),
420
+ `${keyHint("tui.select.confirm", "submit")} ${keyHint("tui.select.cancel", "cancel")}`,
421
+ (text: string) => theme.fg("accent", text),
422
+ ),
423
+ )
424
+ : await ctx.ui.input("API key", "sk-... or local");
425
+
426
+ if (apiKey === undefined) return undefined;
427
+ if (!apiKey.trim()) throw new Error("API key cannot be empty.");
428
+ return apiKey;
429
+ }
430
+
431
+ interface ProviderEdit {
432
+ provider: StoredProvider;
433
+ apiKey?: string;
434
+ }
435
+
436
+ async function promptForProviderEdit(
437
+ ctx: ExtensionCommandContext,
438
+ provider: StoredProvider,
439
+ ): Promise<ProviderEdit | undefined> {
440
+ if (!ctx.hasUI) throw new Error("/provider edit requires an interactive UI.");
441
+
442
+ let updatedProvider = { ...provider };
443
+ let updatedApiKey: string | undefined;
444
+
445
+ while (true) {
446
+ const choice = await ctx.ui.select(`Edit provider: ${provider.id}`, [
447
+ `Change display name (${updatedProvider.name})`,
448
+ `Change Base URL (${updatedProvider.baseUrl})`,
449
+ "Change API key",
450
+ "Save changes",
451
+ ]);
452
+ if (choice === undefined) return undefined;
453
+ if (choice === "Save changes") return { provider: updatedProvider, apiKey: updatedApiKey };
454
+
455
+ if (choice.startsWith("Change display name")) {
456
+ const name = await ctx.ui.input("Provider display name", `Current value: ${updatedProvider.name}`);
457
+ if (name?.trim()) updatedProvider = { ...updatedProvider, name: name.trim() };
458
+ continue;
459
+ }
460
+
461
+ if (choice.startsWith("Change Base URL")) {
462
+ const baseUrlInput = await ctx.ui.input("OpenAI-compatible Base URL", `Current value: ${updatedProvider.baseUrl}`);
463
+ if (!baseUrlInput?.trim()) continue;
464
+ try {
465
+ updatedProvider = { ...updatedProvider, baseUrl: validateBaseUrl(baseUrlInput) };
466
+ } catch (error) {
467
+ commandNotify(ctx, error instanceof Error ? error.message : String(error), "error");
468
+ }
469
+ continue;
470
+ }
471
+
472
+ const apiKey = await promptForApiKey(ctx);
473
+ if (apiKey !== undefined) updatedApiKey = apiKey;
474
+ }
475
+ }
476
+
477
+ function findManagedProvider(managed: ReadonlyMap<string, StoredProvider>, name: string): StoredProvider | undefined {
478
+ const providerById = managed.get(name);
479
+ if (providerById) return providerById;
480
+
481
+ const matches = [...managed.values()].filter((provider) => provider.name === name);
482
+ if (matches.length > 1) {
483
+ throw new Error(`Multiple providers have the display name '${name}'. Use a provider ID instead.`);
484
+ }
485
+ return matches[0];
486
+ }
487
+
488
+ function providerListMessage(
489
+ providers: readonly StoredProvider[],
490
+ secrets: StoredSecrets,
491
+ ctx: ExtensionCommandContext,
492
+ ): string {
493
+ if (providers.length === 0) return "No managed providers.";
494
+
495
+ return ["Managed providers:", ...providers.map((provider) => {
496
+ const modelCount = ctx.modelRegistry.getProvider(provider.id)?.getModels().length ?? 0;
497
+ const apiKeyStatus = secrets.apiKeys[provider.id] ? "configured" : "missing";
498
+ return `- ${provider.id} (${provider.name})\n Base URL: ${provider.baseUrl}\n API key: ${apiKeyStatus} · Models: ${modelCount}`;
499
+ })].join("\n");
500
+ }
501
+
502
+ export default async function (pi: ExtensionAPI) {
503
+ const state = await loadState();
504
+ const secrets = await loadSecrets();
505
+ const managed = new Map<string, StoredProvider>();
506
+
507
+ for (const provider of state.providers) {
508
+ if (managed.has(provider.id)) continue;
509
+ managed.set(provider.id, provider);
510
+ pi.registerProvider(provider.id, createManagedProvider(provider, () => secrets.apiKeys[provider.id]));
511
+ }
512
+
513
+ pi.registerCommand("provider", {
514
+ description: "Add, list, edit, refresh, and delete OpenAI-compatible providers",
515
+ handler: async (args, ctx) => {
516
+ try {
517
+ const [subcommand, ...rest] = parseArgs(args);
518
+
519
+ if (!subcommand) {
520
+ commandNotify(ctx, usage(), "warning");
521
+ return;
522
+ }
523
+
524
+ if (subcommand === "list") {
525
+ if (rest.length > 0) throw new Error("/provider list does not accept arguments.");
526
+ commandNotify(ctx, providerListMessage([...managed.values()], secrets, ctx));
527
+ return;
528
+ }
529
+
530
+ if (subcommand === "add") {
531
+ if (rest.length > 0) throw new Error("/provider add does not accept arguments.");
532
+ const provider = await promptForProvider(ctx);
533
+ if (!provider) return;
534
+ if (managed.has(provider.id) || ctx.modelRegistry.getProvider(provider.id)) {
535
+ throw new Error(`Provider '${provider.id}' is already registered.`);
536
+ }
537
+ const apiKey = await promptForApiKey(ctx);
538
+ if (!apiKey) return;
539
+
540
+ const nextState: StoredState = { providers: [...state.providers, provider] };
541
+ const previousApiKey = secrets.apiKeys[provider.id];
542
+ secrets.apiKeys[provider.id] = apiKey;
543
+ try {
544
+ await saveState(nextState);
545
+ await saveSecrets(secrets);
546
+ pi.registerProvider(provider.id, createManagedProvider(provider, () => secrets.apiKeys[provider.id]));
547
+ state.providers = nextState.providers;
548
+ managed.set(provider.id, provider);
549
+ } catch (error) {
550
+ if (previousApiKey === undefined) delete secrets.apiKeys[provider.id];
551
+ else secrets.apiKeys[provider.id] = previousApiKey;
552
+ await saveState({ providers: state.providers }).catch(() => undefined);
553
+ await saveSecrets(secrets).catch(() => undefined);
554
+ pi.unregisterProvider(provider.id);
555
+ throw error;
556
+ }
557
+
558
+ commandNotify(ctx, `Provider '${provider.id}' was added. Fetching its model list.`);
559
+ await refreshProviders(ctx, [provider.id]);
560
+ return;
561
+ }
562
+
563
+ if (subcommand === "edit") {
564
+ if (rest.length !== 1) throw new Error("Usage: /provider edit <provider_name>");
565
+ const currentProvider = findManagedProvider(managed, rest[0]);
566
+ if (!currentProvider) throw new Error(`Managed provider '${rest[0]}' was not found.`);
567
+
568
+ const edit = await promptForProviderEdit(ctx, currentProvider);
569
+ if (!edit) return;
570
+ const providerChanged =
571
+ edit.provider.name !== currentProvider.name || edit.provider.baseUrl !== currentProvider.baseUrl;
572
+ if (!providerChanged && edit.apiKey === undefined) {
573
+ commandNotify(ctx, "No provider settings were changed.", "warning");
574
+ return;
575
+ }
576
+
577
+ const previousState: StoredState = { providers: [...state.providers] };
578
+ const previousApiKey = secrets.apiKeys[currentProvider.id];
579
+ const nextState: StoredState = {
580
+ providers: state.providers.map((provider) =>
581
+ provider.id === currentProvider.id ? edit.provider : provider,
582
+ ),
583
+ };
584
+ if (edit.apiKey !== undefined) secrets.apiKeys[currentProvider.id] = edit.apiKey;
585
+
586
+ try {
587
+ await saveState(nextState);
588
+ if (edit.apiKey !== undefined) await saveSecrets(secrets);
589
+ pi.registerProvider(
590
+ currentProvider.id,
591
+ createManagedProvider(edit.provider, () => secrets.apiKeys[currentProvider.id]),
592
+ );
593
+ state.providers = nextState.providers;
594
+ managed.set(currentProvider.id, edit.provider);
595
+ } catch (error) {
596
+ if (previousApiKey === undefined) delete secrets.apiKeys[currentProvider.id];
597
+ else secrets.apiKeys[currentProvider.id] = previousApiKey;
598
+ await saveState(previousState).catch(() => undefined);
599
+ if (edit.apiKey !== undefined) await saveSecrets(secrets).catch(() => undefined);
600
+ pi.registerProvider(
601
+ currentProvider.id,
602
+ createManagedProvider(currentProvider, () => secrets.apiKeys[currentProvider.id]),
603
+ );
604
+ throw error;
605
+ }
606
+
607
+ commandNotify(ctx, `Saved settings for provider '${currentProvider.id}'. Fetching its model list.`);
608
+ await refreshProviders(ctx, [currentProvider.id]);
609
+ return;
610
+ }
611
+
612
+ if (subcommand === "reload") {
613
+ if (rest.length !== 1) throw new Error("Usage: /provider reload --all | <provider_name>");
614
+ const providerIds = rest[0] === "--all" ? [...managed.keys()] : [rest[0]];
615
+ for (const providerId of providerIds) {
616
+ if (!managed.has(providerId)) throw new Error(`Managed provider '${providerId}' was not found.`);
617
+ }
618
+ await refreshProviders(ctx, providerIds);
619
+ return;
620
+ }
621
+
622
+ if (subcommand === "delete") {
623
+ if (rest.length !== 1) throw new Error("Usage: /provider delete <provider_name>");
624
+ const providerId = rest[0];
625
+ if (!managed.has(providerId)) throw new Error(`Managed provider '${providerId}' was not found.`);
626
+ if (!ctx.hasUI) throw new Error("/provider delete requires an interactive UI.");
627
+ const shouldDelete = await ctx.ui.confirm(
628
+ "Delete provider",
629
+ `Delete provider '${providerId}' and its stored API key?`,
630
+ );
631
+ if (!shouldDelete) return;
632
+
633
+ const previousState: StoredState = { providers: [...state.providers] };
634
+ const previousApiKey = secrets.apiKeys[providerId];
635
+ const nextState: StoredState = {
636
+ providers: state.providers.filter((provider) => provider.id !== providerId),
637
+ };
638
+ delete secrets.apiKeys[providerId];
639
+ try {
640
+ await saveState(nextState);
641
+ await saveSecrets(secrets);
642
+ pi.unregisterProvider(providerId);
643
+ managed.delete(providerId);
644
+ state.providers = nextState.providers;
645
+ } catch (error) {
646
+ if (previousApiKey !== undefined) secrets.apiKeys[providerId] = previousApiKey;
647
+ await saveState(previousState).catch(() => undefined);
648
+ await saveSecrets(secrets).catch(() => undefined);
649
+ throw error;
650
+ }
651
+ commandNotify(ctx, `Provider '${providerId}' was deleted.`);
652
+ return;
653
+ }
654
+
655
+ throw new Error(`Unknown provider command: ${subcommand}\n\n${usage()}`);
656
+ } catch (error) {
657
+ commandNotify(ctx, error instanceof Error ? error.message : String(error), "error");
658
+ }
659
+ },
660
+ });
661
+
662
+ pi.on("session_start", async (_event, ctx) => {
663
+ if (managed.size === 0) return;
664
+ const result = await ctx.modelRegistry.refresh({
665
+ providers: [...managed.keys()],
666
+ allowNetwork: true,
667
+ signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS),
668
+ });
669
+ if (result.errors.size > 0 && ctx.hasUI) {
670
+ ctx.ui.notify(`Could not refresh model lists for: ${[...result.errors.keys()].join(", ")}`, "warning");
671
+ }
672
+ });
673
+ }
package/package.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "@2tle/pi-provider-manager",
3
+ "version": "0.1.0",
4
+ "description": "Manage OpenAI-compatible providers and model catalogs in Pi Agent",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "keywords": ["pi-package"],
8
+ "pi": {
9
+ "extensions": ["./index.ts"]
10
+ },
11
+ "peerDependencies": {
12
+ "@earendil-works/pi-ai": "*",
13
+ "@earendil-works/pi-coding-agent": "*",
14
+ "@earendil-works/pi-tui": "*"
15
+ }
16
+ }