@code-yeongyu/senpi-ai 2026.8.12 → 2026.8.13
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 +26 -8
- package/dist/api/anthropic-messages.js.map +1 -1
- package/dist/api/azure-openai-responses.js +5 -1
- package/dist/api/azure-openai-responses.js.map +1 -1
- package/dist/api/bedrock-converse-stream.js.map +1 -1
- package/dist/api/bedrock-converse-stream.lazy.js.map +1 -1
- package/dist/api/google-generative-ai.d.ts.map +1 -1
- package/dist/api/google-generative-ai.js +2 -2
- package/dist/api/google-generative-ai.js.map +1 -1
- package/dist/api/google-shared.d.ts +15 -1
- package/dist/api/google-shared.d.ts.map +1 -1
- package/dist/api/google-shared.js +103 -4
- package/dist/api/google-shared.js.map +1 -1
- package/dist/api/google-vertex.d.ts.map +1 -1
- package/dist/api/google-vertex.js +2 -2
- package/dist/api/google-vertex.js.map +1 -1
- package/dist/api/lazy.d.ts +5 -1
- package/dist/api/lazy.d.ts.map +1 -1
- package/dist/api/lazy.js +19 -7
- package/dist/api/lazy.js.map +1 -1
- package/dist/api/openai-codex-responses.js.map +1 -1
- package/dist/api/openai-completions.d.ts +3 -1
- package/dist/api/openai-completions.d.ts.map +1 -1
- package/dist/api/openai-completions.js +47 -7
- package/dist/api/openai-completions.js.map +1 -1
- package/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/dist/api/openai-responses-shared.js +22 -9
- package/dist/api/openai-responses-shared.js.map +1 -1
- package/dist/api/openai-responses.js +5 -1
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/api/pi-messages.d.ts.map +1 -1
- package/dist/api/pi-messages.js.map +1 -1
- package/dist/api/simple-options.d.ts +2 -0
- package/dist/api/simple-options.d.ts.map +1 -1
- package/dist/api/simple-options.js +8 -2
- package/dist/api/simple-options.js.map +1 -1
- package/dist/api/transform-messages.js.map +1 -1
- package/dist/api/warm-prompt-cache.js.map +1 -1
- package/dist/auth/credential-store.d.ts +6 -6
- package/dist/auth/credential-store.d.ts.map +1 -1
- package/dist/auth/credential-store.js +22 -11
- 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 +7 -2
- package/dist/auth/helpers.js.map +1 -1
- package/dist/auth/oauth/anthropic.d.ts.map +1 -1
- package/dist/auth/oauth/anthropic.js +14 -8
- package/dist/auth/oauth/anthropic.js.map +1 -1
- package/dist/auth/oauth/device-code.d.ts +1 -1
- package/dist/auth/oauth/device-code.d.ts.map +1 -1
- package/dist/auth/oauth/device-code.js +4 -4
- package/dist/auth/oauth/device-code.js.map +1 -1
- package/dist/auth/oauth/github-copilot.d.ts.map +1 -1
- package/dist/auth/oauth/github-copilot.js +43 -30
- package/dist/auth/oauth/github-copilot.js.map +1 -1
- package/dist/auth/oauth/kimi-coding.d.ts.map +1 -1
- package/dist/auth/oauth/kimi-coding.js +17 -5
- package/dist/auth/oauth/kimi-coding.js.map +1 -1
- package/dist/auth/oauth/load.d.ts.map +1 -1
- package/dist/auth/oauth/load.js.map +1 -1
- package/dist/auth/oauth/openai-codex.d.ts.map +1 -1
- package/dist/auth/oauth/openai-codex.js +12 -5
- package/dist/auth/oauth/openai-codex.js.map +1 -1
- package/dist/auth/oauth/openrouter.d.ts.map +1 -1
- package/dist/auth/oauth/openrouter.js +10 -10
- package/dist/auth/oauth/openrouter.js.map +1 -1
- package/dist/auth/oauth/radius.d.ts.map +1 -1
- package/dist/auth/oauth/radius.js +8 -7
- package/dist/auth/oauth/radius.js.map +1 -1
- package/dist/auth/oauth/xai.d.ts.map +1 -1
- package/dist/auth/oauth/xai.js +3 -2
- package/dist/auth/oauth/xai.js.map +1 -1
- package/dist/auth/resolve.d.ts +1 -0
- package/dist/auth/resolve.d.ts.map +1 -1
- package/dist/auth/resolve.js +24 -13
- package/dist/auth/resolve.js.map +1 -1
- package/dist/auth/types.d.ts +21 -8
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/auth/types.js.map +1 -1
- package/dist/cli.js +1 -0
- package/dist/cli.js.map +1 -1
- package/dist/compat.js.map +1 -1
- package/dist/env-api-keys.d.ts.map +1 -1
- package/dist/env-api-keys.js +3 -0
- package/dist/env-api-keys.js.map +1 -1
- package/dist/image-models.generated.d.ts +69 -54
- package/dist/image-models.generated.d.ts.map +1 -1
- package/dist/image-models.generated.js +15 -0
- package/dist/image-models.generated.js.map +1 -1
- package/dist/images-models.d.ts.map +1 -1
- package/dist/images-models.js +1 -0
- package/dist/images-models.js.map +1 -1
- package/dist/model.d.ts +2 -0
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js.map +1 -1
- package/dist/models-store.d.ts +9 -12
- package/dist/models-store.d.ts.map +1 -1
- package/dist/models-store.js +6 -3
- package/dist/models-store.js.map +1 -1
- package/dist/models.d.ts +40 -18
- package/dist/models.d.ts.map +1 -1
- package/dist/models.generated.d.ts +6 -0
- package/dist/models.generated.d.ts.map +1 -1
- package/dist/models.generated.js +6 -0
- package/dist/models.generated.js.map +1 -1
- package/dist/models.js +247 -91
- package/dist/models.js.map +1 -1
- package/dist/node/provider-scope.d.ts.map +1 -1
- package/dist/providers/all.d.ts.map +1 -1
- package/dist/providers/all.js +6 -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 +15 -7
- package/dist/providers/amazon-bedrock.js.map +1 -1
- package/dist/providers/anthropic.d.ts.map +1 -1
- package/dist/providers/anthropic.js +15 -6
- package/dist/providers/anthropic.js.map +1 -1
- package/dist/providers/baseten.d.ts +3 -0
- package/dist/providers/baseten.d.ts.map +1 -0
- package/dist/providers/baseten.js +15 -0
- package/dist/providers/baseten.js.map +1 -0
- package/dist/providers/baseten.models.d.ts +4 -0
- package/dist/providers/baseten.models.d.ts.map +1 -0
- package/dist/providers/baseten.models.js +6 -0
- package/dist/providers/baseten.models.js.map +1 -0
- package/dist/providers/cloudflare-auth.d.ts.map +1 -1
- package/dist/providers/cloudflare-auth.js +15 -10
- package/dist/providers/cloudflare-auth.js.map +1 -1
- package/dist/providers/data/.manifest.json +1 -1
- package/dist/providers/data/baseten.json +1 -0
- package/dist/providers/data/fireworks.json +1 -1
- package/dist/providers/data/github-copilot.json +1 -1
- package/dist/providers/data/opencode-go.json +1 -1
- package/dist/providers/data/opencode.json +1 -1
- package/dist/providers/data/opengateway.json +1 -0
- package/dist/providers/data/openrouter.json +1 -1
- package/dist/providers/data/qwen-token-plan-cn.json +1 -1
- package/dist/providers/data/qwen-token-plan-individual.json +1 -0
- package/dist/providers/data/qwen-token-plan.json +1 -1
- package/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/providers/data/xai.json +1 -1
- package/dist/providers/faux.d.ts +18 -13
- package/dist/providers/faux.d.ts.map +1 -1
- package/dist/providers/faux.js +95 -5
- package/dist/providers/faux.js.map +1 -1
- package/dist/providers/github-copilot.js +1 -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 +15 -7
- package/dist/providers/google-vertex.js.map +1 -1
- package/dist/providers/kimi-coding.d.ts.map +1 -1
- package/dist/providers/kimi-coding.js +1 -0
- package/dist/providers/kimi-coding.js.map +1 -1
- package/dist/providers/ollama.d.ts.map +1 -1
- package/dist/providers/ollama.js +1 -2
- package/dist/providers/ollama.js.map +1 -1
- package/dist/providers/openai-codex.d.ts.map +1 -1
- package/dist/providers/openai-codex.js +5 -1
- package/dist/providers/openai-codex.js.map +1 -1
- package/dist/providers/opengateway.d.ts +3 -0
- package/dist/providers/opengateway.d.ts.map +1 -0
- package/dist/providers/opengateway.js +15 -0
- package/dist/providers/opengateway.js.map +1 -0
- package/dist/providers/opengateway.models.d.ts +4 -0
- package/dist/providers/opengateway.models.d.ts.map +1 -0
- package/dist/providers/opengateway.models.js +6 -0
- package/dist/providers/opengateway.models.js.map +1 -0
- package/dist/providers/qwen-token-plan-individual.d.ts +3 -0
- package/dist/providers/qwen-token-plan-individual.d.ts.map +1 -0
- package/dist/providers/qwen-token-plan-individual.js +15 -0
- package/dist/providers/qwen-token-plan-individual.js.map +1 -0
- package/dist/providers/qwen-token-plan-individual.models.d.ts +4 -0
- package/dist/providers/qwen-token-plan-individual.models.d.ts.map +1 -0
- package/dist/providers/qwen-token-plan-individual.models.js +6 -0
- package/dist/providers/qwen-token-plan-individual.models.js.map +1 -0
- package/dist/providers/radius.d.ts.map +1 -1
- package/dist/providers/radius.js +36 -26
- package/dist/providers/radius.js.map +1 -1
- package/dist/providers/xai.d.ts.map +1 -1
- package/dist/providers/xai.js +1 -0
- package/dist/providers/xai.js.map +1 -1
- package/dist/tool-call-middleware/context-transformer.js.map +1 -1
- package/dist/tool-call-middleware/protocols/anthropic-xml/recovery-wrapper-state.d.ts.map +1 -1
- package/dist/tool-call-middleware/protocols/kimi-xtml/parse.js.map +1 -1
- package/dist/tool-call-middleware/recovery-content-lifecycle.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-event-stream.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-native-projection.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-native-projection.js.map +1 -1
- package/dist/tool-call-middleware/recovery-stream-terminal.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-stream-wrapper.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-stream-wrapper.js +5 -0
- package/dist/tool-call-middleware/recovery-stream-wrapper.js.map +1 -1
- package/dist/tool-call-middleware/recovery-text-projection.d.ts.map +1 -1
- package/dist/tool-call-middleware/recovery-text-projection.js.map +1 -1
- package/dist/tool-call-middleware/stream-thinking-projection.d.ts.map +1 -1
- package/dist/tool-call-middleware/stream-wrapper-shared.d.ts.map +1 -1
- package/dist/tool-call-middleware/stream-wrapper-shared.js.map +1 -1
- package/dist/tool-call-middleware/stream-wrapper.js.map +1 -1
- package/dist/types.d.ts +94 -87
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/abort.d.ts +8 -0
- package/dist/utils/abort.d.ts.map +1 -0
- package/dist/utils/abort.js +49 -0
- package/dist/utils/abort.js.map +1 -0
- package/dist/utils/deferred-tools.js.map +1 -1
- package/dist/utils/event-stream.d.ts.map +1 -1
- package/dist/utils/overflow.d.ts +14 -1
- package/dist/utils/overflow.d.ts.map +1 -1
- package/dist/utils/overflow.js +18 -1
- package/dist/utils/overflow.js.map +1 -1
- package/dist/utils/prompt-cache-ttl.d.ts +3 -1
- package/dist/utils/prompt-cache-ttl.d.ts.map +1 -1
- package/dist/utils/prompt-cache-ttl.js +2 -0
- package/dist/utils/prompt-cache-ttl.js.map +1 -1
- package/dist/utils/provider-retry.js.map +1 -1
- package/dist/utils/retry.d.ts +25 -0
- package/dist/utils/retry.d.ts.map +1 -1
- package/dist/utils/retry.js +64 -0
- package/dist/utils/retry.js.map +1 -1
- package/dist/utils/tool-schema-compat.d.ts.map +1 -1
- package/dist/utils/tool-schema-compat.js +1 -0
- package/dist/utils/tool-schema-compat.js.map +1 -1
- package/dist/utils/validation.d.ts.map +1 -1
- package/dist/utils/validation.js +6 -0
- package/dist/utils/validation.js.map +1 -1
- package/package.json +2 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xai.js","sourceRoot":"","sources":["../../../src/auth/oauth/xai.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,MAAM,aAAa,GAAG,sCAAsC,CAAC;AAC7D,MAAM,SAAS,GAAG,gEAAgE,CAAC;AACnF,MAAM,mBAAmB,GAAG,sCAAsC,CAAC;AACnE,MAAM,aAAa,GAAG,gCAAgC,CAAC;AACvD,4FAA4F;AAC5F,MAAM,eAAe,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AACtC,MAAM,8BAA8B,GAAG,IAAI,CAAC;AAmB5C,SAAS,cAAc,CAAC,IAAgB,EAAE,KAAa;I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,EAAE,MAAM,CAAC,QAAQ;QACzB,eAAe,EAAE,MAAM,CAAC,uBAAuB,IAAI,MAAM,CAAC,eAAe;QACzE,eAAe,EAAE,MAAM,CAAC,eAAe;QACvC,gBAAgB,EAAE,MAAM,CAAC,gBAAgB;KACzC,CAAC,CAAC;IACH,OAAO,aAAa,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;AAClD,CAAC;AAED,KAAK,UAAU,eAAe,CAAC,YAAoB,EAAE,MAAoB;IACxE,MAAM,QAAQ,GAAG,MAAM,QAAQ,CAC9B,aAAa,EACb;QACC,UAAU,EAAE,eAAe;QAC3B,SAAS,EAAE,aAAa;QACxB,aAAa,EAAE,YAAY;KAC3B,EACD,MAAM,CACN,CAAC;IACF,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QAClB,MAAM,cAAc,CAAC,eAAe,EAAE,QAAQ,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,4BAA4B,CAAC,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;AAClE,CAAC;AAED,MAAM,CAAC,MAAM,QAAQ,GAAc;IAClC,IAAI,EAAE,2BAA2B;IACjC,UAAU,EAAE,qCAAqC;IACjD,KAAK,EAAE,QAAQ;IACf,OAAO,EAAE,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,CAAC,eAAe,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC;IAE5E,KAAK,CAAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/**\n * xAI OAuth device-code flow.\n */\n\nimport type { AuthInteraction, OAuthAuth, OAuthCredential } from \"../types.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\n\nconst XAI_CLIENT_ID = \"b1a00492-073a-47ea-816f-4c329264a828\";\nconst XAI_SCOPE = \"openid profile email offline_access grok-cli:access api:access\";\nconst XAI_DEVICE_CODE_URL = \"https://auth.x.ai/oauth2/device/code\";\nconst XAI_TOKEN_URL = \"https://auth.x.ai/oauth2/token\";\n// Refresh slightly before the reported expiry to avoid using a token that dies mid-request.\nconst REFRESH_SKEW_MS = 5 * 60 * 1000;\nconst DEFAULT_TOKEN_LIFETIME_SECONDS = 3600;\n\ntype JsonObject = Record<string, unknown>;\n\ntype OAuthHttpResponse = {\n\tok: boolean;\n\tstatus: number;\n\tbody: JsonObject;\n};\n\ntype XaiDeviceCode = {\n\tdeviceCode: string;\n\tuserCode: string;\n\tverificationUri: string;\n\tverificationUriComplete?: string;\n\tintervalSeconds?: number;\n\texpiresInSeconds: number;\n};\n\nfunction requiredString(body: JsonObject, field: string): string {\n\tconst value = body[field];\n\tif (typeof value !== \"string\" || value.length === 0) {\n\t\tthrow new Error(`Invalid xAI OAuth response field: ${field}`);\n\t}\n\treturn value;\n}\n\nfunction positiveNumber(body: JsonObject, field: string): number {\n\tconst value = body[field];\n\tif (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) {\n\t\tthrow new Error(`Invalid xAI OAuth response field: ${field}`);\n\t}\n\treturn value;\n}\n\n// The verification URI is opened in the user's browser; force it to be an https URL\n// so a malicious response cannot make `open` launch something else.\nfunction validateVerificationUri(raw: string): string {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(raw);\n\t} catch {\n\t\tthrow new Error(\"Untrusted verification URI in xAI OAuth response\");\n\t}\n\tif (url.protocol !== \"https:\") {\n\t\tthrow new Error(\"Untrusted verification URI in xAI OAuth response\");\n\t}\n\treturn url.href;\n}\n\nasync function postForm(url: string, fields: Record<string, string>, signal?: AbortSignal): Promise<OAuthHttpResponse> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\t},\n\t\t\tbody: new URLSearchParams(fields),\n\t\t\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tif (signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tlet body: JsonObject;\n\ttry {\n\t\tconst parsed = (await response.json()) as unknown;\n\t\tbody = parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? (parsed as JsonObject) : {};\n\t} catch {\n\t\tif (signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow new Error(`xAI OAuth returned invalid JSON (HTTP ${response.status})`);\n\t}\n\treturn {\n\t\tok: response.ok,\n\t\tstatus: response.status,\n\t\tbody,\n\t};\n}\n\nfunction requestFailure(action: string, response: OAuthHttpResponse): Error {\n\tconst error = typeof response.body.error === \"string\" ? response.body.error : undefined;\n\tconst description =\n\t\ttypeof response.body.error_description === \"string\" ? response.body.error_description : undefined;\n\tconst detail = [error, description].filter(Boolean).join(\": \");\n\treturn new Error(`xAI OAuth ${action} failed (HTTP ${response.status})${detail ? `: ${detail}` : \"\"}`);\n}\n\nfunction parseDeviceCode(body: JsonObject): XaiDeviceCode {\n\t// RFC 8628 allows interval 0 (no minimum wait); fall back to the poller's\n\t// default instead of failing on non-positive or malformed values.\n\tconst interval = body.interval;\n\tconst intervalSeconds =\n\t\ttypeof interval === \"number\" && Number.isFinite(interval) && interval > 0 ? interval : undefined;\n\tconst verificationUriComplete =\n\t\ttypeof body.verification_uri_complete === \"string\" && body.verification_uri_complete.length > 0\n\t\t\t? validateVerificationUri(body.verification_uri_complete)\n\t\t\t: undefined;\n\treturn {\n\t\tdeviceCode: requiredString(body, \"device_code\"),\n\t\tuserCode: requiredString(body, \"user_code\"),\n\t\tverificationUri: validateVerificationUri(requiredString(body, \"verification_uri\")),\n\t\tverificationUriComplete,\n\t\tintervalSeconds,\n\t\texpiresInSeconds: positiveNumber(body, \"expires_in\"),\n\t};\n}\n\nfunction credentialsFromTokenResponse(body: JsonObject, previousRefreshToken?: string): OAuthCredential {\n\tconst access = requiredString(body, \"access_token\");\n\t// xAI may omit refresh_token on refresh when the token is not rotated.\n\tconst refresh =\n\t\tbody.refresh_token === undefined && previousRefreshToken\n\t\t\t? previousRefreshToken\n\t\t\t: requiredString(body, \"refresh_token\");\n\tconst expiresInSeconds =\n\t\tbody.expires_in === undefined ? DEFAULT_TOKEN_LIFETIME_SECONDS : positiveNumber(body, \"expires_in\");\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess,\n\t\trefresh,\n\t\texpires: Date.now() + expiresInSeconds * 1000 - REFRESH_SKEW_MS,\n\t};\n}\n\nasync function requestDeviceCode(signal?: AbortSignal): Promise<XaiDeviceCode> {\n\tconst response = await postForm(\n\t\tXAI_DEVICE_CODE_URL,\n\t\t{\n\t\t\tclient_id: XAI_CLIENT_ID,\n\t\t\tscope: XAI_SCOPE,\n\t\t\treferrer: \"pi\",\n\t\t},\n\t\tsignal,\n\t);\n\tif (!response.ok) {\n\t\tthrow requestFailure(\"device authorization\", response);\n\t}\n\treturn parseDeviceCode(response.body);\n}\n\nasync function pollForTokens(device: XaiDeviceCode, signal?: AbortSignal): Promise<OAuthCredential> {\n\treturn pollOAuthDeviceCodeFlow<OAuthCredential>({\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: device.expiresInSeconds,\n\t\twaitBeforeFirstPoll: true,\n\t\tsignal,\n\t\tpoll: async () => {\n\t\t\tconst response = await postForm(\n\t\t\t\tXAI_TOKEN_URL,\n\t\t\t\t{\n\t\t\t\t\tgrant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n\t\t\t\t\tclient_id: XAI_CLIENT_ID,\n\t\t\t\t\tdevice_code: device.deviceCode,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\n\t\t\tif (response.ok) {\n\t\t\t\treturn { status: \"complete\", value: credentialsFromTokenResponse(response.body) };\n\t\t\t}\n\n\t\t\tconst error = response.body.error;\n\t\t\tif (error === \"authorization_pending\") {\n\t\t\t\treturn { status: \"pending\" };\n\t\t\t}\n\t\t\tif (error === \"slow_down\") {\n\t\t\t\tconst interval = response.body.interval;\n\t\t\t\treturn { status: \"slow_down\", intervalSeconds: typeof interval === \"number\" ? interval : undefined };\n\t\t\t}\n\t\t\tif (error === \"access_denied\" || error === \"authorization_denied\") {\n\t\t\t\treturn { status: \"failed\", message: \"xAI device authorization was denied\" };\n\t\t\t}\n\t\t\tif (error === \"expired_token\") {\n\t\t\t\treturn { status: \"failed\", message: \"xAI device code expired\" };\n\t\t\t}\n\t\t\treturn { status: \"failed\", message: requestFailure(\"device token polling\", response).message };\n\t\t},\n\t});\n}\n\nasync function loginXai(interaction: AuthInteraction): Promise<OAuthCredential> {\n\tconst device = await requestDeviceCode(interaction.signal);\n\tinteraction.notify({\n\t\ttype: \"device_code\",\n\t\tuserCode: device.userCode,\n\t\tverificationUri: device.verificationUriComplete ?? device.verificationUri,\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: device.expiresInSeconds,\n\t});\n\treturn pollForTokens(device, interaction.signal);\n}\n\nasync function refreshXaiToken(refreshToken: string, signal?: AbortSignal): Promise<OAuthCredential> {\n\tconst response = await postForm(\n\t\tXAI_TOKEN_URL,\n\t\t{\n\t\t\tgrant_type: \"refresh_token\",\n\t\t\tclient_id: XAI_CLIENT_ID,\n\t\t\trefresh_token: refreshToken,\n\t\t},\n\t\tsignal,\n\t);\n\tif (!response.ok) {\n\t\tthrow requestFailure(\"token refresh\", response);\n\t}\n\treturn credentialsFromTokenResponse(response.body, refreshToken);\n}\n\nexport const xaiOAuth: OAuthAuth = {\n\tname: \"xAI (Grok/X subscription)\",\n\tloginLabel: \"Sign in with SuperGrok or X Premium\",\n\tlogin: loginXai,\n\trefresh: (credential, signal) => refreshXaiToken(credential.refresh, signal),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
|
|
1
|
+
{"version":3,"file":"xai.js","sourceRoot":"","sources":["../../../src/auth/o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,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,CAAC,eAAe,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC;IAE5E,KAAK,CAAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/**\n * xAI OAuth device-code flow.\n */\n\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\n\nconst XAI_CLIENT_ID = \"b1a00492-073a-47ea-816f-4c329264a828\";\nconst XAI_SCOPE = \"openid profile email offline_access grok-cli:access api:access\";\nconst XAI_DEVICE_CODE_URL = \"https://auth.x.ai/oauth2/device/code\";\nconst XAI_TOKEN_URL = \"https://auth.x.ai/oauth2/token\";\n// Refresh slightly before the reported expiry to avoid using a token that dies mid-request.\nconst REFRESH_SKEW_MS = 5 * 60 * 1000;\nconst DEFAULT_TOKEN_LIFETIME_SECONDS = 3600;\n\ntype JsonObject = Record<string, unknown>;\n\ntype OAuthHttpResponse = {\n\tok: boolean;\n\tstatus: number;\n\tbody: JsonObject;\n};\n\ntype XaiDeviceCode = {\n\tdeviceCode: string;\n\tuserCode: string;\n\tverificationUri: string;\n\tverificationUriComplete?: string;\n\tintervalSeconds?: number;\n\texpiresInSeconds: number;\n};\n\nfunction requiredString(body: JsonObject, field: string): string {\n\tconst value = body[field];\n\tif (typeof value !== \"string\" || value.length === 0) {\n\t\tthrow new Error(`Invalid xAI OAuth response field: ${field}`);\n\t}\n\treturn value;\n}\n\nfunction positiveNumber(body: JsonObject, field: string): number {\n\tconst value = body[field];\n\tif (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) {\n\t\tthrow new Error(`Invalid xAI OAuth response field: ${field}`);\n\t}\n\treturn value;\n}\n\n// The verification URI is opened in the user's browser; force it to be an https URL\n// so a malicious response cannot make `open` launch something else.\nfunction validateVerificationUri(raw: string): string {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(raw);\n\t} catch {\n\t\tthrow new Error(\"Untrusted verification URI in xAI OAuth response\");\n\t}\n\tif (url.protocol !== \"https:\") {\n\t\tthrow new Error(\"Untrusted verification URI in xAI OAuth response\");\n\t}\n\treturn url.href;\n}\n\nasync function postForm(url: string, fields: Record<string, string>, signal: AbortSignal): Promise<OAuthHttpResponse> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\t},\n\t\t\tbody: new URLSearchParams(fields),\n\t\t\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tif (signal.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tlet body: JsonObject;\n\ttry {\n\t\tconst parsed = (await response.json()) as unknown;\n\t\tbody = parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? (parsed as JsonObject) : {};\n\t} catch {\n\t\tif (signal.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow new Error(`xAI OAuth returned invalid JSON (HTTP ${response.status})`);\n\t}\n\treturn {\n\t\tok: response.ok,\n\t\tstatus: response.status,\n\t\tbody,\n\t};\n}\n\nfunction requestFailure(action: string, response: OAuthHttpResponse): Error {\n\tconst error = typeof response.body.error === \"string\" ? response.body.error : undefined;\n\tconst description =\n\t\ttypeof response.body.error_description === \"string\" ? response.body.error_description : undefined;\n\tconst detail = [error, description].filter(Boolean).join(\": \");\n\treturn new Error(`xAI OAuth ${action} failed (HTTP ${response.status})${detail ? `: ${detail}` : \"\"}`);\n}\n\nfunction parseDeviceCode(body: JsonObject): XaiDeviceCode {\n\t// RFC 8628 allows interval 0 (no minimum wait); fall back to the poller's\n\t// default instead of failing on non-positive or malformed values.\n\tconst interval = body.interval;\n\tconst intervalSeconds =\n\t\ttypeof interval === \"number\" && Number.isFinite(interval) && interval > 0 ? interval : undefined;\n\tconst verificationUriComplete =\n\t\ttypeof body.verification_uri_complete === \"string\" && body.verification_uri_complete.length > 0\n\t\t\t? validateVerificationUri(body.verification_uri_complete)\n\t\t\t: undefined;\n\treturn {\n\t\tdeviceCode: requiredString(body, \"device_code\"),\n\t\tuserCode: requiredString(body, \"user_code\"),\n\t\tverificationUri: validateVerificationUri(requiredString(body, \"verification_uri\")),\n\t\tverificationUriComplete,\n\t\tintervalSeconds,\n\t\texpiresInSeconds: positiveNumber(body, \"expires_in\"),\n\t};\n}\n\nfunction credentialsFromTokenResponse(body: JsonObject, previousRefreshToken?: string): OAuthCredential {\n\tconst access = requiredString(body, \"access_token\");\n\t// xAI may omit refresh_token on refresh when the token is not rotated.\n\tconst refresh =\n\t\tbody.refresh_token === undefined && previousRefreshToken\n\t\t\t? previousRefreshToken\n\t\t\t: requiredString(body, \"refresh_token\");\n\tconst expiresInSeconds =\n\t\tbody.expires_in === undefined ? DEFAULT_TOKEN_LIFETIME_SECONDS : positiveNumber(body, \"expires_in\");\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess,\n\t\trefresh,\n\t\texpires: Date.now() + expiresInSeconds * 1000 - REFRESH_SKEW_MS,\n\t};\n}\n\nasync function requestDeviceCode(signal: AbortSignal): Promise<XaiDeviceCode> {\n\tconst response = await postForm(\n\t\tXAI_DEVICE_CODE_URL,\n\t\t{\n\t\t\tclient_id: XAI_CLIENT_ID,\n\t\t\tscope: XAI_SCOPE,\n\t\t\treferrer: \"pi\",\n\t\t},\n\t\tsignal,\n\t);\n\tif (!response.ok) {\n\t\tthrow requestFailure(\"device authorization\", response);\n\t}\n\treturn parseDeviceCode(response.body);\n}\n\nasync function pollForTokens(device: XaiDeviceCode, signal: AbortSignal): Promise<OAuthCredential> {\n\treturn pollOAuthDeviceCodeFlow<OAuthCredential>({\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: device.expiresInSeconds,\n\t\twaitBeforeFirstPoll: true,\n\t\tsignal,\n\t\tpoll: async () => {\n\t\t\tconst response = await postForm(\n\t\t\t\tXAI_TOKEN_URL,\n\t\t\t\t{\n\t\t\t\t\tgrant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n\t\t\t\t\tclient_id: XAI_CLIENT_ID,\n\t\t\t\t\tdevice_code: device.deviceCode,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\n\t\t\tif (response.ok) {\n\t\t\t\treturn { status: \"complete\", value: credentialsFromTokenResponse(response.body) };\n\t\t\t}\n\n\t\t\tconst error = response.body.error;\n\t\t\tif (error === \"authorization_pending\") {\n\t\t\t\treturn { status: \"pending\" };\n\t\t\t}\n\t\t\tif (error === \"slow_down\") {\n\t\t\t\tconst interval = response.body.interval;\n\t\t\t\treturn { status: \"slow_down\", intervalSeconds: typeof interval === \"number\" ? interval : undefined };\n\t\t\t}\n\t\t\tif (error === \"access_denied\" || error === \"authorization_denied\") {\n\t\t\t\treturn { status: \"failed\", message: \"xAI device authorization was denied\" };\n\t\t\t}\n\t\t\tif (error === \"expired_token\") {\n\t\t\t\treturn { status: \"failed\", message: \"xAI device code expired\" };\n\t\t\t}\n\t\t\treturn { status: \"failed\", message: requestFailure(\"device token polling\", response).message };\n\t\t},\n\t});\n}\n\nasync function loginXai(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst device = await requestDeviceCode(interaction.signal);\n\tinteraction.notify({\n\t\ttype: \"device_code\",\n\t\tuserCode: device.userCode,\n\t\tverificationUri: device.verificationUriComplete ?? device.verificationUri,\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: device.expiresInSeconds,\n\t});\n\treturn pollForTokens(device, interaction.signal);\n}\n\nasync function refreshXaiToken(refreshToken: string, signal: AbortSignal): Promise<OAuthCredential> {\n\tconst response = await postForm(\n\t\tXAI_TOKEN_URL,\n\t\t{\n\t\t\tgrant_type: \"refresh_token\",\n\t\t\tclient_id: XAI_CLIENT_ID,\n\t\t\trefresh_token: refreshToken,\n\t\t},\n\t\tsignal,\n\t);\n\tif (!response.ok) {\n\t\tthrow requestFailure(\"token refresh\", response);\n\t}\n\treturn credentialsFromTokenResponse(response.body, refreshToken);\n}\n\nexport const xaiOAuth: OAuthAuth = {\n\tname: \"xAI (Grok/X subscription)\",\n\tisSubscription: true,\n\tloginLabel: \"Sign in with SuperGrok or X Premium\",\n\tlogin: loginXai,\n\trefresh: (credential, signal) => refreshXaiToken(credential.refresh, signal),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
|
package/dist/auth/resolve.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ export interface AuthResolutionOverrides {
|
|
|
6
6
|
env?: ProviderEnv;
|
|
7
7
|
/** Require this much remaining OAuth-token validity; defaults to five minutes. */
|
|
8
8
|
minOAuthValidityMs?: number;
|
|
9
|
+
signal?: AbortSignal;
|
|
9
10
|
}
|
|
10
11
|
export declare class ModelsError extends Error {
|
|
11
12
|
readonly code: ModelsErrorCode;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/auth/resolve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../../src/auth/resolve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAG/C,OAAO,KAAK,EAGX,WAAW,EACX,UAAU,EAEV,eAAe,EAGf,YAAY,EACZ,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,eAAe,GAAG,cAAc,GAAG,kBAAkB,GAAG,UAAU,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;AAE7G,MAAM,WAAW,uBAAuB;IACvC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,GAAG,CAAC,EAAE,WAAW,CAAC;IAClB,kFAAkF;IAClF,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,qBAAa,WAAY,SAAQ,KAAK;IACrC,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC;gBAEnB,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE;CAKjF;AAUD;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAClC,QAAQ,EAAE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,YAAY,CAAA;CAAE,EAC5C,WAAW,EAAE,eAAe,EAC5B,WAAW,EAAE,WAAW,EACxB,SAAS,CAAC,EAAE,uBAAuB,GACjC,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAMjC"}
|
package/dist/auth/resolve.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { operationSignal, raceWithAbortSignal } from "../utils/abort.js";
|
|
1
2
|
import { formatThrownValue } from "../utils/diagnostics.js";
|
|
2
3
|
export class ModelsError extends Error {
|
|
3
4
|
constructor(code, message, options) {
|
|
@@ -21,29 +22,34 @@ function withCauseDetail(message, cause) {
|
|
|
21
22
|
* nothing is stored. No silent env fallback after a failed refresh or for a
|
|
22
23
|
* credential type without a matching handler.
|
|
23
24
|
*/
|
|
24
|
-
export
|
|
25
|
+
export function resolveProviderAuth(provider, credentials, authContext, overrides) {
|
|
26
|
+
const signal = operationSignal(overrides?.signal);
|
|
27
|
+
return raceWithAbortSignal(resolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal), signal);
|
|
28
|
+
}
|
|
29
|
+
async function resolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal) {
|
|
30
|
+
signal.throwIfAborted();
|
|
25
31
|
const requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;
|
|
26
32
|
if (overrides?.apiKey !== undefined && provider.auth.apiKey) {
|
|
27
33
|
return resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, {
|
|
28
34
|
type: "api_key",
|
|
29
35
|
key: overrides.apiKey,
|
|
30
36
|
env: overrides.env,
|
|
31
|
-
});
|
|
37
|
+
}, signal);
|
|
32
38
|
}
|
|
33
|
-
const stored = await readCredential(credentials, provider.id);
|
|
39
|
+
const stored = await readCredential(credentials, provider.id, signal);
|
|
34
40
|
if (stored) {
|
|
35
41
|
if (stored.type === "oauth" && provider.auth.oauth) {
|
|
36
|
-
return resolveStoredOAuth(credentials, provider.id, provider.auth.oauth, stored, overrides?.minOAuthValidityMs);
|
|
42
|
+
return resolveStoredOAuth(credentials, provider.id, provider.auth.oauth, stored, signal, overrides?.minOAuthValidityMs);
|
|
37
43
|
}
|
|
38
44
|
if (stored.type === "api_key" && provider.auth.apiKey) {
|
|
39
45
|
const credential = overrides?.env ? { ...stored, env: { ...stored.env, ...overrides.env } } : stored;
|
|
40
|
-
return resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, credential);
|
|
46
|
+
return resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, credential, signal);
|
|
41
47
|
}
|
|
42
48
|
return undefined;
|
|
43
49
|
}
|
|
44
50
|
// Ambient (env vars, AWS profiles, ADC files).
|
|
45
51
|
return provider.auth.apiKey
|
|
46
|
-
? resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, undefined)
|
|
52
|
+
? resolveApiKey(requestAuthContext, provider.auth.apiKey, provider.id, undefined, signal)
|
|
47
53
|
: undefined;
|
|
48
54
|
}
|
|
49
55
|
function overlayEnvAuthContext(base, env) {
|
|
@@ -53,12 +59,13 @@ function overlayEnvAuthContext(base, env) {
|
|
|
53
59
|
};
|
|
54
60
|
}
|
|
55
61
|
const DEFAULT_OAUTH_MINIMUM_VALIDITY_MS = 5 * 60 * 1000;
|
|
62
|
+
const DEFAULT_OAUTH_REFRESH_TIMEOUT_MS = 15_000;
|
|
56
63
|
/**
|
|
57
64
|
* OAuth resolution with double-checked locking: tokens with less than five
|
|
58
65
|
* minutes remaining lock, re-check expiry under the lock, refresh once
|
|
59
66
|
* globally, and persist the rotated credential before release.
|
|
60
67
|
*/
|
|
61
|
-
async function resolveStoredOAuth(credentials, providerId, oauth, stored, minOAuthValidityMs) {
|
|
68
|
+
async function resolveStoredOAuth(credentials, providerId, oauth, stored, signal, minOAuthValidityMs) {
|
|
62
69
|
const minimumValidityMs = Math.max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS, minOAuthValidityMs ?? 0);
|
|
63
70
|
const expiresSoon = (credential) => Date.now() + minimumValidityMs >= credential.expires;
|
|
64
71
|
let credential = stored;
|
|
@@ -72,12 +79,16 @@ async function resolveStoredOAuth(credentials, providerId, oauth, stored, minOAu
|
|
|
72
79
|
if (!expiresSoon(current))
|
|
73
80
|
return undefined; // another process/request refreshed
|
|
74
81
|
try {
|
|
75
|
-
|
|
82
|
+
const refreshSignal = AbortSignal.any([
|
|
83
|
+
signal,
|
|
84
|
+
AbortSignal.timeout(DEFAULT_OAUTH_REFRESH_TIMEOUT_MS),
|
|
85
|
+
]);
|
|
86
|
+
return await oauth.refresh(current, refreshSignal);
|
|
76
87
|
}
|
|
77
88
|
catch (error) {
|
|
78
89
|
throw new ModelsError("oauth", `OAuth refresh failed for ${providerId}`, { cause: error });
|
|
79
90
|
}
|
|
80
|
-
});
|
|
91
|
+
}, { signal });
|
|
81
92
|
}
|
|
82
93
|
catch (error) {
|
|
83
94
|
if (error instanceof ModelsError)
|
|
@@ -101,17 +112,17 @@ async function resolveStoredOAuth(credentials, providerId, oauth, stored, minOAu
|
|
|
101
112
|
throw new ModelsError("oauth", `OAuth auth derivation failed for ${providerId}`, { cause: error });
|
|
102
113
|
}
|
|
103
114
|
}
|
|
104
|
-
async function resolveApiKey(authContext, apiKey, providerId, credential) {
|
|
115
|
+
async function resolveApiKey(authContext, apiKey, providerId, credential, signal) {
|
|
105
116
|
try {
|
|
106
|
-
return await apiKey.resolve({ ctx: authContext, credential });
|
|
117
|
+
return await apiKey.resolve({ ctx: authContext, credential, signal });
|
|
107
118
|
}
|
|
108
119
|
catch (error) {
|
|
109
120
|
throw new ModelsError("auth", `API key auth failed for provider ${providerId}`, { cause: error });
|
|
110
121
|
}
|
|
111
122
|
}
|
|
112
|
-
async function readCredential(credentials, providerId) {
|
|
123
|
+
async function readCredential(credentials, providerId, signal) {
|
|
113
124
|
try {
|
|
114
|
-
return await credentials.read(providerId);
|
|
125
|
+
return await credentials.read(providerId, { signal });
|
|
115
126
|
}
|
|
116
127
|
catch (error) {
|
|
117
128
|
throw new ModelsError("auth", `Credential store read failed for ${providerId}`, { cause: error });
|
package/dist/auth/resolve.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../src/auth/resolve.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAsB5D,MAAM,OAAO,WAAY,SAAQ,KAAK;IAGrC,YAAY,IAAqB,EAAE,OAAe,EAAE,OAA6B;QAChF,KAAK,CAAC,eAAe,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;QACzD,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;QAC1B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;CACD;AAED,iFAAiF;AACjF,SAAS,eAAe,CAAC,OAAe,EAAE,KAAc;IACvD,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,OAAO,CAAC;IAC1D,MAAM,MAAM,GAAG,iBAAiB,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC;IAC/C,IAAI,CAAC,MAAM,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC;QAAE,OAAO,OAAO,CAAC;IACxD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AO,EAAE,CAAC;IAClE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,WAAW,CAAC,OAAO,EAAE,oCAAoC,UAAU,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACpG,CAAC;AACF,CAAC;AAED,KAAK,UAAU,aAAa,CAC3B,WAAwB,EACxB,MAAkB,EAClB,UAAkB,EAClB,UAAwC;IAExC,IAAI,CAAC;QACJ,OAAO,MAAM,MAAM,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,WAAW,EAAE,UAAU,EAAE,CAAC,CAAC;IAC/D,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;AACF,CAAC;AAED,KAAK,UAAU,cAAc,CAAC,WAA4B,EAAE,UAAkB;IAC7E,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;AACF,CAAC","sourcesContent":["import type { ProviderEnv } from \"../types.ts\";\nimport { formatThrownValue } from \"../utils/diagnostics.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\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n}\n\nexport class ModelsError extends Error {\n\treadonly code: ModelsErrorCode;\n\n\tconstructor(code: ModelsErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(withCauseDetail(message, options?.cause), options);\n\t\tthis.name = \"ModelsError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Callers surface `error.message` only, so keep the underlying reason in it. */\nfunction withCauseDetail(message: string, cause: unknown): string {\n\tif (cause === undefined || cause === null) return message;\n\tconst detail = formatThrownValue(cause).trim();\n\tif (!detail || message.includes(detail)) return message;\n\treturn `${message}: ${detail}`;\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(\n\t\t\t\tcredentials,\n\t\t\t\tprovider.id,\n\t\t\t\tprovider.auth.oauth,\n\t\t\t\tstored,\n\t\t\t\toverrides?.minOAuthValidityMs,\n\t\t\t);\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\nconst DEFAULT_OAUTH_MINIMUM_VALIDITY_MS = 5 * 60 * 1000;\n\n/**\n * OAuth resolution with double-checked locking: tokens with less than five\n * minutes remaining lock, re-check expiry under the lock, refresh once\n * globally, and persist the rotated credential before release.\n */\nasync function resolveStoredOAuth(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\toauth: OAuthAuth,\n\tstored: OAuthCredential,\n\tminOAuthValidityMs?: number,\n): Promise<AuthResult | undefined> {\n\tconst minimumValidityMs = Math.max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS, minOAuthValidityMs ?? 0);\n\tconst expiresSoon = (credential: OAuthCredential) => Date.now() + minimumValidityMs >= credential.expires;\n\tlet credential = stored;\n\n\tif (expiresSoon(credential)) {\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 (!expiresSoon(current)) 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\t// The normal five-minute window triggers a refresh but does not impose a\n\t\t// provider contract. Explicit callers (such as bearer-token export) do\n\t\t// require the requested minimum after the refresh.\n\t\tif (minOAuthValidityMs !== undefined && expiresSoon(credential)) {\n\t\t\tthrow new ModelsError(\"oauth\", `OAuth refresh returned a token that expires too soon for ${providerId}`);\n\t\t}\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"]}
|
|
1
|
+
{"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../src/auth/resolve.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AACzE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAuB5D,MAAM,OAAO,WAAY,SAAQ,KAAK;IAGrC,YAAY,IAAqB,EAAE,OAAe,EAAE,OAA6B;QAChF,KAAK,CAAC,eAAe,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,OAAO,CAAC,CAAC;QACzD,IAAI,CAAC,IAAI,GAAG,aAAa,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AAmB;IAEnB,IAAI,CAAC;QACJ,OAAO,MAAM,MAAM,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC,CAAC;IACvE,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;AACF,CAAC;AAED,KAAK,UAAU,cAAc,CAC5B,WAA4B,EAC5B,UAAkB,EAClB,MAAmB;IAEnB,IAAI,CAAC;QACJ,OAAO,MAAM,WAAW,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;IACvD,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;AACF,CAAC","sourcesContent":["import type { ProviderEnv } from \"../types.ts\";\nimport { operationSignal, raceWithAbortSignal } from \"../utils/abort.ts\";\nimport { formatThrownValue } from \"../utils/diagnostics.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\t/** Require this much remaining OAuth-token validity; defaults to five minutes. */\n\tminOAuthValidityMs?: number;\n\tsignal?: AbortSignal;\n}\n\nexport class ModelsError extends Error {\n\treadonly code: ModelsErrorCode;\n\n\tconstructor(code: ModelsErrorCode, message: string, options?: { cause?: unknown }) {\n\t\tsuper(withCauseDetail(message, options?.cause), options);\n\t\tthis.name = \"ModelsError\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Callers surface `error.message` only, so keep the underlying reason in it. */\nfunction withCauseDetail(message: string, cause: unknown): string {\n\tif (cause === undefined || cause === null) return message;\n\tconst detail = formatThrownValue(cause).trim();\n\tif (!detail || message.includes(detail)) return message;\n\treturn `${message}: ${detail}`;\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 function resolveProviderAuth(\n\tprovider: { id: string; auth: ProviderAuth },\n\tcredentials: CredentialStore,\n\tauthContext: AuthContext,\n\toverrides?: AuthResolutionOverrides,\n): Promise<AuthResult | undefined> {\n\tconst signal = operationSignal(overrides?.signal);\n\treturn raceWithAbortSignal(\n\t\tresolveProviderAuthWithSignal(provider, credentials, authContext, overrides, signal),\n\t\tsignal,\n\t);\n}\n\nasync function resolveProviderAuthWithSignal(\n\tprovider: { id: string; auth: ProviderAuth },\n\tcredentials: CredentialStore,\n\tauthContext: AuthContext,\n\toverrides: AuthResolutionOverrides | undefined,\n\tsignal: AbortSignal,\n): Promise<AuthResult | undefined> {\n\tsignal.throwIfAborted();\n\tconst requestAuthContext = overrides?.env ? overlayEnvAuthContext(authContext, overrides.env) : authContext;\n\n\tif (overrides?.apiKey !== undefined && provider.auth.apiKey) {\n\t\treturn resolveApiKey(\n\t\t\trequestAuthContext,\n\t\t\tprovider.auth.apiKey,\n\t\t\tprovider.id,\n\t\t\t{\n\t\t\t\ttype: \"api_key\",\n\t\t\t\tkey: overrides.apiKey,\n\t\t\t\tenv: overrides.env,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t}\n\n\tconst stored = await readCredential(credentials, provider.id, signal);\n\tif (stored) {\n\t\tif (stored.type === \"oauth\" && provider.auth.oauth) {\n\t\t\treturn resolveStoredOAuth(\n\t\t\t\tcredentials,\n\t\t\t\tprovider.id,\n\t\t\t\tprovider.auth.oauth,\n\t\t\t\tstored,\n\t\t\t\tsignal,\n\t\t\t\toverrides?.minOAuthValidityMs,\n\t\t\t);\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, signal);\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, signal)\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\nconst DEFAULT_OAUTH_MINIMUM_VALIDITY_MS = 5 * 60 * 1000;\nconst DEFAULT_OAUTH_REFRESH_TIMEOUT_MS = 15_000;\n\n/**\n * OAuth resolution with double-checked locking: tokens with less than five\n * minutes remaining lock, re-check expiry under the lock, refresh once\n * globally, and persist the rotated credential before release.\n */\nasync function resolveStoredOAuth(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\toauth: OAuthAuth,\n\tstored: OAuthCredential,\n\tsignal: AbortSignal,\n\tminOAuthValidityMs?: number,\n): Promise<AuthResult | undefined> {\n\tconst minimumValidityMs = Math.max(DEFAULT_OAUTH_MINIMUM_VALIDITY_MS, minOAuthValidityMs ?? 0);\n\tconst expiresSoon = (credential: OAuthCredential) => Date.now() + minimumValidityMs >= credential.expires;\n\tlet credential = stored;\n\n\tif (expiresSoon(credential)) {\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(\n\t\t\t\tproviderId,\n\t\t\t\tasync (current) => {\n\t\t\t\t\tif (current?.type !== \"oauth\") return undefined; // logged out meanwhile\n\t\t\t\t\tif (!expiresSoon(current)) return undefined; // another process/request refreshed\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst refreshSignal = AbortSignal.any([\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\tAbortSignal.timeout(DEFAULT_OAUTH_REFRESH_TIMEOUT_MS),\n\t\t\t\t\t\t]);\n\t\t\t\t\t\treturn await oauth.refresh(current, refreshSignal);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthrow new ModelsError(\"oauth\", `OAuth refresh failed for ${providerId}`, { cause: error });\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ signal },\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\t// The normal five-minute window triggers a refresh but does not impose a\n\t\t// provider contract. Explicit callers (such as bearer-token export) do\n\t\t// require the requested minimum after the refresh.\n\t\tif (minOAuthValidityMs !== undefined && expiresSoon(credential)) {\n\t\t\tthrow new ModelsError(\"oauth\", `OAuth refresh returned a token that expires too soon for ${providerId}`);\n\t\t}\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\tsignal: AbortSignal,\n): Promise<AuthResult | undefined> {\n\ttry {\n\t\treturn await apiKey.resolve({ ctx: authContext, credential, signal });\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(\n\tcredentials: CredentialStore,\n\tproviderId: string,\n\tsignal: AbortSignal,\n): Promise<Credential | undefined> {\n\ttry {\n\t\treturn await credentials.read(providerId, { signal });\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
|
@@ -35,6 +35,10 @@ export interface CredentialInfo {
|
|
|
35
35
|
providerId: string;
|
|
36
36
|
type: Credential["type"];
|
|
37
37
|
}
|
|
38
|
+
/** Optional cancellation for public auth and credential operations. */
|
|
39
|
+
export interface AuthOperationOptions {
|
|
40
|
+
signal?: AbortSignal;
|
|
41
|
+
}
|
|
38
42
|
/**
|
|
39
43
|
* App-owned credential storage, keyed by `Provider.id`, one credential per
|
|
40
44
|
* provider. `modify` is the only write path, so every mutation is a
|
|
@@ -55,12 +59,12 @@ export interface CredentialStore {
|
|
|
55
59
|
* Read the stored credential, possibly expired. Display/status use;
|
|
56
60
|
* resolved request auth comes from `Models.getAuth()`.
|
|
57
61
|
*/
|
|
58
|
-
read(providerId: string): Promise<Credential | undefined>;
|
|
62
|
+
read(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined>;
|
|
59
63
|
/**
|
|
60
64
|
* List stored credential metadata without resolving or exposing secrets.
|
|
61
65
|
* Implementations must not execute configured API-key commands while listing.
|
|
62
66
|
*/
|
|
63
|
-
list(): Promise<readonly CredentialInfo[]>;
|
|
67
|
+
list(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]>;
|
|
64
68
|
/**
|
|
65
69
|
* Serialized write — the only write path. `fn` sees the current credential
|
|
66
70
|
* because correct writes (refresh, login-during-refresh) depend on it;
|
|
@@ -69,9 +73,9 @@ export interface CredentialStore {
|
|
|
69
73
|
* store supports it (e.g. a file lock). Resolves with the post-write
|
|
70
74
|
* credential. Rejections from `fn` propagate.
|
|
71
75
|
*/
|
|
72
|
-
modify(providerId: string, fn: (current: Credential | undefined) => Promise<Credential | undefined
|
|
76
|
+
modify(providerId: string, fn: (current: Credential | undefined) => Promise<Credential | undefined>, options?: AuthOperationOptions): Promise<Credential | undefined>;
|
|
73
77
|
/** Remove a credential (logout). Implementations serialize this against `modify`. */
|
|
74
|
-
delete(providerId: string): Promise<void>;
|
|
78
|
+
delete(providerId: string, options?: AuthOperationOptions): Promise<void>;
|
|
75
79
|
}
|
|
76
80
|
/** Environment access for auth resolution. Injectable for tests and browsers. */
|
|
77
81
|
export interface AuthContext {
|
|
@@ -155,6 +159,10 @@ export interface AuthInteraction {
|
|
|
155
159
|
prompt(prompt: AuthPrompt): Promise<string>;
|
|
156
160
|
notify(event: AuthEvent): void;
|
|
157
161
|
}
|
|
162
|
+
/** Normalized interaction passed to provider login implementations. */
|
|
163
|
+
export type ProviderAuthInteraction = AuthInteraction & {
|
|
164
|
+
signal: AbortSignal;
|
|
165
|
+
};
|
|
158
166
|
/**
|
|
159
167
|
* Api-key auth: stored key/provider env plus ambient sources (env vars, AWS
|
|
160
168
|
* profiles, ADC files). Ambient-only providers omit `login`.
|
|
@@ -163,7 +171,7 @@ export interface ApiKeyAuth {
|
|
|
163
171
|
/** Display name, e.g. "Anthropic API key". */
|
|
164
172
|
name: string;
|
|
165
173
|
/** Interactive setup (prompt for key/provider env). Absent = ambient-only. */
|
|
166
|
-
login?(interaction:
|
|
174
|
+
login?(interaction: ProviderAuthInteraction): Promise<ApiKeyCredential>;
|
|
167
175
|
/**
|
|
168
176
|
* Optional side-effect-free availability check. Use this when `resolve()` may
|
|
169
177
|
* execute commands or perform other request-time work. Missing means Models
|
|
@@ -172,6 +180,7 @@ export interface ApiKeyAuth {
|
|
|
172
180
|
check?(input: {
|
|
173
181
|
ctx: AuthContext;
|
|
174
182
|
credential?: ApiKeyCredential;
|
|
183
|
+
signal: AbortSignal;
|
|
175
184
|
}): Promise<AuthCheck | undefined>;
|
|
176
185
|
/**
|
|
177
186
|
* Resolve auth from the stored credential and/or ambient sources, merging
|
|
@@ -182,6 +191,7 @@ export interface ApiKeyAuth {
|
|
|
182
191
|
resolve(input: {
|
|
183
192
|
ctx: AuthContext;
|
|
184
193
|
credential?: ApiKeyCredential;
|
|
194
|
+
signal: AbortSignal;
|
|
185
195
|
}): Promise<AuthResult | undefined>;
|
|
186
196
|
}
|
|
187
197
|
/**
|
|
@@ -192,14 +202,16 @@ export interface ApiKeyAuth {
|
|
|
192
202
|
export interface OAuthAuth {
|
|
193
203
|
/** Display name, e.g. "Anthropic (Claude Pro/Max)". */
|
|
194
204
|
name: string;
|
|
195
|
-
/**
|
|
205
|
+
/** Whether access through this auth method is backed by a provider subscription. */
|
|
206
|
+
isSubscription?: boolean;
|
|
207
|
+
/** Selector label for the OAuth login option, e.g. "Sign in with SuperGrok or X Premium". */
|
|
196
208
|
loginLabel?: string;
|
|
197
|
-
login(interaction:
|
|
209
|
+
login(interaction: ProviderAuthInteraction): Promise<OAuthCredential>;
|
|
198
210
|
/**
|
|
199
211
|
* Exchange the refresh token. Network call; throws on failure
|
|
200
212
|
* (invalid_grant etc.). `Models` runs this under the store lock.
|
|
201
213
|
*/
|
|
202
|
-
refresh(credential: OAuthCredential, signal
|
|
214
|
+
refresh(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential>;
|
|
203
215
|
/**
|
|
204
216
|
* Optional side-effect-free availability check, mirroring `ApiKeyAuth.check`.
|
|
205
217
|
* Supply this when a stored OAuth credential does not by itself imply the
|
|
@@ -209,6 +221,7 @@ export interface OAuthAuth {
|
|
|
209
221
|
check?(input: {
|
|
210
222
|
ctx: AuthContext;
|
|
211
223
|
credential?: OAuthCredential;
|
|
224
|
+
signal: AbortSignal;
|
|
212
225
|
}): Promise<AuthCheck | undefined>;
|
|
213
226
|
/**
|
|
214
227
|
* Side-effect-free derivation of request auth from a valid credential.
|
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":"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1 @@
|
|
|
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:
|
|
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/** Optional cancellation for public auth and credential operations. */\nexport interface AuthOperationOptions {\n\tsignal?: AbortSignal;\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, options?: AuthOperationOptions): 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(options?: AuthOperationOptions): 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\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined>;\n\n\t/** Remove a credential (logout). Implementations serialize this against `modify`. */\n\tdelete(providerId: string, options?: AuthOperationOptions): 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/** Normalized interaction passed to provider login implementations. */\nexport type ProviderAuthInteraction = AuthInteraction & { signal: AbortSignal };\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: ProviderAuthInteraction): 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: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): 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: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\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\t/** Whether access through this auth method is backed by a provider subscription. */\n\tisSubscription?: boolean;\n\n\t/** Selector label for the OAuth login option, e.g. \"Sign in with SuperGrok or X Premium\". */\n\tloginLabel?: string;\n\n\tlogin(interaction: ProviderAuthInteraction): 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 * Optional side-effect-free availability check, mirroring `ApiKeyAuth.check`.\n\t * Supply this when a stored OAuth credential does not by itself imply the\n\t * provider is usable — for example a sentinel envelope that carries zero\n\t * accounts. When absent, any stored OAuth credential counts as configured.\n\t */\n\tcheck?(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: OAuthCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthCheck | undefined>;\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/cli.js
CHANGED
|
@@ -41,6 +41,7 @@ async function login(providerId) {
|
|
|
41
41
|
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
42
42
|
try {
|
|
43
43
|
const credential = await provider.auth.oauth.login({
|
|
44
|
+
signal: new AbortController().signal,
|
|
44
45
|
prompt: (authPrompt) => answerPrompt(rl, authPrompt),
|
|
45
46
|
notify: (event) => {
|
|
46
47
|
switch (event.type) {
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAEhD,OAAO,EAAE,gBA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AAC,QAAQ,CAAC,EAAE,KAAK,UAAU,CAAC,EAAE,CAAC;YAC9E,MAAM,IAAI,KAAK,CAAC,qBAAqB,UAAU,IAAI,EAAE,EAAE,CAAC,CAAC;QAC1D,CAAC;QACD,MAAM,KAAK,CAAC,UAAU,CAAC,CAAC;QACxB,OAAO;IACR,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,oBAAoB,OAAO,EAAE,CAAC,CAAC;AAChD,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC/B,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAChF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACjB,CAAC,CAAC,CAAC","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"]}
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,eAAe,EAAE,MA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;QACD,IAAI,CAAC,UAAU,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,KAAK,UAAU,CAAC,EAAE,CAAC;YAC9E,MAAM,IAAI,KAAK,CAAC,qBAAqB,UAAU,IAAI,EAAE,EAAE,CAAC,CAAC;QAC1D,CAAC;QACD,MAAM,KAAK,CAAC,UAAU,CAAC,CAAC;QACxB,OAAO;IACR,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,oBAAoB,OAAO,EAAE,CAAC,CAAC;AAChD,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC/B,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAChF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACjB,CAAC,CAAC,CAAC","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\tsignal: new AbortController().signal,\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/compat.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"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AO,YAAY,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAC3D,CAAC;QACD,OAAO,eAAe,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,aAAa,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;IACpF,CAAC;IACD,MAAM,QAAQ,GAAG,kBAAkB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC/C,OAAO,QAAQ,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,aAAa,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;AAC7E,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,CACnC,KAAkB,EAClB,OAAgB,EAChB,OAA6B;IAE7B,MAAM,CAAC,GAAG,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAChD,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AACnB,CAAC","sourcesContent":["/**\n * Temporary compatibility entrypoint preserving the old global pi-ai API\n * surface: api-dispatch `stream()`/`complete()` with env API key injection,\n * the api-registry, generated catalog reads (`getModel`/`getModels`/\n * `getProviders`), per-API lazy stream wrappers, and image generation.\n *\n * Existing apps switch imports from \"@earendil-works/pi-ai\" to\n * \"@earendil-works/pi-ai/compat\" unchanged; new code uses `createModels()`\n * and the provider factories. This module is deleted with the coding-agent\n * ModelManager migration.\n */\n\nexport * from \"./api/anthropic-messages.lazy.ts\";\nexport * from \"./api/azure-openai-responses.lazy.ts\";\nexport * from \"./api/bedrock-converse-stream.lazy.ts\";\nexport * from \"./api/google-generative-ai.lazy.ts\";\nexport * from \"./api/google-vertex.lazy.ts\";\nexport * from \"./api/mistral-conversations.lazy.ts\";\nexport * from \"./api/openai-codex-responses.lazy.ts\";\nexport * from \"./api/openai-completions.lazy.ts\";\nexport * from \"./api/openai-responses.lazy.ts\";\nexport * from \"./api/pi-messages.lazy.ts\";\nexport * from \"./env-api-keys.ts\";\nexport * from \"./image-models.ts\";\nexport * from \"./images.ts\";\nexport * from \"./images-api-registry.ts\";\nexport * from \"./index.ts\";\nexport * from \"./legacy-api-aliases.ts\";\nexport * from \"./providers/images/register-builtins.ts\";\nexport {\n\tgetProtocol,\n\tgetToolCallFormat,\n\ttransformContext,\n\twrapStreamWithToolCallMiddleware,\n} from \"./tool-call-middleware/index.ts\";\n\nimport { anthropicMessagesApi } from \"./api/anthropic-messages.lazy.ts\";\nimport { azureOpenAIResponsesApi } from \"./api/azure-openai-responses.lazy.ts\";\nimport { bedrockConverseStreamApi } from \"./api/bedrock-converse-stream.lazy.ts\";\nimport { googleGenerativeAIApi } from \"./api/google-generative-ai.lazy.ts\";\nimport { googleVertexApi } from \"./api/google-vertex.lazy.ts\";\nimport { mistralConversationsApi } from \"./api/mistral-conversations.lazy.ts\";\nimport { openAICodexResponsesApi } from \"./api/openai-codex-responses.lazy.ts\";\nimport { openAICompletionsApi } from \"./api/openai-completions.lazy.ts\";\nimport { openAIResponsesApi } from \"./api/openai-responses.lazy.ts\";\nimport { piMessagesApi } from \"./api/pi-messages.lazy.ts\";\nimport { getEnvApiKey } from \"./env-api-keys.ts\";\nimport type { ModelsApiStreamOptions } from \"./models.ts\";\nimport { builtinModels, getBuiltinModel, getBuiltinModels, getBuiltinProviders } from \"./providers/all.ts\";\n\nexport type { BuiltinProvider } from \"./providers/all.ts\";\n\nimport { createFauxCore, type FauxProviderRegistration, type RegisterFauxProviderOptions } from \"./providers/faux.ts\";\nimport {\n\tgetProtocol,\n\tgetToolCallFormat,\n\ttransformContext,\n\twrapStreamWithToolCallMiddleware,\n} from \"./tool-call-middleware/index.ts\";\nimport type {\n\tApi,\n\tApiStreamOptions,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tProviderStreamOptions,\n\tProviderStreams,\n\tSimpleStreamOptions,\n\tStreamOptions,\n} from \"./types.ts\";\n\n/** @deprecated Static catalog read. Use `getBuiltinModel` from \"@earendil-works/pi-ai/providers/all\" or `Models.getModel()`. */\nexport const getModel = getBuiltinModel;\n\n/** @deprecated Static catalog read. Use `getBuiltinModels` from \"@earendil-works/pi-ai/providers/all\" or `Models.getModels()`. */\nexport const getModels = getBuiltinModels;\n\n/** @deprecated Static catalog read. Use `getBuiltinProviders` from \"@earendil-works/pi-ai/providers/all\" or `Models.getProviders()`. */\nexport const getProviders = getBuiltinProviders;\n\nexport {\n\ttype ApiProvider,\n\ttype ApiProviderInternal,\n\ttype ApiStreamFunction,\n\ttype ApiStreamSimpleFunction,\n\tgetApiProvider,\n\tgetApiProviders,\n\tregisterApiProvider,\n\tunregisterApiProviders,\n} from \"./api-registry.ts\";\n\nimport {\n\tclearApiProviders,\n\tgetApiProvider,\n\tregisterApiProvider,\n\tregisterBuiltinApiProvider,\n\tunregisterApiProviders,\n} from \"./api-registry.ts\";\n\nexport function registerFauxProvider(options: RegisterFauxProviderOptions = {}): FauxProviderRegistration {\n\tconst core = createFauxCore(options);\n\tconst sourceId = `faux-provider-${Math.random().toString(36).slice(2, 10)}`;\n\tregisterApiProvider({ api: core.api, stream: core.stream, streamSimple: core.streamSimple }, sourceId);\n\treturn {\n\t\tapi: core.api,\n\t\tmodels: core.models,\n\t\tgetModel: core.getModel,\n\t\tstate: core.state,\n\t\tsetResponses: core.setResponses,\n\t\tappendResponses: core.appendResponses,\n\t\tgetPendingResponseCount: core.getPendingResponseCount,\n\t\tgetCallLog: core.getCallLog,\n\t\tunregister() {\n\t\t\tunregisterApiProviders(sourceId);\n\t\t},\n\t};\n}\n\nconst BUILTIN_APIS: [Api, ProviderStreams][] = [\n\t[\"anthropic-messages\", anthropicMessagesApi()],\n\t[\"openai-completions\", openAICompletionsApi()],\n\t[\"openai-responses\", openAIResponsesApi()],\n\t[\"openai-codex-responses\", openAICodexResponsesApi()],\n\t[\"azure-openai-responses\", azureOpenAIResponsesApi()],\n\t[\"google-generative-ai\", googleGenerativeAIApi()],\n\t[\"google-vertex\", googleVertexApi()],\n\t[\"mistral-conversations\", mistralConversationsApi()],\n\t[\"bedrock-converse-stream\", bedrockConverseStreamApi()],\n\t[\"pi-messages\", piMessagesApi()],\n];\n\nconst builtinApiProviderInstances = new Map<Api, ReturnType<typeof getApiProvider>>();\n\n/**\n * Registers the builtin API implementations into the api-registry without\n * clobbering existing entries: compat may load after a test or extension has\n * already registered an override for a builtin api id.\n */\nexport function registerBuiltInApiProviders(): void {\n\tfor (const [api, streams] of BUILTIN_APIS) {\n\t\tregisterBuiltinApiProvider({ api, stream: streams.stream, streamSimple: streams.streamSimple });\n\t\tif (!getApiProvider(api)) {\n\t\t\tregisterApiProvider({ api, stream: streams.stream, streamSimple: streams.streamSimple });\n\t\t}\n\t\tbuiltinApiProviderInstances.set(api, getApiProvider(api));\n\t}\n}\n\nexport function resetApiProviders(): void {\n\tclearApiProviders();\n\tbuiltinApiProviderInstances.clear();\n\tregisterBuiltInApiProviders();\n}\n\nregisterBuiltInApiProviders();\n\nconst compatModels = builtinModels();\nconst AMBIENT_AUTH_MARKER = \"<authenticated>\";\n\nfunction hasExplicitApiKey(apiKey: string | undefined): apiKey is string {\n\treturn typeof apiKey === \"string\" && apiKey.trim().length > 0;\n}\n\nfunction withEnvApiKey<TOptions extends StreamOptions>(\n\tmodel: Model<Api>,\n\toptions: TOptions | undefined,\n): TOptions | undefined {\n\tif (hasExplicitApiKey(options?.apiKey)) return options;\n\tconst apiKey = getEnvApiKey(model.provider, options?.env);\n\tif (!apiKey || apiKey === AMBIENT_AUTH_MARKER) return options;\n\treturn { ...options, apiKey } as TOptions;\n}\n\nfunction hasResolvedCloudflareAuth(options: StreamOptions | undefined): boolean {\n\treturn hasExplicitApiKey(options?.apiKey) || typeof options?.headers?.[\"cf-aig-authorization\"] === \"string\";\n}\n\nfunction getBuiltinProviderForModel(model: Model<Api>) {\n\tif (getApiProvider(model.api) !== builtinApiProviderInstances.get(model.api)) return undefined;\n\tconst provider = compatModels.getProvider(model.provider);\n\treturn provider?.getModels().some((candidate) => candidate.api === model.api) ? provider : undefined;\n}\n\nfunction resolveApiProvider(api: Api) {\n\tconst provider = getApiProvider(api);\n\tif (!provider) {\n\t\tthrow new Error(`No API provider registered for api: ${api}`);\n\t}\n\treturn provider;\n}\n\nexport function stream<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): AssistantMessageEventStream {\n\tconst format = getToolCallFormat(model);\n\tif (format && context.tools && context.tools.length > 0) {\n\t\tconst protocol = getProtocol(format);\n\t\tconst transformedContext = transformContext(context, protocol);\n\t\tconst innerStream = stream(model, transformedContext, options);\n\t\treturn wrapStreamWithToolCallMiddleware(innerStream, protocol, context.tools);\n\t}\n\n\tconst builtinProvider = getBuiltinProviderForModel(model);\n\tif (builtinProvider) {\n\t\tif (model.provider.startsWith(\"cloudflare-\") && !hasResolvedCloudflareAuth(options)) {\n\t\t\treturn compatModels.stream(model, context, options as ModelsApiStreamOptions<TApi> | undefined);\n\t\t}\n\t\treturn builtinProvider.stream(model, context, withEnvApiKey(model, options) as ApiStreamOptions<TApi>);\n\t}\n\tconst provider = resolveApiProvider(model.api);\n\treturn provider.stream(model, context, withEnvApiKey(model, options) as StreamOptions);\n}\n\nexport async function complete<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = stream(model, context, options);\n\treturn s.result();\n}\n\nexport function streamSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream {\n\tconst format = getToolCallFormat(model);\n\tif (format && context.tools && context.tools.length > 0) {\n\t\tconst protocol = getProtocol(format);\n\t\tconst transformedContext = transformContext(context, protocol);\n\t\tconst innerStream = streamSimple(model, transformedContext, options);\n\t\treturn wrapStreamWithToolCallMiddleware(innerStream, protocol, context.tools);\n\t}\n\n\tconst builtinProvider = getBuiltinProviderForModel(model);\n\tif (builtinProvider) {\n\t\tif (model.provider.startsWith(\"cloudflare-\") && !hasResolvedCloudflareAuth(options)) {\n\t\t\treturn compatModels.streamSimple(model, context, options);\n\t\t}\n\t\treturn builtinProvider.streamSimple(model, context, withEnvApiKey(model, options));\n\t}\n\tconst provider = resolveApiProvider(model.api);\n\treturn provider.streamSimple(model, context, withEnvApiKey(model, options));\n}\n\nexport async function completeSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = streamSimple(model, context, options);\n\treturn s.result();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compat.js","sourceRoot":"","sources":["../src/compat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,cAAc,kCAAkC,CAAC;AACjD,cAAc,sCAAsC,CAAC;AACrD,cAAc,uCAAuC,CAAC;AACtD,cAAc,oCAAoC,CAAC;AACnD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,qCAAqC,CAAC;AACpD,cAAc,sCAAsC,CAAC;AACrD,cAAc,kCAAkC,CAAC;AACjD,cAAc,gCAAgC,CAAC;AAC/C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC;AAClC,cAAc,mBAAmB,CAAC;AAClC,cAAc,aAAa,CAAC;AAC5B,cAAc,0BAA0B,CAAC;AACzC,cAAc,YAAY,CAAC;AAC3B,cAAc,yBAAyB,CAAC;AACxC,cAAc,yCAAyC,CAAC;AACxD,OAAO,EACN,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,gCAAgC,GAChC,MAAM,iCAAiC,CAAC;AAEzC,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,EAAE,uBAAuB,EAAE,MAAM,sCAAsC,CAAC;AAC/E,OAAO,EAAE,wBAAwB,EAAE,MAAM,uCAAuC,CAAC;AACjF,OAAO,EAAE,qBAAqB,EAAE,MAAM,oCAAoC,CAAC;AAC3E,OAAO,EAAE,e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AAM,WAAW,GAAG,YAAY,CAAC,KAAK,EAAE,kBAAkB,EAAE,OAAO,CAAC,CAAC;QACrE,OAAO,gCAAgC,CAAC,WAAW,EAAE,QAAQ,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;IAC/E,CAAC;IAED,MAAM,eAAe,GAAG,0BAA0B,CAAC,KAAK,CAAC,CAAC;IAC1D,IAAI,eAAe,EAAE,CAAC;QACrB,IAAI,KAAK,CAAC,QAAQ,CAAC,UAAU,CAAC,aAAa,CAAC,IAAI,CAAC,yBAAyB,CAAC,OAAO,CAAC,EAAE,CAAC;YACrF,OAAO,YAAY,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAC3D,CAAC;QACD,OAAO,eAAe,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,aAAa,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;IACpF,CAAC;IACD,MAAM,QAAQ,GAAG,kBAAkB,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC/C,OAAO,QAAQ,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,aAAa,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;AAC7E,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,CACnC,KAAkB,EAClB,OAAgB,EAChB,OAA6B;IAE7B,MAAM,CAAC,GAAG,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAChD,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC;AACnB,CAAC","sourcesContent":["/**\n * Temporary compatibility entrypoint preserving the old global pi-ai API\n * surface: api-dispatch `stream()`/`complete()` with env API key injection,\n * the api-registry, generated catalog reads (`getModel`/`getModels`/\n * `getProviders`), per-API lazy stream wrappers, and image generation.\n *\n * Existing apps switch imports from \"@earendil-works/pi-ai\" to\n * \"@earendil-works/pi-ai/compat\" unchanged; new code uses `createModels()`\n * and the provider factories. This module is deleted with the coding-agent\n * ModelManager migration.\n */\n\nexport * from \"./api/anthropic-messages.lazy.ts\";\nexport * from \"./api/azure-openai-responses.lazy.ts\";\nexport * from \"./api/bedrock-converse-stream.lazy.ts\";\nexport * from \"./api/google-generative-ai.lazy.ts\";\nexport * from \"./api/google-vertex.lazy.ts\";\nexport * from \"./api/mistral-conversations.lazy.ts\";\nexport * from \"./api/openai-codex-responses.lazy.ts\";\nexport * from \"./api/openai-completions.lazy.ts\";\nexport * from \"./api/openai-responses.lazy.ts\";\nexport * from \"./api/pi-messages.lazy.ts\";\nexport * from \"./env-api-keys.ts\";\nexport * from \"./image-models.ts\";\nexport * from \"./images.ts\";\nexport * from \"./images-api-registry.ts\";\nexport * from \"./index.ts\";\nexport * from \"./legacy-api-aliases.ts\";\nexport * from \"./providers/images/register-builtins.ts\";\nexport {\n\tgetProtocol,\n\tgetToolCallFormat,\n\ttransformContext,\n\twrapStreamWithToolCallMiddleware,\n} from \"./tool-call-middleware/index.ts\";\n\nimport { anthropicMessagesApi } from \"./api/anthropic-messages.lazy.ts\";\nimport { azureOpenAIResponsesApi } from \"./api/azure-openai-responses.lazy.ts\";\nimport { bedrockConverseStreamApi } from \"./api/bedrock-converse-stream.lazy.ts\";\nimport { googleGenerativeAIApi } from \"./api/google-generative-ai.lazy.ts\";\nimport { googleVertexApi } from \"./api/google-vertex.lazy.ts\";\nimport { mistralConversationsApi } from \"./api/mistral-conversations.lazy.ts\";\nimport { openAICodexResponsesApi } from \"./api/openai-codex-responses.lazy.ts\";\nimport { openAICompletionsApi } from \"./api/openai-completions.lazy.ts\";\nimport { openAIResponsesApi } from \"./api/openai-responses.lazy.ts\";\nimport { piMessagesApi } from \"./api/pi-messages.lazy.ts\";\nimport { getEnvApiKey } from \"./env-api-keys.ts\";\nimport type { ModelsApiStreamOptions } from \"./models.ts\";\nimport { builtinModels, getBuiltinModel, getBuiltinModels, getBuiltinProviders } from \"./providers/all.ts\";\n\nexport type { BuiltinProvider } from \"./providers/all.ts\";\n\nimport { createFauxCore, type FauxProviderRegistration, type RegisterFauxProviderOptions } from \"./providers/faux.ts\";\nimport {\n\tgetProtocol,\n\tgetToolCallFormat,\n\ttransformContext,\n\twrapStreamWithToolCallMiddleware,\n} from \"./tool-call-middleware/index.ts\";\nimport type {\n\tApi,\n\tApiStreamOptions,\n\tAssistantMessage,\n\tAssistantMessageEventStream,\n\tContext,\n\tModel,\n\tProviderStreamOptions,\n\tProviderStreams,\n\tSimpleStreamOptions,\n\tStreamOptions,\n} from \"./types.ts\";\n\n/** @deprecated Static catalog read. Use `getBuiltinModel` from \"@earendil-works/pi-ai/providers/all\" or `Models.getModel()`. */\nexport const getModel = getBuiltinModel;\n\n/** @deprecated Static catalog read. Use `getBuiltinModels` from \"@earendil-works/pi-ai/providers/all\" or `Models.getModels()`. */\nexport const getModels = getBuiltinModels;\n\n/** @deprecated Static catalog read. Use `getBuiltinProviders` from \"@earendil-works/pi-ai/providers/all\" or `Models.getProviders()`. */\nexport const getProviders = getBuiltinProviders;\n\nexport {\n\ttype ApiProvider,\n\ttype ApiProviderInternal,\n\ttype ApiStreamFunction,\n\ttype ApiStreamSimpleFunction,\n\tgetApiProvider,\n\tgetApiProviders,\n\tregisterApiProvider,\n\tunregisterApiProviders,\n} from \"./api-registry.ts\";\n\nimport {\n\tclearApiProviders,\n\tgetApiProvider,\n\tregisterApiProvider,\n\tregisterBuiltinApiProvider,\n\tunregisterApiProviders,\n} from \"./api-registry.ts\";\n\nexport function registerFauxProvider(options: RegisterFauxProviderOptions = {}): FauxProviderRegistration {\n\tconst core = createFauxCore(options);\n\tconst sourceId = `faux-provider-${Math.random().toString(36).slice(2, 10)}`;\n\tregisterApiProvider({ api: core.api, stream: core.stream, streamSimple: core.streamSimple }, sourceId);\n\treturn {\n\t\tapi: core.api,\n\t\tmodels: core.models,\n\t\tgetModel: core.getModel,\n\t\tstate: core.state,\n\t\tsetResponses: core.setResponses,\n\t\tappendResponses: core.appendResponses,\n\t\tgetPendingResponseCount: core.getPendingResponseCount,\n\t\tgetCallLog: core.getCallLog,\n\t\tunregister() {\n\t\t\tunregisterApiProviders(sourceId);\n\t\t},\n\t};\n}\n\nconst BUILTIN_APIS: [Api, ProviderStreams][] = [\n\t[\"anthropic-messages\", anthropicMessagesApi()],\n\t[\"openai-completions\", openAICompletionsApi()],\n\t[\"openai-responses\", openAIResponsesApi()],\n\t[\"openai-codex-responses\", openAICodexResponsesApi()],\n\t[\"azure-openai-responses\", azureOpenAIResponsesApi()],\n\t[\"google-generative-ai\", googleGenerativeAIApi()],\n\t[\"google-vertex\", googleVertexApi()],\n\t[\"mistral-conversations\", mistralConversationsApi()],\n\t[\"bedrock-converse-stream\", bedrockConverseStreamApi()],\n\t[\"pi-messages\", piMessagesApi()],\n];\n\nconst builtinApiProviderInstances = new Map<Api, ReturnType<typeof getApiProvider>>();\n\n/**\n * Registers the builtin API implementations into the api-registry without\n * clobbering existing entries: compat may load after a test or extension has\n * already registered an override for a builtin api id.\n */\nexport function registerBuiltInApiProviders(): void {\n\tfor (const [api, streams] of BUILTIN_APIS) {\n\t\tregisterBuiltinApiProvider({ api, stream: streams.stream, streamSimple: streams.streamSimple });\n\t\tif (!getApiProvider(api)) {\n\t\t\tregisterApiProvider({ api, stream: streams.stream, streamSimple: streams.streamSimple });\n\t\t}\n\t\tbuiltinApiProviderInstances.set(api, getApiProvider(api));\n\t}\n}\n\nexport function resetApiProviders(): void {\n\tclearApiProviders();\n\tbuiltinApiProviderInstances.clear();\n\tregisterBuiltInApiProviders();\n}\n\nregisterBuiltInApiProviders();\n\nconst compatModels = builtinModels();\nconst AMBIENT_AUTH_MARKER = \"<authenticated>\";\n\nfunction hasExplicitApiKey(apiKey: string | undefined): apiKey is string {\n\treturn typeof apiKey === \"string\" && apiKey.trim().length > 0;\n}\n\nfunction withEnvApiKey<TOptions extends StreamOptions>(\n\tmodel: Model<Api>,\n\toptions: TOptions | undefined,\n): TOptions | undefined {\n\tif (hasExplicitApiKey(options?.apiKey)) return options;\n\tconst apiKey = getEnvApiKey(model.provider, options?.env);\n\tif (!apiKey || apiKey === AMBIENT_AUTH_MARKER) return options;\n\treturn { ...options, apiKey } as TOptions;\n}\n\nfunction hasResolvedCloudflareAuth(options: StreamOptions | undefined): boolean {\n\treturn hasExplicitApiKey(options?.apiKey) || typeof options?.headers?.[\"cf-aig-authorization\"] === \"string\";\n}\n\nfunction getBuiltinProviderForModel(model: Model<Api>) {\n\tif (getApiProvider(model.api) !== builtinApiProviderInstances.get(model.api)) return undefined;\n\tconst provider = compatModels.getProvider(model.provider);\n\treturn provider?.getModels().some((candidate) => candidate.api === model.api) ? provider : undefined;\n}\n\nfunction resolveApiProvider(api: Api) {\n\tconst provider = getApiProvider(api);\n\tif (!provider) {\n\t\tthrow new Error(`No API provider registered for api: ${api}`);\n\t}\n\treturn provider;\n}\n\nexport function stream<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): AssistantMessageEventStream {\n\tconst format = getToolCallFormat(model);\n\tif (format && context.tools && context.tools.length > 0) {\n\t\tconst protocol = getProtocol(format);\n\t\tconst transformedContext = transformContext(context, protocol);\n\t\tconst innerStream = stream(model, transformedContext, options);\n\t\treturn wrapStreamWithToolCallMiddleware(innerStream, protocol, context.tools);\n\t}\n\n\tconst builtinProvider = getBuiltinProviderForModel(model);\n\tif (builtinProvider) {\n\t\tif (model.provider.startsWith(\"cloudflare-\") && !hasResolvedCloudflareAuth(options)) {\n\t\t\treturn compatModels.stream(model, context, options as ModelsApiStreamOptions<TApi> | undefined);\n\t\t}\n\t\treturn builtinProvider.stream(model, context, withEnvApiKey(model, options) as ApiStreamOptions<TApi>);\n\t}\n\tconst provider = resolveApiProvider(model.api);\n\treturn provider.stream(model, context, withEnvApiKey(model, options) as StreamOptions);\n}\n\nexport async function complete<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: ProviderStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = stream(model, context, options);\n\treturn s.result();\n}\n\nexport function streamSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream {\n\tconst format = getToolCallFormat(model);\n\tif (format && context.tools && context.tools.length > 0) {\n\t\tconst protocol = getProtocol(format);\n\t\tconst transformedContext = transformContext(context, protocol);\n\t\tconst innerStream = streamSimple(model, transformedContext, options);\n\t\treturn wrapStreamWithToolCallMiddleware(innerStream, protocol, context.tools);\n\t}\n\n\tconst builtinProvider = getBuiltinProviderForModel(model);\n\tif (builtinProvider) {\n\t\tif (model.provider.startsWith(\"cloudflare-\") && !hasResolvedCloudflareAuth(options)) {\n\t\t\treturn compatModels.streamSimple(model, context, options);\n\t\t}\n\t\treturn builtinProvider.streamSimple(model, context, withEnvApiKey(model, options));\n\t}\n\tconst provider = resolveApiProvider(model.api);\n\treturn provider.streamSimple(model, context, withEnvApiKey(model, options));\n}\n\nexport async function completeSimple<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): Promise<AssistantMessage> {\n\tconst s = streamSimple(model, context, options);\n\treturn s.result();\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"env-api-keys.d.ts","sourceRoot":"","sources":["../src/env-api-keys.ts"],"names":[],"mappings":"AAyBA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAG7D,eAAO,MAAM,wBAAwB,yBAAyB,CAAC;AAC/D,eAAO,MAAM,yBAAyB,0BAA0B,CAAC;AACjE,eAAO,MAAM,qBAAqB,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"env-api-keys.d.ts","sourceRoot":"","sources":["../src/env-api-keys.ts"],"names":[],"mappings":"AAyBA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAG7D,eAAO,MAAM,wBAAwB,yBAAyB,CAAC;AAC/D,eAAO,MAAM,yBAAyB,0BAA0B,CAAC;AACjE,eAAO,MAAM,qBAAqB,sBAAsB,CAAC;AA8FzD;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;AAC9F,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;AASvF;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,GAAG,SAAS,CAAC;AAC7F,wBAAgB,YAAY,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,GAAG,SAAS,CAAC"}
|
package/dist/env-api-keys.js
CHANGED
|
@@ -74,6 +74,7 @@ function getApiKeyEnvVars(provider) {
|
|
|
74
74
|
"ant-ling": "ANT_LING_API_KEY",
|
|
75
75
|
"qwen-token-plan": "QWEN_TOKEN_PLAN_API_KEY",
|
|
76
76
|
"qwen-token-plan-cn": "QWEN_TOKEN_PLAN_CN_API_KEY",
|
|
77
|
+
"qwen-token-plan-individual": "QWEN_TOKEN_PLAN_API_KEY",
|
|
77
78
|
openai: "OPENAI_API_KEY",
|
|
78
79
|
ollama: "OLLAMA_API_KEY",
|
|
79
80
|
"azure-openai-responses": "AZURE_OPENAI_API_KEY",
|
|
@@ -87,6 +88,7 @@ function getApiKeyEnvVars(provider) {
|
|
|
87
88
|
radius: "RADIUS_API_KEY",
|
|
88
89
|
openrouter: "OPENROUTER_API_KEY",
|
|
89
90
|
"vercel-ai-gateway": "AI_GATEWAY_API_KEY",
|
|
91
|
+
opengateway: "OPENGATEWAY_API_KEY",
|
|
90
92
|
zai: "ZAI_API_KEY",
|
|
91
93
|
"zai-coding-cn": "ZAI_CODING_CN_API_KEY",
|
|
92
94
|
mistral: "MISTRAL_API_KEY",
|
|
@@ -97,6 +99,7 @@ function getApiKeyEnvVars(provider) {
|
|
|
97
99
|
huggingface: "HF_TOKEN",
|
|
98
100
|
fireworks: "FIREWORKS_API_KEY",
|
|
99
101
|
together: "TOGETHER_API_KEY",
|
|
102
|
+
baseten: "BASETEN_API_KEY",
|
|
100
103
|
opencode: "OPENCODE_API_KEY",
|
|
101
104
|
"opencode-go": "OPENCODE_API_KEY",
|
|
102
105
|
"kimi-coding": "KIMI_API_KEY",
|