Skip to content

Claude Code opened to any LLM — OpenAI, Gemini, DeepSeek, Ollama, and 200+ models via OpenAI-compatible API shim

TypeScript

Merge origin/main into provider-profile-recommendations

Vasanthdev2004ce45bd080ea6
diff --cc scripts/provider-bootstrap.ts
index d54f49d,7e5d1f6..82ebbbb
--- a/scripts/provider-bootstrap.ts
+++ b/scripts/provider-bootstrap.ts
@@@ -2,27 -2,25 +2,28 @@@
import { writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
- DEFAULT_CODEX_BASE_URL,
resolveCodexApiCredentials,
} from '../src/services/api/providerConfig.js'
-
-type ProviderProfile = 'openai' | 'ollama' | 'codex' | 'gemini'
-
-type ProfileFile = {
- profile: ProviderProfile
- env: {
- OPENAI_BASE_URL?: string
- OPENAI_MODEL?: string
- OPENAI_API_KEY?: string
- CODEX_API_KEY?: string
- GEMINI_API_KEY?: string
- GEMINI_MODEL?: string
- GEMINI_BASE_URL?: string
- }
- createdAt: string
-}
+import {
+ getGoalDefaultOpenAIModel,
+ normalizeRecommendationGoal,
+ recommendOllamaModel,
+} from '../src/utils/providerRecommendation.ts'
+import {
+ buildCodexProfileEnv,
++ buildGeminiProfileEnv,
+ buildOllamaProfileEnv,
+ buildOpenAIProfileEnv,
+ createProfileFile,
+ selectAutoProfile,
+ type ProfileFile,
+ type ProviderProfile,
+} from '../src/utils/providerProfile.ts'
+import {
+ getOllamaChatBaseUrl,
+ hasLocalOllama,
+ listOllamaModels,
+} from './provider-discovery.ts'
function parseArg(name: string): string | null {
const args = process.argv.slice(2)
@@@ -71,57 -71,45 +72,72 @@@ async function main(): Promise<void>
selected = provider
}
- const env: ProfileFile['env'] = {}
-
+ let env: ProfileFile['env']
- if (selected === 'ollama') {
+ if (selected === 'gemini') {
- env.GEMINI_MODEL = argModel || process.env.GEMINI_MODEL || 'gemini-2.0-flash'
- const key = sanitizeApiKey(argApiKey || process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY || null)
- if (!key) {
++ const builtEnv = buildGeminiProfileEnv({
++ model: argModel || null,
++ baseUrl: argBaseUrl || null,
++ apiKey: argApiKey || null,
++ processEnv: process.env,
++ })
++
++ if (!builtEnv) {
+ console.error('Gemini profile requires an API key. Use --api-key or set GEMINI_API_KEY.')
+ console.error('Get a free key at: https://aistudio.google.com/apikey')
+ process.exit(1)
+ }
- env.GEMINI_API_KEY = key
- if (argBaseUrl) env.GEMINI_BASE_URL = argBaseUrl
++
++ env = builtEnv
+ } else if (selected === 'ollama') {
- env.OPENAI_BASE_URL = argBaseUrl || 'http://localhost:11434/v1'
- env.OPENAI_MODEL = argModel || process.env.OPENAI_MODEL || 'llama3.1:8b'
- const key = sanitizeApiKey(argApiKey || process.env.OPENAI_API_KEY || null)
- if (key) env.OPENAI_API_KEY = key
+ resolvedOllamaModel ??= await resolveOllamaModel(argModel, argBaseUrl, goal)
+ if (!resolvedOllamaModel) {
+ console.error('No viable Ollama chat model was discovered. Pull a chat model first or pass --model explicitly.')
+ process.exit(1)
+ }
+
+ env = buildOllamaProfileEnv(
+ resolvedOllamaModel,
+ {
+ baseUrl: argBaseUrl,
+ getOllamaChatBaseUrl,
+ },
+ )
} else if (selected === 'codex') {
- env.OPENAI_BASE_URL =
- argBaseUrl || process.env.OPENAI_BASE_URL || DEFAULT_CODEX_BASE_URL
- env.OPENAI_MODEL = argModel || process.env.OPENAI_MODEL || 'codexplan'
- const key = sanitizeApiKey(argApiKey || process.env.CODEX_API_KEY || null)
- if (key) {
- env.CODEX_API_KEY = key
- } else {
- const credentials = resolveCodexApiCredentials(process.env)
+ const builtEnv = buildCodexProfileEnv({
+ model: argModel,
+ baseUrl: argBaseUrl,
+ apiKey: argApiKey || process.env.CODEX_API_KEY || null,
+ processEnv: process.env,
+ })
+
+ if (!builtEnv) {
+ const credentials = resolveCodexApiCredentials(
+ argApiKey
+ ? { ...process.env, CODEX_API_KEY: argApiKey }
+ : process.env,
+ )
+ const authHint = credentials.authPath
+ ? ` or make sure ${credentials.authPath} exists`
+ : ''
if (!credentials.apiKey) {
- const authHint = credentials.authPath
- ? ` or make sure ${credentials.authPath} exists`
- : ''
console.error(`Codex profile requires CODEX_API_KEY${authHint}.`)
- process.exit(1)
+ } else {
+ console.error('Codex profile requires CHATGPT_ACCOUNT_ID or an auth.json that includes it.')
}
+ process.exit(1)
}
+
+ env = builtEnv
} else {
- env.OPENAI_BASE_URL = argBaseUrl || process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1'
- env.OPENAI_MODEL = argModel || process.env.OPENAI_MODEL || 'gpt-4o'
- const key = sanitizeApiKey(argApiKey || process.env.OPENAI_API_KEY || null)
- if (!key) {
+ const builtEnv = buildOpenAIProfileEnv({
+ goal,
+ model: argModel || null,
+ baseUrl: argBaseUrl || null,
+ apiKey: argApiKey || process.env.OPENAI_API_KEY || null,
+ processEnv: process.env,
+ })
+
+ if (!builtEnv) {
console.error('OpenAI profile requires a real API key. Use --api-key or set OPENAI_API_KEY.')
process.exit(1)
}
@@@ -135,8 -126,6 +151,8 @@@
writeFileSync(outputPath, JSON.stringify(profile, null, 2), 'utf8')
console.log(`Saved profile: ${selected}`)
+ console.log(`Goal: ${goal}`)
- console.log(`Model: ${profile.env.OPENAI_MODEL}`)
++ console.log(`Model: ${profile.env.GEMINI_MODEL || profile.env.OPENAI_MODEL || getGoalDefaultOpenAIModel(goal)}`)
console.log(`Path: ${outputPath}`)
console.log('Next: bun run dev:profile')
}
diff --cc scripts/provider-launch.ts
index 46a8741,4594b63..d8516be
--- a/scripts/provider-launch.ts
+++ b/scripts/provider-launch.ts
@@@ -42,13 -40,7 +42,13 @@@ function parseLaunchOptions(argv: strin
continue
}
+ if (lower === '--goal') {
+ goal = normalizeRecommendationGoal(argv[i + 1] ?? null)
+ i++
+ continue
+ }
+
- if ((lower === 'auto' || lower === 'openai' || lower === 'ollama' || lower === 'codex') && requestedProfile === 'auto') {
+ if ((lower === 'auto' || lower === 'openai' || lower === 'ollama' || lower === 'codex' || lower === 'gemini') && requestedProfile === 'auto') {
requestedProfile = lower as ProviderProfile | 'auto'
continue
}
@@@ -141,7 -193,7 +145,7 @@@ async function main(): Promise<void>
const options = parseLaunchOptions(process.argv.slice(2))
const requestedProfile = options.requestedProfile
if (!requestedProfile) {
- console.error('Usage: bun run scripts/provider-launch.ts [openai|ollama|codex|auto] [--fast] [--goal <latency|balanced|coding>] [-- <cli args>]')
- console.error('Usage: bun run scripts/provider-launch.ts [openai|ollama|codex|gemini|auto] [--fast] [-- <cli args>]')
++ console.error('Usage: bun run scripts/provider-launch.ts [openai|ollama|codex|gemini|auto] [--fast] [--goal <latency|balanced|coding>] [-- <cli args>]')
process.exit(1)
}
diff --cc src/utils/providerProfile.test.ts
index e005075,0000000..e90746c
mode 100644,000000..100644
--- a/src/utils/providerProfile.test.ts
+++ b/src/utils/providerProfile.test.ts
@@@ -1,307 -1,0 +1,383 @@@
+import assert from 'node:assert/strict'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import test from 'node:test'
+
+import {
+ buildCodexProfileEnv,
++ buildGeminiProfileEnv,
+ buildLaunchEnv,
+ buildOllamaProfileEnv,
+ buildOpenAIProfileEnv,
+ selectAutoProfile,
+ type ProfileFile,
+} from './providerProfile.ts'
+
+function profile(profile: ProfileFile['profile'], env: ProfileFile['env']): ProfileFile {
+ return {
+ profile,
+ env,
+ createdAt: '2026-04-01T00:00:00.000Z',
+ }
+}
+
+const missingCodexAuthPath = join(tmpdir(), 'openclaude-missing-codex-auth.json')
+
+test('matching persisted ollama env is reused for ollama launch', async () => {
+ const env = await buildLaunchEnv({
+ profile: 'ollama',
+ persisted: profile('ollama', {
+ OPENAI_BASE_URL: 'http://127.0.0.1:11435/v1',
+ OPENAI_MODEL: 'mistral:7b-instruct',
+ }),
+ goal: 'balanced',
+ processEnv: {},
+ getOllamaChatBaseUrl: () => 'http://localhost:11434/v1',
+ resolveOllamaDefaultModel: async () => 'llama3.1:8b',
+ })
+
+ assert.equal(env.OPENAI_BASE_URL, 'http://127.0.0.1:11435/v1')
+ assert.equal(env.OPENAI_MODEL, 'mistral:7b-instruct')
+})
+
+test('ollama launch ignores mismatched persisted openai env and shell model fallback', async () => {
+ const env = await buildLaunchEnv({
+ profile: 'ollama',
+ persisted: profile('openai', {
+ OPENAI_BASE_URL: 'https://api.openai.com/v1',
+ OPENAI_MODEL: 'gpt-4o',
+ OPENAI_API_KEY: 'sk-persisted',
+ }),
+ goal: 'coding',
+ processEnv: {
+ OPENAI_BASE_URL: 'https://api.deepseek.com/v1',
+ OPENAI_MODEL: 'gpt-4o-mini',
+ OPENAI_API_KEY: 'sk-live',
+ CODEX_API_KEY: 'codex-live',
+ CHATGPT_ACCOUNT_ID: 'acct_live',
+ },
+ getOllamaChatBaseUrl: () => 'http://localhost:11434/v1',
+ resolveOllamaDefaultModel: async () => 'qwen2.5-coder:7b',
+ })
+
+ assert.equal(env.OPENAI_BASE_URL, 'http://localhost:11434/v1')
+ assert.equal(env.OPENAI_MODEL, 'qwen2.5-coder:7b')
+ assert.equal(env.OPENAI_API_KEY, undefined)
+ assert.equal(env.CODEX_API_KEY, undefined)
+ assert.equal(env.CHATGPT_ACCOUNT_ID, undefined)
+})
+
+test('openai launch ignores mismatched persisted ollama env', async () => {
+ const env = await buildLaunchEnv({
+ profile: 'openai',
+ persisted: profile('ollama', {
+ OPENAI_BASE_URL: 'http://localhost:11434/v1',
+ OPENAI_MODEL: 'llama3.1:8b',
+ }),
+ goal: 'latency',
+ processEnv: {
+ OPENAI_API_KEY: 'sk-live',
+ CODEX_API_KEY: 'codex-live',
+ CHATGPT_ACCOUNT_ID: 'acct_live',
+ },
+ getOllamaChatBaseUrl: () => 'http://localhost:11434/v1',
+ resolveOllamaDefaultModel: async () => 'llama3.1:8b',
+ })
+
+ assert.equal(env.OPENAI_BASE_URL, 'https://api.openai.com/v1')
+ assert.equal(env.OPENAI_MODEL, 'gpt-4o-mini')
+ assert.equal(env.OPENAI_API_KEY, 'sk-live')
+ assert.equal(env.CODEX_API_KEY, undefined)
+ assert.equal(env.CHATGPT_ACCOUNT_ID, undefined)
+})
+
+test('openai launch ignores codex shell transport hints', async () => {
+ const env = await buildLaunchEnv({
+ profile: 'openai',
+ persisted: null,
+ goal: 'balanced',
+ processEnv: {
+ OPENAI_API_KEY: 'sk-live',
+ OPENAI_BASE_URL: 'https://chatgpt.com/backend-api/codex',
+ OPENAI_MODEL: 'codexplan',
+ },
+ })
+
+ assert.equal(env.OPENAI_BASE_URL, 'https://api.openai.com/v1')
+ assert.equal(env.OPENAI_MODEL, 'gpt-4o')
+ assert.equal(env.OPENAI_API_KEY, 'sk-live')
+})
+
+test('openai launch ignores codex persisted transport hints', async () => {
+ const env = await buildLaunchEnv({
+ profile: 'openai',
+ persisted: profile('openai', {
+ OPENAI_BASE_URL: 'https://chatgpt.com/backend-api/codex',
+ OPENAI_MODEL: 'codexplan',
+ OPENAI_API_KEY: 'sk-persisted',
+ }),
+ goal: 'balanced',
+ processEnv: {
+ OPENAI_API_KEY: 'sk-live',
+ },
+ })
+
+ assert.equal(env.OPENAI_BASE_URL, 'https://api.openai.com/v1')
+ assert.equal(env.OPENAI_MODEL, 'gpt-4o')
+ assert.equal(env.OPENAI_API_KEY, 'sk-live')
+})
+
++test('matching persisted gemini env is reused for gemini launch', async () => {
++ const env = await buildLaunchEnv({
++ profile: 'gemini',
++ persisted: profile('gemini', {
++ GEMINI_MODEL: 'gemini-2.5-flash',
++ GEMINI_API_KEY: 'gem-persisted',
++ GEMINI_BASE_URL: 'https://example.test/v1beta/openai',
++ }),
++ goal: 'balanced',
++ processEnv: {},
++ })
++
++ assert.equal(env.CLAUDE_CODE_USE_GEMINI, '1')
++ assert.equal(env.CLAUDE_CODE_USE_OPENAI, undefined)
++ assert.equal(env.GEMINI_MODEL, 'gemini-2.5-flash')
++ assert.equal(env.GEMINI_API_KEY, 'gem-persisted')
++ assert.equal(env.GEMINI_BASE_URL, 'https://example.test/v1beta/openai')
++})
++
++test('gemini launch ignores mismatched persisted openai env and strips other provider secrets', async () => {
++ const env = await buildLaunchEnv({
++ profile: 'gemini',
++ persisted: profile('openai', {
++ OPENAI_BASE_URL: 'https://api.openai.com/v1',
++ OPENAI_MODEL: 'gpt-4o',
++ OPENAI_API_KEY: 'sk-persisted',
++ }),
++ goal: 'balanced',
++ processEnv: {
++ GEMINI_API_KEY: 'gem-live',
++ GOOGLE_API_KEY: 'google-live',
++ OPENAI_API_KEY: 'sk-live',
++ OPENAI_BASE_URL: 'https://api.openai.com/v1',
++ OPENAI_MODEL: 'gpt-4o-mini',
++ CODEX_API_KEY: 'codex-live',
++ CHATGPT_ACCOUNT_ID: 'acct_live',
++ CLAUDE_CODE_USE_OPENAI: '1',
++ },
++ })
++
++ assert.equal(env.CLAUDE_CODE_USE_GEMINI, '1')
++ assert.equal(env.CLAUDE_CODE_USE_OPENAI, undefined)
++ assert.equal(env.GEMINI_MODEL, 'gemini-2.0-flash')
++ assert.equal(env.GEMINI_API_KEY, 'gem-live')
++ assert.equal(
++ env.GEMINI_BASE_URL,
++ 'https://generativelanguage.googleapis.com/v1beta/openai',
++ )
++ assert.equal(env.GOOGLE_API_KEY, undefined)
++ assert.equal(env.OPENAI_API_KEY, undefined)
++ assert.equal(env.CODEX_API_KEY, undefined)
++ assert.equal(env.CHATGPT_ACCOUNT_ID, undefined)
++})
++
+test('matching persisted codex env is reused for codex launch', async () => {
+ const env = await buildLaunchEnv({
+ profile: 'codex',
+ persisted: profile('codex', {
+ OPENAI_BASE_URL: 'https://chatgpt.com/backend-api/codex',
+ OPENAI_MODEL: 'codexspark',
+ CODEX_API_KEY: 'codex-persisted',
+ CHATGPT_ACCOUNT_ID: 'acct_persisted',
+ }),
+ goal: 'balanced',
+ processEnv: {
+ CODEX_AUTH_JSON_PATH: missingCodexAuthPath,
+ },
+ })
+
+ assert.equal(env.OPENAI_BASE_URL, 'https://chatgpt.com/backend-api/codex')
+ assert.equal(env.OPENAI_MODEL, 'codexspark')
+ assert.equal(env.CODEX_API_KEY, 'codex-persisted')
+ assert.equal(env.CHATGPT_ACCOUNT_ID, 'acct_persisted')
+})
+
+test('codex launch normalizes poisoned persisted base urls', async () => {
+ const env = await buildLaunchEnv({
+ profile: 'codex',
+ persisted: profile('codex', {
+ OPENAI_BASE_URL: 'https://api.openai.com/v1',
+ OPENAI_MODEL: 'codexspark',
+ CHATGPT_ACCOUNT_ID: 'acct_persisted',
+ }),
+ goal: 'balanced',
+ processEnv: {
+ CODEX_AUTH_JSON_PATH: missingCodexAuthPath,
+ },
+ })
+
+ assert.equal(env.OPENAI_BASE_URL, 'https://chatgpt.com/backend-api/codex')
+ assert.equal(env.OPENAI_MODEL, 'codexspark')
+})
+
+test('codex launch ignores mismatched persisted openai env', async () => {
+ const env = await buildLaunchEnv({
+ profile: 'codex',
+ persisted: profile('openai', {
+ OPENAI_BASE_URL: 'https://api.openai.com/v1',
+ OPENAI_MODEL: 'gpt-4o',
+ OPENAI_API_KEY: 'sk-persisted',
+ }),
+ goal: 'balanced',
+ processEnv: {
+ OPENAI_BASE_URL: 'https://api.openai.com/v1',
+ OPENAI_MODEL: 'gpt-4o-mini',
+ OPENAI_API_KEY: 'sk-live',
+ CODEX_API_KEY: 'codex-live',
+ CHATGPT_ACCOUNT_ID: 'acct_live',
+ },
+ })
+
+ assert.equal(env.OPENAI_BASE_URL, 'https://chatgpt.com/backend-api/codex')
+ assert.equal(env.OPENAI_MODEL, 'codexplan')
+ assert.equal(env.OPENAI_API_KEY, undefined)
+ assert.equal(env.CODEX_API_KEY, 'codex-live')
+ assert.equal(env.CHATGPT_ACCOUNT_ID, 'acct_live')
+})
+
+test('codex launch ignores placeholder codex env keys', async () => {
+ const env = await buildLaunchEnv({
+ profile: 'codex',
+ persisted: profile('codex', {
+ OPENAI_BASE_URL: 'https://chatgpt.com/backend-api/codex',
+ OPENAI_MODEL: 'codexspark',
+ CODEX_API_KEY: 'codex-persisted',
+ CHATGPT_ACCOUNT_ID: 'acct_persisted',
+ }),
+ goal: 'balanced',
+ processEnv: {
+ CODEX_API_KEY: 'SUA_CHAVE',
+ CODEX_AUTH_JSON_PATH: missingCodexAuthPath,
+ },
+ })
+
+ assert.equal(env.CODEX_API_KEY, 'codex-persisted')
+ assert.equal(env.CHATGPT_ACCOUNT_ID, 'acct_persisted')
+})
+
+test('codex launch prefers auth account id over stale persisted value', async () => {
+ const codexHome = mkdtempSync(join(tmpdir(), 'openclaude-codex-'))
+ try {
+ writeFileSync(
+ join(codexHome, 'auth.json'),
+ JSON.stringify({
+ access_token: 'codex-live',
+ account_id: 'acct_auth',
+ }),
+ 'utf8',
+ )
+
+ const env = await buildLaunchEnv({
+ profile: 'codex',
+ persisted: profile('codex', {
+ OPENAI_BASE_URL: 'https://chatgpt.com/backend-api/codex',
+ OPENAI_MODEL: 'codexspark',
+ CHATGPT_ACCOUNT_ID: 'acct_persisted',
+ }),
+ goal: 'balanced',
+ processEnv: {
+ CODEX_HOME: codexHome,
+ },
+ })
+
+ assert.equal(env.CHATGPT_ACCOUNT_ID, 'acct_auth')
+ } finally {
+ rmSync(codexHome, { recursive: true, force: true })
+ }
+})
+
+test('ollama profiles never persist openai api keys', () => {
+ const env = buildOllamaProfileEnv('llama3.1:8b', {
+ getOllamaChatBaseUrl: () => 'http://localhost:11434/v1',
+ })
+
+ assert.deepEqual(env, {
+ OPENAI_BASE_URL: 'http://localhost:11434/v1',
+ OPENAI_MODEL: 'llama3.1:8b',
+ })
+ assert.equal('OPENAI_API_KEY' in env, false)
+})
+
+test('codex profiles accept explicit codex credentials', () => {
+ const env = buildCodexProfileEnv({
+ model: 'codexspark',
+ apiKey: 'codex-live',
+ processEnv: {
+ CHATGPT_ACCOUNT_ID: 'acct_123',
+ },
+ })
+
+ assert.deepEqual(env, {
+ OPENAI_BASE_URL: 'https://chatgpt.com/backend-api/codex',
+ OPENAI_MODEL: 'codexspark',
+ CODEX_API_KEY: 'codex-live',
+ CHATGPT_ACCOUNT_ID: 'acct_123',
+ })
+})
+
+test('codex profiles require a chatgpt account id', () => {
+ const env = buildCodexProfileEnv({
+ model: 'codexspark',
+ apiKey: 'codex-live',
+ processEnv: {
+ CODEX_AUTH_JSON_PATH: missingCodexAuthPath,
+ },
+ })
+
+ assert.equal(env, null)
+})
+
++test('gemini profiles accept google api key fallback', () => {
++ const env = buildGeminiProfileEnv({
++ processEnv: {
++ GOOGLE_API_KEY: 'gem-live',
++ },
++ })
++
++ assert.deepEqual(env, {
++ GEMINI_MODEL: 'gemini-2.0-flash',
++ GEMINI_API_KEY: 'gem-live',
++ })
++})
++
++test('gemini profiles require a key', () => {
++ const env = buildGeminiProfileEnv({
++ processEnv: {},
++ })
++
++ assert.equal(env, null)
++})
++
+test('openai profiles ignore codex shell transport hints', () => {
+ const env = buildOpenAIProfileEnv({
+ goal: 'balanced',
+ apiKey: 'sk-live',
+ processEnv: {
+ OPENAI_BASE_URL: 'https://chatgpt.com/backend-api/codex',
+ OPENAI_MODEL: 'codexplan',
+ OPENAI_API_KEY: 'sk-live',
+ },
+ })
+
+ assert.deepEqual(env, {
+ OPENAI_BASE_URL: 'https://api.openai.com/v1',
+ OPENAI_MODEL: 'gpt-4o',
+ OPENAI_API_KEY: 'sk-live',
+ })
+})
+
+test('auto profile falls back to openai when no viable ollama model exists', () => {
+ assert.equal(selectAutoProfile(null), 'openai')
+ assert.equal(selectAutoProfile('qwen2.5-coder:7b'), 'ollama')
+})
diff --cc src/utils/providerProfile.ts
index 466c966,0000000..866c19c
mode 100644,000000..100644
--- a/src/utils/providerProfile.ts
+++ b/src/utils/providerProfile.ts
@@@ -1,232 -1,0 +1,314 @@@
+import {
+ DEFAULT_CODEX_BASE_URL,
+ DEFAULT_OPENAI_BASE_URL,
+ isCodexBaseUrl,
+ resolveCodexApiCredentials,
+ resolveProviderRequest,
+} from '../services/api/providerConfig.ts'
+import {
+ getGoalDefaultOpenAIModel,
+ type RecommendationGoal,
+} from './providerRecommendation.ts'
+
- export type ProviderProfile = 'openai' | 'ollama' | 'codex'
++const DEFAULT_GEMINI_BASE_URL = 'https://generativelanguage.googleapis.com/v1beta/openai'
++const DEFAULT_GEMINI_MODEL = 'gemini-2.0-flash'
++
++export type ProviderProfile = 'openai' | 'ollama' | 'codex' | 'gemini'
+
+export type ProfileEnv = {
+ OPENAI_BASE_URL?: string
+ OPENAI_MODEL?: string
+ OPENAI_API_KEY?: string
+ CODEX_API_KEY?: string
+ CHATGPT_ACCOUNT_ID?: string
+ CODEX_ACCOUNT_ID?: string
++ GEMINI_API_KEY?: string
++ GEMINI_MODEL?: string
++ GEMINI_BASE_URL?: string
+}
+
+export type ProfileFile = {
+ profile: ProviderProfile
+ env: ProfileEnv
+ createdAt: string
+}
+
+export function sanitizeApiKey(
+ key: string | null | undefined,
+): string | undefined {
+ if (!key || key === 'SUA_CHAVE') return undefined
+ return key
+}
+
+export function buildOllamaProfileEnv(
+ model: string,
+ options: {
+ baseUrl?: string | null
+ getOllamaChatBaseUrl: (baseUrl?: string) => string
+ },
+): ProfileEnv {
+ return {
+ OPENAI_BASE_URL: options.getOllamaChatBaseUrl(options.baseUrl ?? undefined),
+ OPENAI_MODEL: model,
+ }
+}
+
++export function buildGeminiProfileEnv(options: {
++ model?: string | null
++ baseUrl?: string | null
++ apiKey?: string | null
++ processEnv?: NodeJS.ProcessEnv
++}): ProfileEnv | null {
++ const processEnv = options.processEnv ?? process.env
++ const key = sanitizeApiKey(
++ options.apiKey ??
++ processEnv.GEMINI_API_KEY ??
++ processEnv.GOOGLE_API_KEY,
++ )
++ if (!key) {
++ return null
++ }
++
++ const env: ProfileEnv = {
++ GEMINI_MODEL:
++ options.model || processEnv.GEMINI_MODEL || DEFAULT_GEMINI_MODEL,
++ GEMINI_API_KEY: key,
++ }
++
++ const baseUrl = options.baseUrl || processEnv.GEMINI_BASE_URL
++ if (baseUrl) {
++ env.GEMINI_BASE_URL = baseUrl
++ }
++
++ return env
++}
++
+export function buildOpenAIProfileEnv(options: {
+ goal: RecommendationGoal
+ model?: string | null
+ baseUrl?: string | null
+ apiKey?: string | null
+ processEnv?: NodeJS.ProcessEnv
+}): ProfileEnv | null {
+ const processEnv = options.processEnv ?? process.env
+ const key = sanitizeApiKey(options.apiKey ?? processEnv.OPENAI_API_KEY)
+ if (!key) {
+ return null
+ }
+
+ const defaultModel = getGoalDefaultOpenAIModel(options.goal)
+ const shellOpenAIRequest = resolveProviderRequest({
+ model: processEnv.OPENAI_MODEL,
+ baseUrl: processEnv.OPENAI_BASE_URL,
+ fallbackModel: defaultModel,
+ })
+ const useShellOpenAIConfig = shellOpenAIRequest.transport === 'chat_completions'
+
+ return {
+ OPENAI_BASE_URL:
+ options.baseUrl ||
+ (useShellOpenAIConfig ? processEnv.OPENAI_BASE_URL : undefined) ||
+ DEFAULT_OPENAI_BASE_URL,
+ OPENAI_MODEL:
+ options.model ||
+ (useShellOpenAIConfig ? processEnv.OPENAI_MODEL : undefined) ||
+ defaultModel,
+ OPENAI_API_KEY: key,
+ }
+}
+
+export function buildCodexProfileEnv(options: {
+ model?: string | null
+ baseUrl?: string | null
+ apiKey?: string | null
+ processEnv?: NodeJS.ProcessEnv
+}): ProfileEnv | null {
+ const processEnv = options.processEnv ?? process.env
+ const key = sanitizeApiKey(options.apiKey ?? processEnv.CODEX_API_KEY)
+ const credentialEnv = key
+ ? ({ ...processEnv, CODEX_API_KEY: key } as NodeJS.ProcessEnv)
+ : processEnv
+ const credentials = resolveCodexApiCredentials(credentialEnv)
+ if (!credentials.apiKey || !credentials.accountId) {
+ return null
+ }
+
+ const env: ProfileEnv = {
+ OPENAI_BASE_URL: options.baseUrl || DEFAULT_CODEX_BASE_URL,
+ OPENAI_MODEL: options.model || 'codexplan',
+ }
+
+ if (key) {
+ env.CODEX_API_KEY = key
+ }
+
+ env.CHATGPT_ACCOUNT_ID = credentials.accountId
+
+ return env
+}
+
+export function createProfileFile(
+ profile: ProviderProfile,
+ env: ProfileEnv,
+): ProfileFile {
+ return {
+ profile,
+ env,
+ createdAt: new Date().toISOString(),
+ }
+}
+
+export function selectAutoProfile(
+ recommendedOllamaModel: string | null,
+): ProviderProfile {
+ return recommendedOllamaModel ? 'ollama' : 'openai'
+}
+
+export async function buildLaunchEnv(options: {
+ profile: ProviderProfile
+ persisted: ProfileFile | null
+ goal: RecommendationGoal
+ processEnv?: NodeJS.ProcessEnv
+ getOllamaChatBaseUrl?: (baseUrl?: string) => string
+ resolveOllamaDefaultModel?: (goal: RecommendationGoal) => Promise<string>
+}): Promise<NodeJS.ProcessEnv> {
+ const processEnv = options.processEnv ?? process.env
+ const persistedEnv =
+ options.persisted?.profile === options.profile
+ ? options.persisted.env ?? {}
+ : {}
+
++ const shellGeminiKey = sanitizeApiKey(
++ processEnv.GEMINI_API_KEY ?? processEnv.GOOGLE_API_KEY,
++ )
++ const persistedGeminiKey = sanitizeApiKey(persistedEnv.GEMINI_API_KEY)
++
++ if (options.profile === 'gemini') {
++ const env: NodeJS.ProcessEnv = {
++ ...processEnv,
++ CLAUDE_CODE_USE_GEMINI: '1',
++ }
++
++ delete env.CLAUDE_CODE_USE_OPENAI
++
++ env.GEMINI_MODEL =
++ processEnv.GEMINI_MODEL ||
++ persistedEnv.GEMINI_MODEL ||
++ DEFAULT_GEMINI_MODEL
++ env.GEMINI_BASE_URL =
++ processEnv.GEMINI_BASE_URL ||
++ persistedEnv.GEMINI_BASE_URL ||
++ DEFAULT_GEMINI_BASE_URL
++
++ const geminiKey = shellGeminiKey || persistedGeminiKey
++ if (geminiKey) {
++ env.GEMINI_API_KEY = geminiKey
++ } else {
++ delete env.GEMINI_API_KEY
++ }
++
++ delete env.GOOGLE_API_KEY
++ delete env.OPENAI_BASE_URL
++ delete env.OPENAI_MODEL
++ delete env.OPENAI_API_KEY
++ delete env.CODEX_API_KEY
++ delete env.CHATGPT_ACCOUNT_ID
++ delete env.CODEX_ACCOUNT_ID
++
++ return env
++ }
++
+ const env: NodeJS.ProcessEnv = {
+ ...processEnv,
+ CLAUDE_CODE_USE_OPENAI: '1',
+ }
+
++ delete env.CLAUDE_CODE_USE_GEMINI
++ delete env.GEMINI_API_KEY
++ delete env.GEMINI_MODEL
++ delete env.GEMINI_BASE_URL
++ delete env.GOOGLE_API_KEY
++
+ if (options.profile === 'ollama') {
+ const getOllamaBaseUrl =
+ options.getOllamaChatBaseUrl ?? (() => 'http://localhost:11434/v1')
+ const resolveOllamaModel =
+ options.resolveOllamaDefaultModel ?? (async () => 'llama3.1:8b')
+
+ env.OPENAI_BASE_URL = persistedEnv.OPENAI_BASE_URL || getOllamaBaseUrl()
+ env.OPENAI_MODEL =
+ persistedEnv.OPENAI_MODEL ||
+ (await resolveOllamaModel(options.goal))
+
+ delete env.OPENAI_API_KEY
+ delete env.CODEX_API_KEY
+ delete env.CHATGPT_ACCOUNT_ID
+ delete env.CODEX_ACCOUNT_ID
+
+ return env
+ }
+
+ if (options.profile === 'codex') {
+ env.OPENAI_BASE_URL =
+ persistedEnv.OPENAI_BASE_URL && isCodexBaseUrl(persistedEnv.OPENAI_BASE_URL)
+ ? persistedEnv.OPENAI_BASE_URL
+ : DEFAULT_CODEX_BASE_URL
+ env.OPENAI_MODEL = persistedEnv.OPENAI_MODEL || 'codexplan'
+ delete env.OPENAI_API_KEY
+
+ const codexKey =
+ sanitizeApiKey(processEnv.CODEX_API_KEY) ||
+ sanitizeApiKey(persistedEnv.CODEX_API_KEY)
+ const liveCodexCredentials = resolveCodexApiCredentials(processEnv)
+ const codexAccountId =
+ processEnv.CHATGPT_ACCOUNT_ID ||
+ processEnv.CODEX_ACCOUNT_ID ||
+ liveCodexCredentials.accountId ||
+ persistedEnv.CHATGPT_ACCOUNT_ID ||
+ persistedEnv.CODEX_ACCOUNT_ID
+ if (codexKey) {
+ env.CODEX_API_KEY = codexKey
+ } else {
+ delete env.CODEX_API_KEY
+ }
+
+ if (codexAccountId) {
+ env.CHATGPT_ACCOUNT_ID = codexAccountId
+ } else {
+ delete env.CHATGPT_ACCOUNT_ID
+ }
+ delete env.CODEX_ACCOUNT_ID
+
+ return env
+ }
+
+ const defaultOpenAIModel = getGoalDefaultOpenAIModel(options.goal)
+ const shellOpenAIRequest = resolveProviderRequest({
+ model: processEnv.OPENAI_MODEL,
+ baseUrl: processEnv.OPENAI_BASE_URL,
+ fallbackModel: defaultOpenAIModel,
+ })
+ const persistedOpenAIRequest = resolveProviderRequest({
+ model: persistedEnv.OPENAI_MODEL,
+ baseUrl: persistedEnv.OPENAI_BASE_URL,
+ fallbackModel: defaultOpenAIModel,
+ })
+ const useShellOpenAIConfig = shellOpenAIRequest.transport === 'chat_completions'
+ const usePersistedOpenAIConfig =
+ (!persistedEnv.OPENAI_MODEL && !persistedEnv.OPENAI_BASE_URL) ||
+ persistedOpenAIRequest.transport === 'chat_completions'
+
+ env.OPENAI_BASE_URL =
+ (useShellOpenAIConfig ? processEnv.OPENAI_BASE_URL : undefined) ||
+ (usePersistedOpenAIConfig ? persistedEnv.OPENAI_BASE_URL : undefined) ||
+ DEFAULT_OPENAI_BASE_URL
+ env.OPENAI_MODEL =
+ (useShellOpenAIConfig ? processEnv.OPENAI_MODEL : undefined) ||
+ (usePersistedOpenAIConfig ? persistedEnv.OPENAI_MODEL : undefined) ||
+ defaultOpenAIModel
+ env.OPENAI_API_KEY = processEnv.OPENAI_API_KEY || persistedEnv.OPENAI_API_KEY
+ delete env.CODEX_API_KEY
+ delete env.CHATGPT_ACCOUNT_ID
+ delete env.CODEX_ACCOUNT_ID
+ return env
+}