diff --git a/README.md b/README.md index 98e5211d23..ade48325d9 100644 --- a/README.md +++ b/README.md @@ -307,7 +307,7 @@ OpenClaude supports multiple providers, but behavior is not identical across all - Tool quality depends heavily on the selected model - Smaller local models can struggle with long multi-step tool flows - Some providers impose lower output caps than the CLI defaults, and OpenClaude adapts where possible -- AI/ML API uses the OpenAI-compatible route, defaults to `gpt-4o`, and only surfaces chat-capable models from its public catalog +- AI/ML API uses the OpenAI-compatible route, defaults to `anthropic/claude-sonnet-5`, supports passwordless guided onboarding/top-up, and only surfaces chat-capable models from its public catalog - Gitlawb Opengateway is the fresh-install startup default and requires an API key from https://gitlawb.com/opengateway/keys. It uses one OpenAI-compatible base URL; switch between `mimo-*` and `google/gemini-3.1-flash-lite-preview` with `/model`, and do not pin the base URL to `/v1/xiaomi-mimo`. - Z.AI GLM Coding Plan uses `https://api.z.ai/api/coding/paas/v4` with `glm-5.2` by default. Use `glm-5.2?reasoning=high` for enhanced reasoning, `glm-5.2?reasoning=xhigh` to request Z.AI `reasoning_effort=max`, or `glm-5.2?thinking=disabled` for faster direct answers. - Xiaomi MiMo uses `api-key` header auth on the direct OpenAI-compatible route and currently does not support `/usage` reporting in OpenClaude diff --git a/docs/aimlapi-setup.md b/docs/aimlapi-setup.md index 06af0de0fc..38c89e5325 100644 --- a/docs/aimlapi-setup.md +++ b/docs/aimlapi-setup.md @@ -4,41 +4,49 @@ OpenClaude connects to [AI/ML API](https://aimlapi.com) through its OpenAI-compa ## Overview -AI/ML API is an aggregating gateway that exposes many chat models behind a single OpenAI-compatible API. OpenClaude ships a first-class `AI/ML API` provider preset: it stores credentials under `AIMLAPI_API_KEY`, sends the OpenClaude attribution headers, and discovers chat-capable models from the public `/models` catalog. It defaults to `gpt-4o`. +AI/ML API is an aggregating gateway that exposes many chat models behind a single OpenAI-compatible API. OpenClaude ships a first-class `AI/ML API` provider preset: it uses `AIMLAPI_API_KEY`, sends the OpenClaude attribution headers, and discovers chat-capable models from the public `/models` catalog. It defaults to `gpt-4o`. ## Prerequisites -None. You don't need to visit first — the guided top-up flow below can create an AI/ML API account and issue a key for you. If you already have a key from the dashboard, you can paste it directly instead. +None. You do not need to visit first - the guided top-up flow can create an account and issue a key. If you already have a dashboard key or set `AIMLAPI_API_KEY`, OpenClaude can use that credential instead. -## Option 1 — Interactive (`/provider`) +## Option 1 - Interactive (`/provider`) 1. Start OpenClaude and run `/provider`. -2. Choose **AI/ML API**, then confirm the default model (Step 1 of 2). -3. Step 2 of 2 — choose how to get an API key: - - **Top up and get API key** — enter your AI/ML API email and password (an account is created automatically if you don't have one yet), pick a top-up amount ($20–$10,000) and payment method (card or crypto), complete payment in the browser, and OpenClaude saves the issued key for you. - - **Enter existing API key** — paste a key you already have from the AI/ML API dashboard. +2. Choose **aimlapi.com**. +3. If aimlapi.com is already configured, choose one of: + - **Continue with your saved API key** - validate the saved key or `AIMLAPI_API_KEY`, check its balance, optionally top up a low balance, then choose a model. + - **Set up a new key or switch account** - enter the new-user or existing-key flow. +4. Otherwise choose how to get an API key: + - **I am a new user** - enter your email. OpenClaude creates a passwordless account, lets you pick a top-up amount and automatic top-up preference, opens card checkout, then saves the issued key. + - **I already have aimlapi.com key** - paste a key from the dashboard. OpenClaude validates it, checks its balance, and offers an optional API-key top-up when the balance is low. -Either way, the base URL (`https://api.aimlapi.com/v1`) and default model (`gpt-4o`) are filled in automatically. +For an email that already has an account, AI/ML API sends a 6-digit sign-in code. OpenClaude creates a new API key for that account, checks its balance, and only offers checkout when the balance is low. You can top up or save the key and skip funding for now. -Switch models any time with `/model` — only chat-capable models from the AI/ML API catalog are listed. +When `AIMLAPI_API_KEY` supplies the credential, OpenClaude uses its runtime value for validation and balance checks but saves an empty credential in the provider profile. The literal environment value is not copied into configuration. -## Option 2 — CLI (`openclaude aimlapi topup`) +Checkout progress is retained while the provider flow remains open. Retrying an ambiguous payment or exchange failure resumes the original partner session instead of creating a second checkout. -Run the same guided top-up flow non-interactively: +The base URL (`https://api.aimlapi.com/v1`) and default model (`gpt-4o`) are filled in automatically. Switch models any time with `/model`; only chat-capable models from the AI/ML API catalog are listed. + +## Option 2 - CLI (`openclaude aimlapi topup`) + +Run the guided account top-up flow from the CLI: ```bash -openclaude aimlapi topup --email you@example.com --amount 25 --method card +openclaude aimlapi topup --email you@example.com --amount 25 ``` -- Credentials: pass `--email` (or set `AIMLAPI_EMAIL`) and set `AIMLAPI_PASSWORD`; if either is missing you're prompted interactively (password entry is hidden). +- Pass `--email` (or set `AIMLAPI_EMAIL`). Existing accounts also need the emailed `--code` (or `AIMLAPI_CODE`); interactive terminals prompt for missing values. - `--amount`: top-up amount in USD (min 20, max 10000; defaults to 25). -- `--method`: `card` (Stripe, default) or `crypto` (NOWPayments). +- Checkout always uses card payment; there is no separate payment-method step. +- `--auto-top-up`: enroll the account in automatic top-up at checkout. - `--model`: default model id written into the provider profile (defaults to `gpt-4o`). - `--no-open`: print the payment URL instead of auto-opening a browser. The issued key is written into OpenClaude's provider profile automatically once payment clears. -## Option 3 — Environment variables +## Option 3 - Environment variables Setting `AIMLAPI_API_KEY` alone is enough; OpenClaude auto-detects the AI/ML API route: @@ -67,4 +75,6 @@ export OPENAI_MODEL="gpt-4o" - Model discovery uses the public, unauthenticated `GET /models` endpoint and surfaces only chat-completions models; image, audio, embeddings, and other modalities are intentionally not routed through the coding workflow. - Requests carry `X-AIMLAPI-Integration-*` attribution headers (owner/repo/version) plus the `HTTP-Referer: OpenClaude` and `X-Title: OpenClaude` headers that AI/ML API uses to attribute integration traffic. +- `AIMLAPI_AUTH_URL`, `AIMLAPI_APP_URL`, `AIMLAPI_PAY_URL`, `AIMLAPI_INFERENCE_URL`, and `AIMLAPI_VERIFICATION_BASE_URL` can point the complete flow at another environment. `AIMLAPI_RETURN_URL` overrides only the browser landing page. +- Checkout success is detected by polling. The browser return target is an HTTPS page; OpenClaude does not install a custom URL-scheme handler. - Usage (`/usage`) reporting is not supported for this provider. diff --git a/src/cli/aimlapiCommand.test.ts b/src/cli/aimlapiCommand.test.ts new file mode 100644 index 0000000000..33c0200b68 --- /dev/null +++ b/src/cli/aimlapiCommand.test.ts @@ -0,0 +1,49 @@ +import { expect, mock, test } from 'bun:test' +import { Command as CommanderCommand } from '@commander-js/extra-typings' + +import { registerAimlapiCommand } from './aimlapiCommand.js' + +test('aimlapi topup forwards the passwordless CLI contract', async () => { + const handler = mock(async () => {}) + const program = new CommanderCommand().exitOverride() + registerAimlapiCommand(program, async () => handler) + + await program.parseAsync([ + 'node', + 'openclaude', + 'aimlapi', + 'topup', + '--email', + 'user@example.com', + '--code', + '123456', + '--auto-top-up', + '--no-open', + ]) + + expect(handler).toHaveBeenCalledWith({ + email: 'user@example.com', + code: '123456', + amountUsd: undefined, + autoTopUp: true, + model: 'gpt-4o', + partnerId: undefined, + noOpen: true, + }) +}) + +test('aimlapi topup rejects the removed method option', async () => { + const program = new CommanderCommand().exitOverride() + registerAimlapiCommand(program, async () => async () => {}) + + await expect( + program.parseAsync([ + 'node', + 'openclaude', + 'aimlapi', + 'topup', + '--method', + 'card', + ]), + ).rejects.toMatchObject({ code: 'commander.unknownOption' }) +}) diff --git a/src/cli/aimlapiCommand.ts b/src/cli/aimlapiCommand.ts new file mode 100644 index 0000000000..9a9827e1ec --- /dev/null +++ b/src/cli/aimlapiCommand.ts @@ -0,0 +1,58 @@ +import { Command as CommanderCommand } from '@commander-js/extra-typings' + +import { + DEFAULT_MODEL, + MAX_AMOUNT_USD_MINOR, + MIN_AMOUNT_USD_MINOR, +} from '../integrations/aimlapi/config.js' +import type { AimlapiTopupOptions } from '../integrations/aimlapi/topup.js' + +type AimlapiTopupHandler = (options: AimlapiTopupOptions) => Promise +type LoadAimlapiTopupHandler = () => Promise + +const loadAimlapiTopupHandler: LoadAimlapiTopupHandler = async () => { + const { aimlapiTopup } = await import('./handlers/aimlapi.js') + return aimlapiTopup +} + +export function registerAimlapiCommand( + program: CommanderCommand, + loadHandler: LoadAimlapiTopupHandler = loadAimlapiTopupHandler, +): CommanderCommand { + const aimlapi = program + .command('aimlapi') + .description('AI/ML API (aimlapi.com) — top up balance and configure the provider') + aimlapi + .command('topup') + .description( + 'Use passwordless sign-in, open AI/ML API top-up, then configure OpenClaude', + ) + .option('--email ', 'AI/ML API account email (or AIMLAPI_EMAIL env)') + .option('--code ', '6-digit code for an existing account (or AIMLAPI_CODE env)') + .option( + '--amount ', + `Top-up amount in USD (min ${MIN_AMOUNT_USD_MINOR / 100}, max ${MAX_AMOUNT_USD_MINOR / 100})`, + ) + .option('--auto-top-up', 'Enable automatic top-up at checkout') + .option( + '--model ', + 'Default model id written into the provider profile', + DEFAULT_MODEL, + ) + .option('--partner-id ', 'Partner id for rebate attribution (part_...)') + .option('--no-open', 'Do not auto-open the browser; print the payment URL instead') + .action(async opts => { + const handler = await loadHandler() + await handler({ + email: opts.email, + code: opts.code, + amountUsd: opts.amount, + autoTopUp: opts.autoTopUp, + model: opts.model, + partnerId: opts.partnerId, + noOpen: opts.open === false, + }) + }) + + return aimlapi +} diff --git a/src/cli/handlers/aimlapi.ts b/src/cli/handlers/aimlapi.ts index ac8e5f7c61..b6cc75ddb0 100644 --- a/src/cli/handlers/aimlapi.ts +++ b/src/cli/handlers/aimlapi.ts @@ -1,6 +1,7 @@ /* eslint-disable custom-rules/no-process-exit -- CLI subcommand handler intentionally exits */ import chalk from 'chalk' +import { redactSensitiveInfo } from '../../utils/redaction.js' import { AimlapiApiError } from '../../integrations/aimlapi/client.js' import { @@ -13,12 +14,14 @@ export async function aimlapiTopup(options: AimlapiTopupOptions): Promise await runAimlapiTopup(options) } catch (error) { if (error instanceof AimlapiApiError) { - console.error(chalk.red(`\n ✗ ${error.message}`)) + console.error(chalk.red(`\n ✗ ${redactSensitiveInfo(error.message)}`)) if (error.body) { - console.error(chalk.dim(` ${error.body}`)) + console.error(chalk.dim(` ${redactSensitiveInfo(error.body)}`)) } } else { - const message = error instanceof Error ? error.message : String(error) + const message = redactSensitiveInfo( + error instanceof Error ? error.message : String(error), + ) console.error(chalk.red(`\n ✗ ${message}`)) } process.exit(1) diff --git a/src/components/ConsoleOAuthFlow.test.tsx b/src/components/ConsoleOAuthFlow.test.tsx index 11b493e81d..d81a1fb9d9 100644 --- a/src/components/ConsoleOAuthFlow.test.tsx +++ b/src/components/ConsoleOAuthFlow.test.tsx @@ -135,7 +135,7 @@ test('third-party provider branch opens the first-run provider manager', async ( expect(output).toContain('Set up provider') // Keep the sentinels near the top of the preset list so adding another // provider does not push the assertion outside the 13-row test frame. - expect(output).toContain('AI/ML API') + expect(output).toContain('aimlapi.com') expect(output).toContain('Anthropic') expect(output).toContain('Azure OpenAI') expect(output).toContain('DeepSeek') diff --git a/src/components/ProviderManager.test.tsx b/src/components/ProviderManager.test.tsx index 9d108b5651..845cf091a1 100644 --- a/src/components/ProviderManager.test.tsx +++ b/src/components/ProviderManager.test.tsx @@ -7,6 +7,7 @@ import { stripVTControlCharacters as stripAnsi } from 'node:util' import { createRoot } from '../ink.js' import { KeybindingSetup } from '../keybindings/KeybindingProviderSetup.js' import { AppStateProvider } from '../state/AppState.js' +import { AIMLAPI_MESSAGES } from '../integrations/aimlapi/messages.js' import { acquireSharedMutationLock, releaseSharedMutationLock, @@ -21,7 +22,6 @@ const actualSettingsModule = (await import( const actualProviderStartupOverridesModule = (await import( `../utils/providerStartupOverrides.ts?providerManagerStartupOverridesActual=${Date.now()}-${Math.random()}` )) as ProviderStartupOverridesModule - const SYNC_START = '\x1B[?2026h' const SYNC_END = '\x1B[?2026l' @@ -31,7 +31,11 @@ const ORIGINAL_ENV = { GITHUB_TOKEN: process.env.GITHUB_TOKEN, GH_TOKEN: process.env.GH_TOKEN, AIMLAPI_EMAIL: process.env.AIMLAPI_EMAIL, - AIMLAPI_PASSWORD: process.env.AIMLAPI_PASSWORD, + AIMLAPI_CODE: process.env.AIMLAPI_CODE, + AIMLAPI_API_KEY: process.env.AIMLAPI_API_KEY, + AIMLAPI_INFERENCE_URL: process.env.AIMLAPI_INFERENCE_URL, + OPENAI_API_KEY: process.env.OPENAI_API_KEY, + OPENAI_API_KEYS: process.env.OPENAI_API_KEYS, } function extractLastFrame(output: string): string { @@ -114,8 +118,8 @@ async function waitForCondition( } // Provider list is sorted from generated preset metadata by description, with -// Gitlawb Opengateway pinned first, Anthropic second, Codex OAuth injected -// after DeepSeek, and the custom endpoints always pinned last. Keep the target-by-label +// Gitlawb Opengateway pinned first, aimlapi.com second, Anthropic third, Codex OAuth injected +// after DeepSeek, and Custom always pinned last. Keep the target-by-label // indirection here so // these tests survive future list edits without hardcoding raw key counts. // @@ -123,8 +127,8 @@ async function waitForCondition( // canUseCodexOAuth === true (default in mocked tests). const PRESET_ORDER = [ 'Gitlawb Opengateway', + 'aimlapi.com', 'Anthropic', - 'AI/ML API', 'Alibaba Coding Plan (China)', 'Alibaba Coding Plan', 'Atlas Cloud', @@ -267,7 +271,7 @@ function mockProviderProfilesModule(options?: { if (preset === 'aimlapi') { return { provider: 'aimlapi', - name: 'AI/ML API', + name: 'aimlapi.com', baseUrl: 'https://api.aimlapi.com/v1', model: 'gpt-4o', apiKey: '', @@ -345,6 +349,16 @@ function mockProviderManagerDependencies( updateProviderProfile?: (...args: any[]) => unknown setActiveProviderProfile?: (...args: any[]) => unknown provisionAimlapiKey?: (...args: any[]) => Promise + topUpAimlapiByApiKey?: (...args: any[]) => Promise + beginAimlapiEmailOnboarding?: (...args: any[]) => Promise + completeAimlapiCodeSignIn?: (...args: any[]) => Promise + validateAimlapiApiKey?: (...args: any[]) => Promise + claimAimlapiTopupState?: (...args: any[]) => unknown + clearAimlapiTopupState?: (...args: any[]) => unknown + saveAimlapiTopupState?: (...args: any[]) => unknown + loadAimlapiSignInKey?: (...args: any[]) => unknown + saveAimlapiSignInKey?: (...args: any[]) => unknown + clearAimlapiSignInKey?: (...args: any[]) => unknown useCodexOAuthFlow?: (options: { onAuthenticated: ( tokens: { @@ -370,6 +384,14 @@ function mockProviderManagerDependencies( } }, ): void { + let persistedAimlapiTopup: Record | undefined + let aimlapiPaymentSequence = 0 + const matchesAimlapiIntent = ( + state: Record | undefined, + intent: Record, + ): boolean => + Boolean(state) && Object.keys(intent).every(key => state?.[key] === intent[key]) + mockProviderProfilesModule({ addProviderProfile: options?.addProviderProfile, getActiveProviderProfile: options?.getActiveProviderProfile, @@ -459,12 +481,84 @@ function mockProviderManagerDependencies( updateSettingsForSource: () => ({ error: null }), })) - mock.module('../integrations/aimlapi/index.js', () => ({ + mock.module('./providerManagerAimlapi.js', () => ({ + AIMLAPI_MESSAGES, + AimlapiApiError: class AimlapiApiError extends Error { + constructor( + message: string, + readonly status: number, + readonly body = '', + ) { + super(message) + } + }, + beginAimlapiEmailOnboarding: + options?.beginAimlapiEmailOnboarding ?? + (async () => ({ action: 'new-account', sessionToken: 'session_test' })), + completeAimlapiCodeSignIn: + options?.completeAimlapiCodeSignIn ?? + (async () => ({ + sessionToken: 'session_test', + apiKey: 'issued_test', + apiKeyId: 'key_test', + balanceStatus: 'confirmed' as const, + lowBalance: false, + })), + validateAimlapiApiKey: + options?.validateAimlapiApiKey ?? + (async () => ({ balance: 25, lowBalance: false, lowBalanceThreshold: 20 })), + claimAimlapiTopupState: + options?.claimAimlapiTopupState ?? + ((intent: Record) => { + if (matchesAimlapiIntent(persistedAimlapiTopup, intent)) { + return { + paymentSessionId: persistedAimlapiTopup?.paymentSessionId, + resumeSessionToken: persistedAimlapiTopup?.resumeSessionToken, + } + } + persistedAimlapiTopup = { + ...intent, + paymentSessionId: `payment-${++aimlapiPaymentSequence}`, + resumeSessionToken: '', + } + return { + paymentSessionId: persistedAimlapiTopup.paymentSessionId, + resumeSessionToken: '', + } + }), + clearAimlapiTopupState: + options?.clearAimlapiTopupState ?? + ((intent: Record) => { + if (matchesAimlapiIntent(persistedAimlapiTopup, intent)) { + persistedAimlapiTopup = undefined + } + }), + saveAimlapiTopupState: + options?.saveAimlapiTopupState ?? + ((state: Record) => { + persistedAimlapiTopup = state + }), + loadAimlapiSignInKey: options?.loadAimlapiSignInKey ?? (() => null), + saveAimlapiSignInKey: options?.saveAimlapiSignInKey ?? (() => {}), + clearAimlapiSignInKey: options?.clearAimlapiSignInKey ?? (() => {}), + parseAimlapiAmountUsd: (value: string | undefined) => { + const amount = Number(value || 25) + if (!Number.isFinite(amount) || amount < 20 || amount > 10000) { + throw new Error('Invalid top-up amount.') + } + return Math.round(amount * 100) + }, + isValidAimlapiEmail: (value: string) => /^[^\s@]+@[^\s@]+\.[A-Za-z]{2,}$/.test(value), provisionAimlapiKey: options?.provisionAimlapiKey ?? (async () => { throw new Error('Unexpected AI/ML API top-up in test') }), + topUpAimlapiByApiKey: + options?.topUpAimlapiByApiKey ?? + (async () => { + throw new Error('Unexpected AI/ML API by-key top-up in test') + }), })) mock.module('./useCodexOAuthFlow.js', () => ({ @@ -481,7 +575,7 @@ function mockProviderManagerDependencies( async function waitForFrameOutput( getOutput: () => string, predicate: (output: string) => boolean, - timeoutMs = 2500, + timeoutMs = 5000, ): Promise { let output = '' @@ -926,9 +1020,15 @@ test('ProviderManager saves AI/ML API preset with OpenAI-compatible defaults', a id: 'aimlapi_profile', ...payload, })) + const validateAimlapiApiKey = mock(async () => ({ + balance: 25, + lowBalance: false, + lowBalanceThreshold: 20, + })) mockProviderManagerDependencies(() => undefined, async () => undefined, { addProviderProfile, + validateAimlapiApiKey, }) const nonce = `${Date.now()}-${Math.random()}` @@ -945,41 +1045,59 @@ test('ProviderManager saves AI/ML API preset with OpenAI-compatible defaults', a frame.includes('Choose provider preset'), ) - await navigateToPreset(mounted.stdin, 'AI/ML API') + await navigateToPreset(mounted.stdin, 'aimlapi.com') mounted.stdin.write('\r') const modelOutput = await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Create provider profile') && frame.includes('Step 1 of 2: Default model'), ) - expect(modelOutput).toContain('AI/ML API') + expect(modelOutput).toContain('aimlapi.com') expect(modelOutput).toContain('gpt-4o') expect(modelOutput).not.toContain('Provider name') expect(modelOutput).not.toContain('Base URL') mounted.stdin.write('\r') const choiceOutput = await waitForFrameOutput(mounted.getOutput, frame => - frame.includes('Step 2 of 2: API key'), + frame.includes('Do you have aimlapi.com key?'), ) - expect(choiceOutput).toContain('Top up and get API key') - expect(choiceOutput).toContain('Enter existing API key') + expect(choiceOutput).toContain('I am a new user') + expect(choiceOutput).toContain('I already have aimlapi.com key') + expect(choiceOutput).not.toContain('One click set up') + expect(choiceOutput).not.toContain('Proceed to paste the key') mounted.stdin.write('j') await Bun.sleep(25) mounted.stdin.write('\r') - await waitForFrameOutput(mounted.getOutput, frame => - frame.includes('Enter the API key for AI/ML API'), + const apiKeyOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Enter your aimlapi.com key.'), + ) + expect(apiKeyOutput).toContain( + 'Your API key will be hidden and verified automatically.', ) + expect(apiKeyOutput).toContain('API key:') + expect(apiKeyOutput).not.toContain('Create provider profile') + expect(apiKeyOutput).not.toContain('Provider type:') + expect(apiKeyOutput).not.toContain('Step 2 of 2: API key') mounted.stdin.write('aimlapi-test-key') await Bun.sleep(25) mounted.stdin.write('\r') await waitForCondition(() => addProviderProfile.mock.calls.length > 0) + expect(validateAimlapiApiKey).toHaveBeenCalledWith( + 'aimlapi-test-key', + expect.any(AbortSignal), + 'https://api.aimlapi.com/v1', + ) + const doneOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Everything is ready.'), + ) + expect(doneOutput).toContain('Press Enter to continue.') expect(addProviderProfile).toHaveBeenCalledWith( expect.objectContaining({ provider: 'aimlapi', - name: 'AI/ML API', + name: 'aimlapi.com', baseUrl: 'https://api.aimlapi.com/v1', model: 'gpt-4o', apiKey: 'aimlapi-test-key', @@ -992,17 +1110,616 @@ test('ProviderManager saves AI/ML API preset with OpenAI-compatible defaults', a } }) +test('ProviderManager offers and reuses an existing AIMLAPI profile', async () => { + delete process.env.AIMLAPI_API_KEY + const profile = { + id: 'aimlapi_existing', + provider: 'aimlapi', + name: 'aimlapi.com', + baseUrl: 'https://api.aimlapi.com/v1', + model: 'old-model', + apiKey: 'saved-key', + apiFormat: 'chat_completions', + } + const updateProviderProfile = mock((id: string, payload: any) => ({ + id, + ...payload, + })) + const validateAimlapiApiKey = mock(async () => ({ + balance: 25, + lowBalance: false, + lowBalanceThreshold: 20, + })) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + getProviderProfiles: () => [profile], + getActiveProviderProfile: () => profile, + updateProviderProfile, + validateAimlapiApiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Provider manager')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Choose provider preset')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + const configured = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('aimlapi.com account is already configured'), + ) + expect(configured).toContain('Continue with your saved API key') + expect(configured).toContain('Set up a new key or switch account') + expect(configured).not.toContain('Use existing configuration') + expect(configured).not.toContain('Configure again') + + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Create provider profile') && frame.includes('Default model'), + ) + expect(validateAimlapiApiKey).toHaveBeenCalledWith( + 'saved-key', + expect.any(AbortSignal), + 'https://api.aimlapi.com/v1', + ) + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForCondition(() => updateProviderProfile.mock.calls.length > 0, { + timeoutMs: 5000, + }) + expect(updateProviderProfile).toHaveBeenCalledWith( + 'aimlapi_existing', + expect.objectContaining({ apiKey: 'saved-key' }), + ) + // Continuing with a saved key never charges the account, so the done + // screen must report readiness rather than a phantom top-up. + const doneOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Everything is ready.'), + ) + expect(doneOutput).not.toContain('Top-up successful') + expect(doneOutput).not.toContain('credited to your account') + } finally { + await mounted.dispose() + } +}, 10_000) + +test('ProviderManager uses OPENAI_API_KEY for an existing keyless AIMLAPI profile', async () => { + delete process.env.AIMLAPI_API_KEY + delete process.env.OPENAI_API_KEYS + process.env.OPENAI_API_KEY = 'openai-fallback-key' + const profile = { + id: 'aimlapi_existing', + provider: 'aimlapi', + name: 'aimlapi.com', + baseUrl: 'https://api.aimlapi.com/v1', + model: 'gpt-4o', + apiKey: undefined, + apiFormat: 'chat_completions', + } + const validateAimlapiApiKey = mock(async () => ({ + balance: 25, + lowBalance: false, + lowBalanceThreshold: 20, + })) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + getProviderProfiles: () => [profile], + getActiveProviderProfile: () => profile, + validateAimlapiApiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Provider manager')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Choose provider preset')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('aimlapi.com account is already configured'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Create provider profile') && frame.includes('Default model'), + ) + expect(validateAimlapiApiKey).toHaveBeenCalledWith( + 'openai-fallback-key', + expect.any(AbortSignal), + 'https://api.aimlapi.com/v1', + ) + } finally { + await mounted.dispose() + } +}, 10_000) + +test('ProviderManager does not send the OPENAI_API_KEY fallback to a custom AIMLAPI endpoint', async () => { + delete process.env.AIMLAPI_API_KEY + delete process.env.OPENAI_API_KEYS + process.env.OPENAI_API_KEY = 'env-runtime-key' + process.env.AIMLAPI_INFERENCE_URL = 'https://proxy.example.test/v1' + const addProviderProfile = mock((payload: any) => ({ + id: 'aimlapi_env', + ...payload, + })) + const validateAimlapiApiKey = mock(async () => ({ + balance: 25, + lowBalance: false, + lowBalanceThreshold: 20, + })) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + addProviderProfile, + validateAimlapiApiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager, { mode: 'first-run' }) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Set up provider')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Create provider profile') && frame.includes('Default model'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Do you have aimlapi.com key?'), + ) + expect(validateAimlapiApiKey).not.toHaveBeenCalled() + expect(addProviderProfile).not.toHaveBeenCalled() + } finally { + await mounted.dispose() + } +}) + +test('ProviderManager refuses guided new-key creation on a custom AIMLAPI endpoint', async () => { + delete process.env.AIMLAPI_API_KEY + delete process.env.AIMLAPI_EMAIL + process.env.AIMLAPI_INFERENCE_URL = 'https://proxy.example.test/v1' + const beginAimlapiEmailOnboarding = mock(async () => ({ action: 'code-sent' as const })) + const provisionAimlapiKey = mock(async () => ({ + apiKey: 'issued', + apiKeyId: 'id', + baseUrl: 'https://proxy.example.test/v1', + model: 'gpt-4o', + })) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + beginAimlapiEmailOnboarding, + provisionAimlapiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager, { mode: 'first-run' }) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Set up provider')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Create provider profile') && frame.includes('Default model'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Do you have aimlapi.com key?'), + ) + // Selecting "I am a new user" must be refused off the canonical endpoint, + // since guided provisioning would mint a production key against the proxy. + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('production endpoint')) + expect(beginAimlapiEmailOnboarding).not.toHaveBeenCalled() + expect(provisionAimlapiKey).not.toHaveBeenCalled() + } finally { + await mounted.dispose() + } +}) + +test('ProviderManager manage flow does not reuse env credentials for a custom AIMLAPI endpoint', async () => { + delete process.env.AIMLAPI_API_KEY + delete process.env.OPENAI_API_KEYS + process.env.OPENAI_API_KEY = 'env-runtime-key' + process.env.AIMLAPI_INFERENCE_URL = 'https://proxy.example.test/v1' + const validateAimlapiApiKey = mock(async () => ({ + balance: 25, + lowBalance: false, + lowBalanceThreshold: 20, + })) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + validateAimlapiApiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Provider manager')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Choose provider preset')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Create provider profile') && frame.includes('Default model'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Do you have aimlapi.com key?'), + ) + expect(validateAimlapiApiKey).not.toHaveBeenCalled() + } finally { + await mounted.dispose() + } +}) + +test('ProviderManager does not persist an invalid or low-balance first-run AIMLAPI env key', async () => { + process.env.AIMLAPI_API_KEY = 'env-runtime-key' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.aimlapi.com/v1' + + for (const scenario of ['invalid', 'low-balance'] as const) { + const addProviderProfile = mock(() => null) + const validateAimlapiApiKey = mock(async () => { + if (scenario === 'invalid') { + throw Object.assign(new Error('Unauthorized'), { status: 401 }) + } + return { balance: 5, lowBalance: true, lowBalanceThreshold: 20 } + }) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + addProviderProfile, + validateAimlapiApiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager, { mode: 'first-run' }) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Set up provider')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Create provider profile') && frame.includes('Default model'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + scenario === 'invalid' + ? frame.includes('API key is invalid.') + : frame.includes('credits are running low'), + ) + expect(validateAimlapiApiKey).toHaveBeenCalledWith( + 'env-runtime-key', + expect.any(AbortSignal), + 'https://api.aimlapi.com/v1', + ) + expect(addProviderProfile).not.toHaveBeenCalled() + } finally { + await mounted.dispose() + } + } +}) + +test('ProviderManager rejects an invalid AIMLAPI key using the Zero error copy', async () => { + const addProviderProfile = mock(() => null) + const validateAimlapiApiKey = mock(async () => { + throw Object.assign(new Error('Unauthorized'), { status: 401 }) + }) + + mockProviderManagerDependencies(() => undefined, async () => undefined, { + addProviderProfile, + validateAimlapiApiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + + try { + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Provider manager'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Choose provider preset'), + ) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Step 1 of 2: Default model'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Do you have aimlapi.com key?'), + ) + mounted.stdin.write('j') + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Enter your aimlapi.com key.'), + ) + + mounted.stdin.write('bad-aimlapi-key') + await Bun.sleep(25) + mounted.stdin.write('\r') + + const invalidOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes( + 'API key is invalid. Please make sure you enter a valid aimlapi.com key.', + ), + ) + expect(invalidOutput).toContain('Enter your aimlapi.com key.') + expect(validateAimlapiApiKey).toHaveBeenCalledWith( + 'bad-aimlapi-key', + expect.any(AbortSignal), + 'https://api.aimlapi.com/v1', + ) + expect(addProviderProfile).not.toHaveBeenCalled() + } finally { + await mounted.dispose() + } +}) + +test('ProviderManager matches the AIMLAPI code and low-credit screen copy', async () => { + const beginAimlapiEmailOnboarding = mock(async () => ({ action: 'code-sent' as const })) + const completeAimlapiCodeSignIn = mock(async () => ({ + sessionToken: 'session_test', + apiKey: 'issued_test', + apiKeyId: 'key_test', + balanceStatus: 'confirmed' as const, + lowBalance: true, + })) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + beginAimlapiEmailOnboarding, + completeAimlapiCodeSignIn, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + try { + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Provider manager'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Choose provider preset'), + ) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Step 1 of 2: Default model'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Do you have aimlapi.com key?'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Enter your email.'), + ) + mounted.stdin.write('stan@aimlapi.com') + await Bun.sleep(25) + mounted.stdin.write('\r') + + const codeOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Enter the 6-digit code sent to stan@aimlapi.com.'), + ) + expect(codeOutput).not.toContain('Enter it below to continue.') + expect(codeOutput).not.toContain('We sent a 6-digit code') + mounted.stdin.write('123456') + await Bun.sleep(25) + const maskedCodeOutput = mounted.getOutput() + expect(maskedCodeOutput).not.toContain('123456') + expect(maskedCodeOutput).toContain('******') + mounted.stdin.write('\r') + + const lowCreditOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Your aimlapi.com credits are running low - top up now?'), + ) + expect(lowCreditOutput).toContain("Sure, let's do that") + expect(lowCreditOutput).toContain("I'll skip for now") + expect(lowCreditOutput).not.toContain( + 'It is recommended to top up your balance.', + ) + } finally { + await mounted.dispose() + } +}) + +test('ProviderManager rejects an empty AIMLAPI top-up amount instead of charging the default', async () => { + delete process.env.AIMLAPI_EMAIL + const provisionAimlapiKey = mock(async () => ({ + apiKey: 'unexpected', + apiKeyId: 'unexpected', + baseUrl: 'https://api.aimlapi.com/v1', + model: 'gpt-4o', + })) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + provisionAimlapiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Provider manager')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Choose provider preset')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Step 1 of 2: Default model')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('I am a new user')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Enter your email.')) + mounted.stdin.write('user@example.com') + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Add credits')) + + mounted.stdin.write('\x15') + await Bun.sleep(25) + mounted.stdin.write('\r') + const output = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Please enter a top-up amount.'), + ) + expect(output).toContain('Please enter a top-up amount.') + expect(provisionAimlapiKey).not.toHaveBeenCalled() + } finally { + await mounted.dispose() + } +}, 10_000) + +test('ProviderManager drops a retained checkout when the onboarding email changes', async () => { + delete process.env.AIMLAPI_EMAIL + const addProviderProfile = mock((payload: any) => ({ id: 'aimlapi_profile', ...payload })) + let accountSequence = 0 + const beginAimlapiEmailOnboarding = mock(async () => ({ + action: 'new-account' as const, + sessionToken: `account-session-${++accountSequence}`, + })) + let provisionSequence = 0 + const provisionAimlapiKey = mock(async (options: any) => { + provisionSequence += 1 + if (provisionSequence === 1) { + options.onSession?.('checkout-for-first-account') + throw new Error('temporary checkout failure') + } + return { + apiKey: 'issued-for-second-account', + apiKeyId: 'key_second', + baseUrl: 'https://api.aimlapi.com/v1', + model: 'gpt-4o', + } + }) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + addProviderProfile, + beginAimlapiEmailOnboarding, + provisionAimlapiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Provider manager')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Choose provider preset')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Step 1 of 2: Default model')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('I am a new user')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Enter your email.')) + const firstEmail = 'first@example.com' + mounted.stdin.write(firstEmail) + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Add credits')) + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForCondition(() => provisionAimlapiKey.mock.calls.length === 1) + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('temporary checkout failure')) + + mounted.stdin.write('\x1b') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Enter your email.')) + mounted.stdin.write('\x7f'.repeat(firstEmail.length)) + mounted.stdin.write('second@example.com') + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Add credits')) + mounted.stdin.write('\r') + await waitForCondition(() => provisionAimlapiKey.mock.calls.length === 2) + + const firstOptions = provisionAimlapiKey.mock.calls[0]?.[0] as any + const secondOptions = provisionAimlapiKey.mock.calls[1]?.[0] as any + expect(firstOptions.sessionToken).toBe('account-session-1') + expect(secondOptions.sessionToken).toBe('account-session-2') + expect(secondOptions.resumeSessionToken).toBe('') + expect(secondOptions.paymentSessionId).not.toBe(firstOptions.paymentSessionId) + } finally { + await mounted.dispose() + } +}) + +test('ProviderManager cancellation returns a live checkout to the resumable amount screen', async () => { + delete process.env.AIMLAPI_EMAIL + let provisionSequence = 0 + const provisionAimlapiKey = mock(async (options: any) => { + provisionSequence += 1 + if (provisionSequence === 1) { + options.onSession?.('live-checkout') + await new Promise((_resolve, reject) => { + options.signal.addEventListener('abort', () => reject(options.signal.reason), { + once: true, + }) + }) + } + return { + apiKey: 'issued-after-resume', + apiKeyId: 'key_after_resume', + baseUrl: 'https://api.aimlapi.com/v1', + model: 'gpt-4o', + } + }) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + provisionAimlapiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Provider manager')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Choose provider preset')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Step 1 of 2: Default model')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('I am a new user')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Enter your email.')) + mounted.stdin.write('user@example.com') + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Add credits')) + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForCondition(() => provisionAimlapiKey.mock.calls.length === 1) + + const firstOptions = provisionAimlapiKey.mock.calls[0]?.[0] as any + mounted.stdin.write('\x1b') + const amountOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Add credits'), + ) + expect(amountOutput).not.toContain('Do you have aimlapi.com key?') + expect(firstOptions.signal.aborted).toBe(true) + + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForCondition(() => provisionAimlapiKey.mock.calls.length === 2) + const secondOptions = provisionAimlapiKey.mock.calls[1]?.[0] as any + expect(secondOptions.resumeSessionToken).toBe('live-checkout') + expect(secondOptions.paymentSessionId).toBe(firstOptions.paymentSessionId) + } finally { + await mounted.dispose() + } +}) + test('ProviderManager can top up AI/ML API and save the issued key', async () => { delete process.env.AIMLAPI_EMAIL - delete process.env.AIMLAPI_PASSWORD + delete process.env.AIMLAPI_CODE const addProviderProfile = mock((payload: any) => ({ id: 'aimlapi_profile', ...payload, })) + const checkoutUrl = + 'https://checkout.stripe.com/c/pay/cs_test_1234567890#signed-checkout-fragment-that-must-remain-visible-across-terminal-lines-tail' const provisionAimlapiKey = mock(async (options: any) => { options.onStatus?.('creating-session') - options.onStatus?.('opening-checkout', 'https://app.aimlapi.com/checkout/test') + await Bun.sleep(150) + options.onStatus?.('opening-checkout', checkoutUrl) + await Bun.sleep(150) options.onStatus?.('waiting-payment') options.onStatus?.('provisioning-key') return { @@ -1012,10 +1729,17 @@ test('ProviderManager can top up AI/ML API and save the issued key', async () => model: 'gpt-4o', } }) + const claimAimlapiTopupState = mock(() => ({ + paymentSessionId: 'persisted-payment-id', + resumeSessionToken: 'persisted-checkout-session', + })) + const clearAimlapiTopupState = mock(() => {}) mockProviderManagerDependencies(() => undefined, async () => undefined, { addProviderProfile, provisionAimlapiKey, + claimAimlapiTopupState, + clearAimlapiTopupState, }) const nonce = `${Date.now()}-${Math.random()}` @@ -1032,7 +1756,7 @@ test('ProviderManager can top up AI/ML API and save the issued key', async () => frame.includes('Choose provider preset'), ) - await navigateToPreset(mounted.stdin, 'AI/ML API') + await navigateToPreset(mounted.stdin, 'aimlapi.com') mounted.stdin.write('\r') await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Step 1 of 2: Default model'), @@ -1040,54 +1764,78 @@ test('ProviderManager can top up AI/ML API and save the issued key', async () => mounted.stdin.write('\r') await waitForFrameOutput(mounted.getOutput, frame => - frame.includes('Top up and get API key'), + frame.includes('I am a new user'), ) mounted.stdin.write('\r') await waitForFrameOutput(mounted.getOutput, frame => - frame.includes('Enter your AI/ML API account email'), + frame.includes('Enter your email.'), ) mounted.stdin.write('user@example.com') await Bun.sleep(25) mounted.stdin.write('\r') await waitForFrameOutput(mounted.getOutput, frame => - frame.includes('Enter your AI/ML API password'), + frame.includes('Add credits') && + frame.includes('Auto top up: on/off'), ) - mounted.stdin.write('secret-password') + await Bun.sleep(25) + mounted.stdin.write('\t') + await Bun.sleep(25) + mounted.stdin.write(' ') + await Bun.sleep(25) + mounted.stdin.write('\t') await Bun.sleep(25) mounted.stdin.write('\r') - await waitForFrameOutput(mounted.getOutput, frame => - frame.includes('Choose a top-up amount in USD') && - frame.includes('25'), + await waitForCondition(() => provisionAimlapiKey.mock.calls.length > 0) + const spinnerOutput = await waitForFrameOutput(mounted.getOutput, frame => + !frame.includes('Auto top up:') && + !frame.includes('Top-up successful -'), ) - mounted.stdin.write('\r') + expect(spinnerOutput).not.toContain('Creating checkout session...') + expect(spinnerOutput).not.toContain('Waiting for payment...') + expect(spinnerOutput).not.toContain('Issuing API key...') - await waitForFrameOutput(mounted.getOutput, frame => - frame.includes('Payment method') && - frame.includes('Card') && - frame.includes('Crypto'), + const paymentOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Opening checkout in browser...'), ) - mounted.stdin.write('j') - await Bun.sleep(25) - mounted.stdin.write('\r') + expect(paymentOutput).toContain( + 'If the browser did not open automatically please use this link to top up your account:', + ) + expect(paymentOutput).toContain('https://checkout.stripe.com/c/pay/cs_test_1234567890') + expect(paymentOutput.replace(/\s/g, '')).toContain(checkoutUrl) await waitForCondition(() => addProviderProfile.mock.calls.length > 0) + const doneOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Top-up successful - $25 credited to your account'), + ) + expect(doneOutput).not.toContain('has been added to your balance') + expect(doneOutput).toContain( + "We've emailed you a magic link to user@example.com. Use it to access your aimlapi.com account and review your usage.", + ) + mounted.stdin.write('\r') + await waitForFrameOutput( + mounted.getOutput, + frame => frame.includes('Provider manager'), + 12_000, + ) expect(provisionAimlapiKey).toHaveBeenCalledWith( expect.objectContaining({ - email: 'user@example.com', - password: 'secret-password', amountUsd: '25', - method: 'crypto', model: 'gpt-4o', + sessionToken: 'session_test', + paymentSessionId: 'persisted-payment-id', + resumeSessionToken: 'persisted-checkout-session', + exchange: true, + autoTopUp: false, onStatus: expect.any(Function), }), ) expect(addProviderProfile).toHaveBeenCalledWith( expect.objectContaining({ provider: 'aimlapi', - name: 'AI/ML API', + name: 'aimlapi.com', baseUrl: 'https://api.aimlapi.com/v1', model: 'gpt-4o', apiKey: 'aimlapi-issued-key', @@ -1095,10 +1843,12 @@ test('ProviderManager can top up AI/ML API and save the issued key', async () => }), expect.objectContaining({ makeActive: true }), ) + expect(claimAimlapiTopupState).toHaveBeenCalledTimes(1) + expect(clearAimlapiTopupState).toHaveBeenCalledTimes(1) } finally { await mounted.dispose() } -}) +}, 20_000) test('ProviderManager saves MiniMax preset with Anthropic-compatible endpoint and type', async () => { const addProviderProfile = mock((payload: any) => ({ diff --git a/src/components/ProviderManager.tsx b/src/components/ProviderManager.tsx index 63326dd844..2e4cc9142d 100644 --- a/src/components/ProviderManager.tsx +++ b/src/components/ProviderManager.tsx @@ -1,7 +1,8 @@ +import { createHash } from 'node:crypto' import figures from 'figures' import * as React from 'react' import { DEFAULT_CODEX_BASE_URL } from '../services/api/providerConfig.js' -import { Box, Text } from '../ink.js' +import { Box, Text, useInput } from '../ink.js' import { useTerminalSize } from '../hooks/useTerminalSize.js' import { useKeybinding } from '../keybindings/useKeybinding.js' import { useSetAppState } from '../state/AppState.js' @@ -44,18 +45,35 @@ import { routeShowsAuthHeaderValue, routeShowsCustomHeaders, resolveProfileRoute, + resolveRouteCredentialValue, resolveRouteIdFromBaseUrl, } from '../integrations/index.js' import { provisionAimlapiKey, + topUpAimlapiByApiKey, + parseAimlapiAmountUsd, + isValidAimlapiEmail, + beginAimlapiEmailOnboarding, + completeAimlapiCodeSignIn, + validateAimlapiApiKey, + AimlapiApiError, + AIMLAPI_MESSAGES, + claimAimlapiTopupState, + clearAimlapiTopupState, + saveAimlapiTopupState, + loadAimlapiSignInKey, + saveAimlapiSignInKey, + clearAimlapiSignInKey, + type AimlapiTopupIntent, type AimlapiTopupStatus, -} from '../integrations/aimlapi/index.js' +} from './providerManagerAimlapi.js' import { DEFAULT_AMOUNT_USD_MINOR, - MAX_AMOUNT_USD_MINOR, - MIN_AMOUNT_USD_MINOR, + DEFAULT_PARTNER_NAME, + isCanonicalAimlapiInferenceBaseUrl, + resolveEndpoints, + resolvePartnerId, } from '../integrations/aimlapi/config.js' -import type { PaymentMethod } from '../integrations/aimlapi/client.js' import { openAIShimSupportsApiFormatForModel } from '../integrations/runtimeMetadata.js' import { probeRouteReadiness } from '../integrations/discoveryService.js' import { @@ -90,13 +108,15 @@ import { recommendOllamaModel, } from '../utils/providerRecommendation.js' import { clearStartupProviderOverrides } from '../utils/providerStartupOverrides.js' -import { redactUrlForDisplay } from '../utils/redaction.js' +import { redactSensitiveInfo, redactUrlForDisplay } from '../utils/redaction.js' +import { registerCleanup } from '../utils/cleanupRegistry.js' import { updateSettingsForSource } from '../utils/settings/settings.js' import { type OptionWithDescription, Select, } from './CustomSelect/index.js' import { Pane } from './design-system/Pane.js' +import { Spinner } from './Spinner.js' import TextInput from './TextInput.js' import { useCodexOAuthFlow } from './useCodexOAuthFlow.js' import { useXaiOAuthFlow } from './useXaiOAuthFlow.js' @@ -124,11 +144,13 @@ type Screen = | 'form' | 'preset-model' | 'aimlapi-api-key-choice' + | 'aimlapi-configured' | 'aimlapi-topup-email' - | 'aimlapi-topup-password' + | 'aimlapi-signin-code' + | 'aimlapi-low-balance' | 'aimlapi-topup-amount' - | 'aimlapi-topup-method' | 'aimlapi-topup-progress' + | 'aimlapi-done' | 'preset-api-key' | 'select-active' | 'select-edit' @@ -789,6 +811,120 @@ function CodexOAuthSetup({ ) } +type AimlapiTopupFormProps = { + amountUsd: string + autoTopUp: boolean + columns: number + cursorOffset: number + onAmountChange: (value: string) => void + onCursorOffsetChange: (offset: number) => void + onAutoTopUpChange: (enabled: boolean) => void + onSubmit: () => void +} + +function wrapAimlapiCheckoutUrl(url: string, width: number): string[] { + const characters = Array.from(url.trim()) + const chunkSize = Math.max(20, width) + const lines: string[] = [] + for (let offset = 0; offset < characters.length; offset += chunkSize) { + lines.push(characters.slice(offset, offset + chunkSize).join('')) + } + return lines +} + +function safeAimlapiErrorMessage( + error: unknown, + secrets: Array = [], +): string { + // AimlapiApiError.message deliberately excludes its server-controlled body. + // Redact exact active values as well as keys matching known credential shapes. + let message = error instanceof Error ? error.message : String(error) + for (const secret of secrets) { + const value = secret?.trim() + if (value) message = message.split(value).join('[REDACTED]') + } + return redactSensitiveInfo(message) +} + +function AimlapiTopupForm({ + amountUsd, + autoTopUp, + columns, + cursorOffset, + onAmountChange, + onCursorOffsetChange, + onAutoTopUpChange, + onSubmit, +}: AimlapiTopupFormProps): React.ReactNode { + const [focusedField, setFocusedField] = React.useState<'amount' | 'auto'>( + 'amount', + ) + + // This small form intentionally mirrors Zero's two-row top-up control while + // keeping OpenClaude's native input and event system. + useInput((input, key, event) => { + if (key.tab || key.upArrow || key.downArrow) { + setFocusedField(field => (field === 'amount' ? 'auto' : 'amount')) + event.stopImmediatePropagation() + return + } + if (focusedField !== 'auto') return + if (key.leftArrow || key.rightArrow || input === ' ') { + onAutoTopUpChange(!autoTopUp) + event.stopImmediatePropagation() + return + } + if (key.return) { + onSubmit() + event.stopImmediatePropagation() + return + } + if (!key.escape) event.stopImmediatePropagation() + }) + + const amountFocused = focusedField === 'amount' + const autoFocused = focusedField === 'auto' + return ( + + + + {amountFocused ? `${figures.pointer} ` : ' '}Amount: $ + + onSubmit()} + focus={amountFocused} + showCursor={amountFocused} + columns={columns} + cursorOffset={cursorOffset} + onChangeCursorOffset={onCursorOffsetChange} + /> + + + + {autoFocused ? `${figures.pointer} ` : ' '}Auto top up:{' '} + + + on + + / + + off + + + + ) +} + export function ProviderManager({ mode, onDone }: Props): React.ReactNode { const { columns: terminalColumns } = useTerminalSize() const inputColumns = Math.max(20, Math.min(80, terminalColumns - 4)) @@ -833,13 +969,65 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { const [aimlapiTopupAmountUsd, setAimlapiTopupAmountUsd] = React.useState( String(DEFAULT_AMOUNT_USD_MINOR / 100), ) - const [aimlapiTopupMethod, setAimlapiTopupMethod] = - React.useState('card') - const [aimlapiTopupPassword, setAimlapiTopupPassword] = React.useState('') + const [aimlapiSignInCode, setAimlapiSignInCode] = React.useState('') + const [aimlapiSessionToken, setAimlapiSessionToken] = React.useState('') + const [aimlapiIssuedKey, setAimlapiIssuedKey] = React.useState('') + const [aimlapiIssuedKeyId, setAimlapiIssuedKeyId] = React.useState('') + const [aimlapiTopupByKey, setAimlapiTopupByKey] = React.useState(false) + const [aimlapiResumeSessionToken, setAimlapiResumeSessionToken] = React.useState('') + const [, setAimlapiPaymentSessionId] = React.useState('') + const [aimlapiExistingProfileId, setAimlapiExistingProfileId] = React.useState(null) + const [aimlapiExistingUsesEnv, setAimlapiExistingUsesEnv] = React.useState(false) + const [aimlapiInferenceBaseUrl, setAimlapiInferenceBaseUrl] = React.useState( + () => resolveEndpoints().inferenceBaseUrl, + ) + const [aimlapiNewAccount, setAimlapiNewAccount] = React.useState(false) + const [aimlapiAutoTopUp, setAimlapiAutoTopUp] = React.useState(true) const [aimlapiTopupStatus, setAimlapiTopupStatus] = React.useState() const [aimlapiTopupDetail, setAimlapiTopupDetail] = React.useState() - const [isAimlapiTopupRunning, setIsAimlapiTopupRunning] = React.useState(false) + const [aimlapiDoneKind, setAimlapiDoneKind] = React.useState<'ready' | 'topup'>( + 'ready', + ) + const [, setIsAimlapiTopupRunning] = React.useState(false) + const [isAimlapiKeyValidating, setIsAimlapiKeyValidating] = React.useState(false) + const aimlapiAbortRef = React.useRef(null) + const aimlapiPersistedIntentRef = React.useRef< + (AimlapiTopupIntent & { paymentSessionId: string }) | null + >(null) + // True only once a top-up payment actually completes. `aimlapiTopupByKey` + // marks that the flow is driven by a saved key, not that money changed hands, + // so the done screen must key off this instead to avoid showing the "Top-up + // successful" copy when the user merely continued with a saved key. + const aimlapiTopupPaidRef = React.useRef(false) + + function resetAimlapiCheckoutIntent(): void { + if (aimlapiPersistedIntentRef.current) { + clearAimlapiTopupState(aimlapiPersistedIntentRef.current) + aimlapiPersistedIntentRef.current = null + } + setAimlapiResumeSessionToken('') + setAimlapiPaymentSessionId('') + } + + function resetAimlapiOnboardingIdentity(): void { + resetAimlapiCheckoutIntent() + setAimlapiSessionToken('') + setAimlapiIssuedKey('') + setAimlapiIssuedKeyId('') + setAimlapiTopupByKey(false) + aimlapiTopupPaidRef.current = false + setAimlapiNewAccount(false) + } + + React.useEffect(() => { + const cancelAimlapi = (): void => aimlapiAbortRef.current?.abort() + const unregister = registerCleanup(cancelAimlapi) + return () => { + unregister() + cancelAimlapi() + } + }, []) const [menuFocusValue, setMenuFocusValue] = React.useState() const [hasStoredCodexOAuthCredentials, setHasStoredCodexOAuthCredentials] = React.useState(false) @@ -1477,6 +1665,8 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { } function closeWithCancelled(message: string): void { + aimlapiAbortRef.current?.abort() + aimlapiAbortRef.current = null onDone({ action: 'cancelled', message: @@ -1578,7 +1768,10 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { const provider = defaults.provider ?? 'openai' const nextDraft = { name: defaults.name, - baseUrl: defaults.baseUrl, + baseUrl: + preset === 'aimlapi' + ? resolveEndpoints().inferenceBaseUrl + : defaults.baseUrl, model: defaults.model, apiKey: defaults.apiKey ?? '', apiFormat: 'chat_completions', @@ -1592,15 +1785,35 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { setPresetRequiresApiKey(defaults.requiresApiKey) setAimlapiTopupEmail('') setAimlapiTopupAmountUsd(String(DEFAULT_AMOUNT_USD_MINOR / 100)) - setAimlapiTopupMethod('card') - setAimlapiTopupPassword('') + aimlapiAbortRef.current?.abort() + aimlapiAbortRef.current = null + setAimlapiSignInCode('') + setAimlapiSessionToken('') + setAimlapiIssuedKey('') + setAimlapiIssuedKeyId('') + setAimlapiTopupByKey(false) + aimlapiTopupPaidRef.current = false + setAimlapiResumeSessionToken('') + setAimlapiPaymentSessionId('') + setAimlapiExistingProfileId(null) + setAimlapiExistingUsesEnv(false) + setAimlapiInferenceBaseUrl( + preset === 'aimlapi' ? nextDraft.baseUrl : resolveEndpoints().inferenceBaseUrl, + ) + setAimlapiNewAccount(false) + setAimlapiAutoTopUp(true) setAimlapiTopupStatus(undefined) setAimlapiTopupDetail(undefined) + setAimlapiDoneKind('ready') setIsAimlapiTopupRunning(false) setFormStepIndex(0) setCursorOffset(nextDraft.name.length) setErrorMessage(undefined) + if (preset === 'aimlapi' && mode === 'manage' && startExistingAimlapi(nextDraft)) { + return + } + if (preset === 'ollama') { setOllamaSelection({ state: 'loading' }) setScreen('select-ollama-model') @@ -1647,6 +1860,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { nextDraft: ProviderDraft = draft, provider: ProviderProfile['provider'] = draftProvider, profileId: string | null = editingProfileId, + options: { deferNavigation?: boolean; onSaved?: () => void } = {}, ): void { if ( provider === 'custom-anthropic' && @@ -1745,6 +1959,11 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { : finalSuccessMessage, ) + if (options.deferNavigation) { + options.onSaved?.() + return + } + if (mode === 'first-run') { onDone({ action: 'saved', @@ -1997,6 +2216,11 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { }) function handleBackFromPresetApiKey(): void { + if (draftProvider === 'aimlapi') { + aimlapiAbortRef.current?.abort() + aimlapiAbortRef.current = null + setIsAimlapiKeyValidating(false) + } setErrorMessage(undefined) setCursorOffset(draft.model.length) setScreen(draftProvider === 'aimlapi' ? 'aimlapi-api-key-choice' : 'preset-model') @@ -2018,7 +2242,21 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { isActive: screen === 'aimlapi-api-key-choice', }) + function handleBackFromAimlapiConfigured(): void { + aimlapiAbortRef.current?.abort() + aimlapiAbortRef.current = null + setIsAimlapiKeyValidating(false) + setErrorMessage(undefined) + setScreen('select-preset') + } + + useKeybinding('confirm:no', handleBackFromAimlapiConfigured, { + context: 'Settings', + isActive: screen === 'aimlapi-configured', + }) + function handleBackFromAimlapiTopupEmail(): void { + aimlapiAbortRef.current?.abort() setErrorMessage(undefined) setCursorOffset(0) setScreen('aimlapi-api-key-choice') @@ -2031,8 +2269,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { function handleBackFromAimlapiTopupAmount(): void { setErrorMessage(undefined) - setCursorOffset(aimlapiTopupPassword.length) - setScreen('aimlapi-topup-password') + setScreen(aimlapiNewAccount ? 'aimlapi-topup-email' : 'aimlapi-low-balance') } useKeybinding('confirm:no', handleBackFromAimlapiTopupAmount, { @@ -2040,35 +2277,48 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { isActive: screen === 'aimlapi-topup-amount', }) - function handleBackFromAimlapiTopupPassword(): void { + function handleBackFromAimlapiSignInCode(): void { + aimlapiAbortRef.current?.abort() setErrorMessage(undefined) - setAimlapiTopupPassword('') + setAimlapiSignInCode('') setCursorOffset(aimlapiTopupEmail.length) setScreen('aimlapi-topup-email') } - useKeybinding('confirm:no', handleBackFromAimlapiTopupPassword, { + useKeybinding('confirm:no', handleBackFromAimlapiSignInCode, { context: 'Settings', - isActive: screen === 'aimlapi-topup-password', + isActive: screen === 'aimlapi-signin-code', }) - function handleBackFromAimlapiTopupMethod(): void { + function handleBackFromAimlapiLowBalance(): void { setErrorMessage(undefined) - setCursorOffset(aimlapiTopupAmountUsd.length) - setScreen('aimlapi-topup-amount') + setScreen( + aimlapiExistingProfileId || aimlapiExistingUsesEnv + ? 'aimlapi-configured' + : 'aimlapi-api-key-choice', + ) } - useKeybinding('confirm:no', handleBackFromAimlapiTopupMethod, { + useKeybinding('confirm:no', handleBackFromAimlapiLowBalance, { context: 'Settings', - isActive: screen === 'aimlapi-topup-method', + isActive: screen === 'aimlapi-low-balance', }) function handleCancelAimlapiTopupProgress(): void { - if (isAimlapiTopupRunning) { - return - } + aimlapiAbortRef.current?.abort() + aimlapiAbortRef.current = null + setIsAimlapiTopupRunning(false) setErrorMessage(undefined) - setScreen('aimlapi-api-key-choice') + setScreen( + aimlapiTopupStatus === 'checking-account' || + aimlapiTopupStatus === 'sending-code' || + aimlapiTopupStatus === 'creating-account' + ? 'aimlapi-topup-email' + : aimlapiTopupStatus === 'verifying-code' || + aimlapiTopupStatus === 'creating-key' + ? 'aimlapi-signin-code' + : 'aimlapi-topup-amount', + ) } useKeybinding('confirm:no', handleCancelAimlapiTopupProgress, { @@ -2076,6 +2326,31 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { isActive: screen === 'aimlapi-topup-progress', }) + function finishAimlapiDone(): void { + if (mode === 'first-run') { + const active = getActiveProviderProfile() + onDone({ + action: 'saved', + activeProfileId: active?.id, + activeProviderName: active?.name, + activeProviderModel: active ? getPrimaryModel(active.model) : undefined, + message: `Provider configured: ${active?.name ?? 'aimlapi.com'}`, + }) + return + } + returnToMenu() + } + + useKeybinding('confirm:yes', finishAimlapiDone, { + context: 'Confirmation', + isActive: screen === 'aimlapi-done', + }) + + useKeybinding('confirm:no', finishAimlapiDone, { + context: 'Confirmation', + isActive: screen === 'aimlapi-done', + }) + // xAI OAuth setup renders a TextInput for the manual-code recovery // path, which registers its own useInput listener. The child-component // useKeybinding inside XaiOAuthSetup ends up racing the input handler @@ -2313,6 +2588,40 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { setDraft(nextDraft) setErrorMessage(undefined) + if (draftProvider === 'aimlapi') { + // An already-resolved existing credential (saved profile or an + // ambient env key adopted earlier, e.g. after a top-up) must + // complete through persistExistingAimlapi so the paid-completion + // path (aimlapiTopupPaidRef) is honored, instead of being + // re-detected into the plain "ready" flow below. + if (aimlapiExistingProfileId || aimlapiExistingUsesEnv) { + persistExistingAimlapi(nextDraft.model) + return + } + const envKey = resolveRouteCredentialValue({ + routeId: 'aimlapi', + baseUrl: nextDraft.baseUrl, + })?.trim() + if ( + mode === 'first-run' && + envKey && + isCanonicalAimlapiInferenceBaseUrl(nextDraft.baseUrl) + ) { + setAimlapiIssuedKey(envKey) + setAimlapiExistingUsesEnv(true) + void validateAndPersistAimlapiKey( + envKey, + nextDraft.baseUrl, + nextDraft.model, + { preserveEnv: true }, + ) + return + } + if (mode === 'manage' && startExistingAimlapi(nextDraft)) { + return + } + } + if (needsApiKey) { setCursorOffset(0) setScreen( @@ -2342,14 +2651,72 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { } function renderPresetApiKey(): React.ReactNode { + const submitApiKey = (value: string): void => { + const apiKey = value.trim() + if (!apiKey) { + setErrorMessage(`API key is required for ${draft.name}.`) + return + } + + const nextDraft = applyPresetApiFormat( + { + ...draft, + apiKey, + }, + draftProvider, + ) + setDraft(nextDraft) + setErrorMessage(undefined) + if (draftProvider === 'aimlapi') { + void validateAndPersistAimlapiKey(apiKey, nextDraft.baseUrl, nextDraft.model) + return + } + persistDraft(nextDraft, draftProvider, null) + } + + if (draftProvider === 'aimlapi') { + return ( + + + {AIMLAPI_MESSAGES.apiKeyInputPrompt} + + {AIMLAPI_MESSAGES.apiKeyHiddenHint} + + API key: + + setDraft(prev => ({ + ...prev, + apiKey: value, + })) + } + onSubmit={submitApiKey} + focus={!isAimlapiKeyValidating} + showCursor={!isAimlapiKeyValidating} + placeholder={`Paste your key${figures.ellipsis}`} + mask="*" + columns={inputColumns} + cursorOffset={cursorOffset} + onChangeCursorOffset={setCursorOffset} + /> + + {isAimlapiKeyValidating ? : null} + {errorMessage && {errorMessage}} + + Press Enter to save. Press Esc to go back. + + + ) + } + return ( Create provider profile - Enter the API key for {draft.name}. Other preset details are already - configured. + Enter the API key for {draft.name}. Other preset details are already configured. Provider type:{' '} @@ -2366,24 +2733,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { apiKey: value, })) } - onSubmit={value => { - const apiKey = value.trim() - if (!apiKey) { - setErrorMessage(`API key is required for ${draft.name}.`) - return - } - - const nextDraft = applyPresetApiFormat( - { - ...draft, - apiKey, - }, - draftProvider, - ) - setDraft(nextDraft) - setErrorMessage(undefined) - persistDraft(nextDraft, draftProvider, null) - }} + onSubmit={submitApiKey} focus={true} showCursor={true} placeholder={`Enter API key${figures.ellipsis}`} @@ -2401,125 +2751,582 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { ) } - function startAimlapiTopup( - email: string, - password: string, - method: PaymentMethod = aimlapiTopupMethod, + async function validateAndPersistAimlapiKey( + apiKey: string, + baseUrl: string, + model: string, + options: { preserveEnv?: boolean } = {}, + ): Promise { + aimlapiAbortRef.current?.abort() + const controller = new AbortController() + aimlapiAbortRef.current = controller + setIsAimlapiKeyValidating(true) + setErrorMessage(undefined) + + try { + const balance = await validateAimlapiApiKey( + apiKey, + controller.signal, + baseUrl, + ) + if (controller.signal.aborted) return + if (balance.lowBalance) { + setAimlapiIssuedKey(apiKey.trim()) + setAimlapiIssuedKeyId('') + setAimlapiTopupByKey(true) + setAimlapiExistingUsesEnv(options.preserveEnv === true) + setIsAimlapiKeyValidating(false) + setScreen('aimlapi-low-balance') + return + } + persistAimlapiKey(apiKey, baseUrl, model, 'ready', options) + } catch (error) { + if (controller.signal.aborted) return + const status = + typeof error === 'object' && error !== null && 'status' in error + ? Number(error.status) + : undefined + if (status === 401 || status === 403) { + setDraft(prev => ({ ...prev, apiKey: '' })) + setCursorOffset(0) + setErrorMessage(AIMLAPI_MESSAGES.apiKeyInvalid) + return + } + const detail = safeAimlapiErrorMessage(error, [apiKey]) + setErrorMessage(detail) + } finally { + if (aimlapiAbortRef.current === controller) aimlapiAbortRef.current = null + if (!controller.signal.aborted) setIsAimlapiKeyValidating(false) + } + } + + function existingAimlapiCredential(): { + apiKey: string + profile?: ProviderProfile + usesEnv: boolean + inferenceBaseUrl: string + } | null { + const isAimlapiProfile = (profile: ProviderProfile): boolean => + profile.provider === 'aimlapi' || + resolveRouteIdFromBaseUrl(profile.baseUrl) === 'aimlapi' + const inferenceBaseUrl = resolveEndpoints().inferenceBaseUrl + if (!isCanonicalAimlapiInferenceBaseUrl(inferenceBaseUrl)) return null + const envKey = resolveRouteCredentialValue({ + routeId: 'aimlapi', + baseUrl: inferenceBaseUrl, + })?.trim() + const active = profiles.find(profile => profile.id === activeProfileId) + const candidates = active + ? [active, ...profiles.filter(profile => profile.id !== active.id)] + : profiles + for (const profile of candidates) { + if (!isAimlapiProfile(profile)) continue + // Saved credentials are eligible for the guided balance/top-up preflight + // only on the production catalog endpoint. A proxy/staging profile remains + // usable normally, but its key must never be sent to another environment. + if (!isCanonicalAimlapiInferenceBaseUrl(profile.baseUrl)) continue + const apiKey = profile.apiKey?.trim() + if (apiKey) { + return { + apiKey, + profile, + usesEnv: false, + inferenceBaseUrl: profile.baseUrl, + } + } + if (envKey) { + return { + apiKey: envKey, + profile, + usesEnv: true, + inferenceBaseUrl: profile.baseUrl, + } + } + } + return envKey + ? { + apiKey: envKey, + usesEnv: true, + inferenceBaseUrl, + } + : null + } + + function persistExistingAimlapi(model = draft.model): void { + const profile = aimlapiExistingProfileId + ? profiles.find(candidate => candidate.id === aimlapiExistingProfileId) + : undefined + if (profile) { + const nextDraft = applyPresetApiFormat( + { ...toDraft(profile), model }, + profile.provider, + ) + setDraft(nextDraft) + persistDraft(nextDraft, profile.provider, profile.id, { + deferNavigation: true, + onSaved: () => { + resetAimlapiCheckoutIntent() + clearAimlapiSignInKey(aimlapiTopupEmail, aimlapiIssuedKeyId) + setAimlapiDoneKind(aimlapiTopupPaidRef.current ? 'topup' : 'ready') + setErrorMessage(undefined) + setScreen('aimlapi-done') + }, + }) + return + } + persistAimlapiKey( + aimlapiIssuedKey, + resolveEndpoints().inferenceBaseUrl, + model, + aimlapiTopupPaidRef.current ? 'topup' : 'ready', + { preserveEnv: aimlapiExistingUsesEnv }, + ) + } + + function startExistingAimlapi(nextDraft: ProviderDraft): boolean { + const existing = existingAimlapiCredential() + if (!existing) return false + setDraft({ + ...nextDraft, + baseUrl: existing.profile?.baseUrl ?? existing.inferenceBaseUrl, + }) + setAimlapiIssuedKey(existing.apiKey) + setAimlapiIssuedKeyId('') + setAimlapiExistingProfileId(existing.profile?.id ?? null) + setAimlapiExistingUsesEnv(existing.usesEnv) + setAimlapiInferenceBaseUrl(existing.inferenceBaseUrl) + setAimlapiTopupByKey(true) + setScreen('aimlapi-configured') + return true + } + + function useExistingAimlapi(): void { + const apiKey = aimlapiIssuedKey.trim() + if (!apiKey) { + setErrorMessage('The existing AI/ML API key is unavailable. Configure again.') + return + } + // Continuing with a saved key is not a payment; clear any stale paid flag + // from an earlier top-up so the done screen shows "Everything is ready." + aimlapiTopupPaidRef.current = false + aimlapiAbortRef.current?.abort() + const controller = new AbortController() + aimlapiAbortRef.current = controller + setIsAimlapiKeyValidating(true) + setErrorMessage(undefined) + void (async () => { + try { + const balance = await validateAimlapiApiKey( + apiKey, + controller.signal, + aimlapiInferenceBaseUrl, + ) + if (controller.signal.aborted) return + setIsAimlapiKeyValidating(false) + if (balance.lowBalance) { + setScreen('aimlapi-low-balance') + } else { + setCursorOffset(draft.model.length) + setScreen('preset-model') + } + } catch (error) { + if (controller.signal.aborted) return + setIsAimlapiKeyValidating(false) + const status = error instanceof AimlapiApiError ? error.status : undefined + setErrorMessage( + status === 401 || status === 403 + ? 'The existing AI/ML API key is invalid. Configure again.' + : safeAimlapiErrorMessage(error, [apiKey]), + ) + } finally { + if (aimlapiAbortRef.current === controller) aimlapiAbortRef.current = null + } + })() + } + + function persistAimlapiKey( + apiKey: string, + baseUrl: string, + model = draft.model, + doneKind: 'ready' | 'topup' = 'ready', + options: { preserveEnv?: boolean } = {}, ): void { + const nextDraft = applyPresetApiFormat( + { + ...draft, + apiKey: options.preserveEnv ? '' : apiKey.trim(), + baseUrl, + model, + }, + draftProvider, + ) + setDraft(nextDraft) + persistDraft(nextDraft, draftProvider, null, { + deferNavigation: true, + onSaved: () => { + resetAimlapiCheckoutIntent() + clearAimlapiSignInKey(aimlapiTopupEmail, aimlapiIssuedKeyId) + setAimlapiDoneKind(doneKind) + setErrorMessage(undefined) + setScreen('aimlapi-done') + }, + }) + } + + function startAimlapiEmailOnboarding(email: string): void { const trimmedEmail = email.trim() - const amountUsd = aimlapiTopupAmountUsd.trim() - const parsedAmountUsd = Number(amountUsd) - if (!trimmedEmail) { - setErrorMessage('AI/ML API email is required.') - setScreen('aimlapi-topup-email') + if (!isValidAimlapiEmail(trimmedEmail)) { + setErrorMessage(AIMLAPI_MESSAGES.emailInvalid) return } - if (!Number.isFinite(parsedAmountUsd) || parsedAmountUsd <= 0) { - setErrorMessage('Enter a valid top-up amount in USD.') - setScreen('aimlapi-topup-amount') + // Submitting the email starts a fresh account-bound flow. Retaining a + // checkout from an earlier email/key path could poll or exchange the wrong + // payment intent, so retries that should resume stay on the amount screen. + resetAimlapiOnboardingIdentity() + aimlapiAbortRef.current?.abort() + const controller = new AbortController() + aimlapiAbortRef.current = controller + setAimlapiTopupEmail(trimmedEmail) + setAimlapiTopupStatus('checking-account') + setAimlapiTopupDetail(undefined) + setErrorMessage(undefined) + setIsAimlapiTopupRunning(true) + setScreen('aimlapi-topup-progress') + + void (async () => { + try { + const account = await beginAimlapiEmailOnboarding( + trimmedEmail, + controller.signal, + ) + if (account.action === 'code-sent') { + setAimlapiTopupStatus('sending-code') + if (controller.signal.aborted) return + setAimlapiNewAccount(false) + setAimlapiSignInCode('') + setCursorOffset(0) + setIsAimlapiTopupRunning(false) + setScreen('aimlapi-signin-code') + return + } + setAimlapiTopupStatus('creating-account') + if (controller.signal.aborted) return + setAimlapiNewAccount(true) + setAimlapiSessionToken(account.sessionToken) + setCursorOffset(aimlapiTopupAmountUsd.length) + setIsAimlapiTopupRunning(false) + setScreen('aimlapi-topup-amount') + } catch (error) { + if (controller.signal.aborted) return + setIsAimlapiTopupRunning(false) + setErrorMessage( + safeAimlapiErrorMessage(error, [trimmedEmail]), + ) + setCursorOffset(trimmedEmail.length) + setScreen('aimlapi-topup-email') + } finally { + if (aimlapiAbortRef.current === controller) aimlapiAbortRef.current = null + } + })() + } + + function verifyAimlapiSignInCode(code: string): void { + const trimmedCode = code.trim() + if (!trimmedCode) { + setErrorMessage(AIMLAPI_MESSAGES.codeIncorrect) return } - if (Math.round(parsedAmountUsd * 100) < MIN_AMOUNT_USD_MINOR) { - setErrorMessage(`Minimum AI/ML API top-up is $${MIN_AMOUNT_USD_MINOR / 100}.`) + aimlapiAbortRef.current?.abort() + const controller = new AbortController() + aimlapiAbortRef.current = controller + setAimlapiTopupStatus('verifying-code') + setErrorMessage(undefined) + setIsAimlapiTopupRunning(true) + setScreen('aimlapi-topup-progress') + + void (async () => { + try { + // Reuse a key already minted for this email (e.g. after closing before + // amount entry or restarting a checkout) instead of creating another. + const retainedSignInKey = loadAimlapiSignInKey(aimlapiTopupEmail) + const result = await completeAimlapiCodeSignIn( + aimlapiTopupEmail, + trimmedCode, + controller.signal, + aimlapiInferenceBaseUrl, + retainedSignInKey ?? undefined, + ) + // Persist immediately so an abort/restart before the checkout completes + // recovers this key rather than minting a second one. + saveAimlapiSignInKey(aimlapiTopupEmail, result.apiKey, result.apiKeyId) + setAimlapiSessionToken(result.sessionToken) + setAimlapiIssuedKey(result.apiKey) + setAimlapiIssuedKeyId(result.apiKeyId) + if (controller.signal.aborted) return + setIsAimlapiTopupRunning(false) + if (result.balanceStatus === 'unknown') { + setDraft(prev => ({ ...prev, apiKey: result.apiKey })) + setCursorOffset(result.apiKey.length) + setErrorMessage( + safeAimlapiErrorMessage(result.balanceError, [result.apiKey]), + ) + setScreen('preset-api-key') + return + } + if (result.lowBalance) { + setScreen('aimlapi-low-balance') + } else { + persistAimlapiKey(result.apiKey, aimlapiInferenceBaseUrl) + } + } catch (error) { + if (controller.signal.aborted) return + setIsAimlapiTopupRunning(false) + setErrorMessage( + error instanceof AimlapiApiError && error.status === 400 + ? AIMLAPI_MESSAGES.codeIncorrect + : safeAimlapiErrorMessage(error, [ + aimlapiTopupEmail, + trimmedCode, + aimlapiSessionToken, + ]), + ) + setCursorOffset(trimmedCode.length) + setScreen('aimlapi-signin-code') + } finally { + if (aimlapiAbortRef.current === controller) aimlapiAbortRef.current = null + } + })() + } + + function startAimlapiTopup(autoTopUp = aimlapiAutoTopUp): void { + const amountUsd = aimlapiTopupAmountUsd.trim() + if (!amountUsd) { + setErrorMessage(AIMLAPI_MESSAGES.amountRequired) setScreen('aimlapi-topup-amount') return } - if (Math.round(parsedAmountUsd * 100) > MAX_AMOUNT_USD_MINOR) { - setErrorMessage(`Maximum AI/ML API top-up is $${MAX_AMOUNT_USD_MINOR / 100}.`) + let amountUsdMinor: number + try { + amountUsdMinor = parseAimlapiAmountUsd(amountUsd) + } catch (error) { + setErrorMessage(error instanceof Error ? error.message : String(error)) setScreen('aimlapi-topup-amount') return } - if (!password) { - setErrorMessage('AI/ML API password is required.') - setScreen('aimlapi-topup-password') + if (!aimlapiTopupByKey && !aimlapiSessionToken.trim()) { + setErrorMessage('Your AI/ML API session expired. Enter your email again.') + setScreen('aimlapi-topup-email') + return + } + + const endpoints = resolveEndpoints() + const intentIdentity = aimlapiTopupByKey + ? `key:${createHash('sha256').update(aimlapiIssuedKey).digest('hex')}` + : aimlapiTopupEmail.trim().toLowerCase() + const intent: AimlapiTopupIntent = { + email: intentIdentity, + amountUsdMinor, + autoTopUp, + partnerId: resolvePartnerId(), + partnerName: DEFAULT_PARTNER_NAME, + appBaseUrl: endpoints.appBaseUrl.trim().replace(/\/+$/, ''), + inferenceBaseUrl: aimlapiInferenceBaseUrl.trim().replace(/\/+$/, ''), + payBaseUrl: endpoints.payBaseUrl.trim().replace(/\/+$/, ''), + verificationBaseUrl: endpoints.verificationBaseUrl.trim().replace(/\/+$/, ''), + } + let checkoutState: ReturnType + try { + checkoutState = claimAimlapiTopupState(intent) + } catch (error) { + setErrorMessage(safeAimlapiErrorMessage(error, [aimlapiIssuedKey])) + setScreen('aimlapi-topup-amount') return } + aimlapiPersistedIntentRef.current = { + ...intent, + paymentSessionId: checkoutState.paymentSessionId, + } + setAimlapiPaymentSessionId(checkoutState.paymentSessionId) + setAimlapiResumeSessionToken(checkoutState.resumeSessionToken) + aimlapiAbortRef.current?.abort() + const controller = new AbortController() + aimlapiAbortRef.current = controller setScreen('aimlapi-topup-progress') setErrorMessage(undefined) - setAimlapiTopupStatus('signing-in') + setAimlapiTopupStatus('creating-session') setAimlapiTopupDetail(undefined) setIsAimlapiTopupRunning(true) void (async () => { try { - const provisioned = await provisionAimlapiKey({ - email: trimmedEmail, - password, - amountUsd, - method, - model: draft.model, - onStatus: (status, detail) => { - setAimlapiTopupStatus(status) - setAimlapiTopupDetail(detail) - }, - }) - const nextDraft = applyPresetApiFormat( - { - ...draft, - apiKey: provisioned.apiKey, - baseUrl: provisioned.baseUrl, - model: provisioned.model, - }, - draftProvider, - ) - setDraft(nextDraft) - setAimlapiTopupPassword('') + const reportStatus = (status: AimlapiTopupStatus, detail?: string): void => { + setAimlapiTopupStatus(status) + if (detail?.trim()) setAimlapiTopupDetail(detail) + } + const reportSession = (sessionToken: string): void => { + if (!sessionToken) { + resetAimlapiCheckoutIntent() + return + } + checkoutState.resumeSessionToken = sessionToken + saveAimlapiTopupState({ ...intent, ...checkoutState }) + setAimlapiResumeSessionToken(sessionToken) + } + const provisioned = aimlapiTopupByKey + ? await topUpAimlapiByApiKey({ + apiKey: aimlapiIssuedKey, + inferenceBaseUrl: aimlapiInferenceBaseUrl, + amountUsd, + autoTopUp, + model: draft.model, + paymentSessionId: checkoutState.paymentSessionId, + resumeSessionToken: checkoutState.resumeSessionToken, + signal: controller.signal, + onStatus: reportStatus, + onSession: reportSession, + }) + : await provisionAimlapiKey({ + amountUsd, + autoTopUp, + model: draft.model, + sessionToken: aimlapiSessionToken, + inferenceBaseUrl: aimlapiInferenceBaseUrl, + exchange: aimlapiNewAccount, + paymentSessionId: checkoutState.paymentSessionId, + existingApiKey: aimlapiIssuedKey, + existingApiKeyId: aimlapiIssuedKeyId, + resumeSessionToken: checkoutState.resumeSessionToken, + signal: controller.signal, + onStatus: reportStatus, + onSession: reportSession, + }) + if (controller.signal.aborted) return setIsAimlapiTopupRunning(false) - persistDraft(nextDraft, draftProvider, null) + // A payment just cleared, so the done screen should report the top-up + // regardless of whether we route through the model picker first. + aimlapiTopupPaidRef.current = true + if (aimlapiTopupByKey) { + if (aimlapiExistingProfileId || aimlapiExistingUsesEnv) { + setCursorOffset(provisioned.model.length) + setScreen('preset-model') + } else { + persistExistingAimlapi(provisioned.model) + } + } else { + persistAimlapiKey( + provisioned.apiKey, + provisioned.baseUrl, + provisioned.model, + 'topup', + ) + } } catch (error) { - const detail = error instanceof Error ? error.message : String(error) + if (controller.signal.aborted) return + const detail = safeAimlapiErrorMessage(error, [ + aimlapiIssuedKey, + aimlapiTopupEmail, + aimlapiSignInCode, + aimlapiSessionToken, + aimlapiResumeSessionToken, + ]) setIsAimlapiTopupRunning(false) - setErrorMessage(`Could not finish AI/ML API top-up: ${detail}`) + setErrorMessage(`${AIMLAPI_MESSAGES.topUpFailed} ${detail}`) + setCursorOffset(amountUsd.length) + setScreen('aimlapi-topup-amount') + } finally { + if (aimlapiAbortRef.current === controller) aimlapiAbortRef.current = null } })() } + function renderAimlapiConfigured(): React.ReactNode { + if (isAimlapiKeyValidating) { + return ( + + aimlapi.com account is already configured + + + Checking balance... + + + ) + } + return ( + + aimlapi.com account is already configured + { setErrorMessage(undefined) if (value === 'manual') { + resetAimlapiOnboardingIdentity() setCursorOffset(draft.apiKey.length) setScreen('preset-api-key') return } - const envEmail = process.env.AIMLAPI_EMAIL?.trim() ?? '' - const envPassword = process.env.AIMLAPI_PASSWORD ?? '' - if (envEmail && envPassword) { - setAimlapiTopupEmail(envEmail) - setAimlapiTopupPassword(envPassword) - setCursorOffset(aimlapiTopupAmountUsd.length) - setScreen('aimlapi-topup-amount') + // Guided provisioning mints a production-account key via production + // auth; it must never be written against a non-canonical inference + // endpoint. Pasting an existing key stays allowed for custom + // endpoints (handled by the 'manual' branch above). + if (!isCanonicalAimlapiInferenceBaseUrl(aimlapiInferenceBaseUrl)) { + setErrorMessage(AIMLAPI_MESSAGES.guidedNeedsCanonicalEndpoint) return } + + resetAimlapiOnboardingIdentity() + const envEmail = process.env.AIMLAPI_EMAIL?.trim() ?? '' setCursorOffset(envEmail.length) setAimlapiTopupEmail(envEmail) setScreen('aimlapi-topup-email') @@ -2539,13 +3346,8 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { return ( - AI/ML API top-up - - - Enter your AI/ML API account email. The checkout flow will use it to - register or sign in. + {AIMLAPI_MESSAGES.enterEmail} - Step 2 of 2: Top up account {figures.pointer} { const email = value.trim() - if (!email) { - setErrorMessage('AI/ML API email is required.') - return - } - setAimlapiTopupEmail(email) - setErrorMessage(undefined) - setCursorOffset(0) - setScreen('aimlapi-topup-password') + startAimlapiEmailOnboarding(email) }} focus={true} showCursor={true} @@ -2578,169 +3373,156 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { ) } - function renderAimlapiTopupAmount(): React.ReactNode { + function renderAimlapiSignInCode(): React.ReactNode { return ( - AI/ML API top-up - - - Choose a top-up amount in USD. Minimum is ${MIN_AMOUNT_USD_MINOR / 100}. + {AIMLAPI_MESSAGES.codeSent(aimlapiTopupEmail)} - Step 2 of 2: Top up account {figures.pointer} { - const amountUsd = value.trim() - const parsedAmountUsd = Number(amountUsd) - if (!Number.isFinite(parsedAmountUsd) || parsedAmountUsd <= 0) { - setErrorMessage('Enter a valid top-up amount in USD.') - return - } - if (Math.round(parsedAmountUsd * 100) < MIN_AMOUNT_USD_MINOR) { - setErrorMessage(`Minimum AI/ML API top-up is $${MIN_AMOUNT_USD_MINOR / 100}.`) - return - } - if (Math.round(parsedAmountUsd * 100) > MAX_AMOUNT_USD_MINOR) { - setErrorMessage(`Maximum AI/ML API top-up is $${MAX_AMOUNT_USD_MINOR / 100}.`) - return - } - setAimlapiTopupAmountUsd(amountUsd) - setErrorMessage(undefined) - setScreen('aimlapi-topup-method') - }} + value={aimlapiSignInCode} + onChange={setAimlapiSignInCode} + onSubmit={verifyAimlapiSignInCode} focus={true} showCursor={true} - placeholder={`Enter amount${figures.ellipsis}`} + mask="*" + placeholder={`6-digit code${figures.ellipsis}`} columns={inputColumns} cursorOffset={cursorOffset} onChangeCursorOffset={setCursorOffset} /> {errorMessage && {errorMessage}} - - Press Enter to continue. Press Esc to go back. - + Press Enter to continue. Press Esc to go back. ) } - function renderAimlapiTopupPassword(): React.ReactNode { + function renderAimlapiLowBalance(): React.ReactNode { return ( - - AI/ML API top-up - - - Enter your AI/ML API password. The CLI will open checkout and save the - issued API key after payment. - - Step 2 of 2: Top up account - - {figures.pointer} - { - if (!value) { - setErrorMessage('AI/ML API password is required.') - return + {AIMLAPI_MESSAGES.lowBalance} + { - const method: PaymentMethod = value === 'crypto' ? 'crypto' : 'card' - setAimlapiTopupMethod(method) - startAimlapiTopup(aimlapiTopupEmail, aimlapiTopupPassword, method) + { + if (value !== aimlapiTopupAmountUsd) { + resetAimlapiCheckoutIntent() + } + setAimlapiTopupAmountUsd(value) + setErrorMessage(undefined) }} - onCancel={handleBackFromAimlapiTopupMethod} - visibleOptionCount={2} + onCursorOffsetChange={setCursorOffset} + onAutoTopUpChange={value => { + if (value !== aimlapiAutoTopUp) { + resetAimlapiCheckoutIntent() + } + setAimlapiAutoTopUp(value) + }} + onSubmit={startAimlapiTopup} /> {errorMessage && {errorMessage}} - - Press Enter to open checkout. Press Esc to go back. - ) } function renderAimlapiTopupProgress(): React.ReactNode { - const labels: Record = { - registering: 'Registering AI/ML API account...', - registered: 'Account registered.', - 'signing-in': 'Signing in to AI/ML API...', - 'signed-in': 'Signed in.', - 'creating-session': 'Creating checkout session...', - 'opening-checkout': 'Opening checkout...', - 'waiting-payment': 'Waiting for payment...', - 'provisioning-key': 'Issuing API key...', - } - const status = aimlapiTopupStatus - ? labels[aimlapiTopupStatus] - : 'Preparing AI/ML API top-up...' - return ( - - AI/ML API top-up - - {status} - {aimlapiTopupDetail ? {aimlapiTopupDetail} : null} + {aimlapiTopupDetail ? ( + <> + Opening checkout in browser... + {AIMLAPI_MESSAGES.topUpBrowserFallback} + {/* Stripe Checkout URLs are signed and can require their query and + fragment verbatim. This is an explicit user-facing fallback, + not a log field, so redacting it would make the link unusable. */} + + {wrapAimlapiCheckoutUrl( + aimlapiTopupDetail, + terminalColumns - 4, + ).map((line, index) => ( + {line} + ))} + + + ) : ( + + )} {errorMessage ? {errorMessage} : null} - - {isAimlapiTopupRunning - ? 'Complete checkout in the browser. This screen will continue automatically.' - : 'Press Esc to go back.'} - + + ) + } + + function renderAimlapiDone(): React.ReactNode { + // Only parse the amount for the top-up screen. When funding is skipped + // (e.g. after an invalid amount), aimlapiTopupAmountUsd may hold an unparsable + // value, and the "ready" screen never shows it — parsing it would throw. + let topUpBody: React.ReactNode = null + if (aimlapiDoneKind === 'topup') { + const amountUsdMinor = parseAimlapiAmountUsd(aimlapiTopupAmountUsd) + const amountUsd = + amountUsdMinor % 100 === 0 + ? String(amountUsdMinor / 100) + : (amountUsdMinor / 100).toFixed(2) + topUpBody = ( + <> + {AIMLAPI_MESSAGES.topUpSuccess(amountUsd)} + {aimlapiNewAccount ? ( + <> + + {AIMLAPI_MESSAGES.successMagicLink(aimlapiTopupEmail)} + + ) : null} + + ) + } + return ( + + {aimlapiDoneKind === 'topup' ? ( + topUpBody + ) : ( + {AIMLAPI_MESSAGES.everythingRuns} + )} + + Press Enter to continue. ) } @@ -3175,21 +3957,27 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { case 'aimlapi-api-key-choice': content = renderAimlapiApiKeyChoice() break + case 'aimlapi-configured': + content = renderAimlapiConfigured() + break case 'aimlapi-topup-email': content = renderAimlapiTopupEmail() break - case 'aimlapi-topup-amount': - content = renderAimlapiTopupAmount() + case 'aimlapi-signin-code': + content = renderAimlapiSignInCode() break - case 'aimlapi-topup-password': - content = renderAimlapiTopupPassword() + case 'aimlapi-low-balance': + content = renderAimlapiLowBalance() break - case 'aimlapi-topup-method': - content = renderAimlapiTopupMethod() + case 'aimlapi-topup-amount': + content = renderAimlapiTopupAmount() break case 'aimlapi-topup-progress': content = renderAimlapiTopupProgress() break + case 'aimlapi-done': + content = renderAimlapiDone() + break case 'preset-api-key': content = renderPresetApiKey() break diff --git a/src/components/providerManagerAimlapi.ts b/src/components/providerManagerAimlapi.ts new file mode 100644 index 0000000000..56c68a6dee --- /dev/null +++ b/src/components/providerManagerAimlapi.ts @@ -0,0 +1,74 @@ +import { + provisionAimlapiKey as provisionAimlapiKeyImpl, + topUpAimlapiByApiKey as topUpAimlapiByApiKeyImpl, + parseAimlapiAmountUsd as parseAimlapiAmountUsdImpl, + isValidAimlapiEmail as isValidAimlapiEmailImpl, + beginAimlapiEmailOnboarding as beginAimlapiEmailOnboardingImpl, + completeAimlapiCodeSignIn as completeAimlapiCodeSignInImpl, + validateAimlapiApiKey as validateAimlapiApiKeyImpl, +} from '../integrations/aimlapi/index.js' +import { + claimAimlapiTopupState as claimAimlapiTopupStateImpl, + clearAimlapiTopupState as clearAimlapiTopupStateImpl, + saveAimlapiTopupState as saveAimlapiTopupStateImpl, + loadAimlapiSignInKey as loadAimlapiSignInKeyImpl, + saveAimlapiSignInKey as saveAimlapiSignInKeyImpl, + clearAimlapiSignInKey as clearAimlapiSignInKeyImpl, +} from '../integrations/aimlapi/topupState.js' +import type { + AimlapiPersistedTopup, + AimlapiTopupIntent, +} from '../integrations/aimlapi/topupState.js' + +export { + AimlapiApiError, + AIMLAPI_MESSAGES, + type AimlapiTopupStatus, +} from '../integrations/aimlapi/index.js' +export type { AimlapiPersistedTopup, AimlapiTopupIntent } + +export const provisionAimlapiKey: typeof provisionAimlapiKeyImpl = options => + provisionAimlapiKeyImpl(options) + +export const topUpAimlapiByApiKey: typeof topUpAimlapiByApiKeyImpl = options => + topUpAimlapiByApiKeyImpl(options) + +export const parseAimlapiAmountUsd: typeof parseAimlapiAmountUsdImpl = value => + parseAimlapiAmountUsdImpl(value) + +export const isValidAimlapiEmail: typeof isValidAimlapiEmailImpl = value => + isValidAimlapiEmailImpl(value) + +export const beginAimlapiEmailOnboarding: typeof beginAimlapiEmailOnboardingImpl = ( + ...args +) => beginAimlapiEmailOnboardingImpl(...args) + +export const completeAimlapiCodeSignIn: typeof completeAimlapiCodeSignInImpl = ( + ...args +) => completeAimlapiCodeSignInImpl(...args) + +export const validateAimlapiApiKey: typeof validateAimlapiApiKeyImpl = (...args) => + validateAimlapiApiKeyImpl(...args) + +export const claimAimlapiTopupState: typeof claimAimlapiTopupStateImpl = intent => + claimAimlapiTopupStateImpl(intent) + +export const clearAimlapiTopupState: typeof clearAimlapiTopupStateImpl = intent => + clearAimlapiTopupStateImpl(intent) + +export const saveAimlapiTopupState: typeof saveAimlapiTopupStateImpl = state => + saveAimlapiTopupStateImpl(state) + +export const loadAimlapiSignInKey: typeof loadAimlapiSignInKeyImpl = email => + loadAimlapiSignInKeyImpl(email) + +export const saveAimlapiSignInKey: typeof saveAimlapiSignInKeyImpl = ( + email, + apiKey, + apiKeyId, +) => saveAimlapiSignInKeyImpl(email, apiKey, apiKeyId) + +export const clearAimlapiSignInKey: typeof clearAimlapiSignInKeyImpl = ( + email, + apiKeyId, +) => clearAimlapiSignInKeyImpl(email, apiKeyId) diff --git a/src/integrations/aimlapi/client.test.ts b/src/integrations/aimlapi/client.test.ts new file mode 100644 index 0000000000..24029bab11 --- /dev/null +++ b/src/integrations/aimlapi/client.test.ts @@ -0,0 +1,296 @@ +import { afterEach, expect, mock, test } from 'bun:test' + +import { AimlapiApiError, AimlapiClient } from './client.js' +import type { AimlapiEndpoints } from './config.js' + +const originalFetch = globalThis.fetch +afterEach(() => { + globalThis.fetch = originalFetch +}) + +const endpoints: AimlapiEndpoints = { + authBaseUrl: 'https://auth.example.test', + appBaseUrl: 'https://app.example.test', + inferenceBaseUrl: 'https://api.example.test/v1', + payBaseUrl: 'https://pay.example.test', + verificationBaseUrl: 'https://front.example.test', +} + +function jsonResponse(value: unknown): Response { + return new Response(JSON.stringify(value), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }) +} + +test('passwordless onboarding methods use the current backend contracts', async () => { + const calls: Array<{ url: string; init?: RequestInit; body?: unknown }> = [] + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input) + calls.push({ + url, + init, + body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, + }) + if (url.endsWith('/v1/auth/account') && init?.method === 'PATCH') { + return jsonResponse({ action: 'sign-in' }) + } + if (url.endsWith('/code/verify')) return jsonResponse({ token: 'bearer', exp: 1 }) + if (url.endsWith('/passwordless')) return jsonResponse({ token: 'new-bearer', exp: 2 }) + if (url.endsWith('/v1/keys')) return jsonResponse({ key: 'key_test', id: 'id_test' }) + if (url.endsWith('/billing/balance')) { + return jsonResponse({ balance: 10, lowBalance: true, lowBalanceThreshold: 20 }) + } + return new Response('', { status: 204 }) + }) as unknown as typeof fetch + + const client = new AimlapiClient(endpoints) + expect(await client.checkAccount('user@example.com')).toEqual({ action: 'sign-in' }) + await client.sendSignInCode('user@example.com') + expect(await client.verifySignInCode('user@example.com', '123456')).toEqual({ + token: 'bearer', + exp: 1, + }) + expect(await client.createPasswordlessAccount('new@example.com')).toEqual({ + token: 'new-bearer', + exp: 2, + }) + expect(await client.createKey('bearer', 'OpenClaude CLI')).toEqual({ + key: 'key_test', + id: 'id_test', + }) + expect((await client.getBalance('key_test')).lowBalance).toBe(true) + + expect(calls.map(call => [call.init?.method, call.url, call.body])).toEqual([ + ['PATCH', 'https://auth.example.test/v1/auth/account', { email: 'user@example.com' }], + ['POST', 'https://auth.example.test/v1/auth/sign-in/code', { email: 'user@example.com' }], + ['POST', 'https://auth.example.test/v1/auth/sign-in/code/verify', { email: 'user@example.com', code: '123456' }], + ['POST', 'https://auth.example.test/v1/auth/account/passwordless', { email: 'new@example.com' }], + ['POST', 'https://app.example.test/v1/keys', { name: 'OpenClaude CLI' }], + ['GET', 'https://api.example.test/v1/billing/balance', undefined], + ]) +}) + +test('pay only sends autoTopUp when it is enabled', async () => { + const bodies: unknown[] = [] + globalThis.fetch = mock(async (_input: string | URL | Request, init?: RequestInit) => { + bodies.push(typeof init?.body === 'string' ? JSON.parse(init.body) : undefined) + return jsonResponse({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test' }, + partnerCheckout: { sessionToken: 'session' }, + }) + }) as unknown as typeof fetch + + const client = new AimlapiClient(endpoints) + await client.pay('bearer', 'session', { + amountUsdMinor: 2500, + paymentSessionId: 'payment-id', + }) + await client.pay('bearer', 'session', { + amountUsdMinor: 2500, + paymentSessionId: 'payment-id', + autoTopUp: true, + }) + expect(bodies).toEqual([ + { amountUsdMinor: 2500, paymentSessionId: 'payment-id', method: 'card' }, + { amountUsdMinor: 2500, paymentSessionId: 'payment-id', method: 'card', autoTopUp: true }, + ]) +}) + +test('topUpByKey uses the v2 billing endpoint and API key bearer', async () => { + let seenUrl = '' + let seenHeaders = new Headers() + let seenBody: unknown + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + seenUrl = String(input) + seenHeaders = new Headers(init?.headers) + seenBody = typeof init?.body === 'string' ? JSON.parse(init.body) : undefined + return jsonResponse({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test' }, + partnerCheckout: { sessionToken: 'session' }, + }) + }) as unknown as typeof fetch + + const client = new AimlapiClient(endpoints) + await client.topUpByKey('key_test', { + sessionToken: 'session', + amountUsdMinor: 2500, + paymentSessionId: 'payment-id', + autoTopUp: true, + }) + + expect(seenUrl).toBe('https://api.example.test/v2/billing/topup') + expect(seenHeaders.get('Authorization')).toBe('Bearer key_test') + expect(seenBody).toEqual({ + sessionToken: 'session', + amountUsdMinor: 2500, + paymentSessionId: 'payment-id', + autoTopUp: true, + }) +}) + +test('typed requests reject an empty successful response', async () => { + globalThis.fetch = mock(async () => new Response('', { status: 204 })) as unknown as typeof fetch + const client = new AimlapiClient(endpoints) + await expect(client.getBalance('key_test')).rejects.toThrow('returned empty body') +}) + +test('getBalance rejects malformed successful payloads', async () => { + const client = new AimlapiClient(endpoints) + for (const payload of [ + {}, + { balance: 25, lowBalance: false }, + { balance: '25', lowBalance: false, lowBalanceThreshold: 20 }, + { balance: 25, lowBalance: 'false', lowBalanceThreshold: 20 }, + { balance: 25, lowBalance: false, lowBalanceThreshold: null }, + ]) { + globalThis.fetch = mock(async () => jsonResponse(payload)) as unknown as typeof fetch + await expect(client.getBalance('key_test')).rejects.toThrow( + 'returned invalid balance response', + ) + } +}) + +test('session tokens are excluded from HTTP and network errors', async () => { + const client = new AimlapiClient(endpoints) + const token = 'session-secret-token' + + globalThis.fetch = mock(async () => new Response('failed', { status: 500 })) as unknown as typeof fetch + let httpError: unknown + try { + await client.getSession(token) + } catch (error) { + httpError = error + } + expect(httpError).toBeInstanceOf(Error) + expect((httpError as Error).message).toContain('https://app.example.test') + expect((httpError as Error).message).not.toContain(token) + + globalThis.fetch = mock(async () => { + throw new Error(`transport failed for ${token}`) + }) as unknown as typeof fetch + let networkError: unknown + try { + await client.exchange('bearer', token) + } catch (error) { + networkError = error + } + expect(networkError).toBeInstanceOf(Error) + expect((networkError as Error).message).not.toContain(token) +}) + +test('response bodies are capped before decoding or surfacing errors', async () => { + globalThis.fetch = mock( + async () => new Response('x'.repeat((1 << 20) + 1), { status: 502 }), + ) as unknown as typeof fetch + const client = new AimlapiClient(endpoints) + await expect(client.getBalance('key_test')).rejects.toThrow( + 'response body exceeds 1048576 bytes', + ) +}) + +test('token-producing methods reject an empty token', async () => { + globalThis.fetch = mock(async () => jsonResponse({ token: '', exp: 1 })) as unknown as typeof fetch + const client = new AimlapiClient(endpoints) + await expect(client.verifySignInCode('user@example.com', '123456')).rejects.toThrow( + 'did not return an auth token', + ) + await expect(client.createPasswordlessAccount('user@example.com')).rejects.toThrow( + 'did not return an auth token', + ) +}) + +test('a request forwards the abort signal to fetch and rejects when cancelled', async () => { + const controller = new AbortController() + let forwardedSignal: AbortSignal | undefined + globalThis.fetch = mock(async (_input: string | URL | Request, init?: RequestInit) => { + forwardedSignal = init?.signal ?? undefined + // Model a transport that only settles when the request is aborted. + return await new Promise((_resolve, reject) => { + init?.signal?.addEventListener( + 'abort', + () => reject(new DOMException('The operation was aborted.', 'AbortError')), + { once: true }, + ) + }) + }) as unknown as typeof fetch + + const client = new AimlapiClient(endpoints) + const pending = client.getSession('resume-token', controller.signal) + controller.abort() + await expect(pending).rejects.toThrow() + // The signal reached the transport layer and observed the cancellation. + expect(forwardedSignal).toBeInstanceOf(AbortSignal) + expect(forwardedSignal?.aborted).toBe(true) +}) + +test('session methods reject a malformed or empty success payload', async () => { + // A structurally-invalid 200 must surface as a non-terminal (status 200) + // error rather than a session with an unknown status, so callers never clear + // the retained payment identity or take an ambiguous retry on it. + const client = new AimlapiClient(endpoints) + + // Empty object: passes the request-level object guard, rejected by the + // session shape check (no valid status). + globalThis.fetch = mock(async () => jsonResponse({})) as unknown as typeof fetch + const emptyError = await client.getSession('resume-token').catch((error: unknown) => error) + expect(emptyError).toBeInstanceOf(AimlapiApiError) + expect(emptyError).toHaveProperty('status', 200) + + // null / non-object: rejected by the request-level guard. + globalThis.fetch = mock(async () => jsonResponse(null)) as unknown as typeof fetch + const nullError = await client.getSession('resume-token').catch((error: unknown) => error) + expect(nullError).toBeInstanceOf(AimlapiApiError) + expect(nullError).toHaveProperty('status', 200) + + // Unknown status: object with a status outside the allowlist. + globalThis.fetch = mock(async () => + jsonResponse({ sessionToken: 'session', status: 'nonsense' }), + ) as unknown as typeof fetch + const badStatusError = await client + .createSession({ partnerId: 'part_x' }) + .catch((error: unknown) => error) + expect(badStatusError).toBeInstanceOf(AimlapiApiError) + expect(badStatusError).toHaveProperty('status', 200) +}) + +test('typed methods reject wrong-typed success fields without a raw TypeError', async () => { + const client = new AimlapiClient(endpoints) + + // A 2xx payload with a numeric token/key/apiKey must not reach .trim(). + globalThis.fetch = mock(async () => jsonResponse({ token: 1 })) as unknown as typeof fetch + await expect(client.verifySignInCode('user@example.com', '123456')).rejects.toThrow( + 'did not return an auth token', + ) + await expect(client.createPasswordlessAccount('user@example.com')).rejects.toThrow( + 'did not return an auth token', + ) + + globalThis.fetch = mock(async () => jsonResponse({ key: 1 })) as unknown as typeof fetch + await expect(client.createKey('bearer', 'OpenClaude CLI')).rejects.toThrow( + 'did not return an API key', + ) + // Key without its required id is an incomplete receipt and must be rejected. + globalThis.fetch = mock(async () => jsonResponse({ key: 'k_only' })) as unknown as typeof fetch + await expect(client.createKey('bearer', 'OpenClaude CLI')).rejects.toThrow( + 'did not return an API key', + ) + + globalThis.fetch = mock(async () => jsonResponse({ apiKey: 1 })) as unknown as typeof fetch + const exchangeError = await client.exchange('bearer', 'session').catch((e: unknown) => e) + expect(exchangeError).toBeInstanceOf(AimlapiApiError) + expect(exchangeError).toHaveProperty('status', 200) + + // apiKey without its required apiKeyId is an incomplete exchange receipt. + globalThis.fetch = mock(async () => + jsonResponse({ apiKey: 'k_only' }), + ) as unknown as typeof fetch + const partialExchange = await client.exchange('bearer', 'session').catch((e: unknown) => e) + expect(partialExchange).toBeInstanceOf(AimlapiApiError) + expect(partialExchange).toHaveProperty('status', 200) + + globalThis.fetch = mock(async () => jsonResponse({ action: 1 })) as unknown as typeof fetch + const accountError = await client.checkAccount('user@example.com').catch((e: unknown) => e) + expect(accountError).toBeInstanceOf(AimlapiApiError) + expect(accountError).toHaveProperty('status', 200) +}) diff --git a/src/integrations/aimlapi/client.ts b/src/integrations/aimlapi/client.ts index 201754dc16..845f2a93cf 100644 --- a/src/integrations/aimlapi/client.ts +++ b/src/integrations/aimlapi/client.ts @@ -1,14 +1,4 @@ -/** - * AI/ML API partner-checkout HTTP client. - * - * Talks to two services: - * - app/auth (`authBaseUrl`) - `POST /v1/auth/account` (signup) / - * `PUT /v1/auth/account` (login) -> Bearer token - * - app/gateway(`appBaseUrl`) - `/v3/partner-checkout/*` - * - * Uses the global `fetch` (Node >= 22). All error bodies are surfaced verbatim - * so failures are debuggable. - */ +/** AI/ML API passwordless onboarding and partner-checkout HTTP client. */ import { createCombinedAbortSignal } from '../../utils/combinedAbortSignal.js' import type { AimlapiEndpoints } from './config.js' @@ -45,15 +35,155 @@ export type PayResult = { partnerCheckout: PartnerCheckoutSession } -export type ExchangeResult = { - apiKey: string - apiKeyId: string -} +export type TopUpByKeyResult = PayResult -export type PaymentMethod = 'card' | 'crypto' +export type ExchangeResult = { apiKey: string; apiKeyId: string } export type AuthResult = { token: string; exp: number } +export type AccountCheckResult = { + action: 'sign-in' | 'sign-up' + provider?: string | null +} +export type CreatedKey = { key: string; id: string } +export type BalanceResult = { + balance: number + lowBalance: boolean + lowBalanceThreshold: number +} -const REQUEST_TIMEOUT_MS = 30_000 +const REQUEST_TIMEOUT_MS = 60_000 +const MAX_RESPONSE_BODY_BYTES = 1 << 20 + +function requestLabel(url: string): string { + try { + return new URL(url).origin + } catch { + return 'AI/ML API endpoint' + } +} + +function redactRequestSecrets( + message: string, + url: string, + bearer: string | undefined, +): string { + const secrets = new Set() + if (bearer?.trim()) secrets.add(bearer.trim()) + try { + for (const segment of new URL(url).pathname.split('/')) { + if (segment.length < 6) continue + secrets.add(segment) + try { + secrets.add(decodeURIComponent(segment)) + } catch { + // Keep the encoded segment when it is not valid percent-encoding. + } + } + } catch { + // The request label already handles malformed URLs without exposing them. + } + let redacted = message + for (const secret of secrets) { + if (secret) redacted = redacted.split(secret).join('[REDACTED]') + } + return redacted +} + +const PARTNER_CHECKOUT_STATUSES: ReadonlySet = new Set([ + 'pending_auth', + 'pending_payment', + 'paid', + 'exchanging', + 'exchanged', + 'cancelled', + 'expired', + 'failed', +]) + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null +} + +function isNonEmptyString(value: unknown): value is string { + return typeof value === 'string' && value.trim().length > 0 +} + +function isAccountCheckResult(value: unknown): value is AccountCheckResult { + return isRecord(value) && typeof value.action === 'string' +} + +function isAuthResult(value: unknown): value is AuthResult { + return isRecord(value) && isNonEmptyString(value.token) +} + +function isCreatedKey(value: unknown): value is CreatedKey { + return isRecord(value) && isNonEmptyString(value.key) && isNonEmptyString(value.id) +} + +function isExchangeResult(value: unknown): value is ExchangeResult { + return isRecord(value) && isNonEmptyString(value.apiKey) && isNonEmptyString(value.apiKeyId) +} + +function isPayResult(value: unknown): value is PayResult { + return isRecord(value) && isRecord(value.checkout) +} + +function isPartnerCheckoutSession(value: unknown): value is PartnerCheckoutSession { + if (typeof value !== 'object' || value === null) return false + const session = value as Record + return ( + isNonEmptyString(session.id) && + isNonEmptyString(session.sessionToken) && + isNonEmptyString(session.partnerId) && + typeof session.status === 'string' && + PARTNER_CHECKOUT_STATUSES.has(session.status) + ) +} + +function isBalanceResult(value: unknown): value is BalanceResult { + if (typeof value !== 'object' || value === null) return false + const result = value as Record + return ( + typeof result.balance === 'number' && + Number.isFinite(result.balance) && + typeof result.lowBalance === 'boolean' && + typeof result.lowBalanceThreshold === 'number' && + Number.isFinite(result.lowBalanceThreshold) + ) +} + +class AimlapiResponseTooLargeError extends Error { + constructor() { + super(`AI/ML API response body exceeds ${MAX_RESPONSE_BODY_BYTES} bytes.`) + this.name = 'AimlapiResponseTooLargeError' + } +} + +async function readResponseText(response: Response): Promise { + if (!response.body) return '' + const reader = response.body.getReader() + const decoder = new TextDecoder() + let totalBytes = 0 + let text = '' + try { + while (true) { + const { done, value } = await reader.read() + if (done) break + totalBytes += value.byteLength + if (totalBytes > MAX_RESPONSE_BODY_BYTES) { + try { + await reader.cancel() + } catch { + // Keep the deterministic size-limit error if stream cancellation fails. + } + throw new AimlapiResponseTooLargeError() + } + text += decoder.decode(value, { stream: true }) + } + return text + decoder.decode() + } finally { + reader.releaseLock() + } +} export class AimlapiApiError extends Error { constructor( @@ -69,161 +199,294 @@ export class AimlapiApiError extends Error { export class AimlapiClient { constructor(private readonly endpoints: AimlapiEndpoints) {} - /** Register a new AI/ML API account -> access (Bearer) token. */ - async signup(input: { - email: string - password: string - inviteCode?: string - }): Promise { - return this.request( - `${this.endpoints.authBaseUrl}/v1/auth/account`, - { - method: 'POST', - body: { - email: input.email, - password: input.password, - ...(input.inviteCode ? { inviteCode: input.inviteCode } : {}), - }, - }, - ) + async checkAccount(email: string, signal?: AbortSignal): Promise { + const url = `${this.endpoints.authBaseUrl}/v1/auth/account` + const result = await this.request(url, { + method: 'PATCH', + body: { email }, + signal, + }) + if (!isAccountCheckResult(result)) { + throw new AimlapiApiError(`PATCH ${requestLabel(url)} returned an invalid account response`, 200, '') + } + return result + } + + async sendSignInCode(email: string, signal?: AbortSignal): Promise { + await this.request(`${this.endpoints.authBaseUrl}/v1/auth/sign-in/code`, { + method: 'POST', + body: { email }, + signal, + expectJson: false, + }) } - /** Sign in with email + password -> access (Bearer) token. */ - async login(email: string, password: string): Promise { - return this.request( - `${this.endpoints.authBaseUrl}/v1/auth/account`, - { method: 'PUT', body: { email, password } }, + async verifySignInCode( + email: string, + code: string, + signal?: AbortSignal, + ): Promise { + const result = await this.request( + `${this.endpoints.authBaseUrl}/v1/auth/sign-in/code/verify`, + { method: 'POST', body: { email, code }, signal }, ) + if (!isAuthResult(result)) throw new Error('AI/ML API did not return an auth token.') + return result } - /** Create a partner-checkout session (public - no auth). */ - async createSession(input: { - partnerId: string - partnerName?: string | null - returnUrl?: string | null - }): Promise { - return this.request( - `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions`, - { - method: 'POST', - body: { - partnerId: input.partnerId, - ...(input.partnerName ? { partnerName: input.partnerName } : {}), - ...(input.returnUrl ? { returnUrl: input.returnUrl } : {}), - }, - }, + async createPasswordlessAccount(email: string, signal?: AbortSignal): Promise { + const result = await this.request( + `${this.endpoints.authBaseUrl}/v1/auth/account/passwordless`, + { method: 'POST', body: { email }, signal }, ) + if (!isAuthResult(result)) throw new Error('AI/ML API did not return an auth token.') + return result + } + + async createKey( + bearer: string, + name: string, + signal?: AbortSignal, + ): Promise { + const result = await this.request(`${this.endpoints.appBaseUrl}/v1/keys`, { + method: 'POST', + bearer, + body: name.trim() ? { name: name.trim() } : {}, + signal, + }) + if (!isCreatedKey(result)) { + throw new Error('AI/ML API did not return an API key.') + } + return result } - /** Poll a session by its one-time token (public - no auth). */ - async getSession(sessionToken: string): Promise { - return this.request( - `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions/${encodeURIComponent(sessionToken)}`, - { method: 'GET' }, + async getBalance(apiKey: string, signal?: AbortSignal): Promise { + const url = `${this.endpoints.inferenceBaseUrl.replace(/\/+$/, '')}/billing/balance` + const result = await this.request( + url, + { method: 'GET', bearer: apiKey, signal }, ) + if (!isBalanceResult(result)) { + throw new AimlapiApiError( + `GET ${requestLabel(url)} returned invalid balance response`, + 200, + '', + ) + } + return result + } + + async createSession( + input: { partnerId: string; partnerName?: string | null; returnUrl?: string | null }, + signal?: AbortSignal, + ): Promise { + const url = `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions` + const result = await this.request(url, { + method: 'POST', + body: { + partnerId: input.partnerId, + ...(input.partnerName ? { partnerName: input.partnerName } : {}), + ...(input.returnUrl ? { returnUrl: input.returnUrl } : {}), + }, + signal, + }) + if (!isPartnerCheckoutSession(result)) { + throw new AimlapiApiError(`POST ${requestLabel(url)} returned an invalid session`, 200, '') + } + return result + } + + async getSession( + sessionToken: string, + signal?: AbortSignal, + ): Promise { + const url = `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions/${encodeURIComponent(sessionToken)}` + const result = await this.request(url, { method: 'GET', signal }) + // A malformed/empty 200 must not read as an unknown status: that would let + // callers clear the retained payment identity or take an ambiguous retry. + // Surface it as a non-terminal error so retained state is preserved. + if (!isPartnerCheckoutSession(result)) { + throw new AimlapiApiError(`GET ${requestLabel(url)} returned an invalid session`, 200, '') + } + return result } - /** - * Bind the session to the logged-in user and open a hosted payment page. - * Requires the Bearer token. Returns `checkout.payUrl` to open in a browser. - * - * `successUrl`/`cancelUrl` are the co-branded `/checkout` return URLs the - * payment provider redirects the browser to after pay/cancel (see - * `buildPartnerCheckoutReturnUrls`). When omitted the backend falls back to a - * bare, non-co-branded `/checkout?checkout=success`. - */ async pay( bearer: string, sessionToken: string, input: { amountUsdMinor: number - method: PaymentMethod + paymentSessionId: string successUrl?: string cancelUrl?: string + autoTopUp?: boolean }, + signal?: AbortSignal, ): Promise { - return this.request( - `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions/${encodeURIComponent(sessionToken)}/pay`, - { - method: 'POST', - bearer, - body: { - amountUsdMinor: input.amountUsdMinor, - method: input.method, - ...(input.successUrl ? { successUrl: input.successUrl } : {}), - ...(input.cancelUrl ? { cancelUrl: input.cancelUrl } : {}), - }, + const url = `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions/${encodeURIComponent(sessionToken)}/pay` + const result = await this.request(url, { + method: 'POST', + bearer, + body: { + amountUsdMinor: input.amountUsdMinor, + paymentSessionId: input.paymentSessionId, + method: 'card', + ...(input.successUrl ? { successUrl: input.successUrl } : {}), + ...(input.cancelUrl ? { cancelUrl: input.cancelUrl } : {}), + ...(input.autoTopUp ? { autoTopUp: true } : {}), }, - ) + signal, + }) + if (!isPayResult(result)) { + throw new AimlapiApiError(`POST ${requestLabel(url)} returned an invalid checkout`, 200, '') + } + return result } - /** - * Exchange a PAID session for the raw CLI key. One-shot: a second call after - * a successful exchange loses the claim and returns no key. Requires Bearer. - */ - async exchange(bearer: string, sessionToken: string): Promise { - return this.request( - `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions/${encodeURIComponent(sessionToken)}/exchange`, - { method: 'POST', bearer }, - ) + async topUpByKey( + apiKey: string, + input: { + sessionToken: string + amountUsdMinor: number + paymentSessionId: string + successUrl?: string + cancelUrl?: string + autoTopUp?: boolean + }, + signal?: AbortSignal, + ): Promise { + const inferenceBase = this.endpoints.inferenceBaseUrl + .trim() + .replace(/\/+$/, '') + .replace(/\/v1$/i, '') + const url = `${inferenceBase}/v2/billing/topup` + const result = await this.request(url, { + method: 'POST', + bearer: apiKey, + body: { + sessionToken: input.sessionToken, + amountUsdMinor: input.amountUsdMinor, + paymentSessionId: input.paymentSessionId, + ...(input.successUrl ? { successUrl: input.successUrl } : {}), + ...(input.cancelUrl ? { cancelUrl: input.cancelUrl } : {}), + ...(input.autoTopUp ? { autoTopUp: true } : {}), + }, + signal, + }) + if (!isPayResult(result)) { + throw new AimlapiApiError(`POST ${requestLabel(url)} returned an invalid checkout`, 200, '') + } + return result + } + + async exchange( + bearer: string, + sessionToken: string, + signal?: AbortSignal, + ): Promise { + const url = `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions/${encodeURIComponent(sessionToken)}/exchange` + const result = await this.request(url, { method: 'POST', bearer, signal }) + if (!isExchangeResult(result)) { + throw new AimlapiApiError(`POST ${requestLabel(url)} returned an invalid exchange response`, 200, '') + } + return result } private async request( url: string, options: { - method: 'GET' | 'POST' | 'PUT' + method: 'GET' | 'POST' | 'PATCH' body?: unknown bearer?: string + signal?: AbortSignal + expectJson?: boolean }, ): Promise { + const label = requestLabel(url) const headers: Record = { Accept: 'application/json' } - if (options.body !== undefined) { - headers['Content-Type'] = 'application/json' - } - if (options.bearer) { - headers.Authorization = `Bearer ${options.bearer}` - } + if (options.body !== undefined) headers['Content-Type'] = 'application/json' + if (options.bearer) headers.Authorization = `Bearer ${options.bearer.trim()}` - const { signal, cleanup } = createCombinedAbortSignal(undefined, { + const combined = createCombinedAbortSignal(options.signal, { timeoutMs: REQUEST_TIMEOUT_MS, }) - let response: Response - let text: string try { response = await fetch(url, { method: options.method, headers, - signal, + signal: combined.signal, ...(options.body !== undefined ? { body: JSON.stringify(options.body) } : {}), }) - text = await response.text() } catch (error) { - const reason = error instanceof Error ? error.message : String(error) - throw new AimlapiApiError(`Network request to ${url} failed: ${reason}`, 0, '') + combined.cleanup() + if (options.signal?.aborted) throw error + const reason = redactRequestSecrets( + error instanceof Error ? error.message : String(error), + url, + options.bearer, + ) + throw new AimlapiApiError(`Network request to ${label} failed: ${reason}`, 0, '') + } + + let text: string + try { + text = await readResponseText(response) + } catch (error) { + if (options.signal?.aborted) throw error + if (error instanceof AimlapiResponseTooLargeError) { + throw new AimlapiApiError( + `${options.method} ${label} response body exceeds ${MAX_RESPONSE_BODY_BYTES} bytes`, + response.status, + '', + ) + } + const reason = redactRequestSecrets( + error instanceof Error ? error.message : String(error), + url, + options.bearer, + ) + throw new AimlapiApiError(`Network response from ${label} failed: ${reason}`, 0, '') } finally { - cleanup() + combined.cleanup() } if (!response.ok) { throw new AimlapiApiError( - `${options.method} ${url} -> ${response.status}`, + `${options.method} ${label} -> ${response.status}`, response.status, text, ) } - - if (!text) { - return undefined as T + if (!text.trim()) { + if (options.expectJson === false) return undefined as T + throw new AimlapiApiError( + `${options.method} ${label} returned empty body`, + response.status, + '', + ) } + let parsed: unknown try { - return JSON.parse(text) as T + parsed = JSON.parse(text) } catch { throw new AimlapiApiError( - `${options.method} ${url} returned non-JSON body`, + `${options.method} ${label} returned non-JSON body`, response.status, text, ) } + // Every endpoint returns a JSON object. Reject null/non-object bodies here so + // no method dereferences a null/primitive success payload (which would throw + // a raw TypeError instead of a controlled, non-terminal error); endpoint + // guards below still validate structural completeness. + if (typeof parsed !== 'object' || parsed === null) { + throw new AimlapiApiError( + `${options.method} ${label} returned an unexpected body`, + response.status, + '', + ) + } + return parsed as T } } diff --git a/src/integrations/aimlapi/config.test.ts b/src/integrations/aimlapi/config.test.ts new file mode 100644 index 0000000000..6dd6118a1e --- /dev/null +++ b/src/integrations/aimlapi/config.test.ts @@ -0,0 +1,124 @@ +import { afterEach, expect, test } from 'bun:test' + +import { + buildPartnerCheckoutReturnUrls, + buildPartnerReturnUrl, + isCanonicalAimlapiInferenceBaseUrl, + resolvePartnerId, + resolveEndpoints, + withResolvedPartnerHeader, +} from './config.js' + +const envNames = [ + 'AIMLAPI_AUTH_URL', + 'AIMLAPI_APP_URL', + 'AIMLAPI_INFERENCE_URL', + 'AIMLAPI_PAY_URL', + 'AIMLAPI_VERIFICATION_BASE_URL', + 'AIMLAPI_RETURN_URL', + 'AIMLAPI_PARTNER_ID', +] as const +const originalEnv = Object.fromEntries(envNames.map(name => [name, process.env[name]])) + +afterEach(() => { + for (const name of envNames) { + const value = originalEnv[name] + if (value === undefined) delete process.env[name] + else process.env[name] = value + } +}) + +test('resolveEndpoints returns the production passwordless and checkout endpoints', () => { + for (const name of envNames) delete process.env[name] + expect(resolveEndpoints()).toEqual({ + authBaseUrl: 'https://auth.aimlapi.com', + appBaseUrl: 'https://app.aimlapi.com', + inferenceBaseUrl: 'https://api.aimlapi.com/v1', + payBaseUrl: 'https://pay.aimlapi.com', + verificationBaseUrl: 'https://aimlapi.com/app', + }) +}) + +test('checkout and browser return URLs stay in the selected environment', () => { + expect(buildPartnerCheckoutReturnUrls('https://pay.example.test/', 'a/b')).toEqual({ + successUrl: + 'https://pay.example.test/checkout?checkout=success&partnerCheckout=1&sessionToken=a%2Fb', + cancelUrl: + 'https://pay.example.test/checkout?checkout=cancel&partnerCheckout=1&sessionToken=a%2Fb', + }) + expect(buildPartnerCheckoutReturnUrls('', 'token')).toEqual({}) + expect(buildPartnerReturnUrl('https://front.example.test/')).toBe( + 'https://front.example.test', + ) +}) + +test('AIMLAPI_RETURN_URL overrides the browser landing page', () => { + process.env.AIMLAPI_RETURN_URL = 'https://return.example.test/done' + expect(buildPartnerReturnUrl('https://front.example.test')).toBe( + 'https://return.example.test/done', + ) +}) + +test('unsafe checkout and return URL overrides are rejected', () => { + expect(buildPartnerCheckoutReturnUrls('file:///tmp/pay', 'token')).toEqual({}) + expect( + buildPartnerCheckoutReturnUrls('https://user:secret@pay.example.test', 'token'), + ).toEqual({}) + expect(buildPartnerCheckoutReturnUrls('not a URL', 'token')).toEqual({}) + expect(buildPartnerCheckoutReturnUrls('http://pay.example.test', 'token')).toEqual( + {}, + ) + expect( + buildPartnerCheckoutReturnUrls('http://127.0.0.1.evil.example', 'token'), + ).toEqual({}) + expect( + buildPartnerCheckoutReturnUrls('https://pay.example.test?environment=test', 'token'), + ).toEqual({}) + expect( + buildPartnerCheckoutReturnUrls('https://pay.example.test/#checkout', 'token'), + ).toEqual({}) + expect(buildPartnerCheckoutReturnUrls('http://127.0.0.1:3000/', 'token')).toEqual({ + successUrl: + 'http://127.0.0.1:3000/checkout?checkout=success&partnerCheckout=1&sessionToken=token', + cancelUrl: + 'http://127.0.0.1:3000/checkout?checkout=cancel&partnerCheckout=1&sessionToken=token', + }) + expect(buildPartnerReturnUrl('http://127.1:3000/')).toBe( + 'http://127.0.0.1:3000', + ) + + for (const override of [ + 'file:///tmp/return', + 'https://user:secret@return.example.test', + 'http://return.example.test', + 'https://return.example.test/done?source=test', + 'https://return.example.test/done#checkout', + 'not a URL', + ]) { + process.env.AIMLAPI_RETURN_URL = override + expect(buildPartnerReturnUrl('https://front.example.test/')).toBe( + 'https://front.example.test', + ) + } + process.env.AIMLAPI_RETURN_URL = 'javascript:alert(1)' + expect(buildPartnerReturnUrl('also invalid')).toBe('https://aimlapi.com/app') +}) + +test('partner id override is shared with the inference header', () => { + process.env.AIMLAPI_PARTNER_ID = 'part_override' + expect(resolvePartnerId()).toBe('part_override') + expect( + withResolvedPartnerHeader({ + 'x-aimlapi-partner-id': 'part_catalog', + 'X-Title': 'OpenClaude', + }), + ).toEqual({ + 'X-AIMLAPI-Partner-ID': 'part_override', + 'X-Title': 'OpenClaude', + }) +}) + +test('canonical endpoint check excludes proxies', () => { + expect(isCanonicalAimlapiInferenceBaseUrl('https://api.aimlapi.com/v1/')).toBe(true) + expect(isCanonicalAimlapiInferenceBaseUrl('https://proxy.example.test/v1')).toBe(false) +}) diff --git a/src/integrations/aimlapi/config.ts b/src/integrations/aimlapi/config.ts index 985efc3484..57005db820 100644 --- a/src/integrations/aimlapi/config.ts +++ b/src/integrations/aimlapi/config.ts @@ -1,13 +1,12 @@ /** * AI/ML API (aimlapi.com) integration - endpoint configuration. * - * Wires OpenClaude to the AI/ML API "partner checkout" flow so a user can log - * in, top up their balance, and have the issued key written back into + * Wires OpenClaude to the AI/ML API passwordless onboarding and partner + * checkout flow so a user can sign in, top up their balance, and have the issued key written back into * OpenClaude's provider profile automatically. Usage attributes to the Gitlawb * rebate partner (see the partner id below). * - * Override any single URL via the `AIMLAPI_AUTH_URL`, `AIMLAPI_APP_URL`, or - * `AIMLAPI_INFERENCE_URL` env vars. + * Override any single URL via the corresponding `AIMLAPI_*_URL` env var. */ export type AimlapiEndpoints = { @@ -15,14 +14,20 @@ export type AimlapiEndpoints = { authBaseUrl: string /** app/gateway BFF - hosts `/v3/partner-checkout/*`. */ appBaseUrl: string + /** hosted checkout frontend base URL. */ + payBaseUrl: string /** OpenAI-compatible inference base URL written into the provider profile. */ inferenceBaseUrl: string + /** browser landing page after checkout / consent completes. */ + verificationBaseUrl: string } const DEFAULT_ENDPOINTS: AimlapiEndpoints = { authBaseUrl: 'https://auth.aimlapi.com', appBaseUrl: 'https://app.aimlapi.com', + payBaseUrl: 'https://pay.aimlapi.com', inferenceBaseUrl: 'https://api.aimlapi.com/v1', + verificationBaseUrl: 'https://aimlapi.com/app', } /** @@ -34,9 +39,11 @@ const DEFAULT_ENDPOINTS: AimlapiEndpoints = { */ export const DEFAULT_PARTNER_ID = 'part_62yQoGYDq4Yqnrj2R1iGrDNJ' export const DEFAULT_PARTNER_NAME = 'Gitlawb' +export const PARTNER_HEADER_NAME = 'X-AIMLAPI-Partner-ID' /** Default model id written into the profile - override with `--model`. */ export const DEFAULT_MODEL = 'gpt-4o' +export const DEFAULT_RETURN_URL = 'https://aimlapi.com/app' /** Top-up bounds enforced by the backend DTO (USD minor units / cents). */ export const MIN_AMOUNT_USD_MINOR = 2000 // $20 @@ -47,11 +54,51 @@ export function resolveEndpoints(): AimlapiEndpoints { return { authBaseUrl: process.env.AIMLAPI_AUTH_URL?.trim() || DEFAULT_ENDPOINTS.authBaseUrl, appBaseUrl: process.env.AIMLAPI_APP_URL?.trim() || DEFAULT_ENDPOINTS.appBaseUrl, + payBaseUrl: process.env.AIMLAPI_PAY_URL?.trim() || DEFAULT_ENDPOINTS.payBaseUrl, inferenceBaseUrl: process.env.AIMLAPI_INFERENCE_URL?.trim() || DEFAULT_ENDPOINTS.inferenceBaseUrl, + verificationBaseUrl: + process.env.AIMLAPI_VERIFICATION_BASE_URL?.trim() || + DEFAULT_ENDPOINTS.verificationBaseUrl, } } +/** Resolve checkout and inference attribution with one shared precedence. */ +export function resolvePartnerId(explicit?: string): string { + return ( + explicit?.trim() || + process.env.AIMLAPI_PARTNER_ID?.trim() || + DEFAULT_PARTNER_ID + ) +} + +/** + * Return a header copy with the effective partner id. Header matching is + * case-insensitive so an override replaces the catalog spelling instead of + * creating a duplicate header. + */ +export function withResolvedPartnerHeader( + headers: Readonly>, + explicit?: string, +): Record { + const resolved: Record = {} + for (const [name, value] of Object.entries(headers)) { + if (name.trim().toLowerCase() === PARTNER_HEADER_NAME.toLowerCase()) continue + resolved[name] = value + } + resolved[PARTNER_HEADER_NAME] = resolvePartnerId(explicit) + return resolved +} + +function normalizeBaseUrl(value: string): string { + return value.trim().replace(/\/+$/, '').toLowerCase() +} + +/** Catalog attribution and existing-key preflight are production-only. */ +export function isCanonicalAimlapiInferenceBaseUrl(value: string): boolean { + return normalizeBaseUrl(value) === normalizeBaseUrl(DEFAULT_ENDPOINTS.inferenceBaseUrl) +} + /** * Build the co-branded checkout return URLs the hosted payment page redirects * to after the user pays or cancels. Carrying `sessionToken` + `partnerCheckout=1` @@ -61,10 +108,11 @@ export function resolveEndpoints(): AimlapiEndpoints { * `/checkout?checkout=success` that is NOT co-branded. */ export function buildPartnerCheckoutReturnUrls( - appBaseUrl: string, + payBaseUrl: string, sessionToken: string, -): { successUrl: string; cancelUrl: string } { - const base = appBaseUrl.replace(/\/+$/, '') +): { successUrl?: string; cancelUrl?: string } { + const base = safeHttpBaseUrl(payBaseUrl) + if (!base) return {} const token = encodeURIComponent(sessionToken) const query = (status: string): string => `checkout=${status}&partnerCheckout=1&sessionToken=${token}` @@ -73,3 +121,37 @@ export function buildPartnerCheckoutReturnUrls( cancelUrl: `${base}/checkout?${query('cancel')}`, } } + +/** + * Browser landing URL after checkout. OpenClaude learns success by polling, so + * this must be an ordinary HTTPS page rather than an unregistered custom scheme. + */ +export function buildPartnerReturnUrl(frontendBaseUrl: string): string { + const override = safeHttpBaseUrl(process.env.AIMLAPI_RETURN_URL) + if (override) return override + return safeHttpBaseUrl(frontendBaseUrl) ?? DEFAULT_RETURN_URL +} + +function safeHttpBaseUrl(value: string | undefined): string | null { + const candidate = value?.trim() + if (!candidate) return null + try { + const url = new URL(candidate) + const loopback = + url.hostname === 'localhost' || + /^127(?:\.\d+){3}$/.test(url.hostname) || + url.hostname === '[::1]' + if ( + (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) || + url.username || + url.password || + url.search || + url.hash + ) { + return null + } + return url.href.replace(/\/+$/, '') + } catch { + return null + } +} diff --git a/src/integrations/aimlapi/index.ts b/src/integrations/aimlapi/index.ts index b25d5bb52d..1409e87fa0 100644 --- a/src/integrations/aimlapi/index.ts +++ b/src/integrations/aimlapi/index.ts @@ -1,12 +1,24 @@ export { provisionAimlapiKey, runAimlapiTopup, + topUpAimlapiByApiKey, + type AimlapiByKeyTopupOptions, type AimlapiProvisionOptions, type AimlapiProvisionedKey, type AimlapiTopupOptions, type AimlapiTopupStatus, + pollUntilPaid, } from './topup.js' +export { isValidAimlapiEmail, parseAimlapiAmountUsd } from './validation.js' +export { + beginAimlapiEmailOnboarding, + completeAimlapiCodeSignIn, + validateAimlapiApiKey, + type AimlapiCodeSignInResult, + type AimlapiEmailOnboardingResult, +} from './onboarding.js' export { AimlapiClient, AimlapiApiError } from './client.js' +export { AIMLAPI_MESSAGES } from './messages.js' export type { AimlapiEndpoints, } from './config.js' diff --git a/src/integrations/aimlapi/messages.ts b/src/integrations/aimlapi/messages.ts new file mode 100644 index 0000000000..81465a611e --- /dev/null +++ b/src/integrations/aimlapi/messages.ts @@ -0,0 +1,30 @@ +/** Canonical AIMLAPI onboarding copy ported from Zero. */ + +export const AIMLAPI_MESSAGES = { + apiKeyInputPrompt: 'Enter your aimlapi.com key.', + apiKeyHiddenHint: 'Your API key will be hidden and verified automatically.', + apiKeyInvalid: + 'API key is invalid. Please make sure you enter a valid aimlapi.com key.', + pickPathPrompt: 'Do you have aimlapi.com key?', + pickPathHaveKey: 'I already have aimlapi.com key', + pickPathNewUser: 'I am a new user', + enterEmail: 'Enter your email.', + emailInvalid: 'Email format is incorrect.', + codeSent: (email: string) => `Enter the 6-digit code sent to ${email}.`, + codeIncorrect: "Code you've entered is incorrect.", + lowBalance: 'Your aimlapi.com credits are running low - top up now?', + lowBalanceTopUp: "Sure, let's do that", + lowBalanceSkip: "I'll skip for now", + topUpPrompt: 'Add credits (min $20).', + amountRequired: 'Please enter a top-up amount.', + guidedNeedsCanonicalEndpoint: + 'Creating a new key requires the aimlapi.com production endpoint. Unset AIMLAPI_INFERENCE_URL, or paste an existing key to use a custom endpoint.', + topUpBrowserFallback: + 'If the browser did not open automatically please use this link to top up your account:', + topUpFailed: 'Top up failed. Please try again.', + everythingRuns: 'Everything is ready.', + topUpSuccess: (amountUsd: string) => + `Top-up successful - $${amountUsd} credited to your account`, + successMagicLink: (email: string) => + `We've emailed you a magic link to ${email}. Use it to access your aimlapi.com account and review your usage.`, +} as const diff --git a/src/integrations/aimlapi/onboarding.test.ts b/src/integrations/aimlapi/onboarding.test.ts new file mode 100644 index 0000000000..ff977bb7c3 --- /dev/null +++ b/src/integrations/aimlapi/onboarding.test.ts @@ -0,0 +1,166 @@ +import { afterEach, expect, mock, test } from 'bun:test' + +import { + beginAimlapiEmailOnboarding, + completeAimlapiCodeSignIn, + validateAimlapiApiKey, +} from './onboarding.js' + +const originalFetch = globalThis.fetch +const originalEnv = { + AIMLAPI_AUTH_URL: process.env.AIMLAPI_AUTH_URL, + AIMLAPI_APP_URL: process.env.AIMLAPI_APP_URL, + AIMLAPI_INFERENCE_URL: process.env.AIMLAPI_INFERENCE_URL, +} + +afterEach(() => { + globalThis.fetch = originalFetch + for (const [name, value] of Object.entries(originalEnv)) { + if (value === undefined) delete process.env[name] + else process.env[name] = value + } +}) + +function response(value: unknown, status = 200): Response { + return new Response(JSON.stringify(value), { status }) +} + +test('existing account onboarding sends a code, creates a key, and reports low balance', async () => { + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input) + calls.push(`${init?.method} ${url}`) + if (url.endsWith('/v1/auth/account')) return response({ action: 'sign-in' }) + if (url.endsWith('/v1/auth/sign-in/code')) return new Response('', { status: 204 }) + if (url.endsWith('/code/verify')) return response({ token: 'session', exp: 1 }) + if (url.endsWith('/v1/keys')) return response({ key: 'key_test', id: 'id_test' }) + if (url.endsWith('/billing/balance')) { + return response({ balance: 5, lowBalance: true, lowBalanceThreshold: 20 }) + } + return response({}, 404) + }) as unknown as typeof fetch + + expect(await beginAimlapiEmailOnboarding('user@example.com')).toEqual({ + action: 'code-sent', + }) + expect(await completeAimlapiCodeSignIn('user@example.com', '123456')).toEqual({ + sessionToken: 'session', + apiKey: 'key_test', + apiKeyId: 'id_test', + balanceStatus: 'confirmed', + lowBalance: true, + }) + expect(calls).toEqual([ + 'PATCH https://auth.example.test/v1/auth/account', + 'POST https://auth.example.test/v1/auth/sign-in/code', + 'POST https://auth.example.test/v1/auth/sign-in/code/verify', + 'POST https://app.example.test/v1/keys', + 'GET https://api.example.test/v1/billing/balance', + ]) +}) + +test('balance failures preserve the issued key without marking it ready', async () => { + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + if (url.endsWith('/code/verify')) return response({ token: 'session', exp: 1 }) + if (url.endsWith('/v1/keys')) return response({ key: 'key_test', id: 'id_test' }) + return response({ error: 'unavailable' }, 503) + }) as unknown as typeof fetch + + const result = await completeAimlapiCodeSignIn('user@example.com', '123456') + expect(result).toEqual({ + sessionToken: 'session', + apiKey: 'key_test', + apiKeyId: 'id_test', + balanceStatus: 'unknown', + balanceError: 'GET https://api.example.test -> 503', + }) + expect(result).not.toHaveProperty('lowBalance') +}) + +test('new account onboarding returns a passwordless session', async () => { + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + return url.endsWith('/passwordless') + ? response({ token: 'new-session', exp: 1 }) + : response({ action: 'sign-up' }) + }) as unknown as typeof fetch + + expect(await beginAimlapiEmailOnboarding('new@example.com')).toEqual({ + action: 'new-account', + sessionToken: 'new-session', + }) +}) + +test('existing API key validation uses the balance endpoint', async () => { + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + expect(String(input)).toBe('https://api.example.test/v1/billing/balance') + expect(init?.method).toBe('GET') + expect(new Headers(init?.headers).get('Authorization')).toBe('Bearer key_test') + return response({ balance: 25, lowBalance: false, lowBalanceThreshold: 20 }) + }) as unknown as typeof fetch + + expect(await validateAimlapiApiKey(' key_test ')).toEqual({ + balance: 25, + lowBalance: false, + lowBalanceThreshold: 20, + }) +}) + +test('existing API key validation can pin the validated endpoint', async () => { + process.env.AIMLAPI_INFERENCE_URL = 'https://override.example.test/v1' + globalThis.fetch = mock(async (input: string | URL | Request) => { + expect(String(input)).toBe('https://api.aimlapi.com/v1/billing/balance') + return response({ balance: 25, lowBalance: false, lowBalanceThreshold: 20 }) + }) as unknown as typeof fetch + + await validateAimlapiApiKey( + 'key_test', + undefined, + 'https://api.aimlapi.com/v1', + ) +}) + +test('unknown account actions are rejected instead of signing up', async () => { + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + globalThis.fetch = mock(async () => response({ action: 'migrate' })) as unknown as typeof fetch + await expect(beginAimlapiEmailOnboarding('user@example.com')).rejects.toThrow( + 'unsupported account action', + ) +}) + +test('completeAimlapiCodeSignIn reuses a supplied key instead of minting a new one', async () => { + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + calls.push(url) + if (url.endsWith('/code/verify')) return response({ token: 'bearer', exp: 1 }) + if (url.endsWith('/billing/balance')) { + return response({ balance: 100, lowBalance: false, lowBalanceThreshold: 20 }) + } + throw new Error(`Unexpected request: ${url}`) + }) as unknown as typeof fetch + + const result = await completeAimlapiCodeSignIn( + 'user@example.com', + '123456', + undefined, + 'https://api.example.test/v1', + { apiKey: 'existing-key', apiKeyId: 'existing-id' }, + ) + + expect(result.apiKey).toBe('existing-key') + expect(result.apiKeyId).toBe('existing-id') + // No key was minted; only verify + balance were called. + expect(calls.some(call => call.endsWith('/v1/keys'))).toBe(false) +}) diff --git a/src/integrations/aimlapi/onboarding.ts b/src/integrations/aimlapi/onboarding.ts new file mode 100644 index 0000000000..5c652c45c9 --- /dev/null +++ b/src/integrations/aimlapi/onboarding.ts @@ -0,0 +1,88 @@ +import { AimlapiClient, type BalanceResult } from './client.js' +import { resolveEndpoints } from './config.js' + +function clientForInferenceBaseUrl(inferenceBaseUrl?: string): AimlapiClient { + const endpoints = resolveEndpoints() + if (inferenceBaseUrl?.trim()) endpoints.inferenceBaseUrl = inferenceBaseUrl.trim() + return new AimlapiClient(endpoints) +} + +export type AimlapiEmailOnboardingResult = + | { action: 'code-sent' } + | { action: 'new-account'; sessionToken: string } + +export type AimlapiCodeSignInResult = { + sessionToken: string + apiKey: string + apiKeyId: string +} & ( + | { balanceStatus: 'confirmed'; lowBalance: boolean } + | { balanceStatus: 'unknown'; balanceError: string } +) + +export async function validateAimlapiApiKey( + apiKey: string, + signal?: AbortSignal, + inferenceBaseUrl?: string, +): Promise { + return clientForInferenceBaseUrl(inferenceBaseUrl).getBalance(apiKey.trim(), signal) +} + +export async function beginAimlapiEmailOnboarding( + email: string, + signal?: AbortSignal, +): Promise { + const client = new AimlapiClient(resolveEndpoints()) + const account = await client.checkAccount(email, signal) + switch (account.action) { + case 'sign-in': + await client.sendSignInCode(email, signal) + return { action: 'code-sent' } + case 'sign-up': { + const auth = await client.createPasswordlessAccount(email, signal) + return { action: 'new-account', sessionToken: auth.token } + } + default: + throw new Error(`AI/ML API returned an unsupported account action.`) + } +} + +export async function completeAimlapiCodeSignIn( + email: string, + code: string, + signal?: AbortSignal, + inferenceBaseUrl?: string, + existingKey?: { apiKey: string; apiKeyId: string }, +): Promise { + const client = clientForInferenceBaseUrl(inferenceBaseUrl) + const auth = await client.verifySignInCode(email, code, signal) + let apiKey = existingKey?.apiKey?.trim() ?? '' + let apiKeyId = existingKey?.apiKeyId ?? '' + if (!apiKey) { + // Reuse a previously issued key when one is supplied so a restart does not + // mint a second key for the same account. + const created = await client.createKey(auth.token, 'OpenClaude CLI', signal) + apiKey = created.key + apiKeyId = created.id + } + try { + const balance = await client.getBalance(apiKey, signal) + return { + sessionToken: auth.token, + apiKey, + apiKeyId, + balanceStatus: 'confirmed', + lowBalance: balance.lowBalance, + } + } catch (error) { + if (signal?.aborted) throw error + // The key is already issued; a balance read failure must not discard it. + return { + sessionToken: auth.token, + apiKey, + apiKeyId, + balanceStatus: 'unknown', + balanceError: error instanceof Error ? error.message : String(error), + } + } +} diff --git a/src/integrations/aimlapi/prompt.test.ts b/src/integrations/aimlapi/prompt.test.ts new file mode 100644 index 0000000000..6efa525bdf --- /dev/null +++ b/src/integrations/aimlapi/prompt.test.ts @@ -0,0 +1,85 @@ +import { afterEach, expect, mock, test } from 'bun:test' +import type { createInterface } from 'node:readline' + +import { promptText } from './prompt.js' + +const originalIsTTY = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY') + +afterEach(() => { + if (originalIsTTY) { + Object.defineProperty(process.stdin, 'isTTY', originalIsTTY) + } else { + Reflect.deleteProperty(process.stdin, 'isTTY') + } +}) + +function setInteractive(): void { + Object.defineProperty(process.stdin, 'isTTY', { + configurable: true, + value: true, + }) +} + +test('promptText trims answers and closes readline', async () => { + setInteractive() + const close = mock(() => {}) + const createReadline = mock(() => ({ + question: (_question: string, resolve: (answer: string) => void) => + resolve(' answer '), + close, + })) + + await expect(promptText('Question', {}, createReadline)).resolves.toBe('answer') + expect(close).toHaveBeenCalledTimes(1) +}) + +test('promptText uses the default for an empty answer', async () => { + setInteractive() + const close = mock(() => {}) + const createReadline = mock(() => ({ + question: (_question: string, resolve: (answer: string) => void) => resolve(' '), + close, + })) + + await expect( + promptText('Question', { defaultValue: 'default' }, createReadline), + ).resolves.toBe('default') + expect(close).toHaveBeenCalledTimes(1) +}) + +test('promptText closes readline when question fails', async () => { + setInteractive() + const close = mock(() => {}) + const createReadline = mock(() => ({ + question: () => { + throw new Error('readline failed') + }, + close, + })) + + await expect(promptText('Question', {}, createReadline)).rejects.toThrow( + 'readline failed', + ) + expect(close).toHaveBeenCalledTimes(1) +}) + +test('promptText masks secret input from terminal output', async () => { + setInteractive() + const written: string[] = [] + const output = { + columns: 80, + write: (chunk: string) => written.push(chunk), + } + const createReadline = mock((options: Parameters[0]) => ({ + question: (_question: string, resolve: (answer: string) => void) => { + options.output?.write('123456') + resolve('123456') + }, + close: () => {}, + })) + + await expect( + promptText('6-digit code', { mask: true }, createReadline, output), + ).resolves.toBe('123456') + expect(written.join('')).toBe('6-digit code: \n') +}) diff --git a/src/integrations/aimlapi/prompt.ts b/src/integrations/aimlapi/prompt.ts index 348aff48fb..acbd9933e7 100644 --- a/src/integrations/aimlapi/prompt.ts +++ b/src/integrations/aimlapi/prompt.ts @@ -4,60 +4,59 @@ * they are not supplied via flags/env. */ -import { createInterface, type Interface } from 'node:readline' +import { createInterface } from 'node:readline' +import { Writable } from 'node:stream' + +type ReadlineInterface = { + question(question: string, callback: (answer: string) => void): void + close(): void +} +type CreateReadlineInterface = ( + options: Parameters[0], +) => ReadlineInterface +type PromptOutput = { + write(chunk: string): unknown + columns?: number +} function assertInteractive(): void { if (!process.stdin.isTTY) { throw new Error( - 'No interactive terminal available. Provide credentials via --email (or AIMLAPI_EMAIL) and the AIMLAPI_PASSWORD env var.', + 'No interactive terminal available. Provide --email (or AIMLAPI_EMAIL) and, for an existing account, --code (or AIMLAPI_CODE).', ) } } export async function promptText( question: string, - opts: { defaultValue?: string } = {}, + opts: { defaultValue?: string; mask?: boolean } = {}, + createReadline: CreateReadlineInterface = createInterface as CreateReadlineInterface, + output: PromptOutput = process.stdout, ): Promise { assertInteractive() const suffix = opts.defaultValue ? ` [${opts.defaultValue}]` : '' - const rl = createInterface({ input: process.stdin, output: process.stdout }) + const label = `${question}${suffix}: ` + const mutedOutput = new Writable({ + write(_chunk, _encoding, done) { + done() + }, + }) as Writable & { columns?: number; isTTY?: boolean } + mutedOutput.columns = output.columns + mutedOutput.isTTY = true + if (opts.mask) output.write(label) + const rl = createReadline({ + input: process.stdin, + output: opts.mask ? mutedOutput : process.stdout, + ...(opts.mask ? { terminal: true } : {}), + }) try { const answer = await new Promise((resolve) => { - rl.question(`${question}${suffix}: `, resolve) + rl.question(opts.mask ? '' : label, resolve) }) const trimmed = answer.trim() return trimmed || opts.defaultValue || '' } finally { rl.close() - } -} - -/** Prompt for a secret without echoing keystrokes to the terminal. */ -export async function promptHidden(question: string): Promise { - assertInteractive() - const rl = createInterface({ - input: process.stdin, - output: process.stdout, - }) as Interface & { _writeToOutput?: (chunk: string) => void } - - // Mask everything except the prompt itself. - let muted = false - rl._writeToOutput = (chunk: string): void => { - if (muted) { - process.stdout.write('*') - } else { - process.stdout.write(chunk) - } - } - - try { - const answer = await new Promise((resolve) => { - rl.question(`${question}: `, resolve) - muted = true - }) - process.stdout.write('\n') - return answer - } finally { - rl.close() + if (opts.mask) output.write('\n') } } diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts new file mode 100644 index 0000000000..e70ab16fff --- /dev/null +++ b/src/integrations/aimlapi/topup.test.ts @@ -0,0 +1,795 @@ +import { afterAll, afterEach, expect, mock, test } from 'bun:test' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { setClaudeConfigHomeDirForTesting } from '../../utils/envUtils.js' +import * as realTopupDependencies from './topupDependencies.js' +import { claimAimlapiTopupState, saveAimlapiTopupState } from './topupState.js' +import { isValidAimlapiEmail, parseAimlapiAmountUsd } from './validation.js' + +let lastSavedProfileEnv: Record | undefined +mock.module('./topupDependencies.js', () => ({ + openBrowser: async () => {}, + saveProfileFile: (arg: { env: Record }) => { + lastSavedProfileEnv = arg.env + return 'profile.json' + }, + promptText: async () => '', +})) +const { pollUntilPaid, provisionAimlapiKey, runAimlapiTopup, topUpAimlapiByApiKey } = + await import('./topup.js') +const { AimlapiClient } = await import('./client.js') + +// createSession/getSession responses are validated against the full +// PartnerCheckoutSession contract, so mocks must carry id + partnerId too. +function sessionJson(session: Record): Response { + return Response.json({ + id: 'sess_test', + partnerId: 'part_62yQoGYDq4Yqnrj2R1iGrDNJ', + ...session, + }) +} + +const originalFetch = globalThis.fetch +const originalEnv = { + AIMLAPI_AUTH_URL: process.env.AIMLAPI_AUTH_URL, + AIMLAPI_APP_URL: process.env.AIMLAPI_APP_URL, + AIMLAPI_INFERENCE_URL: process.env.AIMLAPI_INFERENCE_URL, + AIMLAPI_PAY_URL: process.env.AIMLAPI_PAY_URL, + AIMLAPI_PARTNER_ID: process.env.AIMLAPI_PARTNER_ID, + AIMLAPI_VERIFICATION_BASE_URL: process.env.AIMLAPI_VERIFICATION_BASE_URL, + AIMLAPI_RETURN_URL: process.env.AIMLAPI_RETURN_URL, + AIMLAPI_EMAIL: process.env.AIMLAPI_EMAIL, + AIMLAPI_CODE: process.env.AIMLAPI_CODE, +} +const temporaryDirectories: string[] = [] + +afterAll(() => { + mock.module('./topupDependencies.js', () => realTopupDependencies) +}) + +afterEach(() => { + globalThis.fetch = originalFetch + lastSavedProfileEnv = undefined + setClaudeConfigHomeDirForTesting(undefined) + for (const directory of temporaryDirectories.splice(0)) { + rmSync(directory, { force: true, recursive: true }) + } + for (const [name, value] of Object.entries(originalEnv)) { + if (value === undefined) delete process.env[name] + else process.env[name] = value + } +}) + +test('parseAimlapiAmountUsd enforces checkout bounds', () => { + expect(parseAimlapiAmountUsd(undefined)).toBe(2500) + expect(parseAimlapiAmountUsd('20')).toBe(2000) + expect(parseAimlapiAmountUsd('25.25')).toBe(2525) + expect(parseAimlapiAmountUsd('10000')).toBe(1_000_000) + expect(() => parseAimlapiAmountUsd('19.99')).toThrow('Minimum top-up is $20') + expect(() => parseAimlapiAmountUsd('10000.01')).toThrow('Maximum top-up is $10000') + expect(() => parseAimlapiAmountUsd('19.999')).toThrow('Pass a valid USD amount') + expect(() => parseAimlapiAmountUsd('10000.004')).toThrow('Pass a valid USD amount') + expect(() => parseAimlapiAmountUsd('nope')).toThrow('Pass a positive number of USD') + expect(() => parseAimlapiAmountUsd('Infinity')).toThrow('Pass a positive number of USD') +}) + +test('isValidAimlapiEmail rejects incomplete domains', () => { + expect(isValidAimlapiEmail('user@example.com')).toBe(true) + expect(isValidAimlapiEmail('user@example')).toBe(false) + expect(isValidAimlapiEmail('user@example.c')).toBe(false) + expect(isValidAimlapiEmail('user@.example.com')).toBe(false) +}) + +test('CLI retries reuse the persisted checkout session and payment id', async () => { + const configDirectory = mkdtempSync(join(tmpdir(), 'openclaude-aimlapi-cli-')) + temporaryDirectories.push(configDirectory) + setClaudeConfigHomeDirForTesting(configDirectory) + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_PAY_URL = 'https://pay.example.test' + + let accountChecks = 0 + const payBodies: Array> = [] + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input) + if (url.endsWith('/v1/auth/account')) { + accountChecks += 1 + return Response.json({ action: accountChecks === 1 ? 'sign-up' : 'sign-in' }) + } + if (url.endsWith('/passwordless')) { + return Response.json({ token: 'account-token-one', exp: 1 }) + } + if (url.endsWith('/sign-in/code')) return new Response(null, { status: 204 }) + if (url.endsWith('/code/verify')) { + return Response.json({ token: 'account-token-two', exp: 2 }) + } + if (url.endsWith('/v1/keys')) { + return Response.json({ key: 'key_test', id: 'key_id' }) + } + if (url.endsWith('/v3/partner-checkout/sessions') && init?.method === 'POST') { + return sessionJson({ sessionToken: 'checkout-session', status: 'pending_auth' }) + } + if (url.endsWith('/pay')) { + payBodies.push(JSON.parse(String(init?.body)) as Record) + throw new Error('ambiguous payment response') + } + if (url.endsWith('/v3/partner-checkout/sessions/checkout-session')) { + return sessionJson({ sessionToken: 'checkout-session', status: 'paid' }) + } + throw new Error(`Unexpected request: ${url}`) + }) as unknown as typeof fetch + + await expect( + runAimlapiTopup({ email: 'user@example.com', amountUsd: '25', noOpen: true }), + ).rejects.toThrow('ambiguous payment response') + + const saved = JSON.parse( + readFileSync(join(configDirectory, 'aimlapi-topup.json'), 'utf8'), + ) as { paymentSessionId: string; resumeSessionToken: string } + expect(saved.paymentSessionId).toBeTruthy() + expect(saved.resumeSessionToken).toBe('checkout-session') + expect(payBodies).toHaveLength(1) + expect(payBodies[0]?.paymentSessionId).toBe(saved.paymentSessionId) + + await runAimlapiTopup({ + email: 'user@example.com', + code: '123456', + amountUsd: '25', + noOpen: true, + }) + expect(payBodies).toHaveLength(1) + expect(() => readFileSync(join(configDirectory, 'aimlapi-topup.json'))).toThrow() +}) + +test('CLI retains an already-exchanged checkout and blocks identical retries', async () => { + const configDirectory = mkdtempSync(join(tmpdir(), 'openclaude-aimlapi-cli-')) + temporaryDirectories.push(configDirectory) + setClaudeConfigHomeDirForTesting(configDirectory) + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_PAY_URL = 'https://pay.example.test' + const persisted = claimAimlapiTopupState({ + email: 'user@example.com', + amountUsdMinor: 2500, + autoTopUp: false, + partnerId: 'part_62yQoGYDq4Yqnrj2R1iGrDNJ', + partnerName: 'Gitlawb', + appBaseUrl: 'https://app.example.test', + inferenceBaseUrl: 'https://api.aimlapi.com/v1', + payBaseUrl: 'https://pay.example.test', + verificationBaseUrl: 'https://aimlapi.com/app', + }) + saveAimlapiTopupState({ + email: 'user@example.com', + amountUsdMinor: 2500, + autoTopUp: false, + partnerId: 'part_62yQoGYDq4Yqnrj2R1iGrDNJ', + partnerName: 'Gitlawb', + appBaseUrl: 'https://app.example.test', + inferenceBaseUrl: 'https://api.aimlapi.com/v1', + payBaseUrl: 'https://pay.example.test', + verificationBaseUrl: 'https://aimlapi.com/app', + paymentSessionId: persisted.paymentSessionId, + resumeSessionToken: 'exchanged-session', + }) + + let sessionReads = 0 + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + if (url.endsWith('/v1/auth/account')) return Response.json({ action: 'sign-in' }) + if (url.endsWith('/sign-in/code')) return new Response(null, { status: 204 }) + if (url.endsWith('/code/verify')) { + return Response.json({ token: 'account-token', exp: 1 }) + } + if (url.endsWith('/v1/keys')) { + return Response.json({ key: 'key_test', id: 'created-key' }) + } + if (url.endsWith('/sessions/exchanged-session')) { + sessionReads += 1 + return sessionJson({ + sessionToken: 'exchanged-session', + status: 'exchanged', + issuedKeyId: 'issued-key-id', + }) + } + throw new Error(`Unexpected request: ${url}`) + }) as unknown as typeof fetch + + const retry = (): Promise => + runAimlapiTopup({ + email: 'user@example.com', + code: '123456', + amountUsd: '25', + noOpen: true, + }) + + await expect(retry()).rejects.toThrow('issued key issued-key-id') + await expect(retry()).rejects.toThrow('issued key issued-key-id') + expect(sessionReads).toBe(2) + expect( + JSON.parse(readFileSync(join(configDirectory, 'aimlapi-topup.json'), 'utf8')), + ).toMatchObject({ + paymentSessionId: persisted.paymentSessionId, + resumeSessionToken: 'exchanged-session', + }) +}) + +test('a failed payment retains the issued key for the next run', async () => { + const configDirectory = mkdtempSync(join(tmpdir(), 'openclaude-aimlapi-cli-')) + temporaryDirectories.push(configDirectory) + setClaudeConfigHomeDirForTesting(configDirectory) + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_PAY_URL = 'https://pay.example.test' + // Keep the canonical inference URL so the guided-provisioning gate allows the + // run; the flow uses the app/auth/pay hosts for its requests. + + let keyMints = 0 + let sessionStatus = 'expired' + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input) + if (url.endsWith('/v1/auth/account')) return Response.json({ action: 'sign-in' }) + if (url.endsWith('/sign-in/code')) return new Response(null, { status: 204 }) + if (url.endsWith('/code/verify')) return Response.json({ token: 'account-token', exp: 1 }) + if (url.endsWith('/v1/keys')) { + keyMints += 1 + return Response.json({ key: 'key_test', id: 'key_id' }) + } + if (url.endsWith('/v3/partner-checkout/sessions') && init?.method === 'POST') { + return sessionJson({ sessionToken: 'checkout-session', status: 'pending_auth' }) + } + if (url.endsWith('/pay')) { + return Response.json({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test/pay' }, + partnerCheckout: { sessionToken: 'checkout-session', status: 'pending_payment' }, + }) + } + if (url.endsWith('/v3/partner-checkout/sessions/checkout-session')) { + return sessionJson({ sessionToken: 'checkout-session', status: sessionStatus }) + } + throw new Error(`Unexpected request: ${url}`) + }) as unknown as typeof fetch + + // First run: the payment expires. The issued key must survive the terminal reset. + await expect( + runAimlapiTopup({ email: 'user@example.com', code: '123456', amountUsd: '25', noOpen: true }), + ).rejects.toThrow('Payment expired') + + const afterFailure = JSON.parse( + readFileSync(join(configDirectory, 'aimlapi-topup.json'), 'utf8'), + ) as { apiKey?: string; resumeSessionToken: string } + expect(afterFailure.apiKey).toBe('key_test') + expect(afterFailure.resumeSessionToken).toBe('') + expect(keyMints).toBe(1) + + // Second run: the payment clears and the retained key is reused (not re-minted). + sessionStatus = 'paid' + await runAimlapiTopup({ + email: 'user@example.com', + code: '123456', + amountUsd: '25', + noOpen: true, + }) + expect(keyMints).toBe(1) + expect(() => readFileSync(join(configDirectory, 'aimlapi-topup.json'))).toThrow() +}) + +test('the CLI refuses guided top-up on a non-canonical inference endpoint', async () => { + process.env.AIMLAPI_INFERENCE_URL = 'https://proxy.example.test/v1' + let fetched = false + globalThis.fetch = mock(async () => { + fetched = true + return Response.json({}) + }) as unknown as typeof fetch + + await expect( + runAimlapiTopup({ email: 'user@example.com', amountUsd: '25', noOpen: true }), + ).rejects.toThrow('production endpoint') + // Rejected before any account lookup or key mint. + expect(fetched).toBe(false) +}) + +test('a settled interrupted run resumes the profile write without re-provisioning', async () => { + const configDirectory = mkdtempSync(join(tmpdir(), 'openclaude-aimlapi-cli-')) + temporaryDirectories.push(configDirectory) + setClaudeConfigHomeDirForTesting(configDirectory) + const intent = { + email: 'user@example.com', + amountUsdMinor: 2500, + autoTopUp: false, + partnerId: 'part_62yQoGYDq4Yqnrj2R1iGrDNJ', + partnerName: 'Gitlawb', + appBaseUrl: 'https://app.aimlapi.com', + inferenceBaseUrl: 'https://api.aimlapi.com/v1', + payBaseUrl: 'https://pay.aimlapi.com', + verificationBaseUrl: 'https://aimlapi.com/app', + } + const claimed = claimAimlapiTopupState(intent) + saveAimlapiTopupState({ + ...intent, + paymentSessionId: claimed.paymentSessionId, + resumeSessionToken: 'checkout-session', + apiKey: 'exchanged-key', + apiKeyId: 'exchanged-id', + // Original run provisioned a non-default model. + model: 'anthropic/claude-opus-4-8', + settled: true, + }) + + let fetched = false + globalThis.fetch = mock(async () => { + fetched = true + return Response.json({}) + }) as unknown as typeof fetch + + // Retry without --model: the default would be gpt-4o, but the settled receipt + // must win. + await runAimlapiTopup({ email: 'user@example.com', amountUsd: '25', noOpen: true }) + + // The retained settled key finished the write — no account check/provisioning, + // the persisted model is preserved, and the checkout state is cleared. + expect(fetched).toBe(false) + expect(lastSavedProfileEnv?.OPENAI_API_KEY).toBe('exchanged-key') + expect(lastSavedProfileEnv?.OPENAI_MODEL).toBe('anthropic/claude-opus-4-8') + expect(() => readFileSync(join(configDirectory, 'aimlapi-topup.json'))).toThrow() +}) + +test('topUpAimlapiByApiKey funds the key account without exchange', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + process.env.AIMLAPI_PAY_URL = 'https://pay.example.test' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input) + calls.push(`${init?.method} ${url}`) + if (url.endsWith('/v3/partner-checkout/sessions')) { + return sessionJson({ sessionToken: 'session', status: 'pending_auth' }) + } + if (url.endsWith('/v2/billing/topup')) { + return Response.json({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test' }, + partnerCheckout: { sessionToken: 'session', status: 'pending_payment' }, + }) + } + if (url.endsWith('/v3/partner-checkout/sessions/session')) { + return sessionJson({ sessionToken: 'session', status: 'paid' }) + } + return new Response('', { status: 404 }) + }) as unknown as typeof fetch + + const sessions: string[] = [] + const result = await topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + amountUsd: '25', + noOpen: true, + onSession: session => sessions.push(session), + }) + + expect(result.apiKey).toBe('key_test') + expect(sessions).toEqual(['session']) + expect(calls).toEqual([ + 'POST https://app.example.test/v3/partner-checkout/sessions', + 'POST https://api.example.test/v2/billing/topup', + 'GET https://app.example.test/v3/partner-checkout/sessions/session', + ]) + expect(calls.some(call => call.endsWith('/exchange'))).toBe(false) +}) + +test('topUpAimlapiByApiKey resumes a paid session without charging again', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + calls.push(`${init?.method} ${String(input)}`) + return sessionJson({ sessionToken: 'session', status: 'paid' }) + }) as unknown as typeof fetch + + await topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + resumeSessionToken: 'session', + amountUsd: '25', + noOpen: true, + }) + + expect(calls).toEqual([ + 'GET https://app.example.test/v3/partner-checkout/sessions/session', + ]) +}) + +test('a pending resumed session is polled without paying again', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + const calls: string[] = [] + let reads = 0 + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + calls.push(`${init?.method} ${String(input)}`) + reads += 1 + return sessionJson({ + sessionToken: 'session', + status: reads === 1 ? 'pending_payment' : 'paid', + }) + }) as unknown as typeof fetch + + await topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + resumeSessionToken: 'session', + amountUsd: '25', + noOpen: true, + }) + + expect(calls).toEqual([ + 'GET https://app.example.test/v3/partner-checkout/sessions/session', + 'GET https://app.example.test/v3/partner-checkout/sessions/session', + ]) +}) + +test('a resumed by-key session still exchanging settles before success', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + const calls: string[] = [] + let reads = 0 + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + calls.push(`${init?.method} ${String(input)}`) + reads += 1 + return sessionJson({ + sessionToken: 'session', + status: reads === 1 ? 'exchanging' : 'exchanged', + }) + }) as unknown as typeof fetch + + const result = await topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + resumeSessionToken: 'session', + amountUsd: '25', + noOpen: true, + }) + + expect(result.apiKey).toBe('key_test') + // The first GET resolves the resumed session (exchanging); the settle poll + // then waits for it to reach exchanged instead of reporting success early. + expect(calls).toEqual([ + 'GET https://app.example.test/v3/partner-checkout/sessions/session', + 'GET https://app.example.test/v3/partner-checkout/sessions/session', + ]) +}) + +test('an invalid amount is rejected before any key is minted', async () => { + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + calls.push(url) + if (url.endsWith('/v1/auth/account')) return Response.json({ action: 'sign-in' }) + throw new Error(`Unexpected request: ${url}`) + }) as unknown as typeof fetch + + await expect( + runAimlapiTopup({ + email: 'user@example.com', + code: '123456', + amountUsd: '5', + noOpen: true, + }), + ).rejects.toThrow('Minimum top-up is $20') + expect(calls.some(call => call.endsWith('/v1/keys'))).toBe(false) + expect(calls.some(call => call.endsWith('/sign-in/code'))).toBe(false) +}) + +test('an unsupported account action is rejected without provisioning', async () => { + const configDirectory = mkdtempSync(join(tmpdir(), 'openclaude-aimlapi-cli-')) + temporaryDirectories.push(configDirectory) + setClaudeConfigHomeDirForTesting(configDirectory) + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + calls.push(url) + if (url.endsWith('/v1/auth/account')) return Response.json({ action: 'reset' }) + throw new Error(`Unexpected request: ${url}`) + }) as unknown as typeof fetch + + await expect( + runAimlapiTopup({ email: 'user@example.com', amountUsd: '25', noOpen: true }), + ).rejects.toThrow('unsupported account action') + expect(calls.some(call => call.endsWith('/passwordless'))).toBe(false) + expect(calls.some(call => call.endsWith('/v1/keys'))).toBe(false) +}) + +test('provisionAimlapiKey does not repeat an already completed exchange', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + calls.push(`${init?.method} ${String(input)}`) + return sessionJson({ + sessionToken: 'session', + status: 'exchanged', + issuedKeyId: 'key_recoverable', + }) + }) as unknown as typeof fetch + const sessions: string[] = [] + + await expect( + provisionAimlapiKey({ + sessionToken: 'account-session', + resumeSessionToken: 'session', + paymentSessionId: 'payment-id', + exchange: true, + amountUsd: '25', + noOpen: true, + onSession: session => sessions.push(session), + }), + ).rejects.toThrow('issued key key_recoverable') + + expect(calls).toEqual([ + 'GET https://app.example.test/v3/partner-checkout/sessions/session', + ]) + expect(sessions).toEqual([]) +}) + +test('an in-progress exchange is observed without issuing a second exchange', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + const calls: string[] = [] + let reads = 0 + const sessions: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + calls.push(`${init?.method} ${String(input)}`) + reads += 1 + return sessionJson({ + sessionToken: 'session', + status: reads === 1 ? 'exchanging' : 'exchanged', + }) + }) as unknown as typeof fetch + + await expect( + provisionAimlapiKey({ + sessionToken: 'account-session', + resumeSessionToken: 'session', + paymentSessionId: 'payment-id', + exchange: true, + amountUsd: '25', + noOpen: true, + onSession: session => sessions.push(session), + }), + ).rejects.toThrow('Session was already exchanged') + expect(calls.every(call => call.startsWith('GET '))).toBe(true) + expect(sessions).toEqual(['session']) +}) + +test('email-session checkout carries the stable payment id', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_PAY_URL = 'https://pay.example.test' + let payBody: Record | undefined + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input) + if (url.endsWith('/v3/partner-checkout/sessions')) { + return sessionJson({ sessionToken: 'session', status: 'pending_auth' }) + } + if (url.endsWith('/pay')) { + payBody = JSON.parse(String(init?.body)) as Record + return Response.json({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test/pay' }, + partnerCheckout: { sessionToken: 'session', status: 'pending_payment' }, + }) + } + return sessionJson({ sessionToken: 'session', status: 'paid' }) + }) as unknown as typeof fetch + + await provisionAimlapiKey({ + sessionToken: 'account-session', + paymentSessionId: 'stable-payment-id', + exchange: false, + existingApiKey: 'key_test', + amountUsd: '25', + noOpen: true, + }) + + expect(payBody?.paymentSessionId).toBe('stable-payment-id') +}) + +test('checkout URL must be an absolute credential-free HTTPS URL', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + if (url.endsWith('/v3/partner-checkout/sessions')) { + return sessionJson({ sessionToken: 'session', status: 'pending_auth' }) + } + return Response.json({ + checkout: { providerSessionId: 'provider', payUrl: 'file:///tmp/checkout' }, + partnerCheckout: { sessionToken: 'session', status: 'pending_payment' }, + }) + }) as unknown as typeof fetch + + await expect( + topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + amountUsd: '25', + noOpen: true, + }), + ).rejects.toThrow('valid HTTPS checkout URL') +}) + +test('terminal resumed-session errors clear retained checkout state', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + globalThis.fetch = mock(async () => new Response('gone', { status: 404 })) as unknown as typeof fetch + const sessions: string[] = [] + + await expect( + topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + resumeSessionToken: 'dead-session', + amountUsd: '25', + noOpen: true, + onSession: session => sessions.push(session), + }), + ).rejects.toThrow('404') + expect(sessions).toEqual(['']) +}) + +test('dead sessions observed while polling are cleared immediately', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + if (url.endsWith('/v3/partner-checkout/sessions')) { + return sessionJson({ sessionToken: 'session', status: 'pending_auth' }) + } + if (url.endsWith('/v2/billing/topup')) { + return Response.json({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test/pay' }, + partnerCheckout: { sessionToken: 'session', status: 'pending_payment' }, + }) + } + return sessionJson({ sessionToken: 'session', status: 'expired' }) + }) as unknown as typeof fetch + const sessions: string[] = [] + + await expect( + topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + amountUsd: '25', + noOpen: true, + onSession: session => sessions.push(session), + }), + ).rejects.toThrow('Payment expired') + expect(sessions).toEqual(['session', '']) +}) + +test('aborting during polling stops requests and preserves the retained session', async () => { + const controller = new AbortController() + let getCount = 0 + globalThis.fetch = mock(async () => { + getCount += 1 + controller.abort() + return sessionJson({ sessionToken: 'session', status: 'pending_payment' }) + }) as unknown as typeof fetch + const client = new AimlapiClient({ + authBaseUrl: 'https://auth.example.test', + appBaseUrl: 'https://app.example.test', + inferenceBaseUrl: 'https://api.example.test/v1', + payBaseUrl: 'https://pay.example.test', + verificationBaseUrl: 'https://front.example.test', + }) + const sessions: string[] = [] + + await expect( + pollUntilPaid(client, 'session', controller.signal, value => sessions.push(value)), + ).rejects.toThrow() + // Aborted before the next poll: exactly one GET, and the session is not cleared. + expect(getCount).toBe(1) + expect(sessions).toEqual([]) +}) + +test('terminal API errors observed while polling clear retained checkout state', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + if (url.endsWith('/v3/partner-checkout/sessions')) { + return sessionJson({ sessionToken: 'session', status: 'pending_auth' }) + } + if (url.endsWith('/v2/billing/topup')) { + return Response.json({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test/pay' }, + partnerCheckout: { sessionToken: 'session', status: 'pending_payment' }, + }) + } + return new Response('gone', { status: 410 }) + }) as unknown as typeof fetch + const sessions: string[] = [] + + await expect( + topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + amountUsd: '25', + noOpen: true, + onSession: session => sessions.push(session), + }), + ).rejects.toThrow('410') + expect(sessions).toEqual(['session', '']) +}) + +test('polling retries a transient transport failure', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + let attempts = 0 + globalThis.fetch = mock(async () => { + attempts += 1 + if (attempts === 1) throw new TypeError('temporary connection reset') + return sessionJson({ sessionToken: 'session', status: 'paid' }) + }) as unknown as typeof fetch + const client = new AimlapiClient({ + authBaseUrl: 'https://auth.example.test', + appBaseUrl: 'https://app.example.test', + inferenceBaseUrl: 'https://api.example.test/v1', + payBaseUrl: 'https://pay.example.test', + verificationBaseUrl: 'https://front.example.test', + }) + + await expect(pollUntilPaid(client, 'session')).resolves.toEqual( + expect.objectContaining({ status: 'paid' }), + ) + expect(attempts).toBe(2) +}) + +test('polling retains and retries the same session after a rate limit', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + let attempts = 0 + globalThis.fetch = mock(async () => { + attempts += 1 + if (attempts === 1) return new Response('rate limited', { status: 429 }) + return sessionJson({ sessionToken: 'session', status: 'paid' }) + }) as unknown as typeof fetch + const client = new AimlapiClient({ + authBaseUrl: 'https://auth.example.test', + appBaseUrl: 'https://app.example.test', + inferenceBaseUrl: 'https://api.example.test/v1', + payBaseUrl: 'https://pay.example.test', + verificationBaseUrl: 'https://front.example.test', + }) + const sessions: string[] = [] + + await expect( + pollUntilPaid(client, 'session', undefined, value => sessions.push(value)), + ).resolves.toEqual(expect.objectContaining({ status: 'paid' })) + expect(attempts).toBe(2) + expect(sessions).toEqual([]) +}) + +test('by-key billing stays on the endpoint that validated the key', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://override.example.test/v1' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + calls.push(url) + if (url.endsWith('/v3/partner-checkout/sessions')) { + return sessionJson({ sessionToken: 'session', status: 'pending_auth' }) + } + if (url.endsWith('/v2/billing/topup')) { + return Response.json({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test/pay' }, + partnerCheckout: { sessionToken: 'session', status: 'pending_payment' }, + }) + } + return sessionJson({ sessionToken: 'session', status: 'paid' }) + }) as unknown as typeof fetch + + await topUpAimlapiByApiKey({ + apiKey: 'production-key', + inferenceBaseUrl: 'https://api.aimlapi.com/v1', + paymentSessionId: 'payment-id', + amountUsd: '25', + noOpen: true, + }) + expect(calls).toContain('https://api.aimlapi.com/v2/billing/topup') + expect(calls).not.toContain('https://override.example.test/v2/billing/topup') +}) diff --git a/src/integrations/aimlapi/topup.ts b/src/integrations/aimlapi/topup.ts index a4348259d1..7538015ba4 100644 --- a/src/integrations/aimlapi/topup.ts +++ b/src/integrations/aimlapi/topup.ts @@ -1,58 +1,43 @@ -/** - * AI/ML API seamless top-up flow. - * - * End to end: - * 1. Log in with AI/ML API credentials -> Bearer token (held by the CLI) - * 2. Create a partner-checkout session -> one-time sessionToken - * 3. `pay` binds the session + opens a hosted payment page (Stripe / crypto) - * 4. Open the browser for the user to pay -> no second login ("auto-login": - * the hosted page needs no AI/ML API account, the CLI already holds auth) - * 5. Poll the session until it is `paid` - * 6. Exchange the paid session for a raw key (once) - * 7. Write the key into OpenClaude's provider profile -> the agent now runs - * on AI/ML API's OpenAI-compatible endpoint - * - * After pay/cancel the provider redirects the browser to the co-branded AI/ML - * API `/checkout` success / failure screen - see - * `buildPartnerCheckoutReturnUrls`. - * - * Uses the AI/ML API endpoints from config.ts. - */ +/** AI/ML API passwordless onboarding and partner-checkout orchestration. */ import chalk from 'chalk' -import { openBrowser } from '../../utils/browser.js' -import { saveProfileFile } from '../../utils/providerProfile.js' import { AimlapiApiError, AimlapiClient, type PartnerCheckoutSession, - type PaymentMethod, } from './client.js' import { buildPartnerCheckoutReturnUrls, - DEFAULT_AMOUNT_USD_MINOR, + buildPartnerReturnUrl, DEFAULT_MODEL, - DEFAULT_PARTNER_ID, DEFAULT_PARTNER_NAME, - MAX_AMOUNT_USD_MINOR, - MIN_AMOUNT_USD_MINOR, + isCanonicalAimlapiInferenceBaseUrl, resolveEndpoints, + resolvePartnerId, } from './config.js' -import { promptHidden, promptText } from './prompt.js' +import { openBrowser, promptText, saveProfileFile } from './topupDependencies.js' +import { + claimAimlapiTopupState, + clearAimlapiTopupState, + resetAimlapiCheckoutSession, + saveAimlapiTopupState, + type AimlapiTopupIntent, +} from './topupState.js' +import { isValidAimlapiEmail, parseAimlapiAmountUsd } from './validation.js' export type AimlapiTopupOptions = { email?: string - password?: string + code?: string /** Top-up amount in whole USD (e.g. "25"). */ amountUsd?: string - method?: PaymentMethod + autoTopUp?: boolean model?: string partnerId?: string partnerName?: string - inviteCode?: string /** Skip opening the browser (print the URL instead). */ noOpen?: boolean + signal?: AbortSignal } export type AimlapiProvisionedKey = { @@ -63,297 +48,626 @@ export type AimlapiProvisionedKey = { } export type AimlapiTopupStatus = - | 'registering' - | 'registered' - | 'signing-in' - | 'signed-in' + | 'checking-account' + | 'sending-code' + | 'verifying-code' + | 'creating-account' + | 'creating-key' | 'creating-session' | 'opening-checkout' | 'waiting-payment' | 'provisioning-key' -export type AimlapiProvisionOptions = AimlapiTopupOptions & { +export type AimlapiProvisionOptions = Omit & { + sessionToken: string + /** Endpoint that validated an existing key and must own any key-bound billing. */ + inferenceBaseUrl?: string + exchange: boolean + existingApiKey?: string + existingApiKeyId?: string + resumeSessionToken?: string + /** Stable idempotency handle retained for one amount/auto-top-up intent. */ + paymentSessionId: string + onSession?: (sessionToken: string) => void + onStatus?: (status: AimlapiTopupStatus, detail?: string) => void +} + +export type AimlapiByKeyTopupOptions = Omit & { + apiKey: string + inferenceBaseUrl?: string + paymentSessionId: string + resumeSessionToken?: string + onSession?: (sessionToken: string) => void onStatus?: (status: AimlapiTopupStatus, detail?: string) => void } +type TopupPhase = 'pay' | 'poll' | 'exchange' | 'wait-exchange' + const POLL_INTERVAL_MS = 3000 -const POLL_TIMEOUT_MS = 20 * 60 * 1000 // 20 minutes +const POLL_TIMEOUT_MS = 20 * 60 * 1000 -const sleep = (ms: number): Promise => - new Promise((resolve) => setTimeout(resolve, ms)) +function abortError(signal?: AbortSignal): unknown { + return signal?.reason ?? new DOMException('The operation was aborted.', 'AbortError') +} -function maskKey(key: string): string { - if (key.length <= 10) { - return '****' - } - return `${key.slice(0, 6)}...${key.slice(-4)}` +async function sleep(ms: number, signal?: AbortSignal): Promise { + if (signal?.aborted) throw abortError(signal) + await new Promise((resolve, reject) => { + const cleanup = (): void => signal?.removeEventListener('abort', onAbort) + const timer = setTimeout(() => { + cleanup() + resolve() + }, ms) + const onAbort = (): void => { + clearTimeout(timer) + cleanup() + reject(abortError(signal)) + } + signal?.addEventListener('abort', onAbort, { once: true }) + }) } -function parseAmount(amountUsd: string | undefined): number { - if (!amountUsd) { - return DEFAULT_AMOUNT_USD_MINOR - } - const dollars = Number(amountUsd) - if (!Number.isFinite(dollars) || dollars <= 0) { - throw new Error(`Invalid amount: "${amountUsd}". Pass a positive number of USD.`) - } - const minor = Math.round(dollars * 100) - if (minor < MIN_AMOUNT_USD_MINOR) { - throw new Error(`Minimum top-up is $${MIN_AMOUNT_USD_MINOR / 100}.`) - } - if (minor > MAX_AMOUNT_USD_MINOR) { - throw new Error(`Maximum top-up is $${MAX_AMOUNT_USD_MINOR / 100}.`) - } - return minor +function maskKey(key: string): string { + return key.length <= 10 ? '****' : `${key.slice(0, 6)}...${key.slice(-4)}` } -function describeAimlapiAuthError(error: unknown): string { - if (error instanceof AimlapiApiError) { - const body = error.body.trim() - return body - ? `HTTP ${error.status}: ${body}` - : `HTTP ${error.status}: ${error.message}` - } - return error instanceof Error ? error.message : String(error) +function alreadyExchangedError(session: PartnerCheckoutSession): Error { + const keyHint = session.issuedKeyId?.trim() + ? ` for issued key ${session.issuedKeyId.trim()}` + : '' + return new Error( + `Session was already exchanged${keyHint}. Open https://aimlapi.com/app and rotate the issued key to recover access.`, + ) } -async function authenticateAimlapiAccount( - client: AimlapiClient, - options: { - email: string - password: string - inviteCode?: string - onStatus?: (status: AimlapiTopupStatus, detail?: string) => void - }, -): Promise { - let signupError: unknown - try { - options.onStatus?.('registering') - const { token } = await client.signup({ - email: options.email, - password: options.password, - inviteCode: options.inviteCode, - }) - options.onStatus?.('registered') - return token - } catch (error) { - signupError = error - } +export async function runAimlapiTopup(options: AimlapiTopupOptions): Promise { + const endpoints = resolveEndpoints() + const client = new AimlapiClient(endpoints) + const email = + options.email?.trim() || + process.env.AIMLAPI_EMAIL?.trim() || + (await promptText('AI/ML API email')) + if (!isValidAimlapiEmail(email)) throw new Error('Email format is incorrect.') - try { - options.onStatus?.('signing-in') - const { token } = await client.login(options.email, options.password) - options.onStatus?.('signed-in') - return token - } catch (loginError) { + // Guided provisioning mints/exchanges a production-account key via production + // auth and writes it as OPENAI_BASE_URL. Refuse a non-canonical inference + // override so a freshly minted key is never sent to a custom/proxy endpoint + // (mirrors the provider-manager gate). + if (!isCanonicalAimlapiInferenceBaseUrl(endpoints.inferenceBaseUrl)) { throw new Error( - `Could not register or log in to AI/ML API. Registration: ${describeAimlapiAuthError(signupError)}. Login: ${describeAimlapiAuthError(loginError)}.`, + 'Guided top-up requires the aimlapi.com production endpoint. Unset AIMLAPI_INFERENCE_URL to create or fund a key.', ) } -} -export async function runAimlapiTopup(options: AimlapiTopupOptions): Promise { - const endpoints = resolveEndpoints() - const client = new AimlapiClient(endpoints) + console.log(chalk.bold('\n AI/ML API top-up') + chalk.dim(` - ${endpoints.appBaseUrl}\n`)) - const partnerId = options.partnerId?.trim() || process.env.AIMLAPI_PARTNER_ID?.trim() || DEFAULT_PARTNER_ID + // Validate the amount and claim (or reuse) the retained checkout before any + // account lookup or key mint: an invalid amount must not strand an unused + // key, and an interrupted checkout must resume on the same key rather than + // mint a fresh one on every retry. + const amountUsdMinor = parseAimlapiAmountUsd(options.amountUsd) + const partnerId = resolvePartnerId(options.partnerId) const partnerName = options.partnerName?.trim() || DEFAULT_PARTNER_NAME - const method: PaymentMethod = options.method === 'crypto' ? 'crypto' : 'card' - const model = options.model?.trim() || DEFAULT_MODEL - const amountUsdMinor = parseAmount(options.amountUsd) - - console.log( - chalk.bold(`\n AI/ML API top-up`) + - chalk.dim(` - ${endpoints.appBaseUrl}\n`), - ) + const intent: AimlapiTopupIntent = { + email: email.toLowerCase(), + amountUsdMinor, + autoTopUp: options.autoTopUp === true, + partnerId, + partnerName, + appBaseUrl: endpoints.appBaseUrl.trim().replace(/\/+$/, ''), + inferenceBaseUrl: endpoints.inferenceBaseUrl.trim().replace(/\/+$/, ''), + payBaseUrl: endpoints.payBaseUrl.trim().replace(/\/+$/, ''), + verificationBaseUrl: endpoints.verificationBaseUrl.trim().replace(/\/+$/, ''), + } + const checkoutState = claimAimlapiTopupState(intent) + + const finishProfile = (provisioned: AimlapiProvisionedKey): void => { + const profilePath = saveProfileFile({ + profile: 'openai', + env: { + OPENAI_BASE_URL: provisioned.baseUrl, + OPENAI_API_KEY: provisioned.apiKey, + AIMLAPI_API_KEY: provisioned.apiKey, + OPENAI_MODEL: provisioned.model, + CLAUDE_CODE_PROVIDER_ROUTE_ID: 'aimlapi', + }, + createdAt: new Date().toISOString(), + }) + clearAimlapiTopupState({ ...intent, paymentSessionId: checkoutState.paymentSessionId }) + console.log(chalk.green('\n [OK] Balance topped up and provider configured.')) + console.log(` key ${chalk.dim(maskKey(provisioned.apiKey))} (id ${provisioned.apiKeyId})`) + console.log(` base URL ${chalk.dim(provisioned.baseUrl)}`) + console.log(` model ${chalk.dim(provisioned.model)}`) + console.log(` profile ${chalk.dim(profilePath)}`) + } - // 1. Credentials -> Bearer token. - const email = options.email?.trim() || process.env.AIMLAPI_EMAIL?.trim() || (await promptText('AI/ML API email')) - const password = options.password || process.env.AIMLAPI_PASSWORD || (await promptHidden('AI/ML API password')) - if (!email || !password) { - throw new Error('Email and password are required.') + // Resume: a prior run provisioned the key but was interrupted before the + // profile write. Finish that last step with the retained key instead of + // re-provisioning a now-exchanged (otherwise stranded) session. + if (checkoutState.settled && checkoutState.apiKey) { + finishProfile({ + apiKey: checkoutState.apiKey, + apiKeyId: checkoutState.apiKeyId ?? '', + baseUrl: endpoints.inferenceBaseUrl, + // Prefer the model captured when the key was provisioned; a retry with + // different --model must not silently reconfigure the settled profile. + model: checkoutState.model?.trim() || options.model?.trim() || DEFAULT_MODEL, + }) + return } - console.log(chalk.dim(' -> Signing in...')) - const token = await authenticateAimlapiAccount(client, { - email, - password, - inviteCode: options.inviteCode || process.env.AIMLAPI_INVITE_CODE, - }) - console.log(chalk.green(' [OK] Signed in')) - - // 2. Partner-checkout session. - const session = await client.createSession({ partnerId, partnerName }) - console.log(chalk.dim(` -> Session ${session.id}`)) - - // 3. Bind + open hosted payment page. The co-branded return URLs make the - // post-payment browser redirect land on the AI/ML API success / failure - // screen for this partner. - const { successUrl, cancelUrl } = buildPartnerCheckoutReturnUrls( - endpoints.appBaseUrl, - session.sessionToken, - ) - const { checkout } = await client.pay(token, session.sessionToken, { - amountUsdMinor, - method, - successUrl, - cancelUrl, - }) - if (!checkout.payUrl) { - throw new Error('Payment provider did not return a checkout URL.') + const account = await client.checkAccount(email, options.signal) + const persistSession = (resumeSessionToken: string): void => { + if (!resumeSessionToken) { + // A terminal checkout invalidates the payment session, but a minted + // existing-account key is still valid: retain it (with a fresh payment + // session) so the next run reuses the credential instead of issuing + // another. Fall back to a full clear when there is no key to keep. + if ( + checkoutState.apiKey && + resetAimlapiCheckoutSession({ + ...intent, + paymentSessionId: checkoutState.paymentSessionId, + }) + ) { + return + } + clearAimlapiTopupState({ + ...intent, + paymentSessionId: checkoutState.paymentSessionId, + }) + return + } + checkoutState.resumeSessionToken = resumeSessionToken + saveAimlapiTopupState({ ...intent, ...checkoutState }) } - console.log( - chalk.bold(`\n Pay $${(amountUsdMinor / 100).toFixed(2)} (${method}) to top up:\n`) + - ` ${chalk.cyan(checkout.payUrl)}\n`, - ) - if (options.noOpen) { - console.log(chalk.dim(' (open the link above to complete payment)')) - } else { - const opened = await openBrowser(checkout.payUrl) - if (!opened) { - console.log(chalk.dim(' (could not auto-open a browser - open the link above manually)')) + let sessionToken: string + let apiKey = checkoutState.apiKey?.trim() ?? '' + let apiKeyId = checkoutState.apiKeyId?.trim() ?? '' + let exchange: boolean + + switch (account.action) { + case 'sign-in': { + await client.sendSignInCode(email, options.signal) + const code = + options.code?.trim() || + process.env.AIMLAPI_CODE?.trim() || + (await promptText('6-digit code', { mask: true })) + if (!code) throw new Error('Sign-in code is required.') + sessionToken = (await client.verifySignInCode(email, code, options.signal)).token + if (!apiKey) { + const created = await client.createKey(sessionToken, 'OpenClaude CLI', options.signal) + apiKey = created.key + apiKeyId = created.id + // Retain the issued key with the intent so a retry after an interrupted + // checkout reuses it instead of minting another. + checkoutState.apiKey = apiKey + checkoutState.apiKeyId = apiKeyId + saveAimlapiTopupState({ ...intent, ...checkoutState }) + } + exchange = false + break } + case 'sign-up': { + sessionToken = (await client.createPasswordlessAccount(email, options.signal)).token + exchange = true + break + } + default: + // Fail closed: only the two account actions the flow understands may + // proceed (mirrors the guided onboarding path). + throw new Error('AI/ML API returned an unsupported account action.') } - // 4./5. Poll until paid. - console.log(chalk.dim('\n Waiting for payment...')) - const paid = await pollUntilPaid(client, session.sessionToken) - - // 6. Exchange the paid session for the raw key (once). - console.log(chalk.dim(' -> Provisioning API key...')) - const { apiKey, apiKeyId } = await client.exchange(token, paid.sessionToken) - - // 7. Persist into OpenClaude's provider profile. - const profilePath = saveProfileFile({ - profile: 'openai', - env: { - OPENAI_BASE_URL: endpoints.inferenceBaseUrl, - OPENAI_API_KEY: apiKey, - OPENAI_MODEL: model, + const provisioned = await provisionAimlapiKey({ + amountUsd: options.amountUsd, + autoTopUp: options.autoTopUp, + model: options.model, + partnerId, + partnerName, + noOpen: options.noOpen, + signal: options.signal, + sessionToken, + exchange, + paymentSessionId: checkoutState.paymentSessionId, + resumeSessionToken: checkoutState.resumeSessionToken, + existingApiKey: apiKey, + existingApiKeyId: apiKeyId, + onSession: persistSession, + onStatus: (status, detail) => { + if (status === 'opening-checkout' && detail) console.log(` ${chalk.cyan(detail)}`) + if (status === 'waiting-payment') console.log(chalk.dim(' Waiting for payment...')) }, - createdAt: new Date().toISOString(), }) - console.log(chalk.green(`\n [OK] Balance topped up and provider configured.`)) - console.log(` key ${chalk.dim(maskKey(apiKey))} (id ${apiKeyId})`) - console.log(` base URL ${chalk.dim(endpoints.inferenceBaseUrl)}`) - console.log(` model ${chalk.dim(model)}`) - console.log(` profile ${chalk.dim(profilePath)}`) - console.log(chalk.dim(`\n Run ${chalk.bold('openclaude')} to start coding on AI/ML API.\n`)) + // Persist the provisioned key (and its model) as recoverable before the + // profile write, so an interruption or a failed write resumes the write + // instead of stranding a paid, one-shot-exchanged key. + checkoutState.apiKey = provisioned.apiKey + checkoutState.apiKeyId = provisioned.apiKeyId + checkoutState.model = provisioned.model + checkoutState.settled = true + saveAimlapiTopupState({ ...intent, ...checkoutState }) + + finishProfile(provisioned) } export async function provisionAimlapiKey( options: AimlapiProvisionOptions, ): Promise { + if (!options.sessionToken.trim()) throw new Error('A session is required to top up.') + if (!options.paymentSessionId?.trim()) { + throw new Error('A payment session id is required to top up.') + } const endpoints = resolveEndpoints() + if (options.inferenceBaseUrl?.trim()) { + endpoints.inferenceBaseUrl = options.inferenceBaseUrl.trim() + } const client = new AimlapiClient(endpoints) - - const partnerId = - options.partnerId?.trim() || - process.env.AIMLAPI_PARTNER_ID?.trim() || - DEFAULT_PARTNER_ID + const amountUsdMinor = parseAimlapiAmountUsd(options.amountUsd) + const partnerId = resolvePartnerId(options.partnerId) const partnerName = options.partnerName?.trim() || DEFAULT_PARTNER_NAME - const method: PaymentMethod = options.method === 'crypto' ? 'crypto' : 'card' - const model = options.model?.trim() || DEFAULT_MODEL - const amountUsdMinor = parseAmount(options.amountUsd) - - const email = - options.email?.trim() || - process.env.AIMLAPI_EMAIL?.trim() || - (await promptText('AI/ML API email')) - const password = - options.password || - process.env.AIMLAPI_PASSWORD || - (await promptHidden('AI/ML API password')) - if (!email || !password) { - throw new Error('Email and password are required.') - } - - const token = await authenticateAimlapiAccount(client, { - email, - password, - inviteCode: options.inviteCode || process.env.AIMLAPI_INVITE_CODE, - onStatus: options.onStatus, - }) options.onStatus?.('creating-session') - const session = await client.createSession({ partnerId, partnerName }) - - options.onStatus?.('opening-checkout') - const { successUrl, cancelUrl } = buildPartnerCheckoutReturnUrls( - endpoints.appBaseUrl, - session.sessionToken, - ) - const { checkout } = await client.pay(token, session.sessionToken, { - amountUsdMinor, - method, - successUrl, - cancelUrl, + const { sessionToken, phase } = await resolveTopupSession(client, { + resumeSessionToken: options.resumeSessionToken, + partnerId, + partnerName, + verificationBaseUrl: endpoints.verificationBaseUrl, + signal: options.signal, + onSession: options.onSession, }) - if (!checkout.payUrl) { - throw new Error('Payment provider did not return a checkout URL.') + options.onSession?.(sessionToken) + + if (phase === 'pay') { + const returnUrls = buildPartnerCheckoutReturnUrls(endpoints.payBaseUrl, sessionToken) + options.onStatus?.('opening-checkout') + const { checkout } = await client.pay( + options.sessionToken, + sessionToken, + { + amountUsdMinor, + paymentSessionId: options.paymentSessionId, + ...returnUrls, + autoTopUp: options.autoTopUp, + }, + options.signal, + ) + await announceCheckout(checkout?.payUrl, options) } - if (options.noOpen) { - options.onStatus?.('opening-checkout', checkout.payUrl) - } else { - const opened = await openBrowser(checkout.payUrl) - options.onStatus?.( - 'opening-checkout', - opened ? checkout.payUrl : `Open manually: ${checkout.payUrl}`, + let paidToken = sessionToken + let settledPhase = phase + if (phase === 'pay' || phase === 'poll') { + options.onStatus?.('waiting-payment') + const paid = await pollUntilPaid( + client, + sessionToken, + options.signal, + options.onSession, ) + paidToken = paid.sessionToken + if (paid.status === 'exchanging') settledPhase = 'wait-exchange' + } + let apiKey = options.existingApiKey?.trim() || '' + let apiKeyId = options.existingApiKeyId?.trim() || '' + if (options.exchange) { + options.onStatus?.('provisioning-key') + if (settledPhase === 'wait-exchange') { + await pollUntilExchangeSettled( + client, + sessionToken, + options.signal, + options.onSession, + ) + } + const exchanged = await client.exchange( + options.sessionToken, + paidToken, + options.signal, + ) + apiKey = exchanged.apiKey?.trim() + apiKeyId = exchanged.apiKeyId?.trim() + } + if (!apiKey) throw new Error('AI/ML API did not return an API key.') + + return { + apiKey, + apiKeyId, + baseUrl: endpoints.inferenceBaseUrl, + model: options.model?.trim() || DEFAULT_MODEL, } +} - options.onStatus?.('waiting-payment') - const paid = await pollUntilPaid(client, session.sessionToken) +export async function topUpAimlapiByApiKey( + options: AimlapiByKeyTopupOptions, +): Promise { + const apiKey = options.apiKey.trim() + if (!apiKey) throw new Error('An API key is required to top up.') + if (!options.paymentSessionId.trim()) { + throw new Error('A payment session id is required to top up.') + } + const endpoints = resolveEndpoints() + if (options.inferenceBaseUrl?.trim()) { + endpoints.inferenceBaseUrl = options.inferenceBaseUrl.trim() + } + const client = new AimlapiClient(endpoints) + const amountUsdMinor = parseAimlapiAmountUsd(options.amountUsd) + const partnerId = resolvePartnerId(options.partnerId) + const partnerName = options.partnerName?.trim() || DEFAULT_PARTNER_NAME - options.onStatus?.('provisioning-key') - const { apiKey, apiKeyId } = await client.exchange(token, paid.sessionToken) + options.onStatus?.('creating-session') + const { sessionToken, phase } = await resolveTopupSession(client, { + resumeSessionToken: options.resumeSessionToken, + partnerId, + partnerName, + verificationBaseUrl: endpoints.verificationBaseUrl, + signal: options.signal, + onSession: options.onSession, + byKey: true, + }) + options.onSession?.(sessionToken) + + if (phase === 'pay') { + const returnUrls = buildPartnerCheckoutReturnUrls(endpoints.payBaseUrl, sessionToken) + options.onStatus?.('opening-checkout') + const { checkout } = await client.topUpByKey( + apiKey, + { + sessionToken, + amountUsdMinor, + paymentSessionId: options.paymentSessionId, + ...returnUrls, + autoTopUp: options.autoTopUp, + }, + options.signal, + ) + await announceCheckout(checkout?.payUrl, options) + } + if (phase === 'pay' || phase === 'poll') { + options.onStatus?.('waiting-payment') + const paid = await pollUntilPaid(client, sessionToken, options.signal, options.onSession) + if (paid.status === 'exchanging') { + await pollUntilByKeyToppedUp(client, sessionToken, options.signal, options.onSession) + } + } else if (phase === 'wait-exchange') { + // A resumed session was still settling the top-up; wait for it to reach a + // terminal state before reporting success, otherwise the caller marks the + // balance credited while the billing operation is still in flight. + options.onStatus?.('waiting-payment') + await pollUntilByKeyToppedUp(client, sessionToken, options.signal, options.onSession) + } return { apiKey, - apiKeyId, + apiKeyId: '', baseUrl: endpoints.inferenceBaseUrl, - model, + model: options.model?.trim() || DEFAULT_MODEL, + } +} + +async function announceCheckout( + payUrl: string | null | undefined, + options: Pick & { + onStatus?: (status: AimlapiTopupStatus, detail?: string) => void + }, +): Promise { + const checkoutUrl = payUrl?.trim() + if (!checkoutUrl) throw new Error('Payment provider did not return a valid HTTPS checkout URL.') + let parsed: URL + try { + parsed = new URL(checkoutUrl) + } catch { + throw new Error('Payment provider did not return a valid HTTPS checkout URL.') + } + if ( + parsed.protocol !== 'https:' || + !parsed.hostname || + parsed.username !== '' || + parsed.password !== '' + ) { + throw new Error('Payment provider did not return a valid HTTPS checkout URL.') + } + // Surface the validated checkout URL before attempting to open a browser: a + // launcher failure (e.g. on a headless host) must not hide an already-created + // checkout, or the user cannot finish paying and retries only re-poll. + options.onStatus?.('opening-checkout', checkoutUrl) + if (!options.noOpen) { + try { + await openBrowser(checkoutUrl) + } catch { + // The URL is already surfaced; a failed launch must not abort payment. + } + } +} + +async function resolveTopupSession( + client: AimlapiClient, + options: { + resumeSessionToken?: string + partnerId: string + partnerName: string + verificationBaseUrl: string + signal?: AbortSignal + onSession?: (sessionToken: string) => void + byKey?: boolean + }, +): Promise<{ sessionToken: string; phase: TopupPhase }> { + const resume = options.resumeSessionToken?.trim() + if (!resume) { + const session = await client.createSession( + { + partnerId: options.partnerId, + partnerName: options.partnerName, + returnUrl: buildPartnerReturnUrl(options.verificationBaseUrl), + }, + options.signal, + ) + return { sessionToken: session.sessionToken, phase: 'pay' } + } + let session: PartnerCheckoutSession + try { + session = await client.getSession(resume, options.signal) + } catch (error) { + if (isTerminalSessionApiError(error)) options.onSession?.('') + throw error + } + switch (session.status) { + case 'pending_auth': + return { sessionToken: resume, phase: 'pay' } + case 'pending_payment': + return { sessionToken: resume, phase: 'poll' } + case 'paid': + return { sessionToken: resume, phase: 'exchange' } + case 'exchanging': + // Not settled yet for either flow: the account flow must wait then + // exchange, the by-key flow must wait for the top-up to finish crediting. + return { sessionToken: resume, phase: 'wait-exchange' } + case 'exchanged': + if (options.byKey) return { sessionToken: resume, phase: 'exchange' } + throw alreadyExchangedError(session) + default: + options.onSession?.('') + throw new Error(`Payment ${session.status}. Re-run the top-up to try again.`) } } -async function pollUntilPaid( +async function pollUntilExchangeSettled( client: AimlapiClient, sessionToken: string, -): Promise { + signal?: AbortSignal, + onSession?: (sessionToken: string) => void, +): Promise { const deadline = Date.now() + POLL_TIMEOUT_MS while (Date.now() < deadline) { - let session: PartnerCheckoutSession + if (signal?.aborted) throw abortError(signal) try { - session = await client.getSession(sessionToken) + const session = await client.getSession(sessionToken, signal) + if (session.status === 'exchanged') { + throw alreadyExchangedError(session) + } + if ( + session.status === 'cancelled' || + session.status === 'expired' || + session.status === 'failed' + ) { + onSession?.('') + throw new Error( + `Key provisioning ${session.status}. Rotate the key from the AI/ML API dashboard.`, + ) + } + if (session.status !== 'exchanging') { + throw new Error( + `Key provisioning returned to ${session.status}. Re-run the top-up.`, + ) + } } catch (error) { - // Transient poll failures shouldn't abort a payment in progress. - // status 0 is a network-level failure (see client.ts), not a real HTTP response. - if (error instanceof AimlapiApiError && (error.status === 0 || error.status >= 500)) { - await sleep(POLL_INTERVAL_MS) + if (signal?.aborted) throw abortError(signal) + if (isRetryableSessionApiError(error)) { + await sleep(POLL_INTERVAL_MS, signal) continue } + if (isTerminalSessionApiError(error)) onSession?.('') throw error } + await sleep(POLL_INTERVAL_MS, signal) + } + throw new Error( + 'Timed out waiting for key provisioning. Retry to check the same session.', + ) +} - switch (session.status) { - case 'paid': - case 'exchanging': - return session - case 'exchanged': - throw new Error( - 'Session was already exchanged. The key can only be issued once - rotate it from the AI/ML API dashboard.', - ) - case 'cancelled': - case 'expired': - case 'failed': - throw new Error(`Payment ${session.status}. Re-run the top-up to try again.`) - default: - // pending_auth / pending_payment -> keep waiting. - await sleep(POLL_INTERVAL_MS) +async function pollUntilByKeyToppedUp( + client: AimlapiClient, + sessionToken: string, + signal?: AbortSignal, + onSession?: (sessionToken: string) => void, +): Promise { + const deadline = Date.now() + POLL_TIMEOUT_MS + while (Date.now() < deadline) { + if (signal?.aborted) throw abortError(signal) + try { + const session = await client.getSession(sessionToken, signal) + switch (session.status) { + case 'paid': + case 'exchanged': + return + case 'cancelled': + case 'expired': + case 'failed': + onSession?.('') + throw new Error(`Top-up ${session.status}. Re-run the top-up to try again.`) + default: + // pending_* / exchanging -> keep waiting for the balance to settle. + await sleep(POLL_INTERVAL_MS, signal) + } + } catch (error) { + if (signal?.aborted) throw abortError(signal) + if (isRetryableSessionApiError(error)) { + await sleep(POLL_INTERVAL_MS, signal) + continue + } + if (isTerminalSessionApiError(error)) onSession?.('') + throw error + } + } + throw new Error('Timed out waiting for the top-up to settle. Re-run once it clears.') +} + +export async function pollUntilPaid( + client: AimlapiClient, + sessionToken: string, + signal?: AbortSignal, + onSession?: (sessionToken: string) => void, +): Promise { + const deadline = Date.now() + POLL_TIMEOUT_MS + while (Date.now() < deadline) { + if (signal?.aborted) throw abortError(signal) + try { + const session = await client.getSession(sessionToken, signal) + switch (session.status) { + case 'paid': + case 'exchanging': + return session + case 'exchanged': + throw alreadyExchangedError(session) + case 'cancelled': + case 'expired': + case 'failed': + onSession?.('') + throw new Error(`Payment ${session.status}. Re-run the top-up to try again.`) + default: + await sleep(POLL_INTERVAL_MS, signal) + } + } catch (error) { + if (signal?.aborted) throw abortError(signal) + if (isRetryableSessionApiError(error)) { + await sleep(POLL_INTERVAL_MS, signal) + continue + } + if (isTerminalSessionApiError(error)) onSession?.('') + throw error } } throw new Error('Timed out waiting for payment. Re-run once the payment clears.') } + +function isTerminalSessionApiError(error: unknown): boolean { + return ( + error instanceof AimlapiApiError && + error.status >= 400 && + error.status < 500 && + !isRetryableSessionApiError(error) + ) +} + +function isRetryableSessionApiError(error: unknown): boolean { + return ( + error instanceof AimlapiApiError && + (error.status === 0 || + error.status === 408 || + error.status === 429 || + error.status >= 500) + ) +} diff --git a/src/integrations/aimlapi/topupDependencies.ts b/src/integrations/aimlapi/topupDependencies.ts new file mode 100644 index 0000000000..37fca21b4f --- /dev/null +++ b/src/integrations/aimlapi/topupDependencies.ts @@ -0,0 +1,10 @@ +import { openBrowser as openBrowserImpl } from '../../utils/browser.js' +import { saveProfileFile as saveProfileFileImpl } from '../../utils/providerProfile.js' +import { promptText as promptTextImpl } from './prompt.js' + +export const openBrowser: typeof openBrowserImpl = url => openBrowserImpl(url) + +export const saveProfileFile: typeof saveProfileFileImpl = options => + saveProfileFileImpl(options) + +export const promptText: typeof promptTextImpl = (...args) => promptTextImpl(...args) diff --git a/src/integrations/aimlapi/topupState.test.ts b/src/integrations/aimlapi/topupState.test.ts new file mode 100644 index 0000000000..334649828e --- /dev/null +++ b/src/integrations/aimlapi/topupState.test.ts @@ -0,0 +1,191 @@ +import { afterEach, expect, test } from 'bun:test' +import { + existsSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { setClaudeConfigHomeDirForTesting } from '../../utils/envUtils.js' +import { + claimAimlapiTopupState, + clearAimlapiTopupState, + clearAimlapiSignInKey, + loadAimlapiSignInKey, + loadAimlapiTopupState, + saveAimlapiSignInKey, + saveAimlapiTopupState, + type AimlapiTopupIntent, +} from './topupState.js' + +const directories: string[] = [] + +afterEach(() => { + setClaudeConfigHomeDirForTesting(undefined) + for (const directory of directories.splice(0)) { + rmSync(directory, { force: true, recursive: true }) + } +}) + +function useTemporaryConfig(): string { + const directory = mkdtempSync(join(tmpdir(), 'openclaude-aimlapi-topup-')) + directories.push(directory) + setClaudeConfigHomeDirForTesting(directory) + return directory +} + +const intent: AimlapiTopupIntent = { + email: 'user@example.com', + amountUsdMinor: 2500, + autoTopUp: false, + partnerId: 'part_test', + partnerName: 'OpenClaude', + appBaseUrl: 'https://app.example.test', + inferenceBaseUrl: 'https://api.example.test/v1', + payBaseUrl: 'https://pay.example.test', + verificationBaseUrl: 'https://front.example.test', +} + +test('top-up state round-trips only for the same checkout intent', () => { + const directory = useTemporaryConfig() + const claimed = claimAimlapiTopupState(intent) + saveAimlapiTopupState({ + ...intent, + paymentSessionId: claimed.paymentSessionId, + resumeSessionToken: 'session-token', + }) + + expect(loadAimlapiTopupState(intent)).toEqual({ + paymentSessionId: claimed.paymentSessionId, + resumeSessionToken: 'session-token', + }) + expect(loadAimlapiTopupState({ ...intent, amountUsdMinor: 3000 })).toBeNull() + expect(readFileSync(join(directory, 'aimlapi-topup.json'), 'utf8')).toContain( + 'session-token', + ) + if (process.platform !== 'win32') { + expect(statSync(join(directory, 'aimlapi-topup.json')).mode & 0o777).toBe(0o600) + } +}) + +test('top-up state is cleared only by its matching intent', () => { + useTemporaryConfig() + const claimed = claimAimlapiTopupState(intent) + saveAimlapiTopupState({ + ...intent, + paymentSessionId: claimed.paymentSessionId, + resumeSessionToken: 'session-token', + }) + + clearAimlapiTopupState({ + ...intent, + email: 'other@example.com', + paymentSessionId: claimed.paymentSessionId, + }) + expect(loadAimlapiTopupState(intent)).not.toBeNull() + clearAimlapiTopupState({ ...intent, paymentSessionId: claimed.paymentSessionId }) + expect(loadAimlapiTopupState(intent)).toBeNull() +}) + +test('claiming the same checkout intent reuses one payment id', () => { + useTemporaryConfig() + const first = claimAimlapiTopupState(intent) + const second = claimAimlapiTopupState(intent) + + expect(first.paymentSessionId).toBeTruthy() + expect(second).toEqual(first) +}) + +test('stale writers cannot overwrite a newly claimed checkout', () => { + useTemporaryConfig() + const stale = claimAimlapiTopupState(intent) + clearAimlapiTopupState({ ...intent, paymentSessionId: stale.paymentSessionId }) + + const currentIntent = { ...intent, email: 'new@example.com' } + const current = claimAimlapiTopupState(currentIntent) + saveAimlapiTopupState({ + ...intent, + ...stale, + resumeSessionToken: 'stale-session', + }) + + expect(loadAimlapiTopupState(currentIntent)).toEqual(current) + expect(loadAimlapiTopupState(intent)).toBeNull() +}) + +test('stale clear cannot delete a replacement checkout', () => { + useTemporaryConfig() + const stale = claimAimlapiTopupState(intent) + clearAimlapiTopupState({ ...intent, paymentSessionId: stale.paymentSessionId }) + + const current = claimAimlapiTopupState(intent) + clearAimlapiTopupState({ ...intent, paymentSessionId: stale.paymentSessionId }) + + expect(current.paymentSessionId).not.toBe(stale.paymentSessionId) + expect(loadAimlapiTopupState(intent)).toEqual(current) +}) + +test('sign-in key cache round-trips by normalized email and clears', () => { + useTemporaryConfig() + + expect(loadAimlapiSignInKey('User@Example.com')).toBeNull() + + saveAimlapiSignInKey('User@Example.com', 'k_signin', 'id_signin') + // Lookup is case/whitespace-insensitive on the email. + expect(loadAimlapiSignInKey('user@example.com')).toEqual({ + apiKey: 'k_signin', + apiKeyId: 'id_signin', + }) + // A different email must not read this key. + expect(loadAimlapiSignInKey('other@example.com')).toBeNull() + + clearAimlapiSignInKey('user@example.com', 'id_signin') + expect(loadAimlapiSignInKey('user@example.com')).toBeNull() +}) + +test('sign-in key cache rejects records missing the key identifier', () => { + const directory = useTemporaryConfig() + const cachePath = join(directory, 'aimlapi-signin-key.json') + + // A persisted record without a usable apiKeyId cannot bypass createKey. + writeFileSync( + cachePath, + JSON.stringify({ email: 'user@example.com', apiKey: 'k_signin', apiKeyId: '' }), + ) + expect(loadAimlapiSignInKey('user@example.com')).toBeNull() + + writeFileSync( + cachePath, + JSON.stringify({ email: 'user@example.com', apiKey: 'k_signin' }), + ) + expect(loadAimlapiSignInKey('user@example.com')).toBeNull() + + // The save guard refuses to persist an incomplete receipt in the first place. + rmSync(cachePath, { force: true }) + saveAimlapiSignInKey('user@example.com', 'k_signin', ' ') + expect(loadAimlapiSignInKey('user@example.com')).toBeNull() + expect(existsSync(cachePath)).toBe(false) +}) + +test('sign-in key clear leaves a newer cached record intact', () => { + useTemporaryConfig() + saveAimlapiSignInKey('user@example.com', 'k_signin', 'id_signin') + + // A concurrent flow replaced the cache with a newer key for another email. + saveAimlapiSignInKey('other@example.com', 'k_other', 'id_other') + + // The stale completion for the original email/id must not delete it. + clearAimlapiSignInKey('user@example.com', 'id_signin') + expect(loadAimlapiSignInKey('other@example.com')).toEqual({ + apiKey: 'k_other', + apiKeyId: 'id_other', + }) + + // The owning flow still clears its own record. + clearAimlapiSignInKey('other@example.com', 'id_other') + expect(loadAimlapiSignInKey('other@example.com')).toBeNull() +}) diff --git a/src/integrations/aimlapi/topupState.ts b/src/integrations/aimlapi/topupState.ts new file mode 100644 index 0000000000..1d419bf8d9 --- /dev/null +++ b/src/integrations/aimlapi/topupState.ts @@ -0,0 +1,433 @@ +import { + chmodSync, + closeSync, + mkdirSync, + openSync, + readFileSync, + renameSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs' +import { dirname, join } from 'node:path' +import { randomUUID } from 'node:crypto' + +import { getClaudeConfigHomeDir } from '../../utils/envUtils.js' + +export type AimlapiTopupIntent = { + email: string + amountUsdMinor: number + autoTopUp: boolean + partnerId: string + partnerName: string + appBaseUrl: string + inferenceBaseUrl: string + payBaseUrl: string + verificationBaseUrl: string +} + +export type AimlapiPersistedTopup = AimlapiTopupIntent & { + paymentSessionId: string + resumeSessionToken: string + /** + * Existing-account key issued for this intent, retained so an interrupted + * checkout resumes on the same credential instead of minting another key. + */ + apiKey?: string + apiKeyId?: string + /** + * Model chosen for this provisioning; retained with the settled receipt so a + * resumed profile write configures the original model instead of recomputing + * it from (possibly different) retry arguments. + */ + model?: string + /** + * Set once payment/exchange has completed and `apiKey` is the final + * provisioned credential. The next run then resumes the profile write with + * that key instead of re-provisioning a one-shot-exchanged (now stranded) + * session. + */ + settled?: boolean +} + +type AimlapiCheckoutState = Pick< + AimlapiPersistedTopup, + | 'paymentSessionId' + | 'resumeSessionToken' + | 'apiKey' + | 'apiKeyId' + | 'model' + | 'settled' +> + +function statePath(): string { + return join(getClaudeConfigHomeDir(), 'aimlapi-topup.json') +} + +const LOCK_RETRY_MS = 25 +const LOCK_TIMEOUT_MS = 5_000 +const LOCK_STALE_MS = 30_000 +const INTENT_KEYS: ReadonlyArray = [ + 'email', + 'amountUsdMinor', + 'autoTopUp', + 'partnerId', + 'partnerName', + 'appBaseUrl', + 'inferenceBaseUrl', + 'payBaseUrl', + 'verificationBaseUrl', +] + +function waitForLock(): void { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, LOCK_RETRY_MS) +} + +function withStateLock(operation: () => T, target: string = statePath()): T { + const lockPath = `${target}.lock` + mkdirSync(dirname(target), { recursive: true }) + const deadline = Date.now() + LOCK_TIMEOUT_MS + // Ownership token written into the lock so recovery can tell this holder's + // lock apart from a replacement another process wrote after stealing a stale + // lock. + const token = `${process.pid}.${randomUUID()}` + let held = false + + while (!held) { + try { + const descriptor = openSync(lockPath, 'wx', 0o600) + try { + writeFileSync(descriptor, token, { encoding: 'utf8' }) + } finally { + closeSync(descriptor) + } + held = true + } catch (error) { + const code = + typeof error === 'object' && error !== null && 'code' in error + ? String(error.code) + : undefined + if (code !== 'EEXIST') throw error + let stale = false + try { + const lock = statSync(lockPath) + stale = Date.now() - lock.mtimeMs > LOCK_STALE_MS + } catch { + // Lock vanished between open and stat; retry the create immediately. + continue + } + if (stale) { + // Record the token we observed as stale so recovery can prove it is + // discarding the SAME lock and not a live replacement written between + // the staleness check and the steal. + let observedToken: string | undefined + try { + observedToken = readFileSync(lockPath, 'utf8') + } catch { + // Vanished already; retry the create immediately. + continue + } + const stealPath = `${lockPath}.${token}.stale` + let stolen = false + try { + // Atomic: only one racer can rename a given inode away. + renameSync(lockPath, stealPath) + stolen = true + } catch { + // Another racer already claimed it, or a live holder keeps it open + // (Windows cannot rename an open file); fall through to the wait. + } + if (stolen) { + let stolenToken: string | undefined + try { + stolenToken = readFileSync(stealPath, 'utf8') + } catch { + // Already gone; nothing to revalidate. + } + if (stolenToken === undefined || stolenToken === observedToken) { + // Exactly the stale lock we observed (or already gone): drop it. + rmSync(stealPath, { force: true }) + continue + } + // A live replacement slipped in and we renamed it away. Fail closed: + // put it back and wait rather than remove a lock we do not own. + try { + renameSync(stealPath, lockPath) + } catch { + rmSync(stealPath, { force: true }) + } + } + } + if (Date.now() >= deadline) { + throw new Error('Timed out waiting for the AI/ML API checkout state lock.') + } + waitForLock() + } + } + + try { + return operation() + } finally { + // Only remove a lock this holder still owns. A stale-lock steal may have + // replaced ours with another process's lock; deleting that would admit a + // third process while the second still mutates the checkout state. + try { + if (readFileSync(lockPath, 'utf8') === token) { + rmSync(lockPath, { force: true }) + } + } catch { + // Lock already released or replaced by another owner. + } + } +} + +function matchesIntent( + state: AimlapiPersistedTopup, + intent: AimlapiTopupIntent, +): boolean { + return INTENT_KEYS.every(key => state[key] === intent[key]) +} + +function isPersistedTopup(value: unknown): value is AimlapiPersistedTopup { + if (typeof value !== 'object' || value === null) return false + const state = value as Record + return ( + typeof state.email === 'string' && + typeof state.amountUsdMinor === 'number' && + Number.isSafeInteger(state.amountUsdMinor) && + typeof state.autoTopUp === 'boolean' && + typeof state.partnerId === 'string' && + typeof state.partnerName === 'string' && + typeof state.appBaseUrl === 'string' && + typeof state.inferenceBaseUrl === 'string' && + typeof state.payBaseUrl === 'string' && + typeof state.verificationBaseUrl === 'string' && + typeof state.paymentSessionId === 'string' && + Boolean(state.paymentSessionId.trim()) && + typeof state.resumeSessionToken === 'string' && + (state.apiKey === undefined || typeof state.apiKey === 'string') && + (state.apiKeyId === undefined || typeof state.apiKeyId === 'string') && + (state.model === undefined || typeof state.model === 'string') && + (state.settled === undefined || typeof state.settled === 'boolean') + ) +} + +function readAimlapiTopupStateUnlocked(): AimlapiPersistedTopup | null { + try { + const state: unknown = JSON.parse(readFileSync(statePath(), 'utf8')) + return isPersistedTopup(state) ? state : null + } catch { + return null + } +} + +function writeAimlapiTopupStateUnlocked(state: AimlapiPersistedTopup): void { + const target = statePath() + mkdirSync(dirname(target), { recursive: true }) + const temporary = `${target}.${process.pid}.${randomUUID()}.tmp` + try { + writeFileSync(temporary, `${JSON.stringify(state, null, 2)}\n`, { + encoding: 'utf8', + flag: 'wx', + mode: 0o600, + }) + chmodSync(temporary, 0o600) + renameSync(temporary, target) + } finally { + rmSync(temporary, { force: true }) + } +} + +export function loadAimlapiTopupState( + intent: AimlapiTopupIntent, +): AimlapiCheckoutState | null { + const state = readAimlapiTopupStateUnlocked() + if (!state || !matchesIntent(state, intent)) return null + return { + paymentSessionId: state.paymentSessionId, + resumeSessionToken: state.resumeSessionToken, + apiKey: state.apiKey, + apiKeyId: state.apiKeyId, + model: state.model, + settled: state.settled, + } +} + +export function saveAimlapiTopupState(state: AimlapiPersistedTopup): void { + withStateLock(() => { + const current = readAimlapiTopupStateUnlocked() + if ( + !current || + !matchesIntent(current, state) || + current.paymentSessionId !== state.paymentSessionId + ) { + return + } + writeAimlapiTopupStateUnlocked(state) + }) +} + +export function claimAimlapiTopupState( + intent: AimlapiTopupIntent, +): AimlapiCheckoutState { + return withStateLock(() => { + const existing = readAimlapiTopupStateUnlocked() + if (existing && matchesIntent(existing, intent)) { + return { + paymentSessionId: existing.paymentSessionId, + resumeSessionToken: existing.resumeSessionToken, + apiKey: existing.apiKey, + apiKeyId: existing.apiKeyId, + model: existing.model, + settled: existing.settled, + } + } + const claimed: AimlapiCheckoutState = { + paymentSessionId: randomUUID(), + resumeSessionToken: '', + } + writeAimlapiTopupStateUnlocked({ ...intent, ...claimed }) + return claimed + }) +} + +/** + * A terminal checkout (cancelled/expired/failed, or a dead session) invalidates + * the payment session but not an already-issued existing-account key. Drop the + * dead session/payment identifiers and mint a fresh payment session while + * retaining the key, so the next run reuses the credential instead of minting + * another. Returns the refreshed checkout, or null when no matching keyed state + * exists (callers clear the state instead). + */ +export function resetAimlapiCheckoutSession( + expected: AimlapiTopupIntent & Pick, +): AimlapiCheckoutState | null { + return withStateLock(() => { + const current = readAimlapiTopupStateUnlocked() + if ( + !current || + !matchesIntent(current, expected) || + current.paymentSessionId !== expected.paymentSessionId || + !current.apiKey?.trim() + ) { + return null + } + const next: AimlapiPersistedTopup = { + ...current, + paymentSessionId: randomUUID(), + resumeSessionToken: '', + } + writeAimlapiTopupStateUnlocked(next) + return { + paymentSessionId: next.paymentSessionId, + resumeSessionToken: next.resumeSessionToken, + apiKey: next.apiKey, + apiKeyId: next.apiKeyId, + } + }) +} + +export function clearAimlapiTopupState( + expected: AimlapiTopupIntent & Pick, +): void { + withStateLock(() => { + const current = readAimlapiTopupStateUnlocked() + if ( + current && + matchesIntent(current, expected) && + current.paymentSessionId === expected.paymentSessionId + ) { + rmSync(statePath(), { force: true }) + } + }) +} + +// --- Sign-in key cache ------------------------------------------------------ +// The guided provider-manager mints an existing-account key at code sign-in, +// before the top-up amount (and therefore the full checkout intent) is known. +// This lightweight per-email cache retains that key so a restart before/without +// completing the checkout reuses it instead of minting another one. + +type AimlapiSignInKey = { email: string; apiKey: string; apiKeyId: string } + +function signInKeyPath(): string { + return join(getClaudeConfigHomeDir(), 'aimlapi-signin-key.json') +} + +function normalizeEmail(email: string): string { + return email.trim().toLowerCase() +} + +// A cached receipt is only useful if it can bypass createKey, which needs both +// the key and its identifier; treat a record missing either as absent so the +// flow mints a fresh, complete credential rather than propagating an empty id. +function isSignInKey(value: unknown): value is AimlapiSignInKey { + if (typeof value !== 'object' || value === null) return false + const record = value as Record + return ( + typeof record.email === 'string' && + typeof record.apiKey === 'string' && + Boolean(record.apiKey.trim()) && + typeof record.apiKeyId === 'string' && + Boolean(record.apiKeyId.trim()) + ) +} + +function readSignInKeyUnlocked(): AimlapiSignInKey | null { + try { + const raw: unknown = JSON.parse(readFileSync(signInKeyPath(), 'utf8')) + return isSignInKey(raw) ? raw : null + } catch { + // Missing/corrupt cache: mint a fresh key. + return null + } +} + +export function loadAimlapiSignInKey( + email: string, +): { apiKey: string; apiKeyId: string } | null { + const record = readSignInKeyUnlocked() + if (!record || record.email !== normalizeEmail(email)) return null + return { apiKey: record.apiKey, apiKeyId: record.apiKeyId } +} + +export function saveAimlapiSignInKey( + email: string, + apiKey: string, + apiKeyId: string, +): void { + if (!apiKey.trim() || !apiKeyId.trim()) return + const target = signInKeyPath() + const record: AimlapiSignInKey = { email: normalizeEmail(email), apiKey, apiKeyId } + withStateLock(() => { + const temporary = `${target}.${process.pid}.${randomUUID()}.tmp` + try { + writeFileSync(temporary, `${JSON.stringify(record, null, 2)}\n`, { + encoding: 'utf8', + flag: 'wx', + mode: 0o600, + }) + chmodSync(temporary, 0o600) + renameSync(temporary, target) + } finally { + rmSync(temporary, { force: true }) + } + }, target) +} + +// Delete the cache only when it still holds the record this flow saved. A stale +// completion must not remove a newer key another concurrent flow cached for a +// different email, which would force that flow to mint a redundant key. +export function clearAimlapiSignInKey(email: string, apiKeyId: string): void { + const target = signInKeyPath() + withStateLock(() => { + const record = readSignInKeyUnlocked() + if ( + record && + record.email === normalizeEmail(email) && + record.apiKeyId === apiKeyId + ) { + rmSync(target, { force: true }) + } + }, target) +} diff --git a/src/integrations/aimlapi/validation.ts b/src/integrations/aimlapi/validation.ts new file mode 100644 index 0000000000..c67837b7c6 --- /dev/null +++ b/src/integrations/aimlapi/validation.ts @@ -0,0 +1,37 @@ +import { + DEFAULT_AMOUNT_USD_MINOR, + MAX_AMOUNT_USD_MINOR, + MIN_AMOUNT_USD_MINOR, +} from './config.js' + +export function parseAimlapiAmountUsd(amountUsd: string | undefined): number { + if (!amountUsd?.trim()) return DEFAULT_AMOUNT_USD_MINOR + const normalized = amountUsd.trim() + const dollars = Number(normalized) + if (!Number.isFinite(dollars) || dollars <= 0) { + throw new Error(`Invalid amount: "${amountUsd}". Pass a positive number of USD.`) + } + const decimal = /^\d+\.(\d+)$/.exec(normalized) + if (decimal && decimal[1].length > 2) { + throw new Error(`Invalid amount: "${amountUsd}". Pass a valid USD amount.`) + } + const minor = Math.round(dollars * 100) + if (minor < MIN_AMOUNT_USD_MINOR) { + throw new Error(`Minimum top-up is $${MIN_AMOUNT_USD_MINOR / 100}.`) + } + if (minor > MAX_AMOUNT_USD_MINOR) { + throw new Error(`Maximum top-up is $${MAX_AMOUNT_USD_MINOR / 100}.`) + } + return minor +} + +export function isValidAimlapiEmail(value: string): boolean { + const email = value.trim() + const match = /^[^\s@]+@([^\s@]+)$/.exec(email) + if (!match) return false + const domain = match[1] + if (domain.startsWith('.') || domain.endsWith('.') || domain.includes('..')) return false + const labels = domain.split('.') + const tld = labels.at(-1) ?? '' + return labels.length >= 2 && /^[A-Za-z]{2,}$/.test(tld) +} diff --git a/src/integrations/artifactGenerator.test.ts b/src/integrations/artifactGenerator.test.ts index f9fc62d016..1803a9bde3 100644 --- a/src/integrations/artifactGenerator.test.ts +++ b/src/integrations/artifactGenerator.test.ts @@ -69,6 +69,25 @@ describe('integration artifact generator', () => { await expect(generatedIntegrationArtifactsAreCurrent()).resolves.toBe(true) }) + test('pins aimlapi.com as the second provider preset', async () => { + const { manifestContent } = splitGeneratedArtifacts( + await generateIntegrationArtifacts(), + ) + const orderedMatch = manifestContent.match( + /export const ORDERED_PROVIDER_PRESETS = \[\n([\s\S]*?)\n\] as const/, + ) + expect(orderedMatch).not.toBeNull() + const orderedPresetIds = Array.from( + orderedMatch![1]!.matchAll(/"([^"]+)"/g), + match => match[1]!, + ) + expect(orderedPresetIds.slice(0, 3)).toEqual([ + 'gitlawb-opengateway', + 'aimlapi', + 'anthropic', + ]) + }) + test('derives loader and preset manifest entries for a preset gateway from descriptor files', async () => { await withFixtureRepo( { diff --git a/src/integrations/artifactGenerator.ts b/src/integrations/artifactGenerator.ts index 41e65b47cf..2adbd30e34 100644 --- a/src/integrations/artifactGenerator.ts +++ b/src/integrations/artifactGenerator.ts @@ -234,8 +234,8 @@ function compareProviderPresetEntries( return 0 } - // Pin Gitlawb Opengateway first so the startup-default provider is also - // the first guided setup option when users need to add an API key. + // Keep the primary guided providers at the top of setup: Gitlawb + // Opengateway first, aimlapi.com second, then the native Anthropic option. if (leftPreset === 'gitlawb-opengateway') { return -1 } @@ -243,6 +243,13 @@ function compareProviderPresetEntries( return 1 } + if (leftPreset === 'aimlapi') { + return -1 + } + if (rightPreset === 'aimlapi') { + return 1 + } + if (leftPreset === 'anthropic') { return -1 } diff --git a/src/integrations/gateways/aimlapi.ts b/src/integrations/gateways/aimlapi.ts index 106b103ed1..df97d57063 100644 --- a/src/integrations/gateways/aimlapi.ts +++ b/src/integrations/gateways/aimlapi.ts @@ -1,5 +1,6 @@ import { defineGateway } from '../define.js' import { publicBuildVersion } from '../../utils/version.js' +import { withResolvedPartnerHeader } from '../aimlapi/config.js' const AIMLAPI_CHAT_MODEL_TYPES = new Set([ 'openai/chat-completions', @@ -57,7 +58,7 @@ function mapAimlapiModel(raw: unknown) { export default defineGateway({ id: 'aimlapi', - label: 'AI/ML API', + label: 'aimlapi.com', category: 'aggregating', defaultBaseUrl: 'https://api.aimlapi.com/v1', defaultModel: 'gpt-4o', @@ -73,7 +74,7 @@ export default defineGateway({ transportConfig: { kind: 'openai-compatible', openaiShim: { - headers: { + headers: withResolvedPartnerHeader({ 'X-AIMLAPI-Partner-ID': 'part_62yQoGYDq4Yqnrj2R1iGrDNJ', 'X-AIMLAPI-Integration-Repo': 'Gitlawb/openclaude', 'X-AIMLAPI-Integration-Version': publicBuildVersion, @@ -81,13 +82,13 @@ export default defineGateway({ // (issue #835). `HTTP-Referer`/`X-Title` identify the referring app. 'HTTP-Referer': 'OpenClaude', 'X-Title': 'OpenClaude', - }, + }), supportsAuthHeaders: false, }, }, preset: { id: 'aimlapi', - description: '1,000+ models OpenAI compatible endpoint', + description: '1,000+ models, one-click setup', badge: { text: 'Recommended', color: 'success' }, apiKeyEnvVars: ['AIMLAPI_API_KEY'], modelEnvVars: ['OPENAI_MODEL'], diff --git a/src/integrations/generated/integrationManifest.generated.ts b/src/integrations/generated/integrationManifest.generated.ts index 014e53eea2..6799f3803c 100644 --- a/src/integrations/generated/integrationManifest.generated.ts +++ b/src/integrations/generated/integrationManifest.generated.ts @@ -34,29 +34,13 @@ export const PROVIDER_PRESET_MANIFEST = [ "color": "success" } }, - { - "preset": "anthropic", - "routeKind": "vendor", - "routeId": "anthropic", - "vendorId": "anthropic", - "description": "Native Claude API (x-api-key auth)", - "apiKeyEnvVars": [ - "ANTHROPIC_API_KEY" - ], - "baseUrlEnvVars": [ - "ANTHROPIC_BASE_URL" - ], - "modelEnvVars": [ - "ANTHROPIC_MODEL" - ] - }, { "preset": "aimlapi", "routeKind": "gateway", "routeId": "aimlapi", "vendorId": "openai", "gatewayId": "aimlapi", - "description": "1,000+ models OpenAI compatible endpoint", + "description": "1,000+ models, one-click setup", "apiKeyEnvVars": [ "AIMLAPI_API_KEY" ], @@ -68,6 +52,22 @@ export const PROVIDER_PRESET_MANIFEST = [ "color": "success" } }, + { + "preset": "anthropic", + "routeKind": "vendor", + "routeId": "anthropic", + "vendorId": "anthropic", + "description": "Native Claude API (x-api-key auth)", + "apiKeyEnvVars": [ + "ANTHROPIC_API_KEY" + ], + "baseUrlEnvVars": [ + "ANTHROPIC_BASE_URL" + ], + "modelEnvVars": [ + "ANTHROPIC_MODEL" + ] + }, { "preset": "dashscope-cn", "routeKind": "gateway", @@ -508,8 +508,8 @@ export const PROVIDER_PRESET_MANIFEST = [ export type ProviderPreset = (typeof PROVIDER_PRESET_MANIFEST)[number]['preset'] export const ORDERED_PROVIDER_PRESETS = [ "gitlawb-opengateway", - "anthropic", "aimlapi", + "anthropic", "dashscope-cn", "dashscope-intl", "atlas-cloud", diff --git a/src/integrations/index.ts b/src/integrations/index.ts index fb863f4077..1a50acbabb 100644 --- a/src/integrations/index.ts +++ b/src/integrations/index.ts @@ -141,6 +141,7 @@ export { isCloudflareBaseUrl, normalizeXiaomiMimoBaseUrl, resolveActiveRouteIdFromEnv, + resolveRouteCredentialValue, resolveRouteIdFromBaseUrl, routeSupportsApiFormatSelection, routeSupportsAuthHeaders, diff --git a/src/integrations/routeMetadata.test.ts b/src/integrations/routeMetadata.test.ts index ac62a9f45d..75517d45f6 100644 --- a/src/integrations/routeMetadata.test.ts +++ b/src/integrations/routeMetadata.test.ts @@ -556,7 +556,7 @@ test.each([ ['OpenRouter', 'https://openrouter.ai/api/v1', 'openai/gpt-5-mini', 'openrouter'], ['DeepSeek', 'https://api.deepseek.com/v1', 'deepseek-v4-pro', 'deepseek'], ['Hicap', 'https://api.hicap.ai/v1', 'claude-opus-4.8', 'hicap'], - ['AI/ML API', 'https://api.aimlapi.com/v1', 'gpt-4o', 'aimlapi'], + ['aimlapi.com', 'https://api.aimlapi.com/v1', 'gpt-4o', 'aimlapi'], ['Xiaomi MiMo', 'https://api.xiaomimimo.com/v1', 'mimo-v2.5-pro', 'xiaomi-mimo'], ['Venice', 'https://api.venice.ai/api/v1', 'venice-uncensored', 'venice'], ])( diff --git a/src/integrations/runtimeMetadata.test.ts b/src/integrations/runtimeMetadata.test.ts index 042da33dd2..b6dccb314c 100644 --- a/src/integrations/runtimeMetadata.test.ts +++ b/src/integrations/runtimeMetadata.test.ts @@ -162,6 +162,35 @@ describe('resolveModelRuntimeLimits', () => { }) }) +describe('AIMLAPI runtime attribution', () => { + it('uses the partner override only on the canonical endpoint', () => { + const previous = process.env.AIMLAPI_PARTNER_ID + process.env.AIMLAPI_PARTNER_ID = 'part_runtime_override' + try { + const canonical = resolveOpenAIShimRuntimeContext({ + activeProfileProvider: 'aimlapi', + baseUrl: 'https://api.aimlapi.com/v1', + model: 'gpt-4o', + }) + expect(canonical.openaiShimConfig.headers?.['X-AIMLAPI-Partner-ID']).toBe( + 'part_runtime_override', + ) + + const proxy = resolveOpenAIShimRuntimeContext({ + activeProfileProvider: 'aimlapi', + baseUrl: 'https://proxy.example.test/v1', + model: 'gpt-4o', + }) + expect(proxy.openaiShimConfig.headers?.['X-AIMLAPI-Partner-ID']).toBeUndefined() + expect(proxy.openaiShimConfig.headers?.['X-AIMLAPI-Integration-Repo']).toBeUndefined() + expect(proxy.openaiShimConfig.headers?.['HTTP-Referer']).toBeUndefined() + } finally { + if (previous === undefined) delete process.env.AIMLAPI_PARTNER_ID + else process.env.AIMLAPI_PARTNER_ID = previous + } + }) +}) + describe('resolveOpenAIShimRuntimeContext - Z.A.I GLM-5.2', () => { it.each([ 'glm-5.2', diff --git a/src/integrations/runtimeMetadata.ts b/src/integrations/runtimeMetadata.ts index e9b17a1de1..49a4a13fc1 100644 --- a/src/integrations/runtimeMetadata.ts +++ b/src/integrations/runtimeMetadata.ts @@ -27,6 +27,40 @@ import { import { parseCustomHeadersEnv } from '../utils/providerCustomHeaders.js' import { firstUsableCredential } from '../services/api/credentialPool.js' import { ZAI_GLM_OPENAI_SHIM } from './transport/zaiGlmShim.js' +import { + isCanonicalAimlapiInferenceBaseUrl, + PARTNER_HEADER_NAME, + withResolvedPartnerHeader, +} from './aimlapi/config.js' + +const AIMLAPI_CATALOG_HEADER_NAMES = new Set([ + PARTNER_HEADER_NAME.toLowerCase(), + 'x-aimlapi-integration-repo', + 'x-aimlapi-integration-version', + 'http-referer', + 'x-title', +]) + +function resolveRouteOpenAIShimConfig( + routeId: string | null, + baseUrl: string | undefined, + config: OpenAIShimTransportConfig | undefined, +): OpenAIShimTransportConfig | undefined { + if (routeId !== 'aimlapi' || !config?.headers) return config + + if (!baseUrl || isCanonicalAimlapiInferenceBaseUrl(baseUrl)) { + return { ...config, headers: withResolvedPartnerHeader(config.headers) } + } + + return { + ...config, + headers: Object.fromEntries( + Object.entries(config.headers).filter( + ([name]) => !AIMLAPI_CATALOG_HEADER_NAMES.has(name.trim().toLowerCase()), + ), + ), + } +} function normalizeModelApiName( value: string | undefined, @@ -281,6 +315,8 @@ export function resolveOpenAIShimRuntimeContext(options?: { routeId && routeId !== 'anthropic' ? getRouteDescriptor(routeId) : null + const effectiveBaseUrl = + options?.baseUrl ?? runtimeEnv.OPENAI_BASE_URL ?? runtimeEnv.OPENAI_API_BASE const catalogEntry = descriptor && routeId ? getCatalogEntryForModel(routeId, options?.model) @@ -297,7 +333,11 @@ export function resolveOpenAIShimRuntimeContext(options?: { descriptor, catalogEntry, openaiShimConfig: mergeOpenAIShimConfig( - descriptor?.transportConfig.openaiShim, + resolveRouteOpenAIShimConfig( + routeId, + effectiveBaseUrl, + descriptor?.transportConfig.openaiShim, + ), catalogEntry?.transportOverrides?.openaiShim, inferredConfig, ), diff --git a/src/main.tsx b/src/main.tsx index a7832be9b6..5ed3cafeff 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -36,7 +36,7 @@ import { launchRepl } from './replLauncher.js'; import { refreshGrowthBookAfterAuthChange } from './services/analytics/growthbook.js'; import { fetchBootstrapData } from './services/api/bootstrap.js'; import { refreshStartupDiscoveryForActiveRoute } from './integrations/discoveryService.js'; -import { MAX_AMOUNT_USD_MINOR, MIN_AMOUNT_USD_MINOR } from './integrations/aimlapi/config.js'; +import { registerAimlapiCommand } from './cli/aimlapiCommand.js'; import { prefetchOllamaModels } from './utils/model/ollamaModels.js'; import { type DownloadResult, downloadSessionFiles, type FilesApiConfig, parseFileSpecs } from './services/api/filesApi.js'; import { prefetchPassesEligibility } from './services/api/referral.js'; @@ -4015,33 +4015,7 @@ async function run(): Promise { // AI/ML API (aimlapi.com) — log in, open the co-branded top-up page, and // auto-configure the provider with the issued key. - const aimlapi = program.command('aimlapi').description('AI/ML API (aimlapi.com) — top up balance and configure the provider').configureHelp(createSortedHelpConfig()); - aimlapi.command('topup') - .description("Log in, open AI/ML API top-up, then set the issued key as OpenClaude's provider") - .option('--email ', 'AI/ML API account email (or AIMLAPI_EMAIL env)') - .option('--amount ', `Top-up amount in USD (min ${MIN_AMOUNT_USD_MINOR / 100}, max ${MAX_AMOUNT_USD_MINOR / 100})`) - .addOption(new Option('--method ', 'Payment method: card (Stripe) or crypto (NOWPayments)').choices(['card', 'crypto']).default('card')) - .option('--model ', 'Default model id written into the provider profile', 'gpt-4o') - .option('--partner-id ', 'Partner id for rebate attribution (part_...)') - .option('--no-open', 'Do not auto-open the browser; print the payment URL instead') - .action(async (opts: { - email?: string; - amount?: string; - method?: string; - model?: string; - partnerId?: string; - open?: boolean; - }) => { - const { aimlapiTopup } = await import('./cli/handlers/aimlapi.js'); - await aimlapiTopup({ - email: opts.email, - amountUsd: opts.amount, - method: opts.method === 'crypto' ? 'crypto' : 'card', - model: opts.model, - partnerId: opts.partnerId, - noOpen: opts.open === false, - }); - }); + registerAimlapiCommand(program).configureHelp(createSortedHelpConfig()); /** * Helper function to handle marketplace command errors consistently. diff --git a/src/utils/providerDiscovery.test.ts b/src/utils/providerDiscovery.test.ts index 13961640a8..66f0388960 100644 --- a/src/utils/providerDiscovery.test.ts +++ b/src/utils/providerDiscovery.test.ts @@ -118,7 +118,7 @@ test('detects AI/ML API from descriptor route metadata', async () => { expect( getLocalOpenAICompatibleProviderLabel('https://api.aimlapi.com/v1'), - ).toBe('AI/ML API') + ).toBe('aimlapi.com') }) test('detects Z.AI from descriptor route metadata', async () => { diff --git a/src/utils/providerProfiles.test.ts b/src/utils/providerProfiles.test.ts index 5157568163..ae967cf338 100644 --- a/src/utils/providerProfiles.test.ts +++ b/src/utils/providerProfiles.test.ts @@ -1010,7 +1010,7 @@ describe('applyProviderProfileToProcessEnv', () => { expect(getFreshAPIProvider()).toBe('openai') }, 20_000) - test('keyless custom AIMLAPI profile preserves route identity with ambient OpenAI key', async () => { + test('keyless custom AIMLAPI profile preserves route identity without forwarding the ambient key', async () => { const { applyProviderProfileToProcessEnv } = await importFreshProviderProfileModules() process.env.OPENAI_API_KEY = 'ambient-openai-key' @@ -1026,8 +1026,52 @@ describe('applyProviderProfileToProcessEnv', () => { expect(process.env.OPENAI_BASE_URL).toBe('https://proxy.example.com/v1') expect(process.env.OPENAI_MODEL).toBe('gpt-4o') - expect(process.env.OPENAI_API_KEY).toBe('ambient-openai-key') - expect(process.env.AIMLAPI_API_KEY).toBe('ambient-openai-key') + // The base URL is a user-controlled proxy, not the canonical inference + // host, so the canonical AIMLAPI credential must not be forwarded to it. + expect(process.env.OPENAI_API_KEY).toBeUndefined() + expect(process.env.AIMLAPI_API_KEY).toBeUndefined() + expect(process.env.CLAUDE_CODE_PROVIDER_ROUTE_ID).toBe('aimlapi') + }, 20_000) + + test('keyless AIMLAPI profile resolves AIMLAPI_API_KEY without persisting it', async () => { + const { applyProviderProfileToProcessEnv } = + await importFreshProviderProfileModules() + process.env.AIMLAPI_API_KEY = 'ambient-aimlapi-key' + + applyProviderProfileToProcessEnv( + buildProfile({ + name: 'AI/ML API', + provider: 'aimlapi', + baseUrl: 'https://api.aimlapi.com/v1', + model: 'gpt-4o', + apiKey: undefined, + }), + ) + + expect(process.env.OPENAI_API_KEY).toBe('ambient-aimlapi-key') + expect(process.env.AIMLAPI_API_KEY).toBe('ambient-aimlapi-key') + expect(process.env.CLAUDE_CODE_PROVIDER_ROUTE_ID).toBe('aimlapi') + }, 20_000) + + test('keyless AIMLAPI profile without a base URL resolves the ambient key as canonical', async () => { + const { applyProviderProfileToProcessEnv } = + await importFreshProviderProfileModules() + process.env.AIMLAPI_API_KEY = 'ambient-aimlapi-key' + + // A missing base URL resolves to the canonical aimlapi default; the guard + // must treat it as canonical rather than crash on undefined.trim(). + applyProviderProfileToProcessEnv( + buildProfile({ + name: 'AI/ML API', + provider: 'aimlapi', + baseUrl: undefined, + model: 'gpt-4o', + apiKey: undefined, + }), + ) + + expect(process.env.AIMLAPI_API_KEY).toBe('ambient-aimlapi-key') + expect(process.env.OPENAI_API_KEY).toBe('ambient-aimlapi-key') expect(process.env.CLAUDE_CODE_PROVIDER_ROUTE_ID).toBe('aimlapi') }, 20_000) @@ -2403,7 +2447,7 @@ describe('getProviderPresetDefaults', () => { const defaults = getProviderPresetDefaults('aimlapi') expect(defaults.provider).toBe('aimlapi') - expect(defaults.name).toBe('AI/ML API') + expect(defaults.name).toBe('aimlapi.com') expect(defaults.baseUrl).toBe('https://api.aimlapi.com/v1') expect(defaults.model).toBe('gpt-4o') expect(defaults.apiKey).toBe('aimlapi-live-key') diff --git a/src/utils/providerProfiles.ts b/src/utils/providerProfiles.ts index 9351b16892..92334a5539 100644 --- a/src/utils/providerProfiles.ts +++ b/src/utils/providerProfiles.ts @@ -33,6 +33,7 @@ import { type ProfileEnv, type ProviderProfile as ProviderProfileStartup, } from './providerProfile.js' +import { isCanonicalAimlapiInferenceBaseUrl } from '../integrations/aimlapi/config.js' import { refreshStartupDiscoveryForRoute } from '../integrations/discoveryService.js' import { getCatalogEntriesForRoute, @@ -994,12 +995,23 @@ export function applyProviderProfileToProcessEnv( } } if (isAimlapiProfile) { - const ambientOpenAIKey = trimOrUndefined(process.env.OPENAI_API_KEY) openAIProfileEnv.CLAUDE_CODE_PROVIDER_ROUTE_ID = 'aimlapi' - openAIProfileEnv.OPENAI_API_KEY = - openAIProfileEnv.OPENAI_API_KEY ?? ambientOpenAIKey - openAIProfileEnv.AIMLAPI_API_KEY = - openAIProfileEnv.AIMLAPI_API_KEY ?? ambientOpenAIKey + // The ambient AIMLAPI_API_KEY is the canonical aimlapi.com credential. + // Only forward it when the profile targets the canonical inference host; + // a keyless `aimlapi` profile can point at a user-controlled proxy, and + // injecting the credential there would leak it. This mirrors the + // guided-flow validation, which also gates on the canonical URL. A missing + // base URL resolves to the aimlapi default (which is canonical), so treat + // it as canonical rather than passing undefined into the string helper. + if (!profile.baseUrl || isCanonicalAimlapiInferenceBaseUrl(profile.baseUrl)) { + const ambientAimlapiKey = + trimOrUndefined(process.env.AIMLAPI_API_KEY) ?? + trimOrUndefined(process.env.OPENAI_API_KEY) + openAIProfileEnv.OPENAI_API_KEY = + openAIProfileEnv.OPENAI_API_KEY ?? ambientAimlapiKey + openAIProfileEnv.AIMLAPI_API_KEY = + openAIProfileEnv.AIMLAPI_API_KEY ?? ambientAimlapiKey + } } if (route.gatewayId === 'nvidia-nim') { openAIProfileEnv.NVIDIA_NIM = '1' diff --git a/src/utils/status.test.ts b/src/utils/status.test.ts index 234f3e3e5c..59d26f7e75 100644 --- a/src/utils/status.test.ts +++ b/src/utils/status.test.ts @@ -143,7 +143,7 @@ test('buildAPIProviderProperties uses the resolved route label for AI/ML API ses process.env.OPENAI_BASE_URL = 'https://api.aimlapi.com/v1' process.env.OPENAI_MODEL = 'gpt-4o' - expect(await readPropertyValue('Provider route', 'openai')).toBe('AI/ML API') + expect(await readPropertyValue('Provider route', 'openai')).toBe('aimlapi.com') expect(await readPropertyValue('OpenAI base URL', 'openai')).toBe( 'https://api.aimlapi.com/v1', )