How the `--provider` Flag Affects OpenClaude's Startup: A Deep Dive into CLI Initialization
The --provider flag determines OpenClaude's entire runtime configuration by setting provider-specific environment variables, applying defaults, and ensuring the chosen AI service takes precedence over saved settings.
When you launch OpenClaude with a specific provider, the flag triggers a carefully sequenced initialization process that wires up the correct API endpoints, credentials, and model defaults before any chat logic runs. This mechanism ensures clean isolation between competing AI backends and prevents credential leakage across providers.
Early Parsing in the CLI Entrypoint
The --provider flag is detected and processed before configuration files load or profile-based environment merges occur. In src/entrypoints/cli.tsx (lines 100-120), the entrypoint checks for the flag's presence and dynamically imports the provider handling logic.
// src/entrypoints/cli.tsx – early flag handling
if (args.includes('--provider')) {
const { applyProviderFlagFromArgs, reapplyRememberedProviderFlag } = await importers.providerFlag();
reapplyProviderFlagValues = reapplyRememberedProviderFlag;
const result = applyProviderFlagFromArgs(args, { rememberForSettingsEnv: true });
if (result?.error) { console.error(`Error: ${result.error}`); process.exit(1); }
}
The function applyProviderFlagFromArgs validates the provider name and records the selection in rememberedProviderFlag for later re-application. If validation fails, startup aborts immediately with an error message listing valid providers.
Provider-Specific Environment Wiring
The core implementation in src/utils/providerFlag.ts handles the bulk of --provider flag processing. The applyProviderFlag function orchestrates three critical operations:
1. Clearing Competing Provider Flags
All existing CLAUDE_CODE_USE_* environment variables are deleted before setting the selected provider's flag. This prevents accidental cross-provider activation.
// Clear all previous provider flags
delete process.env.CLAUDE_CODE_USE_OPENAI;
delete process.env.CLAUDE_CODE_USE_GEMINI;
// … additional providers
2. Setting Provider-Specific Defaults
Each provider branch applies tailored configuration:
| Provider | Defaults Applied |
|---|---|
| openai | Sets CLAUDE_CODE_USE_OPENAI='1', applies base URL default via applyOpenAIBaseUrlDefault |
| ollama | Points base URL to http://localhost:11434/v1 |
| gemini | Sets CLAUDE_CODE_USE_GEMINI='1', configures GEMINI_MODEL if specified |
| Custom providers | Validates required env vars, removes incompatible variables |
3. API Key Mirroring
Provider-specific credential handling maps dedicated keys to standard names. For example, OPENGATEWAY_API_KEY or NVIDIA_API_KEY populates OPENAI_API_KEY when those providers are selected.
// src/utils/providerFlag.ts – core provider wiring (excerpt)
export function applyProviderFlag(provider: string, args: string[]) {
if (!VALID_PROVIDERS.includes(provider)) {
return { error: `Unknown provider "${provider}". Valid providers: ${VALID_PROVIDERS.join(', ')}` };
}
// Set the flag for the chosen provider
switch (provider) {
case 'openai':
process.env.CLAUDE_CODE_USE_OPENAI = '1';
applyOpenAIBaseUrlDefault(provider, defaultBaseUrl);
if (model) process.env.OPENAI_MODEL = model;
break;
// … other providers with their own defaults …
}
}
Re-Application Across Settings Merges
A critical guarantee of the --provider flag is that it wins over later environment changes. After applySafeConfigEnvironmentVariables loads user settings and applyStartupEnvFromProfile applies saved-profile environment, the entrypoint calls reapplyExplicitProviderInputs().
This function invokes both reapplyRememberedProviderFlag and reapplyRememberedEnvFileValues, restoring the explicit --provider selection (and any --provider-env-file values) to ensure they override merged configuration.
The re-application occurs around line 36 in src/entrypoints/cli.tsx.
Model Flag Interaction
The --provider flag changes how --model is processed. In applyModelFlagFromArgs:
- With
--provider: The provider-specific branch already handled model assignment;applyModelFlagFromArgsskips processing - Without
--provider: The model value routes to the environment variable matching the currently active provider (determined by existingCLAUDE_CODE_USE_*flags)
This design ensures consistent model assignment regardless of which flags the user provides.
Validation Before Main Execution
After all environment preparation completes, src/utils/providerValidation.ts runs validateProviderEnvForStartupOrExit. This final check confirms that the selected provider has all required endpoint, model, and credential variables present. Missing requirements abort startup with a descriptive error.
# Explicit provider selection – OpenAI with model override
openclaude --provider openai --model gpt-4o
Summary
The --provider flag controls OpenClaude's startup through six coordinated stages:
- Early extraction – Parsed and validated before any configuration loads
- Environment isolation – Clears competing provider flags to prevent leakage
- Default injection – Applies provider-specific base URLs, models, and credentials
- Credential mapping – Mirrors compatible API keys to expected variable names
- Settings precedence – Re-applies after profile merges to ensure the flag wins
- Startup gating – Validates all required variables before allowing execution
Frequently Asked Questions
What happens if I specify an invalid provider name?
The startup process aborts immediately. In src/entrypoints/cli.tsx, applyProviderFlagFromArgs returns an error object that triggers process.exit(1) with a message listing all valid providers from the VALID_PROVIDERS array.
Can I override a provider selected in my saved profile?
Yes. The --provider flag takes precedence through the re-application mechanism. Even after applyStartupEnvFromProfile loads your saved environment, reapplyRememberedProviderFlag restores the explicit CLI selection.
Why does OpenClaude clear all provider flags before setting one?
This prevents credential leakage between providers. Without this step, stale CLAUDE_CODE_USE_* variables from previous sessions could activate the wrong backend or expose keys to unintended services.
What is the difference between --provider and --provider-env-file?
--provider selects the AI service directly and triggers built-in defaults. --provider-env-file loads additional environment variables from a file before provider processing, useful for custom endpoints or credential sets not covered by standard providers.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →