@router-for-me/pi-cliproxyapi-provider 1.0.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.
- package/LICENSE +21 -0
- package/README.md +175 -0
- package/extensions/codex-stream.ts +153 -0
- package/extensions/index.ts +624 -0
- package/extensions/lib.ts +418 -0
- package/package.json +56 -0
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CLIProxyAPI dynamic model provider for pi.
|
|
3
|
+
*
|
|
4
|
+
* Supports login-style setup via `/login` and dedicated commands:
|
|
5
|
+
* 1. Provider always appears under "Use a subscription" as CLIProxyAPI
|
|
6
|
+
* (pi only supports multi-field prompts on the oauth/subscription path).
|
|
7
|
+
* 2. Preferred shortcuts: `/login CLIProxyAPI`, `/login cliproxyapi`,
|
|
8
|
+
* or dedicated commands `/cliproxyapi` / `/cpa` (shown only when not authenticated).
|
|
9
|
+
* 3. Setup prompts for baseUrl + apiKey.
|
|
10
|
+
* 4. Final login step validates credentials via /v1/models?client_version=pi
|
|
11
|
+
* (HTTP 200 = success even if the catalog is empty; otherwise re-prompt).
|
|
12
|
+
* 5. On success, models/credentials are saved and `/cliproxyapi` `/cpa` are hidden.
|
|
13
|
+
* 6. Setup commands reappear after `/logout` or when a models request returns HTTP 401.
|
|
14
|
+
*
|
|
15
|
+
* Uses a patched openai-codex-responses implementation that does not require
|
|
16
|
+
* extracting chatgpt_account_id from the API key (plain CPA keys work).
|
|
17
|
+
*
|
|
18
|
+
* Non-interactive setup still works via env vars or ~/.pi/agent/cliproxyapi.json.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { Api, Model, OAuthCredentials, OAuthLoginCallbacks } from "@earendil-works/pi-ai";
|
|
22
|
+
import { type ExtensionAPI, type ExtensionCommandContext, getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
23
|
+
import { CLIPROXYAPI_CODEX_API, type CliproxyCodexStreamSimple, loadCliproxyCodexStreams } from "./codex-stream.ts";
|
|
24
|
+
import {
|
|
25
|
+
CONFIG_FILE_NAME,
|
|
26
|
+
CREDENTIAL_TTL_MS,
|
|
27
|
+
DEFAULT_BASE_URL,
|
|
28
|
+
decodeRefreshMeta,
|
|
29
|
+
encodeRefreshMeta,
|
|
30
|
+
firstNonEmpty,
|
|
31
|
+
isUnauthorizedModelsError,
|
|
32
|
+
loadAuthConnection,
|
|
33
|
+
loadConfigFile,
|
|
34
|
+
loadMappedModels,
|
|
35
|
+
type PiProviderModel,
|
|
36
|
+
resolveConnection,
|
|
37
|
+
resolveEndpoints,
|
|
38
|
+
resolveIdentity,
|
|
39
|
+
saveConfigFile,
|
|
40
|
+
} from "./lib.ts";
|
|
41
|
+
|
|
42
|
+
/** Controls visibility of /cliproxyapi and /cpa in the slash-command menu. */
|
|
43
|
+
interface SetupCommandsController {
|
|
44
|
+
show(): void;
|
|
45
|
+
hide(): void;
|
|
46
|
+
isVisible(): boolean;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function logWarn(message: string): void {
|
|
50
|
+
console.warn(`[pi-cliproxyapi-provider] ${message}`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function logInfo(message: string): void {
|
|
54
|
+
console.info(`[pi-cliproxyapi-provider] ${message}`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function buildOAuthCredentials(baseUrlInput: string, apiKey: string): OAuthCredentials {
|
|
58
|
+
return {
|
|
59
|
+
refresh: encodeRefreshMeta(baseUrlInput),
|
|
60
|
+
access: apiKey,
|
|
61
|
+
expires: Date.now() + CREDENTIAL_TTL_MS,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function resolveDefaultBaseUrl(agentDir: string, providerId: string): string {
|
|
66
|
+
let fileBaseUrl: string | undefined;
|
|
67
|
+
try {
|
|
68
|
+
fileBaseUrl = loadConfigFile(agentDir).baseUrl;
|
|
69
|
+
} catch (error) {
|
|
70
|
+
const err = error as NodeJS.ErrnoException;
|
|
71
|
+
if (err.code !== "ENOENT") {
|
|
72
|
+
logWarn(`failed to read ${CONFIG_FILE_NAME}: ${err.message}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let authBaseUrl: string | undefined;
|
|
77
|
+
try {
|
|
78
|
+
authBaseUrl = loadAuthConnection(agentDir, providerId)?.baseUrl;
|
|
79
|
+
} catch (error) {
|
|
80
|
+
const err = error as Error;
|
|
81
|
+
logWarn(`failed to read auth.json: ${err.message}`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return firstNonEmpty(process.env.CLIPROXYAPI_BASE_URL, fileBaseUrl, authBaseUrl, DEFAULT_BASE_URL)!;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function promptConnection(
|
|
88
|
+
callbacks: OAuthLoginCallbacks,
|
|
89
|
+
defaults: { baseUrl: string },
|
|
90
|
+
): Promise<{ baseUrlInput: string; apiKey: string }> {
|
|
91
|
+
callbacks.onProgress?.("Configure CLIProxyAPI. Preferred baseUrl form: host:port (e.g. http://127.0.0.1:8317).");
|
|
92
|
+
|
|
93
|
+
const baseUrlRaw = await callbacks.onPrompt({
|
|
94
|
+
message: `CLIProxyAPI base URL [${defaults.baseUrl}]:`,
|
|
95
|
+
placeholder: defaults.baseUrl,
|
|
96
|
+
allowEmpty: true,
|
|
97
|
+
});
|
|
98
|
+
const baseUrlInput = firstNonEmpty(baseUrlRaw, defaults.baseUrl)!;
|
|
99
|
+
|
|
100
|
+
// Validate early so users get a clear error before typing the API key.
|
|
101
|
+
resolveEndpoints(baseUrlInput);
|
|
102
|
+
|
|
103
|
+
const apiKey = (
|
|
104
|
+
await callbacks.onPrompt({
|
|
105
|
+
message: "CLIProxyAPI API key:",
|
|
106
|
+
placeholder: "sk-...",
|
|
107
|
+
allowEmpty: false,
|
|
108
|
+
})
|
|
109
|
+
).trim();
|
|
110
|
+
|
|
111
|
+
if (!apiKey) {
|
|
112
|
+
throw new Error("API key cannot be empty.");
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return { baseUrlInput, apiKey };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function configureAndRegister(options: {
|
|
119
|
+
pi: ExtensionAPI;
|
|
120
|
+
agentDir: string;
|
|
121
|
+
providerId: string;
|
|
122
|
+
providerName: string;
|
|
123
|
+
baseUrlInput: string;
|
|
124
|
+
apiKey: string;
|
|
125
|
+
defaultBaseUrl: string;
|
|
126
|
+
streamSimple: CliproxyCodexStreamSimple;
|
|
127
|
+
setupCommands: SetupCommandsController;
|
|
128
|
+
}): Promise<{ modelCount: number; modelsUrl: string }> {
|
|
129
|
+
const { pi, agentDir, providerId, providerName, baseUrlInput, apiKey, defaultBaseUrl, streamSimple, setupCommands } =
|
|
130
|
+
options;
|
|
131
|
+
|
|
132
|
+
const loaded = await loadMappedModels(baseUrlInput, apiKey);
|
|
133
|
+
|
|
134
|
+
saveConfigFile(agentDir, {
|
|
135
|
+
baseUrl: baseUrlInput,
|
|
136
|
+
apiKey,
|
|
137
|
+
providerId,
|
|
138
|
+
providerName,
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
registerProvider(pi, {
|
|
142
|
+
providerId,
|
|
143
|
+
providerName,
|
|
144
|
+
baseUrlInput,
|
|
145
|
+
apiKey,
|
|
146
|
+
models: loaded.models,
|
|
147
|
+
defaultBaseUrl: baseUrlInput || defaultBaseUrl,
|
|
148
|
+
agentDir,
|
|
149
|
+
streamSimple,
|
|
150
|
+
setupCommands,
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
// Login succeeded — hide dedicated setup commands from the slash menu.
|
|
154
|
+
setupCommands.hide();
|
|
155
|
+
|
|
156
|
+
return { modelCount: loaded.models.length, modelsUrl: loaded.modelsUrl };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function createOAuthHandlers(options: {
|
|
160
|
+
pi: ExtensionAPI;
|
|
161
|
+
agentDir: string;
|
|
162
|
+
providerId: string;
|
|
163
|
+
providerName: string;
|
|
164
|
+
defaultBaseUrl: string;
|
|
165
|
+
streamSimple: CliproxyCodexStreamSimple;
|
|
166
|
+
setupCommands: SetupCommandsController;
|
|
167
|
+
}) {
|
|
168
|
+
const { pi, agentDir, providerId, providerName, defaultBaseUrl, streamSimple, setupCommands } = options;
|
|
169
|
+
|
|
170
|
+
return {
|
|
171
|
+
name: providerName,
|
|
172
|
+
|
|
173
|
+
async login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
|
|
174
|
+
let promptDefaultBaseUrl = resolveDefaultBaseUrl(agentDir, providerId) || defaultBaseUrl;
|
|
175
|
+
|
|
176
|
+
// Final login step: validate by calling /v1/models.
|
|
177
|
+
// HTTP 200 (even with an empty catalog) means success; otherwise re-prompt.
|
|
178
|
+
while (true) {
|
|
179
|
+
const { baseUrlInput, apiKey } = await promptConnection(callbacks, {
|
|
180
|
+
baseUrl: promptDefaultBaseUrl,
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
callbacks.onProgress?.("Validating credentials via models endpoint...");
|
|
184
|
+
try {
|
|
185
|
+
const result = await configureAndRegister({
|
|
186
|
+
pi,
|
|
187
|
+
agentDir,
|
|
188
|
+
providerId,
|
|
189
|
+
providerName,
|
|
190
|
+
baseUrlInput,
|
|
191
|
+
apiKey,
|
|
192
|
+
defaultBaseUrl,
|
|
193
|
+
streamSimple,
|
|
194
|
+
setupCommands,
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
logInfo(`login ok: registered ${result.modelCount} models from ${result.modelsUrl}`);
|
|
198
|
+
return buildOAuthCredentials(baseUrlInput, apiKey);
|
|
199
|
+
} catch (error) {
|
|
200
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
201
|
+
logWarn(`login validation failed: ${message}`);
|
|
202
|
+
// Auth failures should keep setup commands available for reconfiguration.
|
|
203
|
+
if (isUnauthorizedModelsError(error)) {
|
|
204
|
+
setupCommands.show();
|
|
205
|
+
}
|
|
206
|
+
callbacks.onProgress?.(`Login validation failed: ${message}\nPlease re-enter base URL and API key.`);
|
|
207
|
+
// Keep last baseUrl as the next default so retyping is easier.
|
|
208
|
+
promptDefaultBaseUrl = baseUrlInput || promptDefaultBaseUrl;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
},
|
|
212
|
+
|
|
213
|
+
async refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
|
|
214
|
+
// API keys do not expire; keep the stored payload as-is.
|
|
215
|
+
return {
|
|
216
|
+
...credentials,
|
|
217
|
+
expires: Date.now() + CREDENTIAL_TTL_MS,
|
|
218
|
+
};
|
|
219
|
+
},
|
|
220
|
+
|
|
221
|
+
getApiKey(credentials: OAuthCredentials): string {
|
|
222
|
+
return credentials.access;
|
|
223
|
+
},
|
|
224
|
+
|
|
225
|
+
modifyModels(models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[] {
|
|
226
|
+
const meta = decodeRefreshMeta(credentials.refresh);
|
|
227
|
+
if (!meta?.baseUrl) {
|
|
228
|
+
return models;
|
|
229
|
+
}
|
|
230
|
+
try {
|
|
231
|
+
const { inferenceBaseUrl } = resolveEndpoints(meta.baseUrl);
|
|
232
|
+
return models.map((model) =>
|
|
233
|
+
model.provider === providerId ? { ...model, baseUrl: inferenceBaseUrl } : model,
|
|
234
|
+
);
|
|
235
|
+
} catch {
|
|
236
|
+
return models;
|
|
237
|
+
}
|
|
238
|
+
},
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function registerProvider(
|
|
243
|
+
pi: ExtensionAPI,
|
|
244
|
+
options: {
|
|
245
|
+
providerId: string;
|
|
246
|
+
providerName: string;
|
|
247
|
+
baseUrlInput: string;
|
|
248
|
+
apiKey?: string;
|
|
249
|
+
models?: PiProviderModel[];
|
|
250
|
+
defaultBaseUrl: string;
|
|
251
|
+
agentDir: string;
|
|
252
|
+
streamSimple: CliproxyCodexStreamSimple;
|
|
253
|
+
setupCommands: SetupCommandsController;
|
|
254
|
+
},
|
|
255
|
+
): void {
|
|
256
|
+
const {
|
|
257
|
+
providerId,
|
|
258
|
+
providerName,
|
|
259
|
+
baseUrlInput,
|
|
260
|
+
apiKey,
|
|
261
|
+
models,
|
|
262
|
+
defaultBaseUrl,
|
|
263
|
+
agentDir,
|
|
264
|
+
streamSimple,
|
|
265
|
+
setupCommands,
|
|
266
|
+
} = options;
|
|
267
|
+
|
|
268
|
+
const endpoints = resolveEndpoints(baseUrlInput);
|
|
269
|
+
const oauth = createOAuthHandlers({
|
|
270
|
+
pi,
|
|
271
|
+
agentDir,
|
|
272
|
+
providerId,
|
|
273
|
+
providerName,
|
|
274
|
+
defaultBaseUrl,
|
|
275
|
+
streamSimple,
|
|
276
|
+
setupCommands,
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
pi.registerProvider(providerId, {
|
|
280
|
+
name: providerName,
|
|
281
|
+
baseUrl: endpoints.inferenceBaseUrl,
|
|
282
|
+
api: CLIPROXYAPI_CODEX_API,
|
|
283
|
+
streamSimple,
|
|
284
|
+
// Keep oauth always registered so /login lists this provider even before models exist.
|
|
285
|
+
oauth,
|
|
286
|
+
// apiKey is optional when oauth is present; include it when known for direct use.
|
|
287
|
+
...(apiKey ? { apiKey } : {}),
|
|
288
|
+
...(models && models.length > 0 ? { models } : {}),
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const SETUP_COMMAND_NAMES = ["cliproxyapi", "cpa"] as const;
|
|
293
|
+
|
|
294
|
+
/** Avoid double-wrapping the same AuthStorage instance across session reloads. */
|
|
295
|
+
const logoutWatchedStorages = new WeakSet<object>();
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* pi has no logout extension event. Wrap authStorage.logout so we can re-show
|
|
299
|
+
* setup commands when this provider is removed via /logout.
|
|
300
|
+
*/
|
|
301
|
+
function watchProviderLogout(
|
|
302
|
+
authStorage: { logout(provider: string): void },
|
|
303
|
+
providerId: string,
|
|
304
|
+
onLogout: () => void,
|
|
305
|
+
): void {
|
|
306
|
+
if (logoutWatchedStorages.has(authStorage as object)) {
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
logoutWatchedStorages.add(authStorage as object);
|
|
310
|
+
|
|
311
|
+
const originalLogout = authStorage.logout.bind(authStorage);
|
|
312
|
+
authStorage.logout = (provider: string): void => {
|
|
313
|
+
originalLogout(provider);
|
|
314
|
+
if (provider === providerId) {
|
|
315
|
+
onLogout();
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Show/hide /cliproxyapi and /cpa.
|
|
322
|
+
*
|
|
323
|
+
* pi has registerCommand but no unregisterCommand, so hide() removes entries from the
|
|
324
|
+
* extension's internal commands Map captured during the first registration.
|
|
325
|
+
*/
|
|
326
|
+
function createSetupCommandsController(options: {
|
|
327
|
+
pi: ExtensionAPI;
|
|
328
|
+
agentDir: string;
|
|
329
|
+
providerId: string;
|
|
330
|
+
providerName: string;
|
|
331
|
+
defaultBaseUrl: string;
|
|
332
|
+
streamSimple: CliproxyCodexStreamSimple;
|
|
333
|
+
}): SetupCommandsController {
|
|
334
|
+
const { pi, agentDir, providerId, providerName, defaultBaseUrl, streamSimple } = options;
|
|
335
|
+
|
|
336
|
+
// Self-referential controller so handlers can hide/show after validation.
|
|
337
|
+
const setupCommands: SetupCommandsController = {
|
|
338
|
+
show() {
|
|
339
|
+
/* replaced below */
|
|
340
|
+
},
|
|
341
|
+
hide() {
|
|
342
|
+
/* replaced below */
|
|
343
|
+
},
|
|
344
|
+
isVisible() {
|
|
345
|
+
return false;
|
|
346
|
+
},
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
let visible = false;
|
|
350
|
+
// Captured extension.commands Map (pi has no public unregisterCommand API).
|
|
351
|
+
let commandMap: Map<string, unknown> | null = null;
|
|
352
|
+
|
|
353
|
+
const handler = async (_args: string, ctx: ExtensionCommandContext): Promise<void> => {
|
|
354
|
+
if (!ctx.hasUI) {
|
|
355
|
+
ctx.ui.notify(
|
|
356
|
+
`Interactive UI unavailable. Use /login ${providerName}, set ${CONFIG_FILE_NAME}, or CLIPROXYAPI_* env vars.`,
|
|
357
|
+
"error",
|
|
358
|
+
);
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const promptDefaultBaseUrl = resolveDefaultBaseUrl(agentDir, providerId) || defaultBaseUrl;
|
|
363
|
+
|
|
364
|
+
const baseUrlRaw = await ctx.ui.input(`CLIProxyAPI base URL [${promptDefaultBaseUrl}]:`, promptDefaultBaseUrl);
|
|
365
|
+
if (baseUrlRaw === undefined) {
|
|
366
|
+
ctx.ui.notify("CLIProxyAPI setup cancelled.", "info");
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
const baseUrlInput = firstNonEmpty(baseUrlRaw, promptDefaultBaseUrl)!;
|
|
370
|
+
|
|
371
|
+
try {
|
|
372
|
+
resolveEndpoints(baseUrlInput);
|
|
373
|
+
} catch (error) {
|
|
374
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
375
|
+
ctx.ui.notify(`Invalid base URL: ${message}`, "error");
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const apiKeyRaw = await ctx.ui.input("CLIProxyAPI API key:", "sk-...");
|
|
380
|
+
if (apiKeyRaw === undefined) {
|
|
381
|
+
ctx.ui.notify("CLIProxyAPI setup cancelled.", "info");
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
const apiKey = apiKeyRaw.trim();
|
|
385
|
+
if (!apiKey) {
|
|
386
|
+
ctx.ui.notify("API key cannot be empty.", "error");
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// Final setup step: validate by calling /v1/models.
|
|
391
|
+
// HTTP 200 (even with an empty catalog) means success; otherwise re-prompt.
|
|
392
|
+
let currentBaseUrl = baseUrlInput;
|
|
393
|
+
let currentApiKey = apiKey;
|
|
394
|
+
while (true) {
|
|
395
|
+
try {
|
|
396
|
+
const result = await configureAndRegister({
|
|
397
|
+
pi,
|
|
398
|
+
agentDir,
|
|
399
|
+
providerId,
|
|
400
|
+
providerName,
|
|
401
|
+
baseUrlInput: currentBaseUrl,
|
|
402
|
+
apiKey: currentApiKey,
|
|
403
|
+
defaultBaseUrl,
|
|
404
|
+
streamSimple,
|
|
405
|
+
setupCommands,
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
// Persist only after successful validation; keep AuthStorage in-memory too.
|
|
409
|
+
ctx.modelRegistry.authStorage.set(providerId, {
|
|
410
|
+
type: "oauth",
|
|
411
|
+
...buildOAuthCredentials(currentBaseUrl, currentApiKey),
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
logInfo(`command setup ok: registered ${result.modelCount} models from ${result.modelsUrl}`);
|
|
415
|
+
ctx.ui.notify(`CLIProxyAPI configured: ${result.modelCount} models from ${result.modelsUrl}`, "info");
|
|
416
|
+
return;
|
|
417
|
+
} catch (error) {
|
|
418
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
419
|
+
logWarn(`command setup failed: ${message}`);
|
|
420
|
+
if (isUnauthorizedModelsError(error)) {
|
|
421
|
+
setupCommands.show();
|
|
422
|
+
}
|
|
423
|
+
ctx.ui.notify(`CLIProxyAPI validation failed: ${message}. Please re-enter base URL and API key.`, "error");
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
// Collect replacement credentials before retrying validation.
|
|
427
|
+
while (true) {
|
|
428
|
+
const retryBaseUrlRaw = await ctx.ui.input(`CLIProxyAPI base URL [${currentBaseUrl}]:`, currentBaseUrl);
|
|
429
|
+
if (retryBaseUrlRaw === undefined) {
|
|
430
|
+
ctx.ui.notify("CLIProxyAPI setup cancelled.", "info");
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
const retryBaseUrl = firstNonEmpty(retryBaseUrlRaw, currentBaseUrl)!;
|
|
434
|
+
try {
|
|
435
|
+
resolveEndpoints(retryBaseUrl);
|
|
436
|
+
} catch (urlError) {
|
|
437
|
+
const urlMessage = urlError instanceof Error ? urlError.message : String(urlError);
|
|
438
|
+
ctx.ui.notify(`Invalid base URL: ${urlMessage}`, "error");
|
|
439
|
+
continue;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const retryApiKeyRaw = await ctx.ui.input("CLIProxyAPI API key:", "sk-...");
|
|
443
|
+
if (retryApiKeyRaw === undefined) {
|
|
444
|
+
ctx.ui.notify("CLIProxyAPI setup cancelled.", "info");
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
const retryApiKey = retryApiKeyRaw.trim();
|
|
448
|
+
if (!retryApiKey) {
|
|
449
|
+
ctx.ui.notify("API key cannot be empty.", "error");
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
currentBaseUrl = retryBaseUrl;
|
|
454
|
+
currentApiKey = retryApiKey;
|
|
455
|
+
break;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
const commandSpecs: Array<{ name: (typeof SETUP_COMMAND_NAMES)[number]; description: string }> = [
|
|
461
|
+
{
|
|
462
|
+
name: "cliproxyapi",
|
|
463
|
+
description: "Configure CLIProxyAPI (baseUrl + API key) and load models. Prefer this or /login CLIProxyAPI.",
|
|
464
|
+
},
|
|
465
|
+
{
|
|
466
|
+
name: "cpa",
|
|
467
|
+
description: "Alias for /cliproxyapi — configure CLIProxyAPI and load models.",
|
|
468
|
+
},
|
|
469
|
+
];
|
|
470
|
+
|
|
471
|
+
const registerAll = (): void => {
|
|
472
|
+
for (const spec of commandSpecs) {
|
|
473
|
+
pi.registerCommand(spec.name, {
|
|
474
|
+
description: spec.description,
|
|
475
|
+
handler,
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
setupCommands.show = (): void => {
|
|
481
|
+
if (visible) {
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
if (!commandMap) {
|
|
486
|
+
// Capture the extension.commands Map during first registration.
|
|
487
|
+
const originalSet = Map.prototype.set;
|
|
488
|
+
Map.prototype.set = function setWithCapture(this: Map<unknown, unknown>, key: unknown, value: unknown) {
|
|
489
|
+
if (
|
|
490
|
+
key === "cliproxyapi" &&
|
|
491
|
+
value &&
|
|
492
|
+
typeof value === "object" &&
|
|
493
|
+
"handler" in (value as Record<string, unknown>)
|
|
494
|
+
) {
|
|
495
|
+
commandMap = this as Map<string, unknown>;
|
|
496
|
+
}
|
|
497
|
+
return originalSet.call(this, key, value);
|
|
498
|
+
} as typeof Map.prototype.set;
|
|
499
|
+
try {
|
|
500
|
+
registerAll();
|
|
501
|
+
} finally {
|
|
502
|
+
Map.prototype.set = originalSet;
|
|
503
|
+
}
|
|
504
|
+
if (!commandMap) {
|
|
505
|
+
logWarn("could not capture command map; /cliproxyapi and /cpa cannot be hidden after login");
|
|
506
|
+
}
|
|
507
|
+
} else {
|
|
508
|
+
registerAll();
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
visible = true;
|
|
512
|
+
logInfo("setup commands shown: /cliproxyapi, /cpa");
|
|
513
|
+
};
|
|
514
|
+
|
|
515
|
+
setupCommands.hide = (): void => {
|
|
516
|
+
if (!visible) {
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
if (!commandMap) {
|
|
520
|
+
logWarn("setup commands remain visible (no command map capture for unregister)");
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
for (const name of SETUP_COMMAND_NAMES) {
|
|
524
|
+
commandMap.delete(name);
|
|
525
|
+
}
|
|
526
|
+
visible = false;
|
|
527
|
+
logInfo("setup commands hidden (CLIProxyAPI already authenticated)");
|
|
528
|
+
};
|
|
529
|
+
|
|
530
|
+
setupCommands.isVisible = (): boolean => visible;
|
|
531
|
+
|
|
532
|
+
return setupCommands;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
export { CLIPROXYAPI_CODEX_API } from "./codex-stream.ts";
|
|
536
|
+
export { resolveEndpoints, toPiModel } from "./lib.ts";
|
|
537
|
+
|
|
538
|
+
export default async function (pi: ExtensionAPI): Promise<void> {
|
|
539
|
+
const agentDir = getAgentDir();
|
|
540
|
+
const identity = resolveIdentity(agentDir);
|
|
541
|
+
const defaultBaseUrl = resolveDefaultBaseUrl(agentDir, identity.providerId);
|
|
542
|
+
|
|
543
|
+
let streamSimple: CliproxyCodexStreamSimple;
|
|
544
|
+
try {
|
|
545
|
+
const streams = await loadCliproxyCodexStreams([identity.providerId, "cliproxyapi"]);
|
|
546
|
+
streamSimple = streams.streamSimple;
|
|
547
|
+
logInfo(`using patched protocol api=${streams.api}`);
|
|
548
|
+
} catch (error) {
|
|
549
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
550
|
+
logWarn(`failed to load patched codex protocol: ${message}`);
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
const setupCommands = createSetupCommandsController({
|
|
555
|
+
pi,
|
|
556
|
+
agentDir,
|
|
557
|
+
providerId: identity.providerId,
|
|
558
|
+
providerName: identity.providerName,
|
|
559
|
+
defaultBaseUrl,
|
|
560
|
+
streamSimple,
|
|
561
|
+
});
|
|
562
|
+
|
|
563
|
+
// Re-show setup commands when the user /logout this provider.
|
|
564
|
+
// Installed on session_start because AuthStorage is only available via ctx then.
|
|
565
|
+
pi.on("session_start", (_event, ctx) => {
|
|
566
|
+
watchProviderLogout(ctx.modelRegistry.authStorage, identity.providerId, () => {
|
|
567
|
+
setupCommands.show();
|
|
568
|
+
logInfo(`logout detected for ${identity.providerId}: setup commands restored: /cliproxyapi, /cpa`);
|
|
569
|
+
});
|
|
570
|
+
});
|
|
571
|
+
|
|
572
|
+
// Always register oauth so the provider is visible in /login immediately after install.
|
|
573
|
+
registerProvider(pi, {
|
|
574
|
+
providerId: identity.providerId,
|
|
575
|
+
providerName: identity.providerName,
|
|
576
|
+
baseUrlInput: defaultBaseUrl,
|
|
577
|
+
defaultBaseUrl,
|
|
578
|
+
agentDir,
|
|
579
|
+
streamSimple,
|
|
580
|
+
setupCommands,
|
|
581
|
+
});
|
|
582
|
+
|
|
583
|
+
const connection = resolveConnection(agentDir, identity.providerId);
|
|
584
|
+
if (!connection) {
|
|
585
|
+
setupCommands.show();
|
|
586
|
+
logInfo(
|
|
587
|
+
`not configured yet. Prefer /cliproxyapi (or /cpa), or /login ${identity.providerName}. ` +
|
|
588
|
+
`Menu path: /login → Use a subscription → ${identity.providerName}. ` +
|
|
589
|
+
`Or set ${CONFIG_FILE_NAME} / CLIPROXYAPI_API_KEY.`,
|
|
590
|
+
);
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
try {
|
|
595
|
+
const loaded = await loadMappedModels(connection.baseUrlInput, connection.apiKey);
|
|
596
|
+
registerProvider(pi, {
|
|
597
|
+
providerId: identity.providerId,
|
|
598
|
+
providerName: identity.providerName,
|
|
599
|
+
baseUrlInput: connection.baseUrlInput,
|
|
600
|
+
apiKey: connection.apiKey,
|
|
601
|
+
models: loaded.models,
|
|
602
|
+
defaultBaseUrl,
|
|
603
|
+
agentDir,
|
|
604
|
+
streamSimple,
|
|
605
|
+
setupCommands,
|
|
606
|
+
});
|
|
607
|
+
// Already authenticated — keep /cliproxyapi and /cpa hidden.
|
|
608
|
+
setupCommands.hide();
|
|
609
|
+
logInfo(`loaded ${loaded.models.length} models from ${loaded.modelsUrl}`);
|
|
610
|
+
} catch (error) {
|
|
611
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
612
|
+
if (isUnauthorizedModelsError(error)) {
|
|
613
|
+
// 401 → credentials rejected; re-show setup commands for reconfiguration.
|
|
614
|
+
setupCommands.show();
|
|
615
|
+
logWarn(`models request unauthorized (${message}). Setup commands restored: /cliproxyapi, /cpa.`);
|
|
616
|
+
} else {
|
|
617
|
+
// Other failures (network, etc.): still offer setup so the user can fix baseUrl/key.
|
|
618
|
+
setupCommands.show();
|
|
619
|
+
logWarn(
|
|
620
|
+
`failed to load models (${message}). Provider remains available via /cliproxyapi or /login for reconfiguration.`,
|
|
621
|
+
);
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
}
|