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,316 @@
1
+ // ========================================================================
2
+ // Config persistence and environment merge
3
+ // ========================================================================
4
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "fs";
5
+ import { dirname, join } from "path";
6
+ import type { ExtensionAPI, ExtensionCommandContext, ExtensionContext, AuthStorage } from "@oh-my-pi/pi-coding-agent";
7
+ import { getAgentDir } from "@oh-my-pi/pi-coding-agent";
8
+ import { getModels, getAuthStorage, subProviderName, type SubEntry, type MultiAuthConfig, type ProjectConfig, type EffectiveConfig, type AuthStorageEntry } from "./core.ts";
9
+ import type { Api, Model } from "@oh-my-pi/pi-ai";
10
+ import { PROVIDER_TEMPLATES, SUPPORTED_PROVIDERS, getBaseProvider, subDisplayName } from "./providers.ts";
11
+
12
+ export function globalConfigPath(): string {
13
+ return join(getAgentDir(), "multi-auth.json");
14
+ }
15
+
16
+ export function projectConfigPath(cwd: string): string {
17
+ return join(cwd, ".omp", "multi-auth.json");
18
+ }
19
+
20
+ export function emptyMultiAuthConfig(): MultiAuthConfig {
21
+ return { subscriptions: [], presets: [] };
22
+ }
23
+
24
+
25
+ export function normalizeMultiAuthConfig(raw: unknown): MultiAuthConfig {
26
+ const parsed = raw && typeof raw === "object" ? (raw as Partial<MultiAuthConfig>) : {};
27
+ return {
28
+ subscriptions: Array.isArray(parsed.subscriptions) ? normalizeEntries(parsed.subscriptions) : [],
29
+ presets: Array.isArray(parsed.presets) ? parsed.presets : [],
30
+ };
31
+ }
32
+
33
+
34
+ export function normalizeProjectConfig(raw: unknown): ProjectConfig {
35
+ const parsed = raw && typeof raw === "object" ? (raw as Partial<ProjectConfig>) : {};
36
+ const config: ProjectConfig = {};
37
+ if (Array.isArray(parsed.allowedSubs)) config.allowedSubs = parsed.allowedSubs;
38
+ return config;
39
+ }
40
+
41
+ export function loadGlobalConfig(): MultiAuthConfig {
42
+ const path = globalConfigPath();
43
+ if (!existsSync(path)) return emptyMultiAuthConfig();
44
+ try {
45
+ const raw = JSON.parse(readFileSync(path, "utf-8"));
46
+ return normalizeMultiAuthConfig(raw);
47
+ } catch {
48
+ const config = emptyMultiAuthConfig();
49
+ saveJsonConfig(path, config);
50
+ return config;
51
+ }
52
+ }
53
+
54
+ export function loadProjectConfig(cwd: string): ProjectConfig | undefined {
55
+ const path = projectConfigPath(cwd);
56
+ if (!existsSync(path)) return undefined;
57
+ try {
58
+ return normalizeProjectConfig(JSON.parse(readFileSync(path, "utf-8")));
59
+ } catch {
60
+ return undefined;
61
+ }
62
+ }
63
+
64
+ export function normalizeAllowedProviderNames(allowedSubs: string[] | undefined): string[] | undefined {
65
+ if (!allowedSubs || allowedSubs.length === 0) return undefined;
66
+ const normalized = [...new Set(allowedSubs.map((value) => value.trim()).filter(Boolean))];
67
+ return normalized.length > 0 ? normalized : undefined;
68
+ }
69
+
70
+ export function loadEffectiveConfig(cwd: string): EffectiveConfig {
71
+ const global = loadGlobalConfig();
72
+ const envEntries = parseEnvConfig();
73
+ const mergedSubscriptions = normalizeEntries(mergeConfigs(global, envEntries));
74
+ const project = loadProjectConfig(cwd);
75
+
76
+ if (!project) {
77
+ return {
78
+ subscriptions: mergedSubscriptions,
79
+ presets: global.presets,
80
+ };
81
+ }
82
+
83
+ const allowedProviderNames = normalizeAllowedProviderNames(project.allowedSubs);
84
+ let subs = mergedSubscriptions;
85
+ if (allowedProviderNames) {
86
+ const allowed = new Set(allowedProviderNames);
87
+ subs = mergedSubscriptions.filter((s) => allowed.has(subProviderName(s)));
88
+ }
89
+
90
+ return {
91
+ subscriptions: subs,
92
+ presets: global.presets,
93
+ allowedProviderNames,
94
+ };
95
+ }
96
+
97
+ export function saveJsonConfig(path: string, config: unknown): void {
98
+ const dir = dirname(path);
99
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
100
+
101
+ let backupPath: string | undefined;
102
+ if (existsSync(path)) {
103
+ try {
104
+ JSON.parse(readFileSync(path, "utf-8"));
105
+ } catch {
106
+ backupPath = `${path}.invalid-${Date.now()}-${process.pid}.bak`;
107
+ copyFileSync(path, backupPath);
108
+ }
109
+ }
110
+
111
+ const temporaryPath = `${path}.tmp-${process.pid}-${Date.now()}`;
112
+ try {
113
+ writeFileSync(temporaryPath, JSON.stringify(config, null, 2), "utf-8");
114
+ renameSync(temporaryPath, path);
115
+ } catch (error) {
116
+ try {
117
+ unlinkSync(temporaryPath);
118
+ } catch {}
119
+ throw error;
120
+ }
121
+
122
+ if (backupPath) {
123
+ console.warn(`[omp-multi-auth] Backed up malformed config to ${backupPath}`);
124
+ }
125
+ }
126
+
127
+ export function saveGlobalConfig(config: MultiAuthConfig): void {
128
+ saveJsonConfig(globalConfigPath(), config);
129
+ }
130
+
131
+ export function saveProjectConfig(cwd: string, config: ProjectConfig): void {
132
+ saveJsonConfig(projectConfigPath(cwd), config);
133
+ }
134
+
135
+ export function getProviderDisplayName(providerName: string, subscriptions: SubEntry[]): string {
136
+ const subEntry = subscriptions.find((entry) => subProviderName(entry) === providerName);
137
+ if (subEntry) {
138
+ return subDisplayName(subEntry);
139
+ }
140
+ return PROVIDER_TEMPLATES[providerName]?.displayName || providerName;
141
+ }
142
+
143
+ export function getProjectScopedProviderNames(
144
+ ctx: ExtensionContext | ExtensionCommandContext,
145
+ effective: EffectiveConfig,
146
+ ): string[] {
147
+ const seen = new Set<string>();
148
+ const providerNames: string[] = [];
149
+ const push = (providerName: string) => {
150
+ if (!providerName || seen.has(providerName)) return;
151
+ seen.add(providerName);
152
+ providerNames.push(providerName);
153
+ };
154
+
155
+ if (effective.allowedProviderNames && effective.allowedProviderNames.length > 0) {
156
+ for (const providerName of effective.allowedProviderNames) {
157
+ const isExtraSubscription = effective.subscriptions.some(
158
+ (entry) => subProviderName(entry) === providerName,
159
+ );
160
+ const isSupportedBaseProvider = SUPPORTED_PROVIDERS.includes(providerName);
161
+ if (!isExtraSubscription && !isSupportedBaseProvider) continue;
162
+ push(providerName);
163
+ }
164
+ return providerNames;
165
+ }
166
+
167
+ for (const providerName of SUPPORTED_PROVIDERS) {
168
+ if (getAuthStorage(ctx).hasAuth(providerName)) {
169
+ push(providerName);
170
+ }
171
+ }
172
+ for (const entry of effective.subscriptions) {
173
+ push(subProviderName(entry));
174
+ }
175
+ return providerNames;
176
+ }
177
+
178
+ export function findSelectableModelForProvider(
179
+ ctx: ExtensionContext | ExtensionCommandContext,
180
+ providerName: string,
181
+ preferredModelId?: string,
182
+ ): Model<Api> | undefined {
183
+ if (!getAuthStorage(ctx).hasAuth(providerName)) {
184
+ return undefined;
185
+ }
186
+ if (preferredModelId) {
187
+ const preferred = ctx.modelRegistry.find(providerName, preferredModelId);
188
+ if (preferred) {
189
+ return preferred as Model<Api>;
190
+ }
191
+ }
192
+ const baseProvider = getBaseProvider(providerName);
193
+ if (!baseProvider) {
194
+ return undefined;
195
+ }
196
+ for (const baseModel of getModels(baseProvider as any) as Model<Api>[]) {
197
+ const candidate = ctx.modelRegistry.find(providerName, baseModel.id);
198
+ if (candidate) {
199
+ return candidate as Model<Api>;
200
+ }
201
+ }
202
+ return undefined;
203
+ }
204
+
205
+ export function formatAllowedProviderSummary(effective: EffectiveConfig): string | undefined {
206
+ return effective.allowedProviderNames && effective.allowedProviderNames.length > 0
207
+ ? effective.allowedProviderNames.join(", ")
208
+ : undefined;
209
+ }
210
+
211
+ // ==========================================================================
212
+ // Merge env var into config
213
+ // ==========================================================================
214
+
215
+ export function parseEnvConfig(): SubEntry[] {
216
+ const raw = process.env.MULTI_SUB;
217
+ if (!raw) return [];
218
+ const entries: SubEntry[] = [];
219
+ for (const part of raw.split(",")) {
220
+ const [provider, countStr] = part.trim().split(":");
221
+ if (!provider || !PROVIDER_TEMPLATES[provider]) continue;
222
+ const count = parseInt(countStr || "1", 10);
223
+ if (isNaN(count) || count < 1) continue;
224
+ for (let i = 0; i < count; i++) {
225
+ entries.push({ provider, index: 0 });
226
+ }
227
+ }
228
+ return entries;
229
+ }
230
+
231
+ export function mergeConfigs(fileConfig: MultiAuthConfig, envEntries: SubEntry[]): SubEntry[] {
232
+ const merged = [...fileConfig.subscriptions];
233
+ for (const envEntry of envEntries) {
234
+ const existingCount = merged.filter((s) => s.provider === envEntry.provider).length;
235
+ const envCountForProvider = envEntries.filter((e) => e.provider === envEntry.provider).length;
236
+ if (existingCount < envCountForProvider) {
237
+ const usedIndices = merged
238
+ .filter((s) => s.provider === envEntry.provider)
239
+ .map((s) => s.index);
240
+ let nextIndex = 2;
241
+ while (usedIndices.includes(nextIndex)) nextIndex++;
242
+ merged.push({ provider: envEntry.provider, index: nextIndex });
243
+ }
244
+ }
245
+ return merged;
246
+ }
247
+
248
+ export function normalizeEntries(entries: SubEntry[]): SubEntry[] {
249
+ const byProvider = new Map<string, SubEntry[]>();
250
+ for (const entry of entries) {
251
+ const list = byProvider.get(entry.provider) || [];
252
+ list.push(entry);
253
+ byProvider.set(entry.provider, list);
254
+ }
255
+ const result: SubEntry[] = [];
256
+ for (const [, list] of byProvider) {
257
+ const usedIndices = new Set(list.filter((e) => e.index > 0).map((e) => e.index));
258
+ let nextIndex = 2;
259
+ for (const entry of list) {
260
+ if (entry.index > 0) {
261
+ result.push(entry);
262
+ } else {
263
+ while (usedIndices.has(nextIndex)) nextIndex++;
264
+ result.push({ ...entry, index: nextIndex });
265
+ usedIndices.add(nextIndex);
266
+ nextIndex++;
267
+ }
268
+ }
269
+ }
270
+ return result;
271
+ }
272
+
273
+ export function subAccountIdentifier(authStorage: AuthStorage, providerName: string): string | undefined {
274
+ const auth = authStorage.get(providerName) as AuthStorageEntry | undefined;
275
+ for (const value of [auth?.email, auth?.accountId]) {
276
+ if (typeof value !== "string") continue;
277
+ const identifier = value.trim();
278
+ if (identifier) return identifier;
279
+ }
280
+ return undefined;
281
+ }
282
+ export function formatSubscriptionStatus(entry: SubEntry, authStorage: AuthStorage): string {
283
+ const providerName = subProviderName(entry);
284
+ if (!authStorage.hasAuth(providerName)) return "not logged in";
285
+ const identifier = subAccountIdentifier(authStorage, providerName);
286
+ return identifier ? `logged in ${identifier}` : "logged in";
287
+ }
288
+
289
+ export function getSubscriptionSource(config: MultiAuthConfig, entry: SubEntry): "config" | "env" {
290
+ return config.subscriptions.find(
291
+ (s) => s.provider === entry.provider && s.index === entry.index,
292
+ )
293
+ ? "config"
294
+ : "env";
295
+ }
296
+
297
+ export function formatSubscriptionMeta(
298
+ entry: SubEntry,
299
+ config: MultiAuthConfig,
300
+ authStorage: AuthStorage,
301
+ ): string {
302
+ const name = subProviderName(entry);
303
+ const hasAuth = authStorage.hasAuth(name);
304
+ const status = hasAuth ? "[logged in]" : "[not logged in]";
305
+ const identifier = hasAuth ? subAccountIdentifier(authStorage, name) : undefined;
306
+ const source = getSubscriptionSource(config, entry);
307
+ return `${status}${identifier ? ` ${identifier}` : ""} (${source})`;
308
+ }
309
+
310
+ export function formatSubscriptionListLine(
311
+ entry: SubEntry,
312
+ config: MultiAuthConfig,
313
+ authStorage: AuthStorage,
314
+ ): string {
315
+ return `${subDisplayName(entry)} -- ${formatSubscriptionMeta(entry, config, authStorage)}`;
316
+ }
@@ -0,0 +1,96 @@
1
+ // Cross-module types and zero-dependency helpers.
2
+ import type { ExtensionCommandContext, ExtensionContext, AuthStorage } from "@oh-my-pi/pi-coding-agent";
3
+ import { getBundledModels } from "@oh-my-pi/pi-catalog/models";
4
+ import type { GeneratedProvider } from "@oh-my-pi/pi-catalog/models";
5
+ import type { Api, Model } from "@oh-my-pi/pi-ai";
6
+
7
+ export function getModels(providerId: string): Model<Api>[] {
8
+ return getBundledModels(providerId as GeneratedProvider) as Model<Api>[];
9
+ }
10
+
11
+ export type QuotaStatusKind = "ready" | "watch" | "low" | "blocked" | "error" | "missing-auth";
12
+
13
+ export interface AuthStorageEntry {
14
+ type?: string;
15
+ access?: string;
16
+ refresh?: string;
17
+ expires?: number;
18
+ accountId?: string;
19
+ email?: string;
20
+ projectId?: string;
21
+ [key: string]: unknown;
22
+ }
23
+
24
+ export function getAuthStorage(ctx: ExtensionContext | ExtensionCommandContext): AuthStorage {
25
+ return ctx.modelRegistry.authStorage;
26
+ }
27
+
28
+ export interface QuotaAccount {
29
+ providerName: string;
30
+ baseProvider: string;
31
+ displayName: string;
32
+ auth?: AuthStorageEntry;
33
+ }
34
+
35
+ export interface QuotaCheckResult {
36
+ account: QuotaAccount;
37
+ kind: QuotaStatusKind;
38
+ summary: string;
39
+ details: string[];
40
+ score: number;
41
+ }
42
+
43
+ export interface ProviderQuotaChecker {
44
+ baseProvider: string;
45
+ check(account: QuotaAccount, authStorage: AuthStorage, signal?: AbortSignal): Promise<QuotaCheckResult>;
46
+ }
47
+ export interface SubEntry {
48
+ provider: string;
49
+ index: number;
50
+ label?: string;
51
+ }
52
+
53
+ /** A named routing preset that maps to an ordered list of provider+model entries. */
54
+ export interface PresetEntry {
55
+ /** Provider name (e.g. "openai-codex", "anthropic-2") */
56
+ provider: string;
57
+ /** Model ID to use */
58
+ model: string;
59
+ /** Whether this entry is active */
60
+ enabled: boolean;
61
+ }
62
+
63
+ export interface PresetConfig {
64
+ /** Preset name (e.g. "coding-premium", "coding-budget") */
65
+ name: string;
66
+ /** Ordered provider+model entries to try */
67
+ entries: PresetEntry[];
68
+ /** Whether this preset is available */
69
+ enabled: boolean;
70
+ }
71
+
72
+ export interface MultiAuthConfig {
73
+ subscriptions: SubEntry[];
74
+ presets: PresetConfig[];
75
+ }
76
+
77
+
78
+ /** Project-level config (.omp/multi-auth.json) */
79
+ export interface ProjectConfig {
80
+ /** Restrict which provider names can be used in this project (for example
81
+ * "openai-codex" or "openai-codex-2"). If set, only these exact providers
82
+ * are available in this project. If not set, all global providers are available. */
83
+ allowedSubs?: string[];
84
+ }
85
+
86
+ /** Effective config after merging global + project */
87
+ export interface EffectiveConfig {
88
+ subscriptions: SubEntry[];
89
+ presets: PresetConfig[];
90
+ /** Exact provider names allowed in this project, if restricted. */
91
+ allowedProviderNames?: string[];
92
+ }
93
+
94
+ export function subProviderName(entry: SubEntry): string {
95
+ return `${entry.provider}-${entry.index}`;
96
+ }