omp-multi-auth 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.
@@ -0,0 +1,551 @@
1
+ // ========================================================================
2
+ // /multi-auth command handlers
3
+ // ========================================================================
4
+ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext, AuthStorage } from "@oh-my-pi/pi-coding-agent";
5
+ import type { Api, Model } from "@oh-my-pi/pi-ai";
6
+ import { getAuthStorage, getModels, subProviderName, type MultiAuthConfig, type SubEntry } from "./core.ts";
7
+ import { loadGlobalConfig, loadProjectConfig, saveGlobalConfig, parseEnvConfig, mergeConfigs, normalizeEntries, getSubscriptionSource, formatSubscriptionMeta, formatSubscriptionListLine, formatSubscriptionStatus } from "./config.ts";
8
+ import { PROVIDER_TEMPLATES, SUPPORTED_PROVIDERS, getBaseProvider, subDisplayName, registerSub } from "./providers.ts";
9
+ import { handleSubsLimits } from "./quota.ts";
10
+ import { showWrappedSelect } from "./ui.ts";
11
+ import type { SelectItem } from "@oh-my-pi/pi-tui";
12
+
13
+ export function normalizeSwitchAllowedProviderNames(cwd: string): string[] | undefined {
14
+ const project = loadProjectConfig(cwd);
15
+ if (!project?.allowedSubs || project.allowedSubs.length === 0) return undefined;
16
+ const normalized = [...new Set(project.allowedSubs.map((value) => value.trim()).filter(Boolean))];
17
+ return normalized.length > 0 ? normalized : undefined;
18
+ }
19
+
20
+ export function getSwitchableProviderOptions(
21
+ ctx: ExtensionContext | ExtensionCommandContext,
22
+ ): Array<{ providerName: string; label: string; description: string }> {
23
+ const config = loadGlobalConfig();
24
+ const envEntries = parseEnvConfig();
25
+ const allSubs = normalizeEntries(mergeConfigs(config, envEntries));
26
+ const allowedProviderNames = normalizeSwitchAllowedProviderNames(ctx.cwd);
27
+ const allowed = allowedProviderNames ? new Set(allowedProviderNames) : undefined;
28
+ const options: Array<{ providerName: string; label: string; description: string }> = [];
29
+ const seen = new Set<string>();
30
+ const push = (providerName: string, label: string, description: string) => {
31
+ if (allowed && !allowed.has(providerName)) return;
32
+ if (!getAuthStorage(ctx).hasAuth(providerName)) return;
33
+ if (seen.has(providerName)) return;
34
+ seen.add(providerName);
35
+ options.push({ providerName, label, description });
36
+ };
37
+
38
+ for (const providerName of SUPPORTED_PROVIDERS) {
39
+ push(
40
+ providerName,
41
+ PROVIDER_TEMPLATES[providerName]?.displayName || providerName,
42
+ "base provider",
43
+ );
44
+ }
45
+ for (const entry of allSubs) {
46
+ push(subProviderName(entry), subDisplayName(entry), "extra subscription");
47
+ }
48
+ return options;
49
+ }
50
+
51
+ export function resolveSwitchTargetModel(
52
+ ctx: ExtensionContext | ExtensionCommandContext,
53
+ providerName: string,
54
+ preferredModelId?: string,
55
+ ): Model<Api> | undefined {
56
+ if (!getAuthStorage(ctx).hasAuth(providerName)) {
57
+ return undefined;
58
+ }
59
+ if (preferredModelId) {
60
+ const preferred = ctx.modelRegistry.find(providerName, preferredModelId);
61
+ if (preferred) {
62
+ return preferred as Model<Api>;
63
+ }
64
+ }
65
+ const baseProvider = getBaseProvider(providerName);
66
+ if (!baseProvider) {
67
+ return undefined;
68
+ }
69
+ for (const baseModel of getModels(baseProvider as any) as Model<Api>[]) {
70
+ const candidate = ctx.modelRegistry.find(providerName, baseModel.id);
71
+ if (candidate) {
72
+ return candidate as Model<Api>;
73
+ }
74
+ }
75
+ return undefined;
76
+ }
77
+
78
+ export async function handleSubsSwitch(
79
+ pi: ExtensionAPI,
80
+ ctx: ExtensionCommandContext,
81
+ requestedProviderName?: string,
82
+ ): Promise<void> {
83
+ const options = getSwitchableProviderOptions(ctx);
84
+ if (options.length === 0) {
85
+ const allowedProviderNames = normalizeSwitchAllowedProviderNames(ctx.cwd);
86
+ const suffix = allowedProviderNames && allowedProviderNames.length > 0
87
+ ? ` for this project restriction (${allowedProviderNames.join(", ")})`
88
+ : "";
89
+ ctx.ui.notify(`No authenticated subscriptions are available to switch${suffix}.`, "info");
90
+ return;
91
+ }
92
+
93
+ let providerName = requestedProviderName?.trim();
94
+ if (!providerName) {
95
+ providerName = await showWrappedSelect(ctx, {
96
+ title: "Switch Subscription",
97
+ subtitle: "Select the subscription/provider to use now.",
98
+ items: options.map((option) => ({
99
+ value: option.providerName,
100
+ label: option.label,
101
+ description: option.description,
102
+ })),
103
+ initialValue: ctx.model?.provider,
104
+ confirmHint: "switch",
105
+ cancelHint: "back",
106
+ });
107
+ if (!providerName) return;
108
+ }
109
+
110
+ const selected = options.find((option) => option.providerName === providerName);
111
+ if (!selected) {
112
+ ctx.ui.notify(`Subscription not available for switching: ${providerName}`, "error");
113
+ return;
114
+ }
115
+
116
+ const nextModel = resolveSwitchTargetModel(ctx, selected.providerName, ctx.model?.id);
117
+ if (!nextModel) {
118
+ ctx.ui.notify(`No selectable models found for ${selected.label}.`, "error");
119
+ return;
120
+ }
121
+ if (ctx.model?.provider === nextModel.provider && ctx.model?.id === nextModel.id) {
122
+ ctx.ui.notify(`Already using ${selected.label} (${nextModel.id}).`, "info");
123
+ return;
124
+ }
125
+
126
+ const success = await pi.setModel(nextModel);
127
+ if (!success) {
128
+ ctx.ui.notify(`Failed to switch to ${selected.label}.`, "error");
129
+ return;
130
+ }
131
+ ctx.ui.notify(`Switched to ${selected.label} (${nextModel.id}).`, "info");
132
+ }
133
+
134
+ export async function renameSubscriptionLabel(
135
+ ctx: ExtensionCommandContext,
136
+ config: MultiAuthConfig,
137
+ entry: SubEntry,
138
+ ): Promise<void> {
139
+ const previousName = subDisplayName(entry);
140
+ const nextLabel = await ctx.ui.input(
141
+ "Friendly label (optional)",
142
+ entry.label || "e.g. work, personal, team, outlook",
143
+ );
144
+ if (nextLabel === undefined) return;
145
+
146
+ entry.label = nextLabel.trim() || undefined;
147
+ saveGlobalConfig(config);
148
+
149
+ const nextName = subDisplayName(entry);
150
+ if (nextName === previousName) {
151
+ ctx.ui.notify(`No changes for ${nextName}.`, "info");
152
+ return;
153
+ }
154
+
155
+ ctx.ui.notify(`Updated ${previousName} -> ${nextName}`, "info");
156
+ }
157
+
158
+ export async function removeSubscriptionEntry(
159
+ pi: ExtensionAPI,
160
+ ctx: ExtensionCommandContext,
161
+ config: MultiAuthConfig,
162
+ entry: SubEntry,
163
+ ): Promise<void> {
164
+ const confirmed = await ctx.ui.confirm(
165
+ "Confirm removal",
166
+ `Remove ${subDisplayName(entry)}?\nThis will also logout if authenticated.`,
167
+ );
168
+ if (!confirmed) return;
169
+
170
+ const name = subProviderName(entry);
171
+ if (getAuthStorage(ctx).hasAuth(name)) {
172
+ await getAuthStorage(ctx).logout(name);
173
+ }
174
+ pi.unregisterProvider(name);
175
+
176
+ config.subscriptions = config.subscriptions.filter(
177
+ (candidate) => !(candidate.provider === entry.provider && candidate.index === entry.index),
178
+ );
179
+
180
+ saveGlobalConfig(config);
181
+ ctx.modelRegistry.refresh();
182
+ ctx.ui.notify(`Removed ${subDisplayName(entry)}`, "info");
183
+ }
184
+ export function loginSubscription(ctx: ExtensionCommandContext, entry: SubEntry): void {
185
+ const providerName = subProviderName(entry);
186
+ ctx.ui.setEditorText(`/login ${providerName}`);
187
+ ctx.ui.notify(`Press Enter to authenticate ${subDisplayName(entry)} with /login ${providerName}.`, "info");
188
+ }
189
+ export async function showSubscriptionActions(
190
+ pi: ExtensionAPI,
191
+ ctx: ExtensionCommandContext,
192
+ config: MultiAuthConfig,
193
+ entry: SubEntry,
194
+ ): Promise<void> {
195
+ const source = getSubscriptionSource(config, entry);
196
+ if (source === "env") {
197
+ await showWrappedSelect(ctx, {
198
+ title: `Subscription: ${subDisplayName(entry)}`,
199
+ subtitle: "This entry comes from MULTI_SUB and is read-only here.",
200
+ items: [
201
+ {
202
+ value: subProviderName(entry),
203
+ label: formatSubscriptionListLine(entry, config, getAuthStorage(ctx)),
204
+ },
205
+ ],
206
+ confirmHint: "back",
207
+ cancelHint: "back",
208
+ });
209
+ return;
210
+ }
211
+
212
+ const name = subProviderName(entry);
213
+ const hasAuth = getAuthStorage(ctx).hasAuth(name);
214
+ const actionItems: SelectItem[] = [
215
+ { value: "rename", label: "rename", description: "Change friendly label" },
216
+ hasAuth
217
+ ? { value: "logout", label: "logout", description: "Log out this subscription" }
218
+ : { value: "login", label: "login", description: "Show login instructions" },
219
+ { value: "remove", label: "remove", description: "Remove this subscription" },
220
+ ];
221
+
222
+ const action = await showWrappedSelect(ctx, {
223
+ title: subDisplayName(entry),
224
+ subtitle: "Escape returns to the subscriptions list.",
225
+ items: actionItems,
226
+ confirmHint: "open",
227
+ cancelHint: "back",
228
+ });
229
+ if (!action) return;
230
+
231
+ if (action === "rename") {
232
+ return renameSubscriptionLabel(ctx, config, entry);
233
+ }
234
+ if (action === "login") {
235
+ return loginSubscription(ctx, entry);
236
+ }
237
+ if (action === "logout") {
238
+ await getAuthStorage(ctx).logout(name);
239
+ ctx.ui.notify(`Logged out of ${subDisplayName(entry)}`, "info");
240
+ return;
241
+ }
242
+ if (action === "remove") {
243
+ return removeSubscriptionEntry(pi, ctx, config, entry);
244
+ }
245
+ }
246
+
247
+ export async function handleSubsList(
248
+ pi: ExtensionAPI,
249
+ ctx: ExtensionCommandContext,
250
+ config: MultiAuthConfig,
251
+ ): Promise<void> {
252
+ let preferredProviderName: string | undefined = ctx.model?.provider;
253
+
254
+ while (true) {
255
+ const envEntries = parseEnvConfig();
256
+ const all = normalizeEntries(mergeConfigs(config, envEntries));
257
+
258
+ if (all.length === 0) {
259
+ ctx.ui.notify("No extra subscriptions configured. Use /multi-auth add to create one.", "info");
260
+ return;
261
+ }
262
+
263
+ const selectedProviderName = await showWrappedSelect(ctx, {
264
+ title: "Extra Subscriptions",
265
+ subtitle: "Select a subscription for quick actions.",
266
+ items: all.map((entry) => ({
267
+ value: subProviderName(entry),
268
+ label: subDisplayName(entry),
269
+ description: formatSubscriptionMeta(entry, config, getAuthStorage(ctx)),
270
+ })),
271
+ initialValue: preferredProviderName,
272
+ confirmHint: "open",
273
+ cancelHint: "close",
274
+ });
275
+ if (!selectedProviderName) return;
276
+
277
+ preferredProviderName = selectedProviderName;
278
+ const entry = all.find((candidate) => subProviderName(candidate) === selectedProviderName);
279
+ if (!entry) continue;
280
+ await showSubscriptionActions(pi, ctx, config, entry);
281
+ }
282
+ }
283
+
284
+ export async function handleSubsAdd(pi: ExtensionAPI, ctx: ExtensionCommandContext): Promise<void> {
285
+ const providerItems: SelectItem[] = SUPPORTED_PROVIDERS.map((provider) => ({
286
+ value: provider,
287
+ label: provider,
288
+ description: PROVIDER_TEMPLATES[provider]?.displayName,
289
+ }));
290
+
291
+ const provider = await showWrappedSelect(ctx, {
292
+ title: "Select provider to add",
293
+ items: providerItems,
294
+ confirmHint: "select",
295
+ cancelHint: "close",
296
+ });
297
+ if (!provider) return;
298
+
299
+ if (!PROVIDER_TEMPLATES[provider]) {
300
+ ctx.ui.notify(`Unknown provider: ${provider}`, "error");
301
+ return;
302
+ }
303
+
304
+ const label = await ctx.ui.input("Label (optional)", "e.g. work, personal");
305
+
306
+ const config = loadGlobalConfig();
307
+ const envEntries = parseEnvConfig();
308
+ const allEntries = normalizeEntries(mergeConfigs(config, envEntries));
309
+ const usedIndices = new Set(
310
+ allEntries.filter((e) => e.provider === provider).map((e) => e.index),
311
+ );
312
+ let nextIndex = 2;
313
+ while (usedIndices.has(nextIndex)) nextIndex++;
314
+
315
+ const entry: SubEntry = {
316
+ provider,
317
+ index: nextIndex,
318
+ label: label?.trim() || undefined,
319
+ };
320
+
321
+ config.subscriptions.push(entry);
322
+ saveGlobalConfig(config);
323
+
324
+ registerSub(pi, entry);
325
+ ctx.modelRegistry.refresh();
326
+
327
+ const loginNow = await ctx.ui.confirm(
328
+ subDisplayName(entry),
329
+ `Created ${subDisplayName(entry)}.\n\nLogin now?`,
330
+ );
331
+
332
+ if (loginNow) {
333
+ await loginSubscription(ctx, entry);
334
+ } else {
335
+ ctx.ui.notify(`Added ${subDisplayName(entry)}. Use /multi-auth login to authenticate.`, "info");
336
+ }
337
+ }
338
+
339
+ export async function handleSubsRemove(
340
+ pi: ExtensionAPI,
341
+ ctx: ExtensionCommandContext,
342
+ ): Promise<void> {
343
+ const config = loadGlobalConfig();
344
+ if (config.subscriptions.length === 0) {
345
+ ctx.ui.notify("No saved subscriptions to remove.", "info");
346
+ return;
347
+ }
348
+
349
+ const selectedProviderName = await showWrappedSelect(ctx, {
350
+ title: "Remove subscription",
351
+ subtitle: "Select a saved subscription to remove.",
352
+ initialValue: ctx.model?.provider,
353
+ items: config.subscriptions.map((entry) => ({
354
+ value: subProviderName(entry),
355
+ label: subDisplayName(entry),
356
+ description: formatSubscriptionStatus(entry, getAuthStorage(ctx)),
357
+ })),
358
+ confirmHint: "remove",
359
+ cancelHint: "back",
360
+ });
361
+ if (!selectedProviderName) return;
362
+
363
+ const entry = config.subscriptions.find(
364
+ (candidate) => subProviderName(candidate) === selectedProviderName,
365
+ );
366
+ if (!entry) return;
367
+
368
+ return removeSubscriptionEntry(pi, ctx, config, entry);
369
+ }
370
+
371
+ export async function handleSubsLogin(ctx: ExtensionCommandContext): Promise<void> {
372
+ const config = loadGlobalConfig();
373
+ const envEntries = parseEnvConfig();
374
+ const all = normalizeEntries(mergeConfigs(config, envEntries));
375
+
376
+ const notLoggedIn = all.filter(
377
+ (entry) => !getAuthStorage(ctx).hasAuth(subProviderName(entry)),
378
+ );
379
+
380
+ if (notLoggedIn.length === 0) {
381
+ ctx.ui.notify(
382
+ all.length === 0
383
+ ? "No subscriptions configured. Use /multi-auth add first."
384
+ : "All subscriptions are already logged in.",
385
+ "info",
386
+ );
387
+ return;
388
+ }
389
+
390
+ const selectedProviderName = await showWrappedSelect(ctx, {
391
+ title: "Login to subscription",
392
+ subtitle: "Select a subscription to authenticate.",
393
+ initialValue: ctx.model?.provider,
394
+ items: notLoggedIn.map((entry) => ({
395
+ value: subProviderName(entry),
396
+ label: subDisplayName(entry),
397
+ description: "not logged in",
398
+ })),
399
+ confirmHint: "open",
400
+ cancelHint: "back",
401
+ });
402
+ if (!selectedProviderName) return;
403
+
404
+ const entry = notLoggedIn.find((candidate) => subProviderName(candidate) === selectedProviderName);
405
+ if (!entry) return;
406
+
407
+ return loginSubscription(ctx, entry);
408
+ }
409
+
410
+ export async function handleSubsLogout(ctx: ExtensionCommandContext): Promise<void> {
411
+ const config = loadGlobalConfig();
412
+ const envEntries = parseEnvConfig();
413
+ const all = normalizeEntries(mergeConfigs(config, envEntries));
414
+
415
+ const loggedIn = all.filter((entry) =>
416
+ getAuthStorage(ctx).hasAuth(subProviderName(entry)),
417
+ );
418
+
419
+ if (loggedIn.length === 0) {
420
+ ctx.ui.notify("No subscriptions are currently logged in.", "info");
421
+ return;
422
+ }
423
+
424
+ const selectedProviderName = await showWrappedSelect(ctx, {
425
+ title: "Logout from subscription",
426
+ subtitle: "Select a subscription to log out.",
427
+ initialValue: ctx.model?.provider,
428
+ items: loggedIn.map((entry) => ({
429
+ value: subProviderName(entry),
430
+ label: subDisplayName(entry),
431
+ description: formatSubscriptionStatus(entry, getAuthStorage(ctx)),
432
+ })),
433
+ confirmHint: "logout",
434
+ cancelHint: "back",
435
+ });
436
+ if (!selectedProviderName) return;
437
+
438
+ const entry = loggedIn.find((candidate) => subProviderName(candidate) === selectedProviderName);
439
+ if (!entry) return;
440
+
441
+ await getAuthStorage(ctx).logout(subProviderName(entry));
442
+ ctx.ui.notify(`Logged out of ${subDisplayName(entry)}`, "info");
443
+ }
444
+
445
+ export async function handleSubsStatus(ctx: ExtensionCommandContext): Promise<void> {
446
+ const config = loadGlobalConfig();
447
+ const envEntries = parseEnvConfig();
448
+ const all = normalizeEntries(mergeConfigs(config, envEntries));
449
+
450
+ if (all.length === 0) {
451
+ ctx.ui.notify("No extra subscriptions configured.", "info");
452
+ return;
453
+ }
454
+
455
+ const lines: string[] = [];
456
+ for (const entry of all) {
457
+ const name = subProviderName(entry);
458
+ const cred = getAuthStorage(ctx).get(name);
459
+ const hasAuth = getAuthStorage(ctx).hasAuth(name);
460
+
461
+ let status: string;
462
+ if (!hasAuth) {
463
+ status = "not logged in";
464
+ } else if (cred?.type === "oauth") {
465
+ const expiresIn = typeof cred.expires === "number" ? cred.expires - Date.now() : 0;
466
+ if (expiresIn > 0) {
467
+ const mins = Math.round(expiresIn / 60000);
468
+ status = `logged in (expires ${mins}m)`;
469
+ } else {
470
+ status = "logged in (token expired, will refresh)";
471
+ }
472
+ } else {
473
+ status = "logged in (api key)";
474
+ }
475
+
476
+ const modelCount = (getModels(entry.provider as any) as Model<Api>[]).length;
477
+ const source = config.subscriptions.find(
478
+ (s) => s.provider === entry.provider && s.index === entry.index,
479
+ )
480
+ ? "saved"
481
+ : "env";
482
+
483
+ lines.push(
484
+ `${subDisplayName(entry)} | ${status} | ${modelCount} models | ${source}`,
485
+ );
486
+ }
487
+
488
+ await showWrappedSelect(ctx, {
489
+ title: "Subscription Status",
490
+ subtitle: "Press Enter or Escape to go back.",
491
+ items: lines.map((line, index) => ({ value: `${index}:${line}`, label: line })),
492
+ confirmHint: "back",
493
+ cancelHint: "back",
494
+ });
495
+ }
496
+ export async function handleSubsMenu(
497
+ pi: ExtensionAPI,
498
+ ctx: ExtensionCommandContext,
499
+ ): Promise<void> {
500
+ const actions: SelectItem[] = [
501
+ { value: "list", label: "list", description: "Show all extra subscriptions" },
502
+ { value: "add", label: "add", description: "Add a new subscription" },
503
+ { value: "remove", label: "remove", description: "Remove a subscription" },
504
+ { value: "login", label: "login", description: "Login to a subscription" },
505
+ { value: "logout", label: "logout", description: "Logout from a subscription" },
506
+ { value: "switch", label: "switch", description: "Switch to a different subscription/provider now" },
507
+ { value: "status", label: "status", description: "Show auth status and token info" },
508
+ { value: "limits", label: "limits", description: "Check built-in quota support (Codex + Google)" },
509
+ ];
510
+ let preferredAction = "list";
511
+
512
+ while (true) {
513
+ const action = await showWrappedSelect(ctx, {
514
+ title: "Subscription Manager",
515
+ items: actions,
516
+ initialValue: preferredAction,
517
+ confirmHint: "open",
518
+ cancelHint: "close",
519
+ });
520
+ if (!action) return;
521
+
522
+ preferredAction = action;
523
+ const config = loadGlobalConfig();
524
+ switch (action) {
525
+ case "list":
526
+ await handleSubsList(pi, ctx, config);
527
+ break;
528
+ case "add":
529
+ await handleSubsAdd(pi, ctx);
530
+ break;
531
+ case "remove":
532
+ await handleSubsRemove(pi, ctx);
533
+ break;
534
+ case "login":
535
+ await handleSubsLogin(ctx);
536
+ break;
537
+ case "logout":
538
+ await handleSubsLogout(ctx);
539
+ break;
540
+ case "switch":
541
+ await handleSubsSwitch(pi, ctx);
542
+ break;
543
+ case "status":
544
+ await handleSubsStatus(ctx);
545
+ break;
546
+ case "limits":
547
+ await handleSubsLimits(ctx);
548
+ break;
549
+ }
550
+ }
551
+ }