@earendil-works/pi-ai 0.80.7 → 0.80.9
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 +76 -22
- package/dist/api/lazy.d.ts.map +1 -1
- package/dist/api/lazy.js +9 -10
- package/dist/api/lazy.js.map +1 -1
- package/dist/api/openai-codex-responses.d.ts.map +1 -1
- package/dist/api/openai-codex-responses.js +3 -2
- package/dist/api/openai-codex-responses.js.map +1 -1
- package/dist/api/openai-completions.d.ts +2 -1
- package/dist/api/openai-completions.d.ts.map +1 -1
- package/dist/api/openai-completions.js +42 -2
- package/dist/api/openai-completions.js.map +1 -1
- package/dist/api/openai-responses.d.ts.map +1 -1
- package/dist/api/openai-responses.js +2 -0
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/auth/credential-store.d.ts +2 -1
- package/dist/auth/credential-store.d.ts.map +1 -1
- package/dist/auth/credential-store.js +3 -0
- package/dist/auth/credential-store.js.map +1 -1
- package/dist/auth/helpers.d.ts +1 -0
- package/dist/auth/helpers.d.ts.map +1 -1
- package/dist/auth/helpers.js +4 -3
- package/dist/auth/helpers.js.map +1 -1
- package/dist/auth/oauth/anthropic.d.ts +9 -0
- package/dist/auth/oauth/anthropic.d.ts.map +1 -0
- package/dist/{utils → auth}/oauth/anthropic.js +51 -116
- package/dist/auth/oauth/anthropic.js.map +1 -0
- package/dist/auth/oauth/device-code.d.ts.map +1 -0
- package/dist/auth/oauth/device-code.js.map +1 -0
- package/dist/auth/oauth/github-copilot.d.ts +6 -0
- package/dist/auth/oauth/github-copilot.d.ts.map +1 -0
- package/dist/{utils → auth}/oauth/github-copilot.js +18 -77
- package/dist/auth/oauth/github-copilot.js.map +1 -0
- package/dist/auth/oauth/load.d.ts +23 -0
- package/dist/auth/oauth/load.d.ts.map +1 -0
- package/dist/auth/oauth/load.js +49 -0
- package/dist/auth/oauth/load.js.map +1 -0
- package/dist/auth/oauth/oauth-page.d.ts.map +1 -0
- package/dist/auth/oauth/oauth-page.js.map +1 -0
- package/dist/auth/oauth/openai-codex.d.ts +9 -0
- package/dist/auth/oauth/openai-codex.d.ts.map +1 -0
- package/dist/{utils → auth}/oauth/openai-codex.js +61 -155
- package/dist/auth/oauth/openai-codex.js.map +1 -0
- package/dist/auth/oauth/pkce.d.ts.map +1 -0
- package/dist/auth/oauth/pkce.js.map +1 -0
- package/dist/auth/oauth/radius.d.ts +16 -0
- package/dist/auth/oauth/radius.d.ts.map +1 -0
- package/dist/{utils → auth}/oauth/radius.js +31 -128
- package/dist/auth/oauth/radius.js.map +1 -0
- package/dist/auth/oauth/xai.d.ts +6 -0
- package/dist/auth/oauth/xai.d.ts.map +1 -0
- package/dist/auth/oauth/xai.js +189 -0
- package/dist/auth/oauth/xai.js.map +1 -0
- package/dist/auth/resolve.d.ts +2 -4
- package/dist/auth/resolve.d.ts.map +1 -1
- package/dist/auth/resolve.js +9 -7
- package/dist/auth/resolve.js.map +1 -1
- package/dist/auth/types.d.ts +49 -10
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/auth/types.js.map +1 -1
- package/dist/bun-oauth.d.ts +3 -0
- package/dist/bun-oauth.d.ts.map +1 -0
- package/dist/bun-oauth.js +17 -0
- package/dist/bun-oauth.js.map +1 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +58 -76
- package/dist/cli.js.map +1 -1
- package/dist/compat/extension-oauth-types.d.ts +39 -0
- package/dist/compat/extension-oauth-types.d.ts.map +1 -0
- package/dist/compat/extension-oauth-types.js +2 -0
- package/dist/compat/extension-oauth-types.js.map +1 -0
- package/dist/compat.d.ts.map +1 -1
- package/dist/compat.js +20 -7
- package/dist/compat.js.map +1 -1
- package/dist/env-api-keys.d.ts.map +1 -1
- package/dist/env-api-keys.js +1 -1
- package/dist/env-api-keys.js.map +1 -1
- package/dist/images-models.d.ts +4 -2
- package/dist/images-models.d.ts.map +1 -1
- package/dist/images-models.js +5 -4
- package/dist/images-models.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/models-store.d.ts +25 -0
- package/dist/models-store.d.ts.map +1 -0
- package/dist/models-store.js +14 -0
- package/dist/models-store.js.map +1 -0
- package/dist/models.d.ts +66 -30
- package/dist/models.d.ts.map +1 -1
- package/dist/models.generated.d.ts +244 -4
- package/dist/models.generated.d.ts.map +1 -1
- package/dist/models.js +214 -29
- package/dist/models.js.map +1 -1
- package/dist/oauth.d.ts +2 -1
- package/dist/oauth.d.ts.map +1 -1
- package/dist/oauth.js +1 -1
- package/dist/oauth.js.map +1 -1
- package/dist/providers/all.d.ts +2 -1
- package/dist/providers/all.d.ts.map +1 -1
- package/dist/providers/all.js +3 -0
- package/dist/providers/all.js.map +1 -1
- package/dist/providers/amazon-bedrock.d.ts.map +1 -1
- package/dist/providers/amazon-bedrock.js +51 -10
- package/dist/providers/amazon-bedrock.js.map +1 -1
- package/dist/providers/anthropic.d.ts.map +1 -1
- package/dist/providers/anthropic.js +1 -1
- package/dist/providers/anthropic.js.map +1 -1
- package/dist/providers/cloudflare-ai-gateway.d.ts.map +1 -1
- package/dist/providers/cloudflare-ai-gateway.js +4 -3
- package/dist/providers/cloudflare-ai-gateway.js.map +1 -1
- package/dist/providers/cloudflare-auth.d.ts.map +1 -1
- package/dist/providers/cloudflare-auth.js +13 -20
- package/dist/providers/cloudflare-auth.js.map +1 -1
- package/dist/providers/cloudflare-stream.d.ts +8 -0
- package/dist/providers/cloudflare-stream.d.ts.map +1 -0
- package/dist/providers/cloudflare-stream.js +21 -0
- package/dist/providers/cloudflare-stream.js.map +1 -0
- package/dist/providers/cloudflare-workers-ai.d.ts.map +1 -1
- package/dist/providers/cloudflare-workers-ai.js +2 -1
- package/dist/providers/cloudflare-workers-ai.js.map +1 -1
- package/dist/providers/github-copilot.d.ts.map +1 -1
- package/dist/providers/github-copilot.js +11 -1
- package/dist/providers/github-copilot.js.map +1 -1
- package/dist/providers/google-vertex.d.ts.map +1 -1
- package/dist/providers/google-vertex.js +56 -5
- package/dist/providers/google-vertex.js.map +1 -1
- package/dist/providers/kimi-coding.models.d.ts +40 -0
- package/dist/providers/kimi-coding.models.d.ts.map +1 -1
- package/dist/providers/kimi-coding.models.js +36 -0
- package/dist/providers/kimi-coding.models.js.map +1 -1
- package/dist/providers/moonshotai-cn.models.d.ts +36 -0
- package/dist/providers/moonshotai-cn.models.d.ts.map +1 -1
- package/dist/providers/moonshotai-cn.models.js +19 -0
- package/dist/providers/moonshotai-cn.models.js.map +1 -1
- package/dist/providers/moonshotai.models.d.ts +36 -0
- package/dist/providers/moonshotai.models.d.ts.map +1 -1
- package/dist/providers/moonshotai.models.js +19 -0
- package/dist/providers/moonshotai.models.js.map +1 -1
- package/dist/providers/openai-codex.d.ts.map +1 -1
- package/dist/providers/openai-codex.js +1 -1
- package/dist/providers/openai-codex.js.map +1 -1
- package/dist/providers/openrouter.models.d.ts +42 -0
- package/dist/providers/openrouter.models.d.ts.map +1 -1
- package/dist/providers/openrouter.models.js +178 -142
- package/dist/providers/openrouter.models.js.map +1 -1
- package/dist/providers/radius-config.d.ts +26 -0
- package/dist/providers/radius-config.d.ts.map +1 -0
- package/dist/providers/radius-config.js +59 -0
- package/dist/providers/radius-config.js.map +1 -0
- package/dist/providers/radius.d.ts +9 -0
- package/dist/providers/radius.d.ts.map +1 -0
- package/dist/providers/radius.js +54 -0
- package/dist/providers/radius.js.map +1 -0
- package/dist/providers/vercel-ai-gateway.models.d.ts +84 -0
- package/dist/providers/vercel-ai-gateway.models.d.ts.map +1 -1
- package/dist/providers/vercel-ai-gateway.models.js +74 -2
- package/dist/providers/vercel-ai-gateway.models.js.map +1 -1
- package/dist/providers/xai.d.ts +1 -1
- package/dist/providers/xai.d.ts.map +1 -1
- package/dist/providers/xai.js +15 -3
- package/dist/providers/xai.js.map +1 -1
- package/dist/providers/xai.models.d.ts +6 -4
- package/dist/providers/xai.models.d.ts.map +1 -1
- package/dist/providers/xai.models.js +3 -2
- package/dist/providers/xai.models.js.map +1 -1
- package/dist/types.d.ts +2 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -1
- package/dist/utils/oauth/anthropic.d.ts +0 -27
- package/dist/utils/oauth/anthropic.d.ts.map +0 -1
- package/dist/utils/oauth/anthropic.js.map +0 -1
- package/dist/utils/oauth/device-code.d.ts.map +0 -1
- package/dist/utils/oauth/device-code.js.map +0 -1
- package/dist/utils/oauth/github-copilot.d.ts +0 -32
- package/dist/utils/oauth/github-copilot.d.ts.map +0 -1
- package/dist/utils/oauth/github-copilot.js.map +0 -1
- package/dist/utils/oauth/index.d.ts +0 -59
- package/dist/utils/oauth/index.d.ts.map +0 -1
- package/dist/utils/oauth/index.js +0 -131
- package/dist/utils/oauth/index.js.map +0 -1
- package/dist/utils/oauth/load.d.ts +0 -5
- package/dist/utils/oauth/load.d.ts.map +0 -1
- package/dist/utils/oauth/load.js +0 -22
- package/dist/utils/oauth/load.js.map +0 -1
- package/dist/utils/oauth/oauth-page.d.ts.map +0 -1
- package/dist/utils/oauth/oauth-page.js.map +0 -1
- package/dist/utils/oauth/openai-codex.d.ts +0 -45
- package/dist/utils/oauth/openai-codex.d.ts.map +0 -1
- package/dist/utils/oauth/openai-codex.js.map +0 -1
- package/dist/utils/oauth/pkce.d.ts.map +0 -1
- package/dist/utils/oauth/pkce.js.map +0 -1
- package/dist/utils/oauth/radius.d.ts +0 -39
- package/dist/utils/oauth/radius.d.ts.map +0 -1
- package/dist/utils/oauth/radius.js.map +0 -1
- package/dist/utils/oauth/types.d.ts +0 -64
- package/dist/utils/oauth/types.d.ts.map +0 -1
- package/dist/utils/oauth/types.js +0 -2
- package/dist/utils/oauth/types.js.map +0 -1
- /package/dist/{utils → auth}/oauth/device-code.d.ts +0 -0
- /package/dist/{utils → auth}/oauth/device-code.js +0 -0
- /package/dist/{utils → auth}/oauth/oauth-page.d.ts +0 -0
- /package/dist/{utils → auth}/oauth/oauth-page.js +0 -0
- /package/dist/{utils → auth}/oauth/pkce.d.ts +0 -0
- /package/dist/{utils → auth}/oauth/pkce.js +0 -0
package/dist/auth/resolve.js
CHANGED
|
@@ -12,10 +12,10 @@ export class ModelsError extends Error {
|
|
|
12
12
|
* nothing is stored. No silent env fallback after a failed refresh or for a
|
|
13
13
|
* credential type without a matching handler.
|
|
14
14
|
*/
|
|
15
|
-
export async function resolveProviderAuth(provider,
|
|
15
|
+
export async function resolveProviderAuth(provider, credentials, authContext, overrides) {
|
|
16
16
|
const requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;
|
|
17
17
|
if (overrides?.apiKey !== undefined && provider.auth.apiKey) {
|
|
18
|
-
return resolveApiKey(requestAuthContext, provider.auth.apiKey,
|
|
18
|
+
return resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, {
|
|
19
19
|
type: "api_key",
|
|
20
20
|
key: overrides.apiKey,
|
|
21
21
|
env: overrides.env,
|
|
@@ -28,12 +28,14 @@ export async function resolveProviderAuth(provider, model, credentials, authCont
|
|
|
28
28
|
}
|
|
29
29
|
if (stored.type === "api_key" && provider.auth.apiKey) {
|
|
30
30
|
const credential = overrides?.env ? { ...stored, env: { ...stored.env, ...overrides.env } } : stored;
|
|
31
|
-
return resolveApiKey(requestAuthContext, provider.auth.apiKey,
|
|
31
|
+
return resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, credential);
|
|
32
32
|
}
|
|
33
33
|
return undefined;
|
|
34
34
|
}
|
|
35
35
|
// Ambient (env vars, AWS profiles, ADC files).
|
|
36
|
-
return provider.auth.apiKey
|
|
36
|
+
return provider.auth.apiKey
|
|
37
|
+
? resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, undefined)
|
|
38
|
+
: undefined;
|
|
37
39
|
}
|
|
38
40
|
function overlayEnvAuthContext(base, env) {
|
|
39
41
|
return {
|
|
@@ -82,12 +84,12 @@ async function resolveStoredOAuth(credentials, providerId, oauth, stored) {
|
|
|
82
84
|
throw new ModelsError("oauth", `OAuth auth derivation failed for ${providerId}`, { cause: error });
|
|
83
85
|
}
|
|
84
86
|
}
|
|
85
|
-
async function resolveApiKey(authContext, apiKey,
|
|
87
|
+
async function resolveApiKey(authContext, apiKey, providerId, credential) {
|
|
86
88
|
try {
|
|
87
|
-
return await apiKey.resolve({
|
|
89
|
+
return await apiKey.resolve({ ctx: authContext, credential });
|
|
88
90
|
}
|
|
89
91
|
catch (error) {
|
|
90
|
-
throw new ModelsError("auth", `API key auth failed for provider ${
|
|
92
|
+
throw new ModelsError("auth", `API key auth failed for provider ${providerId}`, { cause: error });
|
|
91
93
|
}
|
|
92
94
|
}
|
|
93
95
|
async function readCredential(credentials, providerId) {
|
package/dist/auth/resolve.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../src/auth/resolve.ts"],"names":[],"mappings":"AAoBA,MAAM,OAAO,WAAY,SAAQ,KAAK;IAC5B,IAAI,CAAkB;IAE/B,YAAY,IAAqB,EAAE,OAAe,EAAE,OAA6B,EAAE;QAClF,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;CACD;
|
|
1
|
+
{"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../src/auth/resolve.ts"],"names":[],"mappings":"AAoBA,MAAM,OAAO,WAAY,SAAQ,KAAK;IAC5B,IAAI,CAAkB;IAE/B,YAAY,IAAqB,EAAE,OAAe,EAAE,OAA6B,EAAE;QAClF,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;CACD;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CACx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U,cAAc,CAAC,WAA4B,EAAE,UAAkB,EAAmC;IAChH,IAAI,CAAC;QACJ,OAAO,MAAM,WAAW,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IAC3C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,WAAW,CAAC,MAAM,EAAE,oCAAoC,UAAU,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACnG,CAAC;AAAA,CACD","sourcesContent":["import type { ProviderEnv } from \"../types.ts\";\nimport type {\n\tApiKeyAuth,\n\tApiKeyCredential,\n\tAuthContext,\n\tAuthResult,\n\tCredential,\n\tCredentialStore,\n\tOAuthAuth,\n\tOAuthCredential,\n\tProviderAuth,\n} from \"./types.ts\";\n\nexport type ModelsErrorCode = \"model_source\" | \"model_validation\" | \"provider\" | \"stream\" | \"auth\" | \"oauth\";\n\nexport interface AuthResolutionOverrides {\n\tapiKey?: string;\n\tenv?: ProviderEnv;\n}\n\nexport class ModelsError extends Error {\n\treadonly code: ModelsErrorCode;\n\n\tconstructor(code: ModelsErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, options);\n\t\tthis.name = \"ModelsError\";\n\t\tthis.code = code;\n\t}\n}\n\n/**\n * Auth resolution shared by the `Models` and `ImagesModels` collections.\n * A stored credential owns the provider: ambient/env is consulted only when\n * nothing is stored. No silent env fallback after a failed refresh or for a\n * credential type without a matching handler.\n */\nexport async function resolveProviderAuth(\n\tprovider: { id: string; auth: ProviderAuth },\n\tcredentials: CredentialStore,\n\tauthContext: AuthContext,\n\toverrides?: AuthResolutionOverrides,\n): Promise<AuthResult | undefined> {\n\tconst requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;\n\n\tif (overrides?.apiKey !== undefined && provider.auth.apiKey) {\n\t\treturn resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, {\n\t\t\ttype: \"api_key\",\n\t\t\tkey: overrides.apiKey,\n\t\t\tenv: overrides.env,\n\t\t});\n\t}\n\n\tconst stored = await readCredential(credentials, provider.id);\n\tif (stored) {\n\t\tif (stored.type === \"oauth\" && provider.auth.oauth) {\n\t\t\treturn resolveStoredOAuth(credentials, provider.id, provider.auth.oauth, stored);\n\t\t}\n\t\tif (stored.type === \"api_key\" && provider.auth.apiKey) {\n\t\t\tconst credential = overrides?.env ? { ...stored, env: { ...stored.env, ...overrides.env } } : stored;\n\t\t\treturn resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, credential);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t// Ambient (env vars, AWS profiles, ADC files).\n\treturn provider.auth.apiKey\n\t\t? resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, undefined)\n\t\t: undefined;\n}\n\nfunction overlayEnvAuthContext(base: AuthContext, env: ProviderEnv): AuthContext {\n\treturn {\n\t\tenv: async (name) => env[name] || (await base.env(name)),\n\t\tfileExists: (path) => base.fileExists(path),\n\t};\n}\n\n/**\n * OAuth resolution with double-checked locking (same pattern as today's\n * AuthStorage): valid tokens cost zero locks; expired tokens lock, re-check\n * expiry under the lock, refresh once globally, and persist the rotated\n * credential before release.\n */\nasync function resolveStoredOAuth(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\toauth: OAuthAuth,\n\tstored: OAuthCredential,\n): Promise<AuthResult | undefined> {\n\tlet credential = stored;\n\n\tif (Date.now() >= credential.expires) {\n\t\t// Optimistic check said expired; the authoritative check runs under the lock.\n\t\tlet post: Credential | undefined;\n\t\ttry {\n\t\t\tpost = await credentials.modify(providerId, async (current) => {\n\t\t\t\tif (current?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\t\t\tif (Date.now() < current.expires) return undefined; // another process/request refreshed\n\t\t\t\ttry {\n\t\t\t\t\treturn await oauth.refresh(current);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthrow new ModelsError(\"oauth\", `OAuth refresh failed for ${providerId}`, { cause: error });\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof ModelsError) throw error;\n\t\t\tthrow new ModelsError(\"auth\", `Credential store modify failed for ${providerId}`, { cause: error });\n\t\t}\n\t\tif (post?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\tcredential = post;\n\t}\n\n\ttry {\n\t\treturn { auth: await oauth.toAuth(credential), source: \"OAuth\" };\n\t} catch (error) {\n\t\tthrow new ModelsError(\"oauth\", `OAuth auth derivation failed for ${providerId}`, { cause: error });\n\t}\n}\n\nasync function resolveApiKey(\n\tauthContext: AuthContext,\n\tapiKey: ApiKeyAuth,\n\tproviderId: string,\n\tcredential: ApiKeyCredential | undefined,\n): Promise<AuthResult | undefined> {\n\ttry {\n\t\treturn await apiKey.resolve({ ctx: authContext, credential });\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `API key auth failed for provider ${providerId}`, { cause: error });\n\t}\n}\n\nasync function readCredential(credentials: CredentialStore, providerId: string): Promise<Credential | undefined> {\n\ttry {\n\t\treturn await credentials.read(providerId);\n\t} catch (error) {\n\t\tthrow new ModelsError(\"auth\", `Credential store read failed for ${providerId}`, { cause: error });\n\t}\n}\n"]}
|
package/dist/auth/types.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import type { OAuthCredentials } from "../utils/oauth/types.ts";
|
|
1
|
+
import type { ProviderEnv, ProviderHeaders } from "../types.ts";
|
|
3
2
|
/**
|
|
4
3
|
* Request auth for a single model request. If a value cannot be expressed as
|
|
5
4
|
* `apiKey`, `headers`, or `baseUrl`, it is provider config, not auth.
|
|
@@ -18,12 +17,24 @@ export interface ApiKeyCredential {
|
|
|
18
17
|
key?: string;
|
|
19
18
|
env?: ProviderEnv;
|
|
20
19
|
}
|
|
21
|
-
/**
|
|
20
|
+
/** OAuth token data returned by extension compatibility flows. */
|
|
21
|
+
export interface OAuthCredentials {
|
|
22
|
+
refresh: string;
|
|
23
|
+
access: string;
|
|
24
|
+
expires: number;
|
|
25
|
+
[key: string]: unknown;
|
|
26
|
+
}
|
|
27
|
+
/** Stored canonical OAuth credential. */
|
|
22
28
|
export interface OAuthCredential extends OAuthCredentials {
|
|
23
29
|
type: "oauth";
|
|
24
30
|
}
|
|
25
31
|
/** One type-tagged credential per provider — the shape of today's auth.json. */
|
|
26
32
|
export type Credential = ApiKeyCredential | OAuthCredential;
|
|
33
|
+
/** Non-secret credential metadata for account/status enumeration. */
|
|
34
|
+
export interface CredentialInfo {
|
|
35
|
+
providerId: string;
|
|
36
|
+
type: Credential["type"];
|
|
37
|
+
}
|
|
27
38
|
/**
|
|
28
39
|
* App-owned credential storage, keyed by `Provider.id`, one credential per
|
|
29
40
|
* provider. `modify` is the only write path, so every mutation is a
|
|
@@ -45,6 +56,11 @@ export interface CredentialStore {
|
|
|
45
56
|
* resolved request auth comes from `Models.getAuth()`.
|
|
46
57
|
*/
|
|
47
58
|
read(providerId: string): Promise<Credential | undefined>;
|
|
59
|
+
/**
|
|
60
|
+
* List stored credential metadata without resolving or exposing secrets.
|
|
61
|
+
* Implementations must not execute configured API-key commands while listing.
|
|
62
|
+
*/
|
|
63
|
+
list(): Promise<readonly CredentialInfo[]>;
|
|
48
64
|
/**
|
|
49
65
|
* Serialized write — the only write path. `fn` sees the current credential
|
|
50
66
|
* because correct writes (refresh, login-during-refresh) depend on it;
|
|
@@ -71,6 +87,11 @@ export interface AuthResult {
|
|
|
71
87
|
/** Human-readable label for status UI: "ANTHROPIC_API_KEY", "OAuth", "~/.aws/credentials". */
|
|
72
88
|
source?: string;
|
|
73
89
|
}
|
|
90
|
+
export interface AuthCheck {
|
|
91
|
+
source?: string;
|
|
92
|
+
type: "api_key" | "oauth";
|
|
93
|
+
}
|
|
94
|
+
export type AuthType = "api_key" | "oauth";
|
|
74
95
|
/**
|
|
75
96
|
* Prompt shown to the user during login. `signal` lets the flow cancel a
|
|
76
97
|
* pending prompt when an out-of-band event resolves the step, e.g. a
|
|
@@ -100,7 +121,15 @@ export type AuthPrompt = {
|
|
|
100
121
|
message: string;
|
|
101
122
|
placeholder?: string;
|
|
102
123
|
});
|
|
124
|
+
export interface AuthInfoLink {
|
|
125
|
+
url: string;
|
|
126
|
+
label?: string;
|
|
127
|
+
}
|
|
103
128
|
export type AuthEvent = {
|
|
129
|
+
type: "info";
|
|
130
|
+
message: string;
|
|
131
|
+
links?: readonly AuthInfoLink[];
|
|
132
|
+
} | {
|
|
104
133
|
type: "auth_url";
|
|
105
134
|
url: string;
|
|
106
135
|
instructions?: string;
|
|
@@ -121,7 +150,7 @@ export type AuthEvent = {
|
|
|
121
150
|
* id). Rejects on cancel/abort. `signal` aborts the whole login flow;
|
|
122
151
|
* per-prompt cancellation uses `AuthPrompt.signal`.
|
|
123
152
|
*/
|
|
124
|
-
export interface
|
|
153
|
+
export interface AuthInteraction {
|
|
125
154
|
signal?: AbortSignal;
|
|
126
155
|
prompt(prompt: AuthPrompt): Promise<string>;
|
|
127
156
|
notify(event: AuthEvent): void;
|
|
@@ -134,15 +163,23 @@ export interface ApiKeyAuth {
|
|
|
134
163
|
/** Display name, e.g. "Anthropic API key". */
|
|
135
164
|
name: string;
|
|
136
165
|
/** Interactive setup (prompt for key/provider env). Absent = ambient-only. */
|
|
137
|
-
login?(
|
|
166
|
+
login?(interaction: AuthInteraction): Promise<ApiKeyCredential>;
|
|
167
|
+
/**
|
|
168
|
+
* Optional side-effect-free availability check. Use this when `resolve()` may
|
|
169
|
+
* execute commands or perform other request-time work. Missing means Models
|
|
170
|
+
* checks availability by resolving auth.
|
|
171
|
+
*/
|
|
172
|
+
check?(input: {
|
|
173
|
+
ctx: AuthContext;
|
|
174
|
+
credential?: ApiKeyCredential;
|
|
175
|
+
}): Promise<AuthCheck | undefined>;
|
|
138
176
|
/**
|
|
139
177
|
* Resolve auth from the stored credential and/or ambient sources, merging
|
|
140
178
|
* per field (`credential.key ?? env("...")`, `credential.env?.NAME ?? env("...")`).
|
|
141
|
-
* undefined = not configured.
|
|
142
|
-
*
|
|
179
|
+
* undefined = not configured. Resolution is provider-scoped; model-specific
|
|
180
|
+
* endpoint preparation happens after auth has been resolved.
|
|
143
181
|
*/
|
|
144
182
|
resolve(input: {
|
|
145
|
-
model: Model<Api> | ImagesModel<ImagesApi>;
|
|
146
183
|
ctx: AuthContext;
|
|
147
184
|
credential?: ApiKeyCredential;
|
|
148
185
|
}): Promise<AuthResult | undefined>;
|
|
@@ -155,12 +192,14 @@ export interface ApiKeyAuth {
|
|
|
155
192
|
export interface OAuthAuth {
|
|
156
193
|
/** Display name, e.g. "Anthropic (Claude Pro/Max)". */
|
|
157
194
|
name: string;
|
|
158
|
-
login
|
|
195
|
+
/** Selector label for the subscription login option, e.g. "Sign in with SuperGrok or X Premium". */
|
|
196
|
+
loginLabel?: string;
|
|
197
|
+
login(interaction: AuthInteraction): Promise<OAuthCredential>;
|
|
159
198
|
/**
|
|
160
199
|
* Exchange the refresh token. Network call; throws on failure
|
|
161
200
|
* (invalid_grant etc.). `Models` runs this under the store lock.
|
|
162
201
|
*/
|
|
163
|
-
refresh(credential: OAuthCredential): Promise<OAuthCredential>;
|
|
202
|
+
refresh(credential: OAuthCredential, signal?: AbortSignal): Promise<OAuthCredential>;
|
|
164
203
|
/**
|
|
165
204
|
* Side-effect-free derivation of request auth from a valid credential.
|
|
166
205
|
* Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers
|
package/dist/auth/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,SAAS,EAAE,WAAW,EAAE,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACpG,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAEhE;;;GAGG;AACH,MAAM,WAAW,SAAS;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,E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AACH,MAAM,WAAW,UAAU;IAC1B,8CAA8C;IAC9C,IAAI,EAAE,MAAM,CAAC;IAEb,8EAA8E;IAC9E,KAAK,CAAC,CAAC,SAAS,EAAE,kBAAkB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;IAEjE;;;;;OAKG;IACH,OAAO,CAAC,KAAK,EAAE;QACd,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,WAAW,CAAC,SAAS,CAAC,CAAC;QAC3C,GAAG,EAAE,WAAW,CAAC;QACjB,UAAU,CAAC,EAAE,gBAAgB,CAAC;KAC9B,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAAC;CACpC;AAED;;;;GAIG;AACH,MAAM,WAAW,SAAS;IACzB,uDAAuD;IACvD,IAAI,EAAE,MAAM,CAAC;IAEb,KAAK,CAAC,SAAS,EAAE,kBAAkB,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAE/D;;;OAGG;IACH,OAAO,CAAC,UAAU,EAAE,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAE/D;;;;OAIG;IACH,MAAM,CAAC,UAAU,EAAE,eAAe,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;CACxD;AAED;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC5B,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,KAAK,CAAC,EAAE,SAAS,CAAC;CAClB","sourcesContent":["import type { Api, ImagesApi, ImagesModel, Model, ProviderEnv, ProviderHeaders } from \"../types.ts\";\nimport type { OAuthCredentials } from \"../utils/oauth/types.ts\";\n\n/**\n * Request auth for a single model request. If a value cannot be expressed as\n * `apiKey`, `headers`, or `baseUrl`, it is provider config, not auth.\n */\nexport interface ModelAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * Stored api-key credential. `env` holds provider-scoped environment/config\n * values such as Cloudflare account/gateway ids.\n */\nexport interface ApiKeyCredential {\n\ttype: \"api_key\";\n\tkey?: string;\n\tenv?: ProviderEnv;\n}\n\n/** Stored OAuth credential (`access`, `refresh`, `expires` from OAuthCredentials). */\nexport interface OAuthCredential extends OAuthCredentials {\n\ttype: \"oauth\";\n}\n\n/** One type-tagged credential per provider — the shape of today's auth.json. */\nexport type Credential = ApiKeyCredential | OAuthCredential;\n\n/**\n * App-owned credential storage, keyed by `Provider.id`, one credential per\n * provider. `modify` is the only write path, so every mutation is a\n * serialized read-modify-write; `Models.getAuth()` runs OAuth refresh inside\n * `modify` so concurrent requests cannot double-refresh a rotated token. The\n * app persists a credential after login via\n * `modify(provider.id, async () => credential)`. Login/logout orchestration\n * is app-owned.\n *\n * Error semantics: `read` resolves `undefined` for missing entries. Methods\n * reject only on storage failure; `Models` wraps such rejections in\n * `ModelsError` with code \"auth\". Best-effort stores that serve an in-memory\n * view and record persistence errors internally (like coding-agent's\n * AuthStorage) are valid implementations.\n */\nexport interface CredentialStore {\n\t/**\n\t * Read the stored credential, possibly expired. Display/status use;\n\t * resolved request auth comes from `Models.getAuth()`.\n\t */\n\tread(providerId: string): Promise<Credential | undefined>;\n\n\t/**\n\t * Serialized write — the only write path. `fn` sees the current credential\n\t * because correct writes (refresh, login-during-refresh) depend on it;\n\t * return the new credential, or undefined to leave the entry unchanged.\n\t * Mutual exclusion per provider id, cross-process too where the backing\n\t * store supports it (e.g. a file lock). Resolves with the post-write\n\t * credential. Rejections from `fn` propagate.\n\t */\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t): Promise<Credential | undefined>;\n\n\t/** Remove a credential (logout). Implementations serialize this against `modify`. */\n\tdelete(providerId: string): Promise<void>;\n}\n\n/** Environment access for auth resolution. Injectable for tests and browsers. */\nexport interface AuthContext {\n\tenv(name: string): Promise<string | undefined>;\n\t/** Check whether a file exists. Supports a leading `~`. Always false in browsers. */\n\tfileExists(path: string): Promise<boolean>;\n}\n\n/** Result of resolving auth for a model. */\nexport interface AuthResult {\n\tauth: ModelAuth;\n\t/** Provider-scoped environment/config values resolved from credentials and ambient context. */\n\tenv?: ProviderEnv;\n\t/** Human-readable label for status UI: \"ANTHROPIC_API_KEY\", \"OAuth\", \"~/.aws/credentials\". */\n\tsource?: string;\n}\n\n/**\n * Prompt shown to the user during login. `signal` lets the flow cancel a\n * pending prompt when an out-of-band event resolves the step, e.g. a\n * `manual_code` prompt raced against a callback server, aborted when the\n * callback wins.\n */\nexport type AuthPrompt = { signal?: AbortSignal } & (\n\t| { type: \"text\"; message: string; placeholder?: string }\n\t| { type: \"secret\"; message: string; placeholder?: string }\n\t| { type: \"select\"; message: string; options: readonly { id: string; label: string; description?: string }[] }\n\t| { type: \"manual_code\"; message: string; placeholder?: string }\n);\n\nexport type AuthEvent =\n\t| { type: \"auth_url\"; url: string; instructions?: string }\n\t| {\n\t\t\ttype: \"device_code\";\n\t\t\tuserCode: string;\n\t\t\tverificationUri: string;\n\t\t\tintervalSeconds?: number;\n\t\t\texpiresInSeconds?: number;\n\t }\n\t| { type: \"progress\"; message: string };\n\n/**\n * Login interaction callbacks serving both api-key and OAuth flows.\n *\n * `prompt()` returns the entered/selected string (`select` returns the option\n * id). Rejects on cancel/abort. `signal` aborts the whole login flow;\n * per-prompt cancellation uses `AuthPrompt.signal`.\n */\nexport interface AuthLoginCallbacks {\n\tsignal?: AbortSignal;\n\n\tprompt(prompt: AuthPrompt): Promise<string>;\n\tnotify(event: AuthEvent): void;\n}\n\n/**\n * Api-key auth: stored key/provider env plus ambient sources (env vars, AWS\n * profiles, ADC files). Ambient-only providers omit `login`.\n */\nexport interface ApiKeyAuth {\n\t/** Display name, e.g. \"Anthropic API key\". */\n\tname: string;\n\n\t/** Interactive setup (prompt for key/provider env). Absent = ambient-only. */\n\tlogin?(callbacks: AuthLoginCallbacks): Promise<ApiKeyCredential>;\n\n\t/**\n\t * Resolve auth from the stored credential and/or ambient sources, merging\n\t * per field (`credential.key ?? env(\"...\")`, `credential.env?.NAME ?? env(\"...\")`).\n\t * undefined = not configured. Receives the chat or image-generation model\n\t * the request is for (both carry `provider` and `baseUrl`).\n\t */\n\tresolve(input: {\n\t\tmodel: Model<Api> | ImagesModel<ImagesApi>;\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t}): Promise<AuthResult | undefined>;\n}\n\n/**\n * OAuth auth. The `refresh`/`toAuth` split lets `Models` own the locked\n * refresh pattern: `refresh` produces a credential, `toAuth` derives request\n * auth from whatever credential ends up stored.\n */\nexport interface OAuthAuth {\n\t/** Display name, e.g. \"Anthropic (Claude Pro/Max)\". */\n\tname: string;\n\n\tlogin(callbacks: AuthLoginCallbacks): Promise<OAuthCredential>;\n\n\t/**\n\t * Exchange the refresh token. Network call; throws on failure\n\t * (invalid_grant etc.). `Models` runs this under the store lock.\n\t */\n\trefresh(credential: OAuthCredential): Promise<OAuthCredential>;\n\n\t/**\n\t * Side-effect-free derivation of request auth from a valid credential.\n\t * Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers\n\t * can load the implementation on first use.\n\t */\n\ttoAuth(credential: OAuthCredential): Promise<ModelAuth>;\n}\n\n/**\n * Provider auth. At least one of `apiKey`/`oauth` must be present: even\n * ambient-credential providers and keyless local servers provide `apiKey`\n * auth whose `resolve()` reports whether the provider is configured.\n */\nexport interface ProviderAuth {\n\tapiKey?: ApiKeyAuth;\n\toauth?: OAuthAuth;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEhE;;;GAGG;AACH,MAAM,WAAW,SAAS;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,eAAe,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,SAAS,CA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IAEb,oGAAoG;IACpG,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB,KAAK,CAAC,WAAW,EAAE,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAE9D;;;OAGG;IACH,OAAO,CAAC,UAAU,EAAE,eAAe,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAErF;;;;OAIG;IACH,MAAM,CAAC,UAAU,EAAE,eAAe,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;CACxD;AAED;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC5B,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,KAAK,CAAC,EAAE,SAAS,CAAC;CAClB","sourcesContent":["import type { ProviderEnv, ProviderHeaders } from \"../types.ts\";\n\n/**\n * Request auth for a single model request. If a value cannot be expressed as\n * `apiKey`, `headers`, or `baseUrl`, it is provider config, not auth.\n */\nexport interface ModelAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * Stored api-key credential. `env` holds provider-scoped environment/config\n * values such as Cloudflare account/gateway ids.\n */\nexport interface ApiKeyCredential {\n\ttype: \"api_key\";\n\tkey?: string;\n\tenv?: ProviderEnv;\n}\n\n/** OAuth token data returned by extension compatibility flows. */\nexport interface OAuthCredentials {\n\trefresh: string;\n\taccess: string;\n\texpires: number;\n\t[key: string]: unknown;\n}\n\n/** Stored canonical OAuth credential. */\nexport interface OAuthCredential extends OAuthCredentials {\n\ttype: \"oauth\";\n}\n\n/** One type-tagged credential per provider — the shape of today's auth.json. */\nexport type Credential = ApiKeyCredential | OAuthCredential;\n\n/** Non-secret credential metadata for account/status enumeration. */\nexport interface CredentialInfo {\n\tproviderId: string;\n\ttype: Credential[\"type\"];\n}\n\n/**\n * App-owned credential storage, keyed by `Provider.id`, one credential per\n * provider. `modify` is the only write path, so every mutation is a\n * serialized read-modify-write; `Models.getAuth()` runs OAuth refresh inside\n * `modify` so concurrent requests cannot double-refresh a rotated token. The\n * app persists a credential after login via\n * `modify(provider.id, async () => credential)`. Login/logout orchestration\n * is app-owned.\n *\n * Error semantics: `read` resolves `undefined` for missing entries. Methods\n * reject only on storage failure; `Models` wraps such rejections in\n * `ModelsError` with code \"auth\". Best-effort stores that serve an in-memory\n * view and record persistence errors internally (like coding-agent's\n * AuthStorage) are valid implementations.\n */\nexport interface CredentialStore {\n\t/**\n\t * Read the stored credential, possibly expired. Display/status use;\n\t * resolved request auth comes from `Models.getAuth()`.\n\t */\n\tread(providerId: string): Promise<Credential | undefined>;\n\n\t/**\n\t * List stored credential metadata without resolving or exposing secrets.\n\t * Implementations must not execute configured API-key commands while listing.\n\t */\n\tlist(): Promise<readonly CredentialInfo[]>;\n\n\t/**\n\t * Serialized write — the only write path. `fn` sees the current credential\n\t * because correct writes (refresh, login-during-refresh) depend on it;\n\t * return the new credential, or undefined to leave the entry unchanged.\n\t * Mutual exclusion per provider id, cross-process too where the backing\n\t * store supports it (e.g. a file lock). Resolves with the post-write\n\t * credential. Rejections from `fn` propagate.\n\t */\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t): Promise<Credential | undefined>;\n\n\t/** Remove a credential (logout). Implementations serialize this against `modify`. */\n\tdelete(providerId: string): Promise<void>;\n}\n\n/** Environment access for auth resolution. Injectable for tests and browsers. */\nexport interface AuthContext {\n\tenv(name: string): Promise<string | undefined>;\n\t/** Check whether a file exists. Supports a leading `~`. Always false in browsers. */\n\tfileExists(path: string): Promise<boolean>;\n}\n\n/** Result of resolving auth for a model. */\nexport interface AuthResult {\n\tauth: ModelAuth;\n\t/** Provider-scoped environment/config values resolved from credentials and ambient context. */\n\tenv?: ProviderEnv;\n\t/** Human-readable label for status UI: \"ANTHROPIC_API_KEY\", \"OAuth\", \"~/.aws/credentials\". */\n\tsource?: string;\n}\n\nexport interface AuthCheck {\n\tsource?: string;\n\ttype: \"api_key\" | \"oauth\";\n}\n\nexport type AuthType = \"api_key\" | \"oauth\";\n\n/**\n * Prompt shown to the user during login. `signal` lets the flow cancel a\n * pending prompt when an out-of-band event resolves the step, e.g. a\n * `manual_code` prompt raced against a callback server, aborted when the\n * callback wins.\n */\nexport type AuthPrompt = { signal?: AbortSignal } & (\n\t| { type: \"text\"; message: string; placeholder?: string }\n\t| { type: \"secret\"; message: string; placeholder?: string }\n\t| { type: \"select\"; message: string; options: readonly { id: string; label: string; description?: string }[] }\n\t| { type: \"manual_code\"; message: string; placeholder?: string }\n);\n\nexport interface AuthInfoLink {\n\turl: string;\n\tlabel?: string;\n}\n\nexport type AuthEvent =\n\t| { type: \"info\"; message: string; links?: readonly AuthInfoLink[] }\n\t| { type: \"auth_url\"; url: string; instructions?: string }\n\t| {\n\t\t\ttype: \"device_code\";\n\t\t\tuserCode: string;\n\t\t\tverificationUri: string;\n\t\t\tintervalSeconds?: number;\n\t\t\texpiresInSeconds?: number;\n\t }\n\t| { type: \"progress\"; message: string };\n\n/**\n * Login interaction callbacks serving both api-key and OAuth flows.\n *\n * `prompt()` returns the entered/selected string (`select` returns the option\n * id). Rejects on cancel/abort. `signal` aborts the whole login flow;\n * per-prompt cancellation uses `AuthPrompt.signal`.\n */\nexport interface AuthInteraction {\n\tsignal?: AbortSignal;\n\n\tprompt(prompt: AuthPrompt): Promise<string>;\n\tnotify(event: AuthEvent): void;\n}\n\n/**\n * Api-key auth: stored key/provider env plus ambient sources (env vars, AWS\n * profiles, ADC files). Ambient-only providers omit `login`.\n */\nexport interface ApiKeyAuth {\n\t/** Display name, e.g. \"Anthropic API key\". */\n\tname: string;\n\n\t/** Interactive setup (prompt for key/provider env). Absent = ambient-only. */\n\tlogin?(interaction: AuthInteraction): Promise<ApiKeyCredential>;\n\n\t/**\n\t * Optional side-effect-free availability check. Use this when `resolve()` may\n\t * execute commands or perform other request-time work. Missing means Models\n\t * checks availability by resolving auth.\n\t */\n\tcheck?(input: { ctx: AuthContext; credential?: ApiKeyCredential }): Promise<AuthCheck | undefined>;\n\n\t/**\n\t * Resolve auth from the stored credential and/or ambient sources, merging\n\t * per field (`credential.key ?? env(\"...\")`, `credential.env?.NAME ?? env(\"...\")`).\n\t * undefined = not configured. Resolution is provider-scoped; model-specific\n\t * endpoint preparation happens after auth has been resolved.\n\t */\n\tresolve(input: { ctx: AuthContext; credential?: ApiKeyCredential }): Promise<AuthResult | undefined>;\n}\n\n/**\n * OAuth auth. The `refresh`/`toAuth` split lets `Models` own the locked\n * refresh pattern: `refresh` produces a credential, `toAuth` derives request\n * auth from whatever credential ends up stored.\n */\nexport interface OAuthAuth {\n\t/** Display name, e.g. \"Anthropic (Claude Pro/Max)\". */\n\tname: string;\n\n\t/** Selector label for the subscription login option, e.g. \"Sign in with SuperGrok or X Premium\". */\n\tloginLabel?: string;\n\n\tlogin(interaction: AuthInteraction): Promise<OAuthCredential>;\n\n\t/**\n\t * Exchange the refresh token. Network call; throws on failure\n\t * (invalid_grant etc.). `Models` runs this under the store lock.\n\t */\n\trefresh(credential: OAuthCredential, signal?: AbortSignal): Promise<OAuthCredential>;\n\n\t/**\n\t * Side-effect-free derivation of request auth from a valid credential.\n\t * Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers\n\t * can load the implementation on first use.\n\t */\n\ttoAuth(credential: OAuthCredential): Promise<ModelAuth>;\n}\n\n/**\n * Provider auth. At least one of `apiKey`/`oauth` must be present: even\n * ambient-credential providers and keyless local servers provide `apiKey`\n * auth whose `resolve()` reports whether the provider is configured.\n */\nexport interface ProviderAuth {\n\tapiKey?: ApiKeyAuth;\n\toauth?: OAuthAuth;\n}\n"]}
|
package/dist/auth/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"","sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ProviderEnv, ProviderHeaders } from \"../types.ts\";\n\n/**\n * Request auth for a single model request. If a value cannot be expressed as\n * `apiKey`, `headers`, or `baseUrl`, it is provider config, not auth.\n */\nexport interface ModelAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * Stored api-key credential. `env` holds provider-scoped environment/config\n * values such as Cloudflare account/gateway ids.\n */\nexport interface ApiKeyCredential {\n\ttype: \"api_key\";\n\tkey?: string;\n\tenv?: ProviderEnv;\n}\n\n/** OAuth token data returned by extension compatibility flows. */\nexport interface OAuthCredentials {\n\trefresh: string;\n\taccess: string;\n\texpires: number;\n\t[key: string]: unknown;\n}\n\n/** Stored canonical OAuth credential. */\nexport interface OAuthCredential extends OAuthCredentials {\n\ttype: \"oauth\";\n}\n\n/** One type-tagged credential per provider — the shape of today's auth.json. */\nexport type Credential = ApiKeyCredential | OAuthCredential;\n\n/** Non-secret credential metadata for account/status enumeration. */\nexport interface CredentialInfo {\n\tproviderId: string;\n\ttype: Credential[\"type\"];\n}\n\n/**\n * App-owned credential storage, keyed by `Provider.id`, one credential per\n * provider. `modify` is the only write path, so every mutation is a\n * serialized read-modify-write; `Models.getAuth()` runs OAuth refresh inside\n * `modify` so concurrent requests cannot double-refresh a rotated token. The\n * app persists a credential after login via\n * `modify(provider.id, async () => credential)`. Login/logout orchestration\n * is app-owned.\n *\n * Error semantics: `read` resolves `undefined` for missing entries. Methods\n * reject only on storage failure; `Models` wraps such rejections in\n * `ModelsError` with code \"auth\". Best-effort stores that serve an in-memory\n * view and record persistence errors internally (like coding-agent's\n * AuthStorage) are valid implementations.\n */\nexport interface CredentialStore {\n\t/**\n\t * Read the stored credential, possibly expired. Display/status use;\n\t * resolved request auth comes from `Models.getAuth()`.\n\t */\n\tread(providerId: string): Promise<Credential | undefined>;\n\n\t/**\n\t * List stored credential metadata without resolving or exposing secrets.\n\t * Implementations must not execute configured API-key commands while listing.\n\t */\n\tlist(): Promise<readonly CredentialInfo[]>;\n\n\t/**\n\t * Serialized write — the only write path. `fn` sees the current credential\n\t * because correct writes (refresh, login-during-refresh) depend on it;\n\t * return the new credential, or undefined to leave the entry unchanged.\n\t * Mutual exclusion per provider id, cross-process too where the backing\n\t * store supports it (e.g. a file lock). Resolves with the post-write\n\t * credential. Rejections from `fn` propagate.\n\t */\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t): Promise<Credential | undefined>;\n\n\t/** Remove a credential (logout). Implementations serialize this against `modify`. */\n\tdelete(providerId: string): Promise<void>;\n}\n\n/** Environment access for auth resolution. Injectable for tests and browsers. */\nexport interface AuthContext {\n\tenv(name: string): Promise<string | undefined>;\n\t/** Check whether a file exists. Supports a leading `~`. Always false in browsers. */\n\tfileExists(path: string): Promise<boolean>;\n}\n\n/** Result of resolving auth for a model. */\nexport interface AuthResult {\n\tauth: ModelAuth;\n\t/** Provider-scoped environment/config values resolved from credentials and ambient context. */\n\tenv?: ProviderEnv;\n\t/** Human-readable label for status UI: \"ANTHROPIC_API_KEY\", \"OAuth\", \"~/.aws/credentials\". */\n\tsource?: string;\n}\n\nexport interface AuthCheck {\n\tsource?: string;\n\ttype: \"api_key\" | \"oauth\";\n}\n\nexport type AuthType = \"api_key\" | \"oauth\";\n\n/**\n * Prompt shown to the user during login. `signal` lets the flow cancel a\n * pending prompt when an out-of-band event resolves the step, e.g. a\n * `manual_code` prompt raced against a callback server, aborted when the\n * callback wins.\n */\nexport type AuthPrompt = { signal?: AbortSignal } & (\n\t| { type: \"text\"; message: string; placeholder?: string }\n\t| { type: \"secret\"; message: string; placeholder?: string }\n\t| { type: \"select\"; message: string; options: readonly { id: string; label: string; description?: string }[] }\n\t| { type: \"manual_code\"; message: string; placeholder?: string }\n);\n\nexport interface AuthInfoLink {\n\turl: string;\n\tlabel?: string;\n}\n\nexport type AuthEvent =\n\t| { type: \"info\"; message: string; links?: readonly AuthInfoLink[] }\n\t| { type: \"auth_url\"; url: string; instructions?: string }\n\t| {\n\t\t\ttype: \"device_code\";\n\t\t\tuserCode: string;\n\t\t\tverificationUri: string;\n\t\t\tintervalSeconds?: number;\n\t\t\texpiresInSeconds?: number;\n\t }\n\t| { type: \"progress\"; message: string };\n\n/**\n * Login interaction callbacks serving both api-key and OAuth flows.\n *\n * `prompt()` returns the entered/selected string (`select` returns the option\n * id). Rejects on cancel/abort. `signal` aborts the whole login flow;\n * per-prompt cancellation uses `AuthPrompt.signal`.\n */\nexport interface AuthInteraction {\n\tsignal?: AbortSignal;\n\n\tprompt(prompt: AuthPrompt): Promise<string>;\n\tnotify(event: AuthEvent): void;\n}\n\n/**\n * Api-key auth: stored key/provider env plus ambient sources (env vars, AWS\n * profiles, ADC files). Ambient-only providers omit `login`.\n */\nexport interface ApiKeyAuth {\n\t/** Display name, e.g. \"Anthropic API key\". */\n\tname: string;\n\n\t/** Interactive setup (prompt for key/provider env). Absent = ambient-only. */\n\tlogin?(interaction: AuthInteraction): Promise<ApiKeyCredential>;\n\n\t/**\n\t * Optional side-effect-free availability check. Use this when `resolve()` may\n\t * execute commands or perform other request-time work. Missing means Models\n\t * checks availability by resolving auth.\n\t */\n\tcheck?(input: { ctx: AuthContext; credential?: ApiKeyCredential }): Promise<AuthCheck | undefined>;\n\n\t/**\n\t * Resolve auth from the stored credential and/or ambient sources, merging\n\t * per field (`credential.key ?? env(\"...\")`, `credential.env?.NAME ?? env(\"...\")`).\n\t * undefined = not configured. Resolution is provider-scoped; model-specific\n\t * endpoint preparation happens after auth has been resolved.\n\t */\n\tresolve(input: { ctx: AuthContext; credential?: ApiKeyCredential }): Promise<AuthResult | undefined>;\n}\n\n/**\n * OAuth auth. The `refresh`/`toAuth` split lets `Models` own the locked\n * refresh pattern: `refresh` produces a credential, `toAuth` derives request\n * auth from whatever credential ends up stored.\n */\nexport interface OAuthAuth {\n\t/** Display name, e.g. \"Anthropic (Claude Pro/Max)\". */\n\tname: string;\n\n\t/** Selector label for the subscription login option, e.g. \"Sign in with SuperGrok or X Premium\". */\n\tloginLabel?: string;\n\n\tlogin(interaction: AuthInteraction): Promise<OAuthCredential>;\n\n\t/**\n\t * Exchange the refresh token. Network call; throws on failure\n\t * (invalid_grant etc.). `Models` runs this under the store lock.\n\t */\n\trefresh(credential: OAuthCredential, signal?: AbortSignal): Promise<OAuthCredential>;\n\n\t/**\n\t * Side-effect-free derivation of request auth from a valid credential.\n\t * Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers\n\t * can load the implementation on first use.\n\t */\n\ttoAuth(credential: OAuthCredential): Promise<ModelAuth>;\n}\n\n/**\n * Provider auth. At least one of `apiKey`/`oauth` must be present: even\n * ambient-credential providers and keyless local servers provide `apiKey`\n * auth whose `resolve()` reports whether the provider is configured.\n */\nexport interface ProviderAuth {\n\tapiKey?: ApiKeyAuth;\n\toauth?: OAuthAuth;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bun-oauth.d.ts","sourceRoot":"","sources":["../src/bun-oauth.ts"],"names":[],"mappings":"AAOA,6EAA6E;AAC7E,wBAAgB,qBAAqB,IAAI,IAAI,CAQ5C","sourcesContent":["import { anthropicOAuth } from \"./auth/oauth/anthropic.ts\";\nimport { githubCopilotOAuth } from \"./auth/oauth/github-copilot.ts\";\nimport { registerBundledOAuthFlowLoaders } from \"./auth/oauth/load.ts\";\nimport { openaiCodexOAuth } from \"./auth/oauth/openai-codex.ts\";\nimport { createRadiusOAuth } from \"./auth/oauth/radius.ts\";\nimport { xaiOAuth } from \"./auth/oauth/xai.ts\";\n\n/** Register OAuth flows statically embedded in the standalone Bun binary. */\nexport function registerBunOAuthFlows(): void {\n\tregisterBundledOAuthFlowLoaders({\n\t\tanthropic: () => anthropicOAuth,\n\t\topenaiCodex: () => openaiCodexOAuth,\n\t\tgithubCopilot: () => githubCopilotOAuth,\n\t\txai: () => xaiOAuth,\n\t\tradius: createRadiusOAuth,\n\t});\n}\n"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { anthropicOAuth } from "./auth/oauth/anthropic.js";
|
|
2
|
+
import { githubCopilotOAuth } from "./auth/oauth/github-copilot.js";
|
|
3
|
+
import { registerBundledOAuthFlowLoaders } from "./auth/oauth/load.js";
|
|
4
|
+
import { openaiCodexOAuth } from "./auth/oauth/openai-codex.js";
|
|
5
|
+
import { createRadiusOAuth } from "./auth/oauth/radius.js";
|
|
6
|
+
import { xaiOAuth } from "./auth/oauth/xai.js";
|
|
7
|
+
/** Register OAuth flows statically embedded in the standalone Bun binary. */
|
|
8
|
+
export function registerBunOAuthFlows() {
|
|
9
|
+
registerBundledOAuthFlowLoaders({
|
|
10
|
+
anthropic: () => anthropicOAuth,
|
|
11
|
+
openaiCodex: () => openaiCodexOAuth,
|
|
12
|
+
githubCopilot: () => githubCopilotOAuth,
|
|
13
|
+
xai: () => xaiOAuth,
|
|
14
|
+
radius: createRadiusOAuth,
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=bun-oauth.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bun-oauth.js","sourceRoot":"","sources":["../src/bun-oauth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AACpE,OAAO,EAAE,+BAA+B,EAAE,MAAM,sBAAsB,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAE/C,6EAA6E;AAC7E,MAAM,UAAU,qBAAqB,GAAS;IAC7C,+BAA+B,CAAC;QAC/B,SAAS,EAAE,GAAG,EAAE,CAAC,cAAc;QAC/B,WAAW,EAAE,GAAG,EAAE,CAAC,gBAAgB;QACnC,aAAa,EAAE,GAAG,EAAE,CAAC,kBAAkB;QACvC,GAAG,EAAE,GAAG,EAAE,CAAC,QAAQ;QACnB,MAAM,EAAE,iBAAiB;KACzB,CAAC,CAAC;AAAA,CACH","sourcesContent":["import { anthropicOAuth } from \"./auth/oauth/anthropic.ts\";\nimport { githubCopilotOAuth } from \"./auth/oauth/github-copilot.ts\";\nimport { registerBundledOAuthFlowLoaders } from \"./auth/oauth/load.ts\";\nimport { openaiCodexOAuth } from \"./auth/oauth/openai-codex.ts\";\nimport { createRadiusOAuth } from \"./auth/oauth/radius.ts\";\nimport { xaiOAuth } from \"./auth/oauth/xai.ts\";\n\n/** Register OAuth flows statically embedded in the standalone Bun binary. */\nexport function registerBunOAuthFlows(): void {\n\tregisterBundledOAuthFlowLoaders({\n\t\tanthropic: () => anthropicOAuth,\n\t\topenaiCodex: () => openaiCodexOAuth,\n\t\tgithubCopilot: () => githubCopilotOAuth,\n\t\txai: () => xaiOAuth,\n\t\tradius: createRadiusOAuth,\n\t});\n}\n"]}
|
package/dist/cli.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"","sourcesContent":["#!/usr/bin/env node\n\nimport {
|
|
1
|
+
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"","sourcesContent":["#!/usr/bin/env node\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\nimport type { AuthPrompt, OAuthCredential, Provider } from \"./index.ts\";\nimport { builtinProviders } from \"./providers/all.ts\";\n\nconst AUTH_FILE = \"auth.json\";\nconst PROVIDERS = builtinProviders().filter(\n\t(provider): provider is Provider & { auth: { oauth: NonNullable<Provider[\"auth\"][\"oauth\"]> } } =>\n\t\tprovider.auth.oauth !== undefined,\n);\n\nfunction prompt(rl: ReturnType<typeof createInterface>, question: string): Promise<string> {\n\treturn new Promise((resolve) => rl.question(question, resolve));\n}\n\nfunction loadAuth(): Record<string, OAuthCredential> {\n\tif (!existsSync(AUTH_FILE)) return {};\n\ttry {\n\t\treturn JSON.parse(readFileSync(AUTH_FILE, \"utf-8\")) as Record<string, OAuthCredential>;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nfunction saveAuth(auth: Record<string, OAuthCredential>): void {\n\twriteFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), \"utf-8\");\n}\n\nasync function answerPrompt(rl: ReturnType<typeof createInterface>, authPrompt: AuthPrompt): Promise<string> {\n\tif (authPrompt.type === \"select\") {\n\t\tconsole.log(`\\n${authPrompt.message}`);\n\t\tfor (let index = 0; index < authPrompt.options.length; index++) {\n\t\t\tconsole.log(` ${index + 1}. ${authPrompt.options[index].label}`);\n\t\t}\n\t\tconst choice = Number.parseInt(await prompt(rl, `Enter number (1-${authPrompt.options.length}): `), 10) - 1;\n\t\tconst selected = authPrompt.options[choice];\n\t\tif (!selected) throw new Error(\"Invalid selection\");\n\t\treturn selected.id;\n\t}\n\treturn prompt(rl, `${authPrompt.message}${authPrompt.placeholder ? ` (${authPrompt.placeholder})` : \"\"}: `);\n}\n\nasync function login(providerId: string): Promise<void> {\n\tconst provider = PROVIDERS.find((entry) => entry.id === providerId);\n\tif (!provider) throw new Error(`Unknown provider: ${providerId}`);\n\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\ttry {\n\t\tconst credential = await provider.auth.oauth.login({\n\t\t\tprompt: (authPrompt) => answerPrompt(rl, authPrompt),\n\t\t\tnotify: (event) => {\n\t\t\t\tswitch (event.type) {\n\t\t\t\t\tcase \"auth_url\":\n\t\t\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${event.url}`);\n\t\t\t\t\t\tif (event.instructions) console.log(event.instructions);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"device_code\":\n\t\t\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${event.verificationUri}`);\n\t\t\t\t\t\tconsole.log(`Enter code: ${event.userCode}`);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"info\":\n\t\t\t\t\tcase \"progress\":\n\t\t\t\t\t\tconsole.log(event.message);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t},\n\t\t});\n\t\tconst auth = loadAuth();\n\t\tauth[providerId] = credential;\n\t\tsaveAuth(auth);\n\t\tconsole.log(`\\nCredentials saved to ${AUTH_FILE}`);\n\t} finally {\n\t\trl.close();\n\t}\n}\n\nasync function main(): Promise<void> {\n\tconst args = process.argv.slice(2);\n\tconst command = args[0];\n\tif (!command || command === \"help\" || command === \"--help\" || command === \"-h\") {\n\t\tconst providerList = PROVIDERS.map((provider) => ` ${provider.id.padEnd(20)} ${provider.name}`).join(\"\\n\");\n\t\tconsole.log(\n\t\t\t`Usage: npx @earendil-works/pi-ai <command> [provider]\\n\\nCommands:\\n login [provider] Login to an OAuth provider\\n list List available providers\\n\\nProviders:\\n${providerList}`,\n\t\t);\n\t\treturn;\n\t}\n\tif (command === \"list\") {\n\t\tfor (const provider of PROVIDERS) console.log(`${provider.id.padEnd(20)} ${provider.name}`);\n\t\treturn;\n\t}\n\tif (command === \"login\") {\n\t\tlet providerId = args[1];\n\t\tif (!providerId) {\n\t\t\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\t\t\ttry {\n\t\t\t\tfor (let index = 0; index < PROVIDERS.length; index++) {\n\t\t\t\t\tconsole.log(` ${index + 1}. ${PROVIDERS[index].name}`);\n\t\t\t\t}\n\t\t\t\tconst index = Number.parseInt(await prompt(rl, `Enter number (1-${PROVIDERS.length}): `), 10) - 1;\n\t\t\t\tproviderId = PROVIDERS[index]?.id;\n\t\t\t} finally {\n\t\t\t\trl.close();\n\t\t\t}\n\t\t}\n\t\tif (!providerId || !PROVIDERS.some((provider) => provider.id === providerId)) {\n\t\t\tthrow new Error(`Unknown provider: ${providerId ?? \"\"}`);\n\t\t}\n\t\tawait login(providerId);\n\t\treturn;\n\t}\n\tthrow new Error(`Unknown command: ${command}`);\n}\n\nmain().catch((error: unknown) => {\n\tconsole.error(\"Error:\", error instanceof Error ? error.message : String(error));\n\tprocess.exit(1);\n});\n"]}
|
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
3
|
import { createInterface } from "node:readline";
|
|
3
|
-
import {
|
|
4
|
-
import { getOAuthProvider, getOAuthProviders } from "./utils/oauth/index.js";
|
|
4
|
+
import { builtinProviders } from "./providers/all.js";
|
|
5
5
|
const AUTH_FILE = "auth.json";
|
|
6
|
-
const PROVIDERS =
|
|
6
|
+
const PROVIDERS = builtinProviders().filter((provider) => provider.auth.oauth !== undefined);
|
|
7
7
|
function prompt(rl, question) {
|
|
8
8
|
return new Promise((resolve) => rl.question(question, resolve));
|
|
9
9
|
}
|
|
@@ -20,43 +20,48 @@ function loadAuth() {
|
|
|
20
20
|
function saveAuth(auth) {
|
|
21
21
|
writeFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), "utf-8");
|
|
22
22
|
}
|
|
23
|
-
async function
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
23
|
+
async function answerPrompt(rl, authPrompt) {
|
|
24
|
+
if (authPrompt.type === "select") {
|
|
25
|
+
console.log(`\n${authPrompt.message}`);
|
|
26
|
+
for (let index = 0; index < authPrompt.options.length; index++) {
|
|
27
|
+
console.log(` ${index + 1}. ${authPrompt.options[index].label}`);
|
|
28
|
+
}
|
|
29
|
+
const choice = Number.parseInt(await prompt(rl, `Enter number (1-${authPrompt.options.length}): `), 10) - 1;
|
|
30
|
+
const selected = authPrompt.options[choice];
|
|
31
|
+
if (!selected)
|
|
32
|
+
throw new Error("Invalid selection");
|
|
33
|
+
return selected.id;
|
|
28
34
|
}
|
|
35
|
+
return prompt(rl, `${authPrompt.message}${authPrompt.placeholder ? ` (${authPrompt.placeholder})` : ""}: `);
|
|
36
|
+
}
|
|
37
|
+
async function login(providerId) {
|
|
38
|
+
const provider = PROVIDERS.find((entry) => entry.id === providerId);
|
|
39
|
+
if (!provider)
|
|
40
|
+
throw new Error(`Unknown provider: ${providerId}`);
|
|
29
41
|
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
30
|
-
const promptFn = (msg) => prompt(rl, `${msg} `);
|
|
31
42
|
try {
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
for (let i = 0; i < p.options.length; i++) {
|
|
50
|
-
console.log(` ${i + 1}. ${p.options[i].label}`);
|
|
43
|
+
const credential = await provider.auth.oauth.login({
|
|
44
|
+
prompt: (authPrompt) => answerPrompt(rl, authPrompt),
|
|
45
|
+
notify: (event) => {
|
|
46
|
+
switch (event.type) {
|
|
47
|
+
case "auth_url":
|
|
48
|
+
console.log(`\nOpen this URL in your browser:\n${event.url}`);
|
|
49
|
+
if (event.instructions)
|
|
50
|
+
console.log(event.instructions);
|
|
51
|
+
break;
|
|
52
|
+
case "device_code":
|
|
53
|
+
console.log(`\nOpen this URL in your browser:\n${event.verificationUri}`);
|
|
54
|
+
console.log(`Enter code: ${event.userCode}`);
|
|
55
|
+
break;
|
|
56
|
+
case "info":
|
|
57
|
+
case "progress":
|
|
58
|
+
console.log(event.message);
|
|
59
|
+
break;
|
|
51
60
|
}
|
|
52
|
-
const choice = await promptFn(`Enter number (1-${p.options.length}):`);
|
|
53
|
-
const index = parseInt(choice, 10) - 1;
|
|
54
|
-
return p.options[index]?.id;
|
|
55
61
|
},
|
|
56
|
-
onProgress: (msg) => console.log(msg),
|
|
57
62
|
});
|
|
58
63
|
const auth = loadAuth();
|
|
59
|
-
auth[providerId] =
|
|
64
|
+
auth[providerId] = credential;
|
|
60
65
|
saveAuth(auth);
|
|
61
66
|
console.log(`\nCredentials saved to ${AUTH_FILE}`);
|
|
62
67
|
}
|
|
@@ -68,63 +73,40 @@ async function main() {
|
|
|
68
73
|
const args = process.argv.slice(2);
|
|
69
74
|
const command = args[0];
|
|
70
75
|
if (!command || command === "help" || command === "--help" || command === "-h") {
|
|
71
|
-
const providerList = PROVIDERS.map((
|
|
72
|
-
console.log(`Usage: npx @earendil-works/pi-ai <command> [provider]
|
|
73
|
-
|
|
74
|
-
Commands:
|
|
75
|
-
login [provider] Login to an OAuth provider
|
|
76
|
-
list List available providers
|
|
77
|
-
|
|
78
|
-
Providers:
|
|
79
|
-
${providerList}
|
|
80
|
-
|
|
81
|
-
Examples:
|
|
82
|
-
npx @earendil-works/pi-ai login # interactive provider selection
|
|
83
|
-
npx @earendil-works/pi-ai login anthropic # login to specific provider
|
|
84
|
-
npx @earendil-works/pi-ai list # list providers
|
|
85
|
-
`);
|
|
76
|
+
const providerList = PROVIDERS.map((provider) => ` ${provider.id.padEnd(20)} ${provider.name}`).join("\n");
|
|
77
|
+
console.log(`Usage: npx @earendil-works/pi-ai <command> [provider]\n\nCommands:\n login [provider] Login to an OAuth provider\n list List available providers\n\nProviders:\n${providerList}`);
|
|
86
78
|
return;
|
|
87
79
|
}
|
|
88
80
|
if (command === "list") {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
console.log(` ${p.id.padEnd(20)} ${p.name}`);
|
|
92
|
-
}
|
|
81
|
+
for (const provider of PROVIDERS)
|
|
82
|
+
console.log(`${provider.id.padEnd(20)} ${provider.name}`);
|
|
93
83
|
return;
|
|
94
84
|
}
|
|
95
85
|
if (command === "login") {
|
|
96
|
-
let
|
|
97
|
-
if (!
|
|
86
|
+
let providerId = args[1];
|
|
87
|
+
if (!providerId) {
|
|
98
88
|
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
89
|
+
try {
|
|
90
|
+
for (let index = 0; index < PROVIDERS.length; index++) {
|
|
91
|
+
console.log(` ${index + 1}. ${PROVIDERS[index].name}`);
|
|
92
|
+
}
|
|
93
|
+
const index = Number.parseInt(await prompt(rl, `Enter number (1-${PROVIDERS.length}): `), 10) - 1;
|
|
94
|
+
providerId = PROVIDERS[index]?.id;
|
|
102
95
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
rl.close();
|
|
106
|
-
const index = parseInt(choice, 10) - 1;
|
|
107
|
-
if (index < 0 || index >= PROVIDERS.length) {
|
|
108
|
-
console.error("Invalid selection");
|
|
109
|
-
process.exit(1);
|
|
96
|
+
finally {
|
|
97
|
+
rl.close();
|
|
110
98
|
}
|
|
111
|
-
provider = PROVIDERS[index].id;
|
|
112
99
|
}
|
|
113
|
-
if (!PROVIDERS.some((
|
|
114
|
-
|
|
115
|
-
console.error(`Use 'npx @earendil-works/pi-ai list' to see available providers`);
|
|
116
|
-
process.exit(1);
|
|
100
|
+
if (!providerId || !PROVIDERS.some((provider) => provider.id === providerId)) {
|
|
101
|
+
throw new Error(`Unknown provider: ${providerId ?? ""}`);
|
|
117
102
|
}
|
|
118
|
-
|
|
119
|
-
await login(provider);
|
|
103
|
+
await login(providerId);
|
|
120
104
|
return;
|
|
121
105
|
}
|
|
122
|
-
|
|
123
|
-
console.error(`Use 'npx @earendil-works/pi-ai --help' for usage`);
|
|
124
|
-
process.exit(1);
|
|
106
|
+
throw new Error(`Unknown command: ${command}`);
|
|
125
107
|
}
|
|
126
|
-
main().catch((
|
|
127
|
-
console.error("Error:",
|
|
108
|
+
main().catch((error) => {
|
|
109
|
+
console.error("Error:", error instanceof Error ? error.message : String(error));
|
|
128
110
|
process.exit(1);
|
|
129
111
|
});
|
|
130
112
|
//# sourceMappingURL=cli.js.map
|