@router-for-me/pi-cliproxyapi-provider 1.4.5 → 1.4.7
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/README.md +14 -23
- package/extensions/codex-stream.ts +58 -1
- package/extensions/index.ts +22 -413
- package/extensions/lib.ts +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -4,8 +4,8 @@ Pi provider extension that discovers models from [CLIProxyAPI](https://github.co
|
|
|
4
4
|
|
|
5
5
|
## What it does
|
|
6
6
|
|
|
7
|
-
1. Registers a provider that always appears in `/login` (account sign-in path)
|
|
8
|
-
2. Interactive setup collects `baseUrl` + `apiKey`.
|
|
7
|
+
1. Registers a provider that always appears in `/login` (account sign-in path).
|
|
8
|
+
2. Interactive setup collects `baseUrl` + `apiKey` via `/login CLIProxyAPI` or `/login cliproxyapi`.
|
|
9
9
|
3. Fetches `{root}/v1/models?client_version=pi`.
|
|
10
10
|
4. Maps the CLIProxyAPI catalog into pi models, including Fast service-tier capability.
|
|
11
11
|
5. Registers inference against `{root}/backend-api/`.
|
|
@@ -29,15 +29,7 @@ pi -e /absolute/path/to/pi-cliproxyapi-provider
|
|
|
29
29
|
|
|
30
30
|
This plugin needs both **baseUrl** and **apiKey**. pi's built-in `/login` only supports multi-field prompts on the account/OAuth path, so CLIProxyAPI appears under **Sign in with an account** (not API key).
|
|
31
31
|
|
|
32
|
-
### Preferred:
|
|
33
|
-
|
|
34
|
-
```text
|
|
35
|
-
/cliproxyapi
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
This slash command is shown only when CLIProxyAPI is **not yet configured** (no usable credentials from env, `cliproxyapi.json`, or `/login` auth). After a successful `/login` or `/cliproxyapi` setup, it is removed from the command registry and filtered out of `/` autocomplete. Reconfigure with `/login CLIProxyAPI`, or clear credentials (`/logout` and/or remove `cliproxyapi.json` / env) to bring `/cliproxyapi` back. Restart pi or run `/reload` after upgrading so the new visibility logic is loaded.
|
|
39
|
-
|
|
40
|
-
### Or use /login shortcuts (skip the menu)
|
|
32
|
+
### Preferred: /login shortcuts
|
|
41
33
|
|
|
42
34
|
```text
|
|
43
35
|
/login CLIProxyAPI
|
|
@@ -71,13 +63,13 @@ Final login validation calls `{root}/v1/models?client_version=pi`:
|
|
|
71
63
|
- **HTTP 200** → login succeeds (empty model list is still OK)
|
|
72
64
|
- **non-200 / network error** → login fails and you are prompted to re-enter base URL + API key
|
|
73
65
|
|
|
74
|
-
On success
|
|
66
|
+
On success:
|
|
75
67
|
|
|
76
68
|
- models are registered immediately in the current session (0 models is allowed)
|
|
77
69
|
- `baseUrl` / `apiKey` are written to `~/.pi/agent/cliproxyapi.json`
|
|
78
|
-
-
|
|
70
|
+
- pi also stores the returned credential in `~/.pi/agent/auth.json`
|
|
79
71
|
|
|
80
|
-
Re-run `/
|
|
72
|
+
Re-run `/login CLIProxyAPI` or `/login cliproxyapi` anytime to reconfigure. The built-in `/logout` command only removes credentials saved in `auth.json`; it does not erase `cliproxyapi.json`. Remove or update that file if you also need to clear the provider configuration.
|
|
81
73
|
|
|
82
74
|
## Non-interactive configuration
|
|
83
75
|
|
|
@@ -172,7 +164,7 @@ Unsupported pi thinking levels are set to `null` so they are hidden in the UI. C
|
|
|
172
164
|
|
|
173
165
|
If you previously maintained a static provider such as `cpa-responses` in `~/.pi/agent/models.json`:
|
|
174
166
|
|
|
175
|
-
1. Install this package and run `/
|
|
167
|
+
1. Install this package and run `/login CLIProxyAPI` or `/login cliproxyapi` (or set `cliproxyapi.json`).
|
|
176
168
|
2. Point `defaultProvider` / `enabledModels` at `cliproxyapi/<model-id>` (or set `providerId` to `cpa-responses` for a drop-in id).
|
|
177
169
|
3. Remove the hand-maintained models array once the dynamic list looks correct.
|
|
178
170
|
|
|
@@ -188,13 +180,12 @@ Disable just this helper via `pi config` if you only want the CLIProxyAPI provid
|
|
|
188
180
|
|
|
189
181
|
## Failure behavior
|
|
190
182
|
|
|
191
|
-
- Before setup / without credentials: provider still appears in `/login`;
|
|
192
|
-
- After successful `/login
|
|
193
|
-
-
|
|
194
|
-
-
|
|
195
|
-
-
|
|
196
|
-
-
|
|
197
|
-
- HTTP 200 (including empty catalog) → credentials are persisted; `/cliproxyapi` is hidden
|
|
183
|
+
- Before setup / without credentials: provider still appears in `/login`; no models are listed yet.
|
|
184
|
+
- After successful `/login`: models are registered; credentials are stored in `auth.json` and mirrored to `cliproxyapi.json`.
|
|
185
|
+
- The built-in `/logout` command removes only the matching `auth.json` credential; environment variables and `cliproxyapi.json` are unchanged.
|
|
186
|
+
- If a models request returns **HTTP 401** or CPA is unreachable during startup, a warning is logged; reconfigure via `/login CLIProxyAPI` or fix config/env.
|
|
187
|
+
- Login final step validates credentials by requesting models:
|
|
188
|
+
- HTTP 200 (including empty catalog) → credentials are persisted
|
|
198
189
|
- non-200 / network / invalid baseUrl → nothing is persisted; re-enter baseUrl + API key
|
|
199
|
-
- If CPA returns HTTP 200 with zero usable models: login still succeeds; re-run
|
|
190
|
+
- If CPA returns HTTP 200 with zero usable models: login still succeeds; re-run `/login CLIProxyAPI` later after models become available.
|
|
200
191
|
- If the selected model does not provide a non-empty `service_tiers` array: the request is left unchanged; `/fast` still updates the global preference and warns when enabling it.
|
|
@@ -98,7 +98,60 @@ function rewriteRelativeImports(source: string, originalDir: string): string {
|
|
|
98
98
|
});
|
|
99
99
|
}
|
|
100
100
|
|
|
101
|
-
function
|
|
101
|
+
function patchWebSocketOnlyTransport(source: string): string {
|
|
102
|
+
const disabledForSession =
|
|
103
|
+
/const websocketDisabledForSession\s*=\s*transport !== "sse" && isWebSocketSseFallbackActive\(options\?\.sessionId\);/;
|
|
104
|
+
const retryVariables = /let retriedWebSocketConnectionLimit\s*=\s*false;/;
|
|
105
|
+
const websocketFailureHandling =
|
|
106
|
+
/const connectionLimitBeforeStart = !websocketStarted && isWebSocketConnectionLimitReachedError\(error\);[\s\S]*?recordWebSocketSseFallback\(options\?\.sessionId\);\s*break;/;
|
|
107
|
+
const fallbackSessionRecord = "websocketSseFallbackSessions.add(sessionId);";
|
|
108
|
+
const fallbackActiveRecord = "stats.websocketFallbackActive = true;";
|
|
109
|
+
|
|
110
|
+
for (const fragment of [fallbackSessionRecord, fallbackActiveRecord]) {
|
|
111
|
+
if (!source.includes(fragment)) {
|
|
112
|
+
throw new Error("openai-codex-responses source no longer supports the WebSocket-only transport patch");
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
for (const pattern of [disabledForSession, retryVariables, websocketFailureHandling]) {
|
|
116
|
+
if (!pattern.test(source)) {
|
|
117
|
+
throw new Error("openai-codex-responses source no longer supports the WebSocket-only transport patch");
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return source
|
|
122
|
+
.replace(disabledForSession, "const websocketDisabledForSession = false;")
|
|
123
|
+
.replace(
|
|
124
|
+
retryVariables,
|
|
125
|
+
`let websocketRetries = 0;
|
|
126
|
+
const maxWebSocketRetries = Number.isFinite(options?.maxRetries)
|
|
127
|
+
? Math.min(Math.max(0, Math.floor(options.maxRetries)), 5)
|
|
128
|
+
: 3;`,
|
|
129
|
+
)
|
|
130
|
+
.replace(
|
|
131
|
+
websocketFailureHandling,
|
|
132
|
+
`const connectionLimitBeforeStart = !websocketStarted && isWebSocketConnectionLimitReachedError(error);
|
|
133
|
+
if (aborted || (isCodexNonTransportError(error) && !connectionLimitBeforeStart)) {
|
|
134
|
+
throw error;
|
|
135
|
+
}
|
|
136
|
+
if (!websocketStarted && websocketRetries < maxWebSocketRetries) {
|
|
137
|
+
websocketRetries++;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
appendAssistantMessageDiagnostic(output, createAssistantMessageDiagnostic("provider_transport_failure", error, {
|
|
141
|
+
configuredTransport: transport,
|
|
142
|
+
fallbackTransport: undefined,
|
|
143
|
+
eventsEmitted: websocketStarted,
|
|
144
|
+
phase: websocketStarted ? "after_message_stream_start" : "before_message_stream_start",
|
|
145
|
+
requestBytes: new TextEncoder().encode(bodyJson).byteLength,
|
|
146
|
+
}));
|
|
147
|
+
recordWebSocketFailure(options?.sessionId, error);
|
|
148
|
+
throw error;`,
|
|
149
|
+
)
|
|
150
|
+
.replace(fallbackSessionRecord, "")
|
|
151
|
+
.replace(fallbackActiveRecord, "stats.websocketFallbackActive = false;");
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function patchCodexSource(source: string, providerIds: string[]): string {
|
|
102
155
|
let src = source;
|
|
103
156
|
|
|
104
157
|
if (!/function extractAccountId\(token\) \{/.test(src)) {
|
|
@@ -131,6 +184,10 @@ function patchCodexSource(source: string, providerIds: string[]): string {
|
|
|
131
184
|
// Keep assistant message api metadata aligned with the registered custom api id.
|
|
132
185
|
src = src.replaceAll(`api: "openai-codex-responses"`, `api: ${JSON.stringify(CLIPROXYAPI_CODEX_API)}`);
|
|
133
186
|
|
|
187
|
+
// CLIProxyAPI needs a persistent WebSocket transport. Reconnect before the
|
|
188
|
+
// response starts and surface a failure rather than silently switching to SSE.
|
|
189
|
+
src = patchWebSocketOnlyTransport(src);
|
|
190
|
+
|
|
134
191
|
// The generated module lives outside the original source map directory.
|
|
135
192
|
src = src.replace(/^\/\/# sourceMappingURL=.*$/gm, "");
|
|
136
193
|
|
package/extensions/index.ts
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* CLIProxyAPI dynamic model provider for pi.
|
|
3
3
|
*
|
|
4
|
-
* Supports login-style setup via `/login
|
|
4
|
+
* Supports login-style setup via `/login`:
|
|
5
5
|
* 1. Provider is registered as OAuth-only so `/login CLIProxyAPI` / `/login cliproxyapi`
|
|
6
6
|
* skip the API-key vs account selector and go straight to multi-field prompts
|
|
7
7
|
* (pi only supports multi-field prompts on the account/OAuth path).
|
|
8
|
-
* 2. Preferred shortcuts: `/login CLIProxyAPI
|
|
9
|
-
* or the dedicated `/cliproxyapi` command (hidden once configured).
|
|
8
|
+
* 2. Preferred shortcuts: `/login CLIProxyAPI` or `/login cliproxyapi`.
|
|
10
9
|
* 3. Setup prompts for baseUrl + apiKey.
|
|
11
10
|
* 4. Final login step validates credentials via /v1/models?client_version=pi
|
|
12
11
|
* (HTTP 200 = success even if the catalog is empty; otherwise re-prompt).
|
|
@@ -20,12 +19,7 @@
|
|
|
20
19
|
*/
|
|
21
20
|
|
|
22
21
|
import type { Api, Model, OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
|
|
23
|
-
import {
|
|
24
|
-
type ExtensionAPI,
|
|
25
|
-
type ExtensionCommandContext,
|
|
26
|
-
type ExtensionContext,
|
|
27
|
-
getAgentDir,
|
|
28
|
-
} from "@earendil-works/pi-coding-agent";
|
|
22
|
+
import { type ExtensionAPI, type ExtensionContext, getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
29
23
|
import { CLIPROXYAPI_CODEX_API, type CliproxyCodexStreamSimple, loadCliproxyCodexStreams } from "./codex-stream.ts";
|
|
30
24
|
import { FastModeController } from "./fast.ts";
|
|
31
25
|
import { FastFooterController } from "./fast-footer.ts";
|
|
@@ -48,36 +42,6 @@ import {
|
|
|
48
42
|
saveConfigFile,
|
|
49
43
|
} from "./lib.ts";
|
|
50
44
|
|
|
51
|
-
/** Show/hide /cliproxyapi in the slash-command menu. */
|
|
52
|
-
interface SetupCommandsController {
|
|
53
|
-
show(): void;
|
|
54
|
-
hide(): void;
|
|
55
|
-
isVisible(): boolean;
|
|
56
|
-
/**
|
|
57
|
-
* Hide when CLIProxyAPI is already configured (env / cliproxyapi.json / auth.json).
|
|
58
|
-
* Show when no connection is available. Pass forceShow after 401 so the user can fix credentials.
|
|
59
|
-
*/
|
|
60
|
-
syncVisibility(options?: { forceShow?: boolean }): void;
|
|
61
|
-
/** Whether any connection source currently provides credentials. */
|
|
62
|
-
isConfigured(): boolean;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
function hasLoginCredential(agentDir: string, providerId: string): boolean {
|
|
66
|
-
try {
|
|
67
|
-
return Boolean(loadAuthConnection(agentDir, providerId)?.apiKey);
|
|
68
|
-
} catch {
|
|
69
|
-
return false;
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
function isProviderConfigured(agentDir: string, providerId: string): boolean {
|
|
74
|
-
try {
|
|
75
|
-
return resolveConnection(agentDir, providerId) !== null;
|
|
76
|
-
} catch {
|
|
77
|
-
return false;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
45
|
class ConfigPersistenceError extends Error {
|
|
82
46
|
constructor(cause: unknown) {
|
|
83
47
|
const message = cause instanceof Error ? cause.message : String(cause);
|
|
@@ -94,6 +58,14 @@ function logInfo(message: string): void {
|
|
|
94
58
|
console.info(`[pi-cliproxyapi-provider] ${message}`);
|
|
95
59
|
}
|
|
96
60
|
|
|
61
|
+
function hasLoginCredential(agentDir: string, providerId: string): boolean {
|
|
62
|
+
try {
|
|
63
|
+
return Boolean(loadAuthConnection(agentDir, providerId)?.apiKey);
|
|
64
|
+
} catch {
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
97
69
|
function buildOAuthCredentials(baseUrlInput: string, apiKey: string): OAuthCredentials {
|
|
98
70
|
return {
|
|
99
71
|
refresh: encodeRefreshMeta(baseUrlInput),
|
|
@@ -164,29 +136,10 @@ async function configureAndRegister(options: {
|
|
|
164
136
|
apiKey: string;
|
|
165
137
|
defaultBaseUrl: string;
|
|
166
138
|
streamSimple: CliproxyCodexStreamSimple;
|
|
167
|
-
setupCommands: SetupCommandsController;
|
|
168
139
|
fastMode: FastModeController;
|
|
169
|
-
/**
|
|
170
|
-
* When true, register a configured API key for ambient request auth.
|
|
171
|
-
* Only used by `/cliproxyapi` (no auth.json write). `/login` must leave this
|
|
172
|
-
* false so the provider stays OAuth-only and `/login <provider>` skips the
|
|
173
|
-
* API-key vs account selector.
|
|
174
|
-
*/
|
|
175
|
-
registerConfiguredApiKey?: boolean;
|
|
176
140
|
}): Promise<{ modelCount: number; modelsUrl: string }> {
|
|
177
|
-
const {
|
|
178
|
-
|
|
179
|
-
agentDir,
|
|
180
|
-
providerId,
|
|
181
|
-
providerName,
|
|
182
|
-
baseUrlInput,
|
|
183
|
-
apiKey,
|
|
184
|
-
defaultBaseUrl,
|
|
185
|
-
streamSimple,
|
|
186
|
-
setupCommands,
|
|
187
|
-
fastMode,
|
|
188
|
-
registerConfiguredApiKey = false,
|
|
189
|
-
} = options;
|
|
141
|
+
const { pi, agentDir, providerId, providerName, baseUrlInput, apiKey, defaultBaseUrl, streamSimple, fastMode } =
|
|
142
|
+
options;
|
|
190
143
|
|
|
191
144
|
const loaded = await loadMappedModels(baseUrlInput, apiKey);
|
|
192
145
|
|
|
@@ -201,16 +154,16 @@ async function configureAndRegister(options: {
|
|
|
201
154
|
throw new ConfigPersistenceError(error);
|
|
202
155
|
}
|
|
203
156
|
|
|
157
|
+
// /login stores oauth credentials itself; keep the provider OAuth-only so
|
|
158
|
+
// `/login <provider>` skips the API-key vs account selector.
|
|
204
159
|
registerProvider(pi, {
|
|
205
160
|
providerId,
|
|
206
161
|
providerName,
|
|
207
162
|
baseUrlInput,
|
|
208
|
-
apiKey: registerConfiguredApiKey ? apiKey : undefined,
|
|
209
163
|
models: loaded.models,
|
|
210
164
|
defaultBaseUrl: baseUrlInput || defaultBaseUrl,
|
|
211
165
|
agentDir,
|
|
212
166
|
streamSimple,
|
|
213
|
-
setupCommands,
|
|
214
167
|
fastMode,
|
|
215
168
|
});
|
|
216
169
|
fastMode.setSupportedModelIds(loaded.fastModelIds);
|
|
@@ -225,10 +178,9 @@ function createOAuthHandlers(options: {
|
|
|
225
178
|
providerName: string;
|
|
226
179
|
defaultBaseUrl: string;
|
|
227
180
|
streamSimple: CliproxyCodexStreamSimple;
|
|
228
|
-
setupCommands: SetupCommandsController;
|
|
229
181
|
fastMode: FastModeController;
|
|
230
182
|
}) {
|
|
231
|
-
const { pi, agentDir, providerId, providerName, defaultBaseUrl, streamSimple,
|
|
183
|
+
const { pi, agentDir, providerId, providerName, defaultBaseUrl, streamSimple, fastMode } = options;
|
|
232
184
|
|
|
233
185
|
return {
|
|
234
186
|
name: providerName,
|
|
@@ -254,12 +206,9 @@ function createOAuthHandlers(options: {
|
|
|
254
206
|
apiKey,
|
|
255
207
|
defaultBaseUrl,
|
|
256
208
|
streamSimple,
|
|
257
|
-
setupCommands,
|
|
258
209
|
fastMode,
|
|
259
210
|
});
|
|
260
211
|
|
|
261
|
-
// /login succeeded — dedicated setup is unnecessary until config is cleared.
|
|
262
|
-
setupCommands.hide();
|
|
263
212
|
logInfo(`login ok: registered ${result.modelCount} models from ${result.modelsUrl}`);
|
|
264
213
|
return buildOAuthCredentials(baseUrlInput, apiKey);
|
|
265
214
|
} catch (error) {
|
|
@@ -269,10 +218,6 @@ function createOAuthHandlers(options: {
|
|
|
269
218
|
callbacks.onProgress?.(message);
|
|
270
219
|
throw error;
|
|
271
220
|
}
|
|
272
|
-
// Auth failures should keep the setup command available for reconfiguration.
|
|
273
|
-
if (isUnauthorizedModelsError(error)) {
|
|
274
|
-
setupCommands.syncVisibility({ forceShow: true });
|
|
275
|
-
}
|
|
276
221
|
callbacks.onProgress?.(`Login validation failed: ${message}\nPlease re-enter base URL and API key.`);
|
|
277
222
|
// Keep last baseUrl as the next default so retyping is easier.
|
|
278
223
|
promptDefaultBaseUrl = baseUrlInput || promptDefaultBaseUrl;
|
|
@@ -320,22 +265,11 @@ function registerProvider(
|
|
|
320
265
|
defaultBaseUrl: string;
|
|
321
266
|
agentDir: string;
|
|
322
267
|
streamSimple: CliproxyCodexStreamSimple;
|
|
323
|
-
setupCommands: SetupCommandsController;
|
|
324
268
|
fastMode: FastModeController;
|
|
325
269
|
},
|
|
326
270
|
): void {
|
|
327
|
-
const {
|
|
328
|
-
|
|
329
|
-
providerName,
|
|
330
|
-
baseUrlInput,
|
|
331
|
-
apiKey,
|
|
332
|
-
models,
|
|
333
|
-
defaultBaseUrl,
|
|
334
|
-
agentDir,
|
|
335
|
-
streamSimple,
|
|
336
|
-
setupCommands,
|
|
337
|
-
fastMode,
|
|
338
|
-
} = options;
|
|
271
|
+
const { providerId, providerName, baseUrlInput, apiKey, models, defaultBaseUrl, agentDir, streamSimple, fastMode } =
|
|
272
|
+
options;
|
|
339
273
|
|
|
340
274
|
const endpoints = resolveEndpoints(baseUrlInput);
|
|
341
275
|
const oauth = createOAuthHandlers({
|
|
@@ -345,7 +279,6 @@ function registerProvider(
|
|
|
345
279
|
providerName,
|
|
346
280
|
defaultBaseUrl,
|
|
347
281
|
streamSimple,
|
|
348
|
-
setupCommands,
|
|
349
282
|
fastMode,
|
|
350
283
|
});
|
|
351
284
|
|
|
@@ -360,297 +293,13 @@ function registerProvider(
|
|
|
360
293
|
streamSimple,
|
|
361
294
|
// OAuth-only keeps `/login <provider>` on the multi-field account path.
|
|
362
295
|
// Pass apiKey only for ambient request auth when no /login credential exists
|
|
363
|
-
// (config file / env
|
|
296
|
+
// (config file / env). Never pass both for /login flows.
|
|
364
297
|
oauth,
|
|
365
298
|
...(apiKey ? { apiKey } : {}),
|
|
366
299
|
...(models && models.length > 0 ? { models } : {}),
|
|
367
300
|
});
|
|
368
301
|
}
|
|
369
302
|
|
|
370
|
-
/**
|
|
371
|
-
* Register /cliproxyapi and allow hiding it after /login.
|
|
372
|
-
*
|
|
373
|
-
* pi has registerCommand but no unregisterCommand, so hide() removes the entry
|
|
374
|
-
* from the extension's internal commands Map captured during first registration.
|
|
375
|
-
*/
|
|
376
|
-
function createSetupCommandsController(options: {
|
|
377
|
-
pi: ExtensionAPI;
|
|
378
|
-
agentDir: string;
|
|
379
|
-
providerId: string;
|
|
380
|
-
providerName: string;
|
|
381
|
-
defaultBaseUrl: string;
|
|
382
|
-
streamSimple: CliproxyCodexStreamSimple;
|
|
383
|
-
fastMode: FastModeController;
|
|
384
|
-
}): SetupCommandsController {
|
|
385
|
-
const { pi, agentDir, providerId, providerName, defaultBaseUrl, streamSimple, fastMode } = options;
|
|
386
|
-
|
|
387
|
-
// Self-referential controller so handlers can hide/show after validation.
|
|
388
|
-
const setupCommands: SetupCommandsController = {
|
|
389
|
-
show() {
|
|
390
|
-
/* replaced below */
|
|
391
|
-
},
|
|
392
|
-
hide() {
|
|
393
|
-
/* replaced below */
|
|
394
|
-
},
|
|
395
|
-
isVisible() {
|
|
396
|
-
return false;
|
|
397
|
-
},
|
|
398
|
-
syncVisibility() {
|
|
399
|
-
/* replaced below */
|
|
400
|
-
},
|
|
401
|
-
isConfigured() {
|
|
402
|
-
return false;
|
|
403
|
-
},
|
|
404
|
-
};
|
|
405
|
-
|
|
406
|
-
let visible = false;
|
|
407
|
-
// Captured extension.commands Map (pi has no public unregisterCommand API).
|
|
408
|
-
let commandMap: Map<string, unknown> | null = null;
|
|
409
|
-
|
|
410
|
-
const handler = async (_args: string, ctx: ExtensionCommandContext): Promise<void> => {
|
|
411
|
-
if (!ctx.hasUI) {
|
|
412
|
-
ctx.ui.notify(
|
|
413
|
-
`Interactive UI unavailable. Use /login ${providerName}, set ${CONFIG_FILE_NAME}, or CLIPROXYAPI_* env vars.`,
|
|
414
|
-
"error",
|
|
415
|
-
);
|
|
416
|
-
return;
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
if (hasLoginCredential(agentDir, providerId)) {
|
|
420
|
-
// Still authenticated via /login — hide the dedicated command and redirect.
|
|
421
|
-
setupCommands.hide();
|
|
422
|
-
ctx.ui.notify(
|
|
423
|
-
`CLIProxyAPI credentials are already stored by /login. Use /login ${providerName} to replace them, or run /logout before /cliproxyapi.`,
|
|
424
|
-
"error",
|
|
425
|
-
);
|
|
426
|
-
return;
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
const promptDefaultBaseUrl = resolveDefaultBaseUrl(agentDir, providerId) || defaultBaseUrl;
|
|
430
|
-
|
|
431
|
-
const baseUrlRaw = await ctx.ui.input(`CLIProxyAPI base URL [${promptDefaultBaseUrl}]:`, promptDefaultBaseUrl);
|
|
432
|
-
if (baseUrlRaw === undefined) {
|
|
433
|
-
ctx.ui.notify("CLIProxyAPI setup cancelled.", "info");
|
|
434
|
-
return;
|
|
435
|
-
}
|
|
436
|
-
const baseUrlInput = firstNonEmpty(baseUrlRaw, promptDefaultBaseUrl)!;
|
|
437
|
-
|
|
438
|
-
try {
|
|
439
|
-
resolveEndpoints(baseUrlInput);
|
|
440
|
-
} catch (error) {
|
|
441
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
442
|
-
ctx.ui.notify(`Invalid base URL: ${message}`, "error");
|
|
443
|
-
return;
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
const apiKeyRaw = await ctx.ui.input("CLIProxyAPI API key:", "sk-...");
|
|
447
|
-
if (apiKeyRaw === undefined) {
|
|
448
|
-
ctx.ui.notify("CLIProxyAPI setup cancelled.", "info");
|
|
449
|
-
return;
|
|
450
|
-
}
|
|
451
|
-
const apiKey = apiKeyRaw.trim();
|
|
452
|
-
if (!apiKey) {
|
|
453
|
-
ctx.ui.notify("API key cannot be empty.", "error");
|
|
454
|
-
return;
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
// Final setup step: validate by calling /v1/models.
|
|
458
|
-
// HTTP 200 (even with an empty catalog) means success; otherwise re-prompt.
|
|
459
|
-
let currentBaseUrl = baseUrlInput;
|
|
460
|
-
let currentApiKey = apiKey;
|
|
461
|
-
while (true) {
|
|
462
|
-
try {
|
|
463
|
-
const result = await configureAndRegister({
|
|
464
|
-
pi,
|
|
465
|
-
agentDir,
|
|
466
|
-
providerId,
|
|
467
|
-
providerName,
|
|
468
|
-
baseUrlInput: currentBaseUrl,
|
|
469
|
-
apiKey: currentApiKey,
|
|
470
|
-
defaultBaseUrl,
|
|
471
|
-
streamSimple,
|
|
472
|
-
setupCommands,
|
|
473
|
-
fastMode,
|
|
474
|
-
// Dedicated command does not write auth.json; keep ambient apiKey
|
|
475
|
-
// so requests work in the current session.
|
|
476
|
-
registerConfiguredApiKey: true,
|
|
477
|
-
});
|
|
478
|
-
|
|
479
|
-
// Config saved — hide dedicated setup until credentials are cleared.
|
|
480
|
-
setupCommands.hide();
|
|
481
|
-
logInfo(`command setup ok: registered ${result.modelCount} models from ${result.modelsUrl}`);
|
|
482
|
-
ctx.ui.notify(`CLIProxyAPI configured: ${result.modelCount} models from ${result.modelsUrl}`, "info");
|
|
483
|
-
return;
|
|
484
|
-
} catch (error) {
|
|
485
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
486
|
-
logWarn(`command setup failed: ${message}`);
|
|
487
|
-
if (error instanceof ConfigPersistenceError) {
|
|
488
|
-
ctx.ui.notify(message, "error");
|
|
489
|
-
return;
|
|
490
|
-
}
|
|
491
|
-
if (isUnauthorizedModelsError(error)) {
|
|
492
|
-
setupCommands.syncVisibility({ forceShow: true });
|
|
493
|
-
}
|
|
494
|
-
ctx.ui.notify(`CLIProxyAPI validation failed: ${message}. Please re-enter base URL and API key.`, "error");
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
// Collect replacement credentials before retrying validation.
|
|
498
|
-
while (true) {
|
|
499
|
-
const retryBaseUrlRaw = await ctx.ui.input(`CLIProxyAPI base URL [${currentBaseUrl}]:`, currentBaseUrl);
|
|
500
|
-
if (retryBaseUrlRaw === undefined) {
|
|
501
|
-
ctx.ui.notify("CLIProxyAPI setup cancelled.", "info");
|
|
502
|
-
return;
|
|
503
|
-
}
|
|
504
|
-
const retryBaseUrl = firstNonEmpty(retryBaseUrlRaw, currentBaseUrl)!;
|
|
505
|
-
try {
|
|
506
|
-
resolveEndpoints(retryBaseUrl);
|
|
507
|
-
} catch (urlError) {
|
|
508
|
-
const urlMessage = urlError instanceof Error ? urlError.message : String(urlError);
|
|
509
|
-
ctx.ui.notify(`Invalid base URL: ${urlMessage}`, "error");
|
|
510
|
-
continue;
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
const retryApiKeyRaw = await ctx.ui.input("CLIProxyAPI API key:", "sk-...");
|
|
514
|
-
if (retryApiKeyRaw === undefined) {
|
|
515
|
-
ctx.ui.notify("CLIProxyAPI setup cancelled.", "info");
|
|
516
|
-
return;
|
|
517
|
-
}
|
|
518
|
-
const retryApiKey = retryApiKeyRaw.trim();
|
|
519
|
-
if (!retryApiKey) {
|
|
520
|
-
ctx.ui.notify("API key cannot be empty.", "error");
|
|
521
|
-
continue;
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
currentBaseUrl = retryBaseUrl;
|
|
525
|
-
currentApiKey = retryApiKey;
|
|
526
|
-
break;
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
};
|
|
530
|
-
|
|
531
|
-
const registerCommand = (): void => {
|
|
532
|
-
pi.registerCommand("cliproxyapi", {
|
|
533
|
-
description: "Configure CLIProxyAPI (baseUrl + API key) and load models. Prefer this or /login CLIProxyAPI.",
|
|
534
|
-
handler,
|
|
535
|
-
});
|
|
536
|
-
};
|
|
537
|
-
|
|
538
|
-
setupCommands.show = (): void => {
|
|
539
|
-
if (visible) {
|
|
540
|
-
return;
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
if (!commandMap) {
|
|
544
|
-
// Capture the extension.commands Map during first registration.
|
|
545
|
-
const originalSet = Map.prototype.set;
|
|
546
|
-
Map.prototype.set = function setWithCapture(this: Map<unknown, unknown>, key: unknown, value: unknown) {
|
|
547
|
-
if (
|
|
548
|
-
key === "cliproxyapi" &&
|
|
549
|
-
value &&
|
|
550
|
-
typeof value === "object" &&
|
|
551
|
-
"handler" in (value as Record<string, unknown>)
|
|
552
|
-
) {
|
|
553
|
-
commandMap = this as Map<string, unknown>;
|
|
554
|
-
}
|
|
555
|
-
return originalSet.call(this, key, value);
|
|
556
|
-
} as typeof Map.prototype.set;
|
|
557
|
-
try {
|
|
558
|
-
registerCommand();
|
|
559
|
-
} finally {
|
|
560
|
-
Map.prototype.set = originalSet;
|
|
561
|
-
}
|
|
562
|
-
if (!commandMap) {
|
|
563
|
-
logWarn("could not capture command map; /cliproxyapi cannot be hidden after login");
|
|
564
|
-
}
|
|
565
|
-
} else {
|
|
566
|
-
registerCommand();
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
visible = true;
|
|
570
|
-
logInfo("setup command shown: /cliproxyapi");
|
|
571
|
-
};
|
|
572
|
-
|
|
573
|
-
setupCommands.hide = (): void => {
|
|
574
|
-
if (!visible) {
|
|
575
|
-
return;
|
|
576
|
-
}
|
|
577
|
-
if (!commandMap) {
|
|
578
|
-
logWarn("setup command remains visible (no command map capture for unregister)");
|
|
579
|
-
return;
|
|
580
|
-
}
|
|
581
|
-
commandMap.delete("cliproxyapi");
|
|
582
|
-
visible = false;
|
|
583
|
-
logInfo("setup command hidden (CLIProxyAPI already configured)");
|
|
584
|
-
};
|
|
585
|
-
|
|
586
|
-
setupCommands.isVisible = (): boolean => visible;
|
|
587
|
-
|
|
588
|
-
setupCommands.isConfigured = (): boolean => isProviderConfigured(agentDir, providerId);
|
|
589
|
-
|
|
590
|
-
setupCommands.syncVisibility = (options?: { forceShow?: boolean }): void => {
|
|
591
|
-
if (options?.forceShow) {
|
|
592
|
-
setupCommands.show();
|
|
593
|
-
return;
|
|
594
|
-
}
|
|
595
|
-
if (isProviderConfigured(agentDir, providerId)) {
|
|
596
|
-
setupCommands.hide();
|
|
597
|
-
} else {
|
|
598
|
-
setupCommands.show();
|
|
599
|
-
}
|
|
600
|
-
};
|
|
601
|
-
|
|
602
|
-
return setupCommands;
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
/**
|
|
606
|
-
* pi's slash autocomplete snapshots commands at setup time. Deleting from the
|
|
607
|
-
* extension command Map alone does not refresh that snapshot, so also filter
|
|
608
|
-
* `/cliproxyapi` out of live suggestions while the provider is configured.
|
|
609
|
-
*/
|
|
610
|
-
function installSetupCommandAutocompleteFilter(options: {
|
|
611
|
-
pi: ExtensionAPI;
|
|
612
|
-
agentDir: string;
|
|
613
|
-
providerId: string;
|
|
614
|
-
setupCommands: SetupCommandsController;
|
|
615
|
-
}): void {
|
|
616
|
-
const { pi, agentDir, providerId, setupCommands } = options;
|
|
617
|
-
let installed = false;
|
|
618
|
-
|
|
619
|
-
pi.on("session_start", (_event, ctx) => {
|
|
620
|
-
setupCommands.syncVisibility();
|
|
621
|
-
|
|
622
|
-
if (installed) {
|
|
623
|
-
return;
|
|
624
|
-
}
|
|
625
|
-
if (typeof ctx.ui.addAutocompleteProvider !== "function") {
|
|
626
|
-
return;
|
|
627
|
-
}
|
|
628
|
-
installed = true;
|
|
629
|
-
|
|
630
|
-
ctx.ui.addAutocompleteProvider((current) => ({
|
|
631
|
-
triggerCharacters: current.triggerCharacters,
|
|
632
|
-
shouldTriggerFileCompletion: current.shouldTriggerFileCompletion?.bind(current),
|
|
633
|
-
applyCompletion: current.applyCompletion.bind(current),
|
|
634
|
-
async getSuggestions(lines, cursorLine, cursorCol, suggestionOptions) {
|
|
635
|
-
// Keep Map visibility in sync when the user opens `/`.
|
|
636
|
-
setupCommands.syncVisibility();
|
|
637
|
-
|
|
638
|
-
const result = await current.getSuggestions(lines, cursorLine, cursorCol, suggestionOptions);
|
|
639
|
-
if (!result?.items?.length || !isProviderConfigured(agentDir, providerId)) {
|
|
640
|
-
return result;
|
|
641
|
-
}
|
|
642
|
-
|
|
643
|
-
const items = result.items.filter((item) => item.value !== "cliproxyapi" && item.label !== "cliproxyapi");
|
|
644
|
-
if (items.length === 0) {
|
|
645
|
-
return null;
|
|
646
|
-
}
|
|
647
|
-
return { ...result, items };
|
|
648
|
-
},
|
|
649
|
-
}));
|
|
650
|
-
logInfo("installed /cliproxyapi autocomplete filter for configured sessions");
|
|
651
|
-
});
|
|
652
|
-
}
|
|
653
|
-
|
|
654
303
|
export function registerFastCommand(options: {
|
|
655
304
|
pi: ExtensionAPI;
|
|
656
305
|
agentDir: string;
|
|
@@ -730,37 +379,6 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
730
379
|
});
|
|
731
380
|
fastFooter.register(pi);
|
|
732
381
|
|
|
733
|
-
const setupCommands = createSetupCommandsController({
|
|
734
|
-
pi,
|
|
735
|
-
agentDir,
|
|
736
|
-
providerId: identity.providerId,
|
|
737
|
-
providerName: identity.providerName,
|
|
738
|
-
defaultBaseUrl,
|
|
739
|
-
streamSimple,
|
|
740
|
-
fastMode,
|
|
741
|
-
});
|
|
742
|
-
|
|
743
|
-
// Reconcile Map visibility + autocomplete filtering when configuration changes.
|
|
744
|
-
// pi has no logout extension event and slash autocomplete is snapshotted, so we:
|
|
745
|
-
// 1) delete/re-add the command Map entry
|
|
746
|
-
// 2) filter suggestions live while any connection source is configured
|
|
747
|
-
// 3) re-check on submitted input after /logout or config edits
|
|
748
|
-
installSetupCommandAutocompleteFilter({
|
|
749
|
-
pi,
|
|
750
|
-
agentDir,
|
|
751
|
-
providerId: identity.providerId,
|
|
752
|
-
setupCommands,
|
|
753
|
-
});
|
|
754
|
-
pi.on("input", () => {
|
|
755
|
-
setupCommands.syncVisibility();
|
|
756
|
-
});
|
|
757
|
-
|
|
758
|
-
// Initial visibility: hide when already configured via env / config / /login.
|
|
759
|
-
setupCommands.syncVisibility();
|
|
760
|
-
if (setupCommands.isConfigured()) {
|
|
761
|
-
logInfo("CLIProxyAPI already configured; /cliproxyapi stays hidden");
|
|
762
|
-
}
|
|
763
|
-
|
|
764
382
|
// Always register oauth so the provider is visible in /login immediately after install.
|
|
765
383
|
registerProvider(pi, {
|
|
766
384
|
providerId: identity.providerId,
|
|
@@ -769,15 +387,13 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
769
387
|
defaultBaseUrl,
|
|
770
388
|
agentDir,
|
|
771
389
|
streamSimple,
|
|
772
|
-
setupCommands,
|
|
773
390
|
fastMode,
|
|
774
391
|
});
|
|
775
392
|
|
|
776
393
|
const connection = resolveConnection(agentDir, identity.providerId);
|
|
777
394
|
if (!connection) {
|
|
778
|
-
setupCommands.syncVisibility();
|
|
779
395
|
logInfo(
|
|
780
|
-
`not configured yet.
|
|
396
|
+
`not configured yet. Use /login ${identity.providerName} or /login ${identity.providerId}. ` +
|
|
781
397
|
`Menu path: /login → Sign in with an account → ${identity.providerName}. ` +
|
|
782
398
|
`Or set ${CONFIG_FILE_NAME} / CLIPROXYAPI_API_KEY.`,
|
|
783
399
|
);
|
|
@@ -800,22 +416,15 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
800
416
|
defaultBaseUrl,
|
|
801
417
|
agentDir,
|
|
802
418
|
streamSimple,
|
|
803
|
-
setupCommands,
|
|
804
419
|
fastMode,
|
|
805
420
|
});
|
|
806
|
-
// Configured successfully — keep /cliproxyapi hidden.
|
|
807
|
-
setupCommands.hide();
|
|
808
421
|
} catch (error) {
|
|
809
422
|
const message = error instanceof Error ? error.message : String(error);
|
|
810
423
|
if (isUnauthorizedModelsError(error)) {
|
|
811
|
-
|
|
812
|
-
setupCommands.syncVisibility({ forceShow: true });
|
|
813
|
-
logWarn(`models request unauthorized (${message}). Setup command available: /cliproxyapi or /login.`);
|
|
424
|
+
logWarn(`models request unauthorized (${message}). Use /login ${identity.providerName} to reconfigure.`);
|
|
814
425
|
} else {
|
|
815
|
-
// Other failures (network, etc.): still offer setup for reconfiguration.
|
|
816
|
-
setupCommands.syncVisibility({ forceShow: true });
|
|
817
426
|
logWarn(
|
|
818
|
-
`failed to load models (${message}).
|
|
427
|
+
`failed to load models (${message}). Use /login ${identity.providerName} or check ${CONFIG_FILE_NAME} / CLIPROXYAPI_* env vars.`,
|
|
819
428
|
);
|
|
820
429
|
}
|
|
821
430
|
}
|
package/extensions/lib.ts
CHANGED
|
@@ -18,7 +18,7 @@ export const CONFIG_FILE_NAME = "cliproxyapi.json";
|
|
|
18
18
|
export const AUTH_FILE_NAME = "auth.json";
|
|
19
19
|
export const CLIENT_VERSION = "pi";
|
|
20
20
|
|
|
21
|
-
/** Keep login credentials effectively permanent; reconfigure via /
|
|
21
|
+
/** Keep login credentials effectively permanent; reconfigure via /login. */
|
|
22
22
|
export const CREDENTIAL_TTL_MS = 100 * 365 * 24 * 60 * 60 * 1000;
|
|
23
23
|
|
|
24
24
|
export const ZERO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } as const;
|
|
@@ -387,7 +387,7 @@ export function toPiModel(model: CodexClientModel): PiProviderModel | null {
|
|
|
387
387
|
};
|
|
388
388
|
}
|
|
389
389
|
|
|
390
|
-
/** HTTP error from /v1/models (used to detect 401
|
|
390
|
+
/** HTTP error from /v1/models (used to detect 401). */
|
|
391
391
|
export class ModelsHttpError extends Error {
|
|
392
392
|
readonly status: number;
|
|
393
393
|
readonly statusText: string;
|
package/package.json
CHANGED