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,356 @@
1
+ // ========================================================================
2
+ // Provider templates
3
+ // ========================================================================
4
+ import type { ExtensionAPI, ProviderConfig, ProviderModelConfig } from "@oh-my-pi/pi-coding-agent";
5
+ import { getProviderDefinition } from "@oh-my-pi/pi-ai/registry";
6
+ import type { OAuthCredentials, OAuthLoginCallbacks } from "@oh-my-pi/pi-ai/oauth";
7
+ import { AssistantMessageEventStream, streamSimple, type Api, type AssistantMessageEvent, type Context, type Model, type SimpleStreamOptions } from "@oh-my-pi/pi-ai";
8
+ import { getModels, subProviderName, type SubEntry } from "./core.ts";
9
+
10
+ export type CopilotCredentials = OAuthCredentials & { enterpriseUrl?: string };
11
+ export type GeminiCredentials = OAuthCredentials & { projectId?: string };
12
+
13
+ /** Native omp provider OAuth configuration. */
14
+ export type ProviderOAuth = NonNullable<ProviderConfig["oauth"]>;
15
+
16
+ export function requireOAuthDefinition(providerId: string) {
17
+ const definition = getProviderDefinition(providerId);
18
+ if (!definition || typeof definition.login !== "function" || typeof definition.refreshToken !== "function") {
19
+ throw new Error(`No renewable OAuth flow available for provider "${providerId}"`);
20
+ }
21
+ return definition;
22
+ }
23
+
24
+ export function getRegisteredProviderApiKey(providerId: string, credentials: OAuthCredentials): string {
25
+ switch (providerId) {
26
+ case "anthropic":
27
+ case "openai-codex":
28
+ case "kimi-code":
29
+ case "xai-oauth":
30
+ return credentials.access;
31
+ case "github-copilot":
32
+ case "google-gemini-cli":
33
+ case "google-antigravity": {
34
+ const registered = credentials as OAuthCredentials & {
35
+ apiEndpoint?: string;
36
+ enterpriseUrl?: string;
37
+ projectId?: string;
38
+ email?: string;
39
+ accountId?: string;
40
+ };
41
+ return JSON.stringify({
42
+ apiEndpoint: registered.apiEndpoint,
43
+ token: registered.access,
44
+ enterpriseUrl: registered.enterpriseUrl,
45
+ projectId: registered.projectId,
46
+ refreshToken: registered.refresh,
47
+ expiresAt: registered.expires,
48
+ email: registered.email,
49
+ accountId: registered.accountId,
50
+ });
51
+ }
52
+ default:
53
+ return credentials.access;
54
+ }
55
+ }
56
+
57
+ export function flowBackedOAuth(providerId: string, name: string): ProviderOAuth {
58
+ const definition = requireOAuthDefinition(providerId);
59
+ return {
60
+ name,
61
+ async login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials | string> {
62
+ const credentials = await definition.login(callbacks);
63
+ if (typeof credentials === "string") {
64
+ throw new Error(`No renewable OAuth flow available for provider "${providerId}"`);
65
+ }
66
+ return credentials;
67
+ },
68
+ async refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
69
+ return definition.refreshToken(credentials);
70
+ },
71
+ getApiKey(credentials: OAuthCredentials): string {
72
+ return getRegisteredProviderApiKey(providerId, credentials);
73
+ },
74
+ };
75
+ }
76
+
77
+
78
+ // GitHub Copilot base URL derivation, ported from the pi-ai OAuth flow
79
+ // (no longer part of the public pi-ai surface).
80
+
81
+ export function normalizeDomain(input: string): string | null {
82
+ const trimmed = input.trim();
83
+ if (!trimmed) return null;
84
+ try {
85
+ const url = trimmed.includes("://") ? new URL(trimmed) : new URL(`https://${trimmed}`);
86
+ return url.hostname;
87
+ } catch {
88
+ return null;
89
+ }
90
+ }
91
+
92
+ export function getBaseUrlFromCopilotToken(token: string): string | null {
93
+ const match = token.match(/proxy-ep=([^;]+)/);
94
+ if (!match) return null;
95
+ // Convert proxy.xxx to api.xxx
96
+ return `https://${match[1].replace(/^proxy\./, "api.")}`;
97
+ }
98
+
99
+ export function getGitHubCopilotBaseUrl(token: string | undefined, enterpriseUrl: string | undefined): string {
100
+ if (token) {
101
+ const fromToken = getBaseUrlFromCopilotToken(token);
102
+ if (fromToken) return fromToken;
103
+ }
104
+ const domain = enterpriseUrl ? normalizeDomain(enterpriseUrl) : null;
105
+ if (domain) return `https://copilot-api.${domain}`;
106
+ return "https://api.individual.githubcopilot.com";
107
+ }
108
+
109
+ // Synthetic provider names change provider-keyed transports. These APIs route
110
+ // through one shared wrapper, which restores canonical identity only inside
111
+ // transport and puts subscription identity back on emitted assistant messages.
112
+ export const SUB_TRANSPORT_CONFIG: Record<string, { builtinApi: Api | ((modelId: string) => Api); customApiId: string }> = {
113
+ "google-antigravity": { builtinApi: "google-gemini-cli", customApiId: "google-antigravity-mp" },
114
+ };
115
+
116
+
117
+ export const ANTIGRAVITY_SENSITIVE_TAGS = ["system-conventions", "system-directive"] as const;
118
+
119
+ /** Case-flip Google's fingerprinted system-prompt tags so Cloud Code Assist stops
120
+ * masking the request as 429 RESOURCE_EXHAUSTED (omp issue #11809). Content is
121
+ * preserved; only the exact-substring fingerprint is defeated. */
122
+ export function defeatAntigravityFingerprint(text: string): string {
123
+ let out = text;
124
+ for (const tag of ANTIGRAVITY_SENSITIVE_TAGS) {
125
+ out = out
126
+ .split(`<${tag}>`).join(`<${tag.toUpperCase()}>`)
127
+ .split(`</${tag}>`).join(`</${tag.toUpperCase()}>`);
128
+ }
129
+ return out;
130
+ }
131
+
132
+ export function rewriteAntigravitySystemInstruction(payload: unknown): unknown {
133
+ if (!payload || typeof payload !== "object") return payload;
134
+ const body = payload as Record<string, unknown>;
135
+ const request = body.request;
136
+ if (!request || typeof request !== "object") return payload;
137
+ const req = request as Record<string, unknown>;
138
+ const sys = req.systemInstruction;
139
+ if (!sys || typeof sys !== "object") return payload;
140
+ const sysObj = sys as Record<string, unknown>;
141
+ if (!Array.isArray(sysObj.parts)) return payload;
142
+ const parts = sysObj.parts.map(part =>
143
+ part && typeof part === "object" && typeof (part as { text?: unknown }).text === "string"
144
+ ? { ...part, text: defeatAntigravityFingerprint((part as { text: string }).text) }
145
+ : part,
146
+ );
147
+ return { ...body, request: { ...req, systemInstruction: { ...sysObj, parts } } };
148
+ }
149
+
150
+ export type SubscriptionStream = (
151
+ model: Model<Api>,
152
+ context: Context,
153
+ options?: SimpleStreamOptions,
154
+ ) => AssistantMessageEventStream;
155
+
156
+ export function restoreSubscriptionProvider(event: AssistantMessageEvent, provider: string): AssistantMessageEvent {
157
+ if (event.type === "done") return { ...event, message: { ...event.message, provider } };
158
+ if (event.type === "error") return { ...event, error: { ...event.error, provider } };
159
+ return { ...event, partial: { ...event.partial, provider } };
160
+ }
161
+
162
+ export function createSubscriptionStream(canonicalProvider: string, builtinApi: Api | ((modelId: string) => Api)): SubscriptionStream {
163
+ return (model, context, options) => {
164
+ const internalApi = typeof builtinApi === "function" ? builtinApi(model.id) : builtinApi;
165
+ const baseModel = getModels(canonicalProvider).find(candidate => candidate.id === model.id);
166
+ if (!baseModel) throw new Error(`Missing bundled model ${canonicalProvider}/${model.id}`);
167
+ const internalModel = { ...baseModel, api: internalApi, provider: canonicalProvider } as Model<Api>;
168
+ const internalOptions: SimpleStreamOptions = {
169
+ ...(options ?? {}),
170
+ headers: options?.headers,
171
+ onPayload: async (payload: unknown) => {
172
+ const rewritten =
173
+ canonicalProvider === "google-antigravity"
174
+ ? rewriteAntigravitySystemInstruction(payload)
175
+ : payload;
176
+ const replacement = await options?.onPayload?.(rewritten, model);
177
+ return replacement ?? rewritten;
178
+ },
179
+ onSseEvent: options?.onSseEvent
180
+ ? (event: Parameters<NonNullable<SimpleStreamOptions["onSseEvent"]>>[0]) => options.onSseEvent?.(event, model)
181
+ : undefined,
182
+ };
183
+ const inner = streamSimple(internalModel, context, internalOptions);
184
+ const outer = new AssistantMessageEventStream();
185
+ outer.forwardLocalWorkFrom(inner);
186
+ void (async () => {
187
+ try {
188
+ for await (const event of inner) {
189
+ outer.push(restoreSubscriptionProvider(event, model.provider));
190
+ }
191
+ } catch (error) {
192
+ outer.fail(error);
193
+ }
194
+ })();
195
+ return outer;
196
+ };
197
+ }
198
+ export const SUBSCRIPTION_STREAMS: Record<string, SubscriptionStream> = {};
199
+ export function getSubscriptionStream(baseProvider: string): SubscriptionStream | undefined {
200
+ const config = SUB_TRANSPORT_CONFIG[baseProvider];
201
+ if (!config) return undefined;
202
+ let stream = SUBSCRIPTION_STREAMS[baseProvider];
203
+ if (!stream) {
204
+ stream = createSubscriptionStream(baseProvider, config.builtinApi);
205
+ SUBSCRIPTION_STREAMS[baseProvider] = stream;
206
+ }
207
+ return stream;
208
+ }
209
+
210
+
211
+
212
+ export interface ProviderTemplate {
213
+ displayName: string;
214
+ apiKey?: string;
215
+ buildOAuth?(index: number): ProviderOAuth;
216
+ buildModifyModels?(providerName: string): ProviderOAuth["modifyModels"];
217
+ }
218
+
219
+ export const PROVIDER_TEMPLATES: Record<string, ProviderTemplate> = {
220
+ anthropic: {
221
+ displayName: "Anthropic (Claude Pro/Max)",
222
+ buildOAuth(index: number) {
223
+ return flowBackedOAuth("anthropic", `Anthropic #${index}`);
224
+ },
225
+ },
226
+
227
+ "openai-codex": {
228
+ displayName: "ChatGPT Plus/Pro (Codex)",
229
+ buildOAuth(index: number) {
230
+ return flowBackedOAuth("openai-codex", `ChatGPT Codex #${index}`);
231
+ },
232
+ },
233
+
234
+ "github-copilot": {
235
+ displayName: "GitHub Copilot",
236
+ buildOAuth(index: number) {
237
+ return flowBackedOAuth("github-copilot", `GitHub Copilot #${index}`);
238
+ },
239
+ buildModifyModels(providerName: string) {
240
+ return (models: Model<Api>[], credentials: OAuthCredentials): Model<Api>[] => {
241
+ const creds = credentials as CopilotCredentials;
242
+ const baseUrl = getGitHubCopilotBaseUrl(creds.access, creds.enterpriseUrl);
243
+ return models.map((m) =>
244
+ m.provider === providerName ? { ...m, baseUrl } : m,
245
+ );
246
+ };
247
+ },
248
+ },
249
+
250
+ "google-gemini-cli": {
251
+ displayName: "Google Cloud Code Assist",
252
+ buildOAuth(index: number) {
253
+ return flowBackedOAuth("google-gemini-cli", `Google Cloud Code Assist #${index}`);
254
+ },
255
+ },
256
+
257
+ "google-antigravity": {
258
+ displayName: "Antigravity",
259
+ buildOAuth(index: number) {
260
+ return flowBackedOAuth("google-antigravity", `Antigravity #${index}`);
261
+ },
262
+ },
263
+
264
+ "kimi-code": {
265
+ displayName: "Kimi Code",
266
+ buildOAuth(index: number) {
267
+ return flowBackedOAuth("kimi-code", `Kimi Code #${index}`);
268
+ },
269
+ },
270
+
271
+ "xai-oauth": {
272
+ displayName: "xAI Grok OAuth",
273
+ buildOAuth(index: number) {
274
+ return flowBackedOAuth("xai-oauth", `xAI Grok OAuth #${index}`);
275
+ },
276
+ },
277
+
278
+ minimax: {
279
+ displayName: "MiniMax (Global)",
280
+ apiKey: "$MINIMAX_API_KEY",
281
+ },
282
+
283
+ "minimax-cn": {
284
+ displayName: "MiniMax (China)",
285
+ apiKey: "$MINIMAX_CN_API_KEY",
286
+ },
287
+ };
288
+
289
+ export const SUPPORTED_PROVIDERS = Object.keys(PROVIDER_TEMPLATES);
290
+
291
+ export function subDisplayName(entry: SubEntry): string {
292
+ const template = PROVIDER_TEMPLATES[entry.provider];
293
+ const providerName = `${template?.displayName || entry.provider} #${entry.index}`;
294
+ if (!entry.label) return providerName;
295
+ return `${entry.label} — ${providerName}`;
296
+ }
297
+ export function getBaseProvider(providerName: string): string | undefined {
298
+ // Direct match
299
+ if (PROVIDER_TEMPLATES[providerName]) return providerName;
300
+ // Strip trailing -N
301
+ const match = providerName.match(/^(.+)-(\d+)$/);
302
+ if (match && PROVIDER_TEMPLATES[match[1]]) return match[1];
303
+ return undefined;
304
+ }
305
+
306
+ // ==========================================================================
307
+ // Model cloning
308
+ // ==========================================================================
309
+
310
+ export function cloneModels(originalProvider: string, index: number): ProviderModelConfig[] {
311
+ const models = getModels(originalProvider);
312
+ return models.map((m) => ({
313
+ id: m.id,
314
+ name: `${m.name} (#${index})`,
315
+ api: SUB_TRANSPORT_CONFIG[originalProvider]?.customApiId ?? m.api,
316
+ reasoning: m.reasoning,
317
+ thinking: m.thinking,
318
+ input: m.input as ("text" | "image")[],
319
+ cost: { ...m.cost },
320
+ premiumMultiplier: m.premiumMultiplier,
321
+ contextWindow: m.contextWindow,
322
+ maxTokens: m.maxTokens,
323
+ preferWebsockets: m.preferWebsockets,
324
+ headers: m.headers ? { ...m.headers } : undefined,
325
+ compat: m.compat,
326
+ }));
327
+ }
328
+
329
+
330
+ // ==========================================================================
331
+ // Register a single subscription as a provider
332
+ // ==========================================================================
333
+
334
+ export function registerSub(pi: ExtensionAPI, entry: SubEntry): void {
335
+ const template = PROVIDER_TEMPLATES[entry.provider];
336
+ if (!template) return;
337
+ const name = subProviderName(entry);
338
+ const oauth = template.buildOAuth?.(entry.index);
339
+ const modifyModels = template.buildModifyModels?.(name);
340
+
341
+ const builtinModels = getModels(entry.provider);
342
+ const transportApi = SUB_TRANSPORT_CONFIG[entry.provider]?.customApiId;
343
+ const streamSimple = getSubscriptionStream(entry.provider);
344
+ const baseUrl = builtinModels[0]?.baseUrl || "";
345
+ const models = cloneModels(entry.provider, entry.index);
346
+
347
+ // Static `models` provide startup catalog for this subscription.
348
+ pi.registerProvider(name, {
349
+ baseUrl,
350
+ api: transportApi ?? builtinModels[0]?.api,
351
+ apiKey: template.apiKey,
352
+ streamSimple,
353
+ oauth: oauth && modifyModels ? { ...oauth, modifyModels } : oauth,
354
+ models,
355
+ });
356
+ }