Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(backends): Codex provider config page end-to-end (Phase A)

cyh72f508915562
diff --git a/config/v2_compat.py b/config/v2_compat.py
index 77a46e995..92c9fdad0 100644
--- a/config/v2_compat.py
+++ b/config/v2_compat.py
@@ -23,6 +23,9 @@ class ClaudeCompatConfig:
default_model: Optional[str] = None
cli_path: Optional[str] = None
idle_timeout_seconds: int = DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS
+ auth_mode: str = "oauth"
+ api_key: Optional[str] = None
+ base_url: Optional[str] = None
def __post_init__(self) -> None:
self.permission_mode = str(self.permission_mode)
diff --git a/config/v2_config.py b/config/v2_config.py
index a8679614c..9b14ab22c 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -5,7 +5,7 @@ import tempfile
import threading
from dataclasses import dataclass, field, fields
from pathlib import Path
-from typing import List, Optional, Union
+from typing import List, Literal, Optional, Union
from config import paths
from config.platform_registry import (
@@ -151,6 +151,10 @@ class OpenCodeConfig:
default_model: Optional[str] = None
default_reasoning_effort: Optional[str] = None
error_retry_limit: int = DEFAULT_OPENCODE_ERROR_RETRY_LIMIT # Max retries on LLM stream errors (0 = no retry)
+ # Provider chosen by default when starting a new session. The provider
+ # catalog itself lives in ~/.config/opencode/opencode.json (OpenCode's
+ # own state file); we only persist the user's UI-selected default here.
+ default_provider: str = "anthropic"
@dataclass
@@ -159,6 +163,12 @@ class ClaudeConfig:
cli_path: str = "claude"
default_model: Optional[str] = None
idle_timeout_seconds: int = DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS
+ # Auth model: "oauth" relies on Claude Code's own credential storage;
+ # "api_key" injects ANTHROPIC_API_KEY (and optionally ANTHROPIC_BASE_URL)
+ # at CLI launch time for API gateway / proxy setups.
+ auth_mode: Literal["oauth", "api_key"] = "oauth"
+ api_key: Optional[str] = None
+ base_url: Optional[str] = None
@dataclass
@@ -167,6 +177,12 @@ class CodexConfig:
cli_path: str = "codex"
default_model: Optional[str] = None
idle_timeout_seconds: int = DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS
+ # Auth model: "oauth" defers to whatever ~/.codex/config.toml already
+ # has (typically `auth.method = "ChatGPT"`); "api_key" writes the
+ # config.toml fields that point Codex at an API key + custom base URL.
+ auth_mode: Literal["oauth", "api_key"] = "oauth"
+ api_key: Optional[str] = None
+ base_url: Optional[str] = None
@dataclass
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index e19f64048..de296bc33 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -564,6 +564,19 @@ class SessionHandler(BaseHandler):
for key in os.environ:
if key.startswith("ANTHROPIC_") or key.startswith("CLAUDE_"):
claude_env[key] = os.environ[key]
+ # V2Config-driven overrides win over ambient shell env: the user
+ # opted in to these via Settings → Backends, so they should beat a
+ # stale ``ANTHROPIC_API_KEY`` exported in the parent shell.
+ claude_cfg = getattr(self.config, "claude", None)
+ if claude_cfg is not None:
+ auth_mode = getattr(claude_cfg, "auth_mode", "oauth")
+ if auth_mode == "api_key":
+ configured_key = (getattr(claude_cfg, "api_key", None) or "").strip()
+ if configured_key:
+ claude_env["ANTHROPIC_API_KEY"] = configured_key
+ configured_base = (getattr(claude_cfg, "base_url", None) or "").strip()
+ if configured_base:
+ claude_env["ANTHROPIC_BASE_URL"] = configured_base
if self._should_force_claude_sandbox():
claude_env["IS_SANDBOX"] = "1"
logger.info("Detected Claude bypassPermissions running as root; forcing IS_SANDBOX=1 for Claude subprocess")
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index e90d3e97a..3cac75ba9 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -6,6 +6,7 @@ import { ChannelList } from './components/steps/ChannelList';
import { UserList } from './components/steps/UserList';
import { SettingsDiagnosticsPage } from './components/settings/SettingsDiagnosticsPage';
import { SettingsBackendsPage } from './components/settings/SettingsBackendsPage';
+import { SettingsCodexProviderPage } from './components/settings/SettingsCodexProviderPage';
import { SettingsLogsPage } from './components/settings/SettingsLogsPage';
import { SettingsMessagingPage } from './components/settings/SettingsMessagingPage';
import { SettingsPlatformsPage } from './components/settings/SettingsPlatformsPage';
@@ -77,6 +78,7 @@ function AppRoutes() {
<Route path="/settings/service" element={<SettingsServicePage />} />
<Route path="/settings/platforms" element={<SettingsPlatformsPage />} />
<Route path="/settings/backends" element={<SettingsBackendsPage />} />
+ <Route path="/settings/backends/codex" element={<SettingsCodexProviderPage />} />
<Route path="/settings/messaging" element={<SettingsMessagingPage />} />
<Route path="/settings/diagnostics" element={<SettingsDiagnosticsPage />} />
<Route path="/settings/logs" element={<SettingsLogsPage />} />
diff --git a/ui/src/components/settings/SettingsCodexProviderPage.tsx b/ui/src/components/settings/SettingsCodexProviderPage.tsx
new file mode 100644
index 000000000..9c5ae2082
--- /dev/null
+++ b/ui/src/components/settings/SettingsCodexProviderPage.tsx
@@ -0,0 +1,241 @@
+import React, { useEffect, useMemo, useState } from 'react';
+import { Link } from 'react-router-dom';
+import { ArrowLeft, Info, KeyRound, RotateCcw, Save } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+
+import { Button } from '../ui/button';
+import { Card, CardContent } from '../ui/card';
+import { Input } from '../ui/input';
+import { Label } from '../ui/label';
+import { useApi } from '@/context/ApiContext';
+import type { CodexAuthMode, CodexAuthState } from '@/context/ApiContext';
+import { useToast } from '@/context/ToastContext';
+import { SettingsPageShell } from './SettingsPageShell';
+
+// Mirrors the segmented-radio pattern in shared/RoutingConfigPanel.tsx so
+// Codex's auth-mode toggle reads like the rest of the Settings surface.
+const SegmentedRadio: React.FC<{
+ value: CodexAuthMode;
+ onChange: (next: CodexAuthMode) => void;
+ options: ReadonlyArray<{ id: CodexAuthMode; label: string }>;
+ ariaLabel: string;
+}> = ({ value, onChange, options, ariaLabel }) => (
+ <div
+ role="radiogroup"
+ aria-label={ariaLabel}
+ className="flex h-9 items-stretch gap-0.5 rounded-md border border-border bg-foreground/[0.03] p-0.5"
+ >
+ {options.map((opt) => {
+ const active = value === opt.id;
+ return (
+ <button
+ key={opt.id}
+ type="button"
+ role="radio"
+ aria-checked={active}
+ onClick={() => onChange(opt.id)}
+ className={clsx(
+ 'flex-1 rounded-[4px] px-3 text-[12px] transition-colors',
+ active
+ ? 'border border-mint/30 bg-mint-soft font-bold text-mint'
+ : 'font-medium text-muted hover:text-foreground'
+ )}
+ >
+ {opt.label}
+ </button>
+ );
+ })}
+ </div>
+);
+
+export const SettingsCodexProviderPage: React.FC = () => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
+
+ const [state, setState] = useState<CodexAuthState | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [authMode, setAuthMode] = useState<CodexAuthMode>('oauth');
+ const [apiKey, setApiKey] = useState('');
+ const [baseUrl, setBaseUrl] = useState('');
+
+ useEffect(() => {
+ let cancelled = false;
+ api
+ .getCodexAuth()
+ .then((data) => {
+ if (cancelled) return;
+ setState(data);
+ setAuthMode(data.auth_mode);
+ setBaseUrl(data.base_url || '');
+ // Never preload the api_key field: the server only returns its
+ // length, and an empty input here is interpreted as "keep what's
+ // stored" on save unless the user types a fresh value.
+ setApiKey('');
+ })
+ .catch(() => {
+ // Errors are already surfaced via ToastContext by ApiContext;
+ // leave the page on the default oauth state so the user can still
+ // make a choice rather than seeing a broken UI.
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [api]);
+
+ const modeOptions = useMemo(
+ () =>
+ [
+ { id: 'oauth' as const, label: t('settings.backends.codexAuthModeOauth') },
+ { id: 'api_key' as const, label: t('settings.backends.codexAuthModeApiKey') },
+ ] as const,
+ [t]
+ );
+
+ const apiKeyStatus = state?.has_api_key
+ ? t('settings.backends.codexApiKeyConfigured', { length: state.api_key_length })
+ : t('settings.backends.codexApiKeyMissing');
+
+ const onSave = async () => {
+ setSaving(true);
+ try {
+ const payload = {
+ auth_mode: authMode,
+ // Send a fresh key only when the user typed one; an empty string
+ // lets the server reuse the stored key (useful when the user is
+ // just updating the base URL).
+ api_key: authMode === 'api_key' ? (apiKey || undefined) : null,
+ base_url: baseUrl.trim() || null,
+ };
+ const result = await api.saveCodexAuth(payload);
+ setState(result);
+ setAuthMode(result.auth_mode);
+ setBaseUrl(result.base_url || '');
+ setApiKey('');
+ if (result.restart?.ok === false) {
+ // Config saved, restart failed — make the partial success visible.
+ showToast(result.restart.message || result.message || t('settings.backends.codexSaveSuccess'), 'warning');
+ } else {
+ showToast(t('settings.backends.codexSaveSuccess'), 'success');
+ }
+ } catch (err: any) {
+ showToast(err?.message || t('settings.backends.codexSaveFailed'), 'error');
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <SettingsPageShell
+ activeTab="backends"
+ title={t('settings.backends.codexTitle')}
+ subtitle={t('settings.backends.codexSubtitle')}
+ breadcrumb={
+ <Link to="/settings/backends" className="inline-flex items-center gap-1.5 hover:text-foreground">
+ <ArrowLeft className="size-3" />
+ {t('settings.backends.codexBackToBackends')}
+ </Link>
+ }
+ >
+ {loading ? (
+ <div className="text-sm text-muted">{t('common.loading')}</div>
+ ) : (
+ <Card>
+ <CardContent className="flex flex-col gap-5 p-6">
+ <div className="flex flex-col gap-2">
+ <Label className="text-xs font-medium uppercase text-muted">
+ {t('settings.backends.codexAuthModeLabel')}
+ </Label>
+ <SegmentedRadio
+ value={authMode}
+ onChange={setAuthMode}
+ options={modeOptions}
+ ariaLabel={t('settings.backends.codexAuthModeLabel') as string}
+ />
+ <p className="text-[12px] leading-relaxed text-muted">
+ {authMode === 'api_key'
+ ? t('settings.backends.codexAuthModeApiKeyHint')
+ : t('settings.backends.codexAuthModeOauthHint')}
+ </p>
+ {authMode === 'oauth' && state?.has_chatgpt_tokens && (
+ <p className="text-[12px] text-mint">
+ {t('settings.backends.codexHasChatgptTokens')}
+ </p>
+ )}
+ </div>
+
+ {authMode === 'api_key' && (
+ <div className="flex flex-col gap-2">
+ <Label htmlFor="codex-api-key" className="text-xs font-medium uppercase text-muted">
+ {t('settings.backends.codexApiKeyLabel')}
+ </Label>
+ <div className="relative">
+ <KeyRound className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted" />
+ <Input
+ id="codex-api-key"
+ type="password"
+ autoComplete="off"
+ spellCheck={false}
+ placeholder={t('settings.backends.codexApiKeyPlaceholder') as string}
+ value={apiKey}
+ onChange={(e) => setApiKey(e.target.value)}
+ className="pl-9 font-mono"
+ />
+ </div>
+ <p className="text-[12px] text-muted">{apiKeyStatus}</p>
+ </div>
+ )}
+
+ <div className="flex flex-col gap-2">
+ <Label htmlFor="codex-base-url" className="text-xs font-medium uppercase text-muted">
+ {t('settings.backends.codexBaseUrlLabel')}
+ </Label>
+ <div className="flex gap-2">
+ <Input
+ id="codex-base-url"
+ type="url"
+ autoComplete="off"
+ spellCheck={false}
+ placeholder={t('settings.backends.codexBaseUrlPlaceholder') as string}
+ value={baseUrl}
+ onChange={(e) => setBaseUrl(e.target.value)}
+ className="font-mono"
+ />
+ <Button
+ type="button"
+ variant="secondary"
+ size="sm"
+ onClick={() => setBaseUrl('')}
+ disabled={!baseUrl}
+ >
+ <RotateCcw className="size-3.5" />
+ {t('settings.backends.codexBaseUrlReset')}
+ </Button>
+ </div>
+ <p className="text-[12px] text-muted">{t('settings.backends.codexBaseUrlHint')}</p>
+ </div>
+
+ <div className="flex items-start gap-2 rounded-lg border border-border bg-surface-2/60 px-3 py-2.5">
+ <Info className="mt-0.5 size-3.5 shrink-0 text-muted" />
+ <p className="text-[12px] leading-relaxed text-muted">
+ {t('settings.backends.codexInfoHint')}
+ </p>
+ </div>
+
+ <div className="flex justify-end">
+ <Button variant="brand" size="default" onClick={onSave} disabled={saving}>
+ <Save className="size-3.5" />
+ {saving ? t('settings.backends.codexSaving') : t('settings.backends.codexSave')}
+ </Button>
+ </div>
+ </CardContent>
+ </Card>
+ )}
+ </SettingsPageShell>
+ );
+};
diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsx
index a9fdba25e..84eb9fff7 100644
--- a/ui/src/components/steps/AgentDetection.tsx
+++ b/ui/src/components/steps/AgentDetection.tsx
@@ -5,10 +5,12 @@ import {
ChevronDown,
ChevronUp,
Download,
+ ExternalLink,
RefreshCw,
Search,
Settings,
} from 'lucide-react';
+import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
@@ -18,6 +20,14 @@ import { BackendLifecycleChip } from '../settings/BackendLifecycleChip';
import { CompactField, CompactSelect, ToggleSwitch } from '../settings/SettingsPrimitives';
import { Button } from '../ui/button';
+// Backends that expose a dedicated provider settings page. The link is
+// rendered only when the wizard is hosted inside Settings (``isPage``) —
+// hiding it during initial setup keeps the wizard linear and avoids
+// landing the user on a half-configured Codex with no app-server yet.
+const PROVIDER_PAGE_ROUTES: Record<string, string> = {
+ codex: '/settings/backends/codex',
+};
+
interface AgentDetectionProps {
data: any;
onNext: (data: any) => void;
@@ -355,6 +365,18 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
</div>
</div>
)}
+
+ {isPage && PROVIDER_PAGE_ROUTES[name] && (
+ <div className="flex justify-end">
+ <Button asChild variant="ghost" size="sm">
+ <Link to={PROVIDER_PAGE_ROUTES[name]}>
+ <Settings className="size-3.5" />
+ {t('settings.backends.openProviderPage')}
+ <ExternalLink className="size-3.5" />
+ </Link>
+ </Button>
+ </div>
+ )}
</div>
</div>
))}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index fef36fdd9..82b5e76ab 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -21,6 +21,8 @@ export type ApiContextType = {
installAgent: (name: string) => Promise<InstallResult>;
getBackendRuntime: (name: string) => Promise<BackendRuntimeInfo>;
restartBackend: (name: string) => Promise<BackendRestartResult>;
+ getCodexAuth: () => Promise<CodexAuthState>;
+ saveCodexAuth: (payload: CodexAuthPayload) => Promise<CodexAuthSaveResult>;
slackAuthTest: (botToken: string, proxyUrl?: string) => Promise<any>;
slackChannels: (botToken: string, browseAll?: boolean) => Promise<any>;
slackManifest: () => Promise<{ ok: boolean; manifest?: string; manifest_compact?: string; error?: string }>;
@@ -117,6 +119,28 @@ export type BackendRestartResult = {
message: string;
};
+export type CodexAuthMode = 'oauth' | 'api_key';
+
+export type CodexAuthState = {
+ ok: boolean;
+ auth_mode: CodexAuthMode;
+ has_api_key: boolean;
+ api_key_length: number;
+ base_url: string | null;
+ has_chatgpt_tokens: boolean;
+ message?: string;
+};
+
+export type CodexAuthPayload = {
+ auth_mode: CodexAuthMode;
+ api_key?: string | null;
+ base_url?: string | null;
+};
+
+export type CodexAuthSaveResult = CodexAuthState & {
+ restart?: BackendRestartResult;
+};
+
const ApiContext = createContext<ApiContextType | undefined>(undefined);
export const useApi = () => {
@@ -195,6 +219,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
installAgent: (name) => postJson(`/agent/${encodeURIComponent(name)}/install`, {}),
getBackendRuntime: (name) => getJson(`/backend/${encodeURIComponent(name)}/runtime`),
restartBackend: (name) => postJson(`/backend/${encodeURIComponent(name)}/restart`, {}),
+ getCodexAuth: () => getJson('/backend/codex/auth'),
+ saveCodexAuth: (payload) => postJson('/backend/codex/auth', payload),
slackAuthTest: (botToken, proxyUrl) => postJson('/slack/auth_test', { bot_token: botToken, proxy_url: proxyUrl || undefined }),
slackChannels: (botToken, browseAll) => postJson('/slack/channels', { bot_token: botToken, browse_all: browseAll || false }),
slackManifest: () => getJson('/slack/manifest'),
diff --git a/ui/src/context/ToastContext.tsx b/ui/src/context/ToastContext.tsx
index 5e3a9da6a..9fa5c3312 100644
--- a/ui/src/context/ToastContext.tsx
+++ b/ui/src/context/ToastContext.tsx
@@ -1,7 +1,7 @@
import React, { createContext, useContext, useState, useCallback } from 'react';
-import { CheckCircle, XCircle, X } from 'lucide-react';
+import { AlertTriangle, CheckCircle, XCircle, X } from 'lucide-react';
-type ToastType = 'success' | 'error';
+type ToastType = 'success' | 'error' | 'warning';
interface Toast {
id: number;
@@ -45,11 +45,15 @@ export const ToastProvider: React.FC<{ children: React.ReactNode }> = ({ childre
className={`flex items-center gap-3 px-4 py-3 rounded-lg shadow-lg border animate-slide-in ${
toast.type === 'success'
? 'bg-success/10 border-success/30 text-success'
+ : toast.type === 'warning'
+ ? 'bg-gold/10 border-gold/30 text-gold'
: 'bg-error/10 border-error/30 text-error'
}`}
>
{toast.type === 'success' ? (
<CheckCircle size={18} />
+ ) : toast.type === 'warning' ? (
+ <AlertTriangle size={18} />
) : (
<XCircle size={18} />
)}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index d46c55894..b814050bb 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -87,6 +87,33 @@
"platformsSubtitle": "Configure which messaging platforms are connected and how each one is enabled.",
"backendsTitle": "Backends",
"backendsSubtitle": "Manage agent backends, default routing, and local CLI availability.",
+ "backends": {
+ "openProviderPage": "Configure provider",
+ "providerOauth": "OAuth (default)",
+ "providerApiKey": "API key",
+ "codexTitle": "Codex provider",
+ "codexSubtitle": "Switch between ChatGPT login and OpenAI API key, and point Codex at a custom endpoint when needed.",
+ "codexBackToBackends": "Back to backends",
+ "codexAuthModeLabel": "Authentication mode",
+ "codexAuthModeOauth": "Sign in with ChatGPT",
+ "codexAuthModeOauthHint": "Run `codex login` in a terminal to complete the OAuth flow. Vibe Remote stops managing the API key while this is selected.",
+ "codexAuthModeApiKey": "OpenAI API key",
+ "codexAuthModeApiKeyHint": "Codex will call the OpenAI-compatible endpoint with the key below. Switch to ChatGPT login if you prefer not to manage a key.",
+ "codexApiKeyLabel": "API key",
+ "codexApiKeyPlaceholder": "sk-...",
+ "codexApiKeyConfigured": "A key of length {{length}} is currently stored.",
+ "codexApiKeyMissing": "No API key stored yet.",
+ "codexBaseUrlLabel": "Base URL (optional)",
+ "codexBaseUrlPlaceholder": "https://api.openai.com/v1",
+ "codexBaseUrlHint": "Leave empty to use OpenAI's default endpoint. Compatible relays (e.g. Azure OpenAI, OpenRouter) accept their own URL here.",
+ "codexBaseUrlReset": "Reset to default",
+ "codexHasChatgptTokens": "Codex has cached ChatGPT credentials from a previous `codex login`.",
+ "codexInfoHint": "Saving here writes `~/.codex/auth.json` and `~/.codex/config.toml`, then restarts the persistent app-server so the next request uses the new settings.",
+ "codexSave": "Save and restart Codex",
+ "codexSaving": "Saving…",
+ "codexSaveSuccess": "Codex auth saved",
+ "codexSaveFailed": "Could not save Codex auth"
+ },
"messagingTitle": "Messaging",
"messagingSubtitle": "Tune global reply behavior, acknowledgements, and message visibility defaults.",
"messagingCardDescription": "Fine-tune how Vibe Remote acknowledges work, retries failures, and formats user-facing replies.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 8937da340..3e04e0262 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -87,6 +87,33 @@
"platformsSubtitle": "配置启用哪些消息平台,以及每个平台的接入状态。",
"backendsTitle": "后端",
"backendsSubtitle": "管理 agent 后端、默认路由和本地 CLI 可用性。",
+ "backends": {
+ "openProviderPage": "配置 Provider",
+ "providerOauth": "OAuth(默认)",
+ "providerApiKey": "API Key",
+ "codexTitle": "Codex Provider",
+ "codexSubtitle": "在 ChatGPT 登录与 OpenAI API Key 之间切换,需要时把 Codex 指向自定义网关。",
+ "codexBackToBackends": "返回后端列表",
+ "codexAuthModeLabel": "认证方式",
+ "codexAuthModeOauth": "使用 ChatGPT 登录",
+ "codexAuthModeOauthHint": "请在终端执行 `codex login` 完成 OAuth 流程。选中此项后,Vibe Remote 不再管理 API Key。",
+ "codexAuthModeApiKey": "OpenAI API Key",
+ "codexAuthModeApiKeyHint": "Codex 会用下方的 Key 调用 OpenAI 兼容接口。如果不希望托管 Key,可切回 ChatGPT 登录。",
+ "codexApiKeyLabel": "API Key",
+ "codexApiKeyPlaceholder": "sk-...",
+ "codexApiKeyConfigured": "当前已保存长度为 {{length}} 的 Key。",
+ "codexApiKeyMissing": "尚未保存 API Key。",
+ "codexBaseUrlLabel": "Base URL(可选)",
+ "codexBaseUrlPlaceholder": "https://api.openai.com/v1",
+ "codexBaseUrlHint": "留空则使用 OpenAI 默认接口。兼容网关(如 Azure OpenAI、OpenRouter)可填入各自的 URL。",
+ "codexBaseUrlReset": "重置为默认",
+ "codexHasChatgptTokens": "检测到上一次 `codex login` 缓存的 ChatGPT 凭据。",
+ "codexInfoHint": "保存会写入 `~/.codex/auth.json` 与 `~/.codex/config.toml`,并重启常驻 app-server 以加载新配置。",
+ "codexSave": "保存并重启 Codex",
+ "codexSaving": "保存中…",
+ "codexSaveSuccess": "Codex 认证已保存",
+ "codexSaveFailed": "保存 Codex 认证失败"
+ },
"messagingTitle": "消息",
"messagingSubtitle": "统一配置全局回复行为、ACK 策略以及消息显示默认值。",
"messagingCardDescription": "细调 Vibe Remote 如何确认收到消息、如何在失败时重试,以及最终向用户展示哪些回复内容。",
diff --git a/vibe/api.py b/vibe/api.py
index ee8c5219a..678dc7ff3 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -279,10 +279,40 @@ def _deep_merge_dicts(base: dict, patch: dict) -> dict:
return merged
+_AGENT_AUTH_FIELDS = ("auth_mode", "api_key", "base_url")
+
+
+def _strip_agent_auth_fields(payload: dict) -> dict:
+ """Drop auth fields from a generic settings patch.
+
+ The UI's Settings → Backends page round-trips the masked agent config
+ on save (api_key arrives as ``None`` after masking), and naive
+ deep-merge would clobber the real key. Auth state changes must go
+ through ``/backend/<name>/auth`` exclusively; this helper enforces
+ that contract on the generic settings POST.
+ """
+ if not isinstance(payload, dict):
+ return payload
+ agents = payload.get("agents")
+ if not isinstance(agents, dict):
+ return payload
+ cleaned_agents = dict(agents)
+ for backend in ("claude", "codex"):
+ backend_payload = cleaned_agents.get(backend)
+ if isinstance(backend_payload, dict):
+ cleaned_backend = {
+ k: v for k, v in backend_payload.items() if k not in _AGENT_AUTH_FIELDS
+ }
+ cleaned_agents[backend] = cleaned_backend
+ return {**payload, "agents": cleaned_agents}
+
+
def save_config(payload: dict) -> V2Config:
if not isinstance(payload, dict):
raise ValueError("Config payload must be an object")
+ payload = _strip_agent_auth_fields(payload)
+
with CONFIG_LOCK:
base_payload: dict = {}
base_config: Optional[V2Config] = None
@@ -316,6 +346,27 @@ def _vibe_cloud_payload(config: V2Config, include_secrets: bool) -> dict:
return payload
+def _agent_payload(raw: dict, *, include_secrets: bool) -> dict:
+ """Project a Claude/Codex config dict for the UI, masking the api_key.
+
+ The UI surfaces *whether* a key is configured (and its length, so the
+ user can see ``****6c1f``-style hints), never the plaintext. Only the
+ secrets-included path (used by the setup wizard's "load existing
+ config" flow) sees the raw value.
+ """
+ payload = dict(raw)
+ api_key = payload.get("api_key")
+ if isinstance(api_key, str):
+ payload["api_key_length"] = len(api_key)
+ payload["has_api_key"] = bool(api_key)
+ else:
+ payload["api_key_length"] = 0
+ payload["has_api_key"] = False
+ if not include_secrets:
+ payload["api_key"] = None
+ return payload
+
+
def config_to_payload(config: V2Config, *, include_secrets: bool = False) -> dict:
from config.platform_registry import platform_descriptors
@@ -344,8 +395,8 @@ def config_to_payload(config: V2Config, *, include_secrets: bool = False) -> dic
"agents": {
"default_backend": config.agents.default_backend,
"opencode": config.agents.opencode.__dict__,
- "claude": config.agents.claude.__dict__,
- "codex": config.agents.codex.__dict__,
+ "claude": _agent_payload(config.agents.claude.__dict__, include_secrets=include_secrets),
+ "codex": _agent_payload(config.agents.codex.__dict__, include_secrets=include_secrets),
},
"gateway": config.gateway.__dict__ if config.gateway else None,
"ui": config.ui.__dict__,
@@ -2005,6 +2056,117 @@ def restart_backend(name: str) -> dict:
return {"ok": True, "message": f"Stopped {len(pids)} Codex process(es); they will respawn on next request."}
+_VALID_AUTH_MODES = {"oauth", "api_key"}
+
+
+def get_codex_auth() -> dict:
+ """Return the user-facing Codex auth state for the Settings UI.
+
+ Merges two sources of truth:
+ - on-disk ``~/.codex/{config.toml,auth.json}`` (what Codex actually
+ reads at launch) — authoritative for ``has_api_key`` / ``base_url`` /
+ ``has_chatgpt_tokens`` so the UI never lies when the user edited the
+ files by hand.
+ - ``V2Config.agents.codex`` — the mode we *intend* to be in, useful as
+ a tiebreaker (e.g. user clicked OAuth but hasn't run ``codex login``
+ yet, so disk has no tokens but our config says oauth).
+
+ Secrets never leave the server; only length is returned.
+ """
+ from vibe.codex_config import read_codex_auth_state
+
+ disk_state = read_codex_auth_state()
+ try:
+ config = load_config()
+ cfg = getattr(getattr(config, "agents", None), "codex", None)
+ configured_mode = getattr(cfg, "auth_mode", None)
+ except Exception:
+ configured_mode = None
+ auth_mode = configured_mode if configured_mode in _VALID_AUTH_MODES else disk_state.get("auth_mode")
+ return {
+ "ok": True,
+ "auth_mode": auth_mode or "oauth",
+ "has_api_key": bool(disk_state.get("has_api_key")),
+ "api_key_length": int(disk_state.get("api_key_length") or 0),
+ "base_url": disk_state.get("base_url"),
+ "has_chatgpt_tokens": bool(disk_state.get("has_chatgpt_tokens")),
+ }
+
+
+def save_codex_auth(payload: dict) -> dict:
+ """Persist Codex auth: V2Config + ``~/.codex/{config.toml,auth.json}``.
+
+ The on-disk write is what Codex actually reads; the V2Config write
+ records the user's intent so the UI can render a coherent state after
+ restart. We treat the disk write as authoritative — if it fails, we
+ surface the error instead of leaving V2Config out of sync.
+
+ After writing, we trigger ``restart_backend('codex')`` so the persistent
+ app-server reloads with the new credentials. The restart failure is
+ surfaced but does not roll back the config write; the user can retry.
+ """
+ if not isinstance(payload, dict):
+ return {"ok": False, "message": "Payload must be an object"}
+
+ auth_mode = payload.get("auth_mode")
+ if auth_mode not in _VALID_AUTH_MODES:
+ return {"ok": False, "message": f"auth_mode must be one of {sorted(_VALID_AUTH_MODES)}"}
+
+ raw_api_key = payload.get("api_key")
+ if raw_api_key is not None and not isinstance(raw_api_key, str):
+ return {"ok": False, "message": "api_key must be a string"}
+ api_key = raw_api_key.strip() if isinstance(raw_api_key, str) else None
+
+ raw_base_url = payload.get("base_url")
+ if raw_base_url is not None and not isinstance(raw_base_url, str):
+ return {"ok": False, "message": "base_url must be a string"}
+ base_url = raw_base_url.strip() if isinstance(raw_base_url, str) else None
+ if base_url == "":
+ base_url = None
+
+ if auth_mode == "api_key" and not api_key:
+ # Allow callers to PATCH base_url alone by reusing the stored key.
+ with CONFIG_LOCK:
+ try:
+ existing = load_config()
+ stored = getattr(getattr(existing, "agents", None), "codex", None)
+ api_key = getattr(stored, "api_key", None) or None
+ except Exception:
+ api_key = None
+ if not api_key:
+ return {"ok": False, "message": "api_key is required when auth_mode='api_key'"}
+
+ from vibe.codex_config import apply_codex_auth
+
+ try:
+ apply_codex_auth(auth_mode=auth_mode, api_key=api_key, base_url=base_url)
+ except ValueError as exc:
+ return {"ok": False, "message": str(exc)}
+ except OSError as exc:
+ logger.error("Failed to write Codex auth files: %s", exc, exc_info=True)
+ return {"ok": False, "message": f"Failed to write Codex config: {exc}"}
+
+ with CONFIG_LOCK:
+ try:
+ config = load_config()
+ except FileNotFoundError:
+ config = V2Config()
+ config.agents.codex.auth_mode = auth_mode
+ config.agents.codex.api_key = api_key if auth_mode == "api_key" else None
+ config.agents.codex.base_url = base_url
+ config.save()
+
+ restart_result = restart_backend("codex")
+ state = get_codex_auth()
+ state["restart"] = restart_result
+ if not restart_result.get("ok", False):
+ # Config written, restart failed — tell the UI both so the toast
+ # can say "saved, but you may need to restart Codex manually".
+ state["ok"] = True
+ state["message"] = restart_result.get("message")
+ return state
+
+
def codex_models() -> dict:
"""Best-effort merged list of Codex model options.
diff --git a/vibe/codex_config.py b/vibe/codex_config.py
new file mode 100644
index 000000000..f01c6a4ab
--- /dev/null
+++ b/vibe/codex_config.py
@@ -0,0 +1,237 @@
+"""Helpers for writing Codex's on-disk auth configuration.
+
+The Codex CLI / ``codex app-server`` reads two files at launch time:
+
+- ``~/.codex/config.toml`` — model + provider preferences (including the
+ ``model_provider`` selector and the ``[model_providers.<id>]`` table that
+ carries ``base_url``).
+- ``~/.codex/auth.json`` — credential bag; the ``OPENAI_API_KEY`` field is
+ the one Codex consumes for API-key mode.
+
+This module mediates writes to those files so the Settings → Backends →
+Codex UI can flip between OAuth (ChatGPT login) and API-key modes without
+the user dropping into a terminal. The persistent app-server picks up
+changes via ``restart_backend('codex')``.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+from pathlib import Path
+from typing import Any, Dict, Optional
+
+logger = logging.getLogger(__name__)
+
+# Provider id we manage in ``[model_providers.<id>]``. Codex ships with a
+# built-in ``openai`` provider; if the user has hand-edited that block we
+# leave their fields alone except for ``base_url`` when one is supplied.
+MANAGED_PROVIDER_ID = "openai"
+
+
+def get_codex_home(home: Path | None = None) -> Path:
+ return (home or Path.home()) / ".codex"
+
+
+def get_codex_config_paths(home: Path | None = None) -> tuple[Path, Path]:
+ """Return ``(config.toml, auth.json)`` paths under ``~/.codex``."""
+ codex_home = get_codex_home(home)
+ return codex_home / "config.toml", codex_home / "auth.json"
+
+
+def _load_toml(path: Path) -> Dict[str, Any]:
+ if not path.exists():
+ return {}
+ try:
+ try:
+ import tomllib # type: ignore[attr-defined]
+ except Exception: # pragma: no cover - py<3.11 fallback
+ import tomli as tomllib # type: ignore[no-redef]
+ return tomllib.loads(path.read_text(encoding="utf-8"))
+ except Exception as exc:
+ logger.warning("Codex config.toml parse failed (%s); rewriting from empty", exc)
+ return {}
+
+
+def _load_auth(path: Path) -> Dict[str, Any]:
+ if not path.exists():
+ return {}
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ if isinstance(data, dict):
+ return data
+ except Exception as exc:
+ logger.warning("Codex auth.json parse failed (%s); rewriting from empty", exc)
+ return {}
+
+
+def _dump_toml_value(value: Any) -> str:
+ """Serialize a single scalar value back to TOML. Tables handled separately."""
+ if isinstance(value, bool):
+ return "true" if value else "false"
+ if isinstance(value, int):
+ return str(value)
+ if isinstance(value, float):
+ return repr(value)
+ if isinstance(value, str):
+ return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
+ if isinstance(value, list):
+ return "[" + ", ".join(_dump_toml_value(item) for item in value) + "]"
+ # Fallback: serialize as JSON-ish string (best-effort for unexpected types).
+ return _dump_toml_value(json.dumps(value))
+
+
+def _dump_toml(data: Dict[str, Any]) -> str:
+ """Minimal TOML emitter for the Codex config shape we manage.
+
+ Handles top-level scalars and one level of nested tables
+ (``[a.b]``). Comments and original ordering are lost — acceptable
+ here because the file is typically generated by ``codex login`` and
+ re-rendered round-trip with our managed fields.
+ """
+ lines: list[str] = []
+ nested: list[tuple[str, Dict[str, Any]]] = []
+ for key, value in data.items():
+ if isinstance(value, dict):
+ nested.append((key, value))
+ continue
+ lines.append(f"{key} = {_dump_toml_value(value)}")
+ for parent, subtree in nested:
+ # ``subtree`` may itself be either scalars (one ``[parent]`` table)
+ # or a dict of named subtables (``[parent.child]``).
+ scalar_children: list[tuple[str, Any]] = []
+ table_children: list[tuple[str, Dict[str, Any]]] = []
+ for child_key, child_value in subtree.items():
+ if isinstance(child_value, dict):
+ table_children.append((child_key, child_value))
+ else:
+ scalar_children.append((child_key, child_value))
+ if scalar_children:
+ lines.append("")
+ lines.append(f"[{parent}]")
+ for child_key, child_value in scalar_children:
+ lines.append(f"{child_key} = {_dump_toml_value(child_value)}")
+ for child_key, grandchildren in table_children:
+ lines.append("")
+ lines.append(f"[{parent}.{child_key}]")
+ for grand_key, grand_value in grandchildren.items():
+ if isinstance(grand_value, dict):
+ # Codex doesn't currently nest deeper than two levels in
+ # the surface we manage; punt on deeper nesting.
+ logger.debug(
+ "Skipping deeply-nested TOML entry %s.%s.%s", parent, child_key, grand_key
+ )
+ continue
+ lines.append(f"{grand_key} = {_dump_toml_value(grand_value)}")
+ return "\n".join(lines) + ("\n" if lines else "")
+
+
+def _atomic_write(path: Path, content: str, *, mode: int = 0o600) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_suffix(path.suffix + ".tmp")
+ tmp.write_text(content, encoding="utf-8")
+ try:
+ os.replace(tmp, path)
+ finally:
+ if tmp.exists():
+ try:
+ tmp.unlink()
+ except OSError: # pragma: no cover - best effort cleanup
+ pass
+ try:
+ path.chmod(mode)
+ except OSError as exc: # pragma: no cover - non-POSIX
+ logger.debug("chmod %s failed: %s", path, exc)
+
+
+def apply_codex_auth(
+ *,
+ auth_mode: str,
+ api_key: Optional[str],
+ base_url: Optional[str],
+ home: Path | None = None,
+) -> None:
+ """Persist the requested auth mode into Codex's on-disk config files.
+
+ - ``api_key`` mode: write ``OPENAI_API_KEY`` into ``auth.json``,
+ optionally set ``[model_providers.openai].base_url`` if a non-default
+ URL was supplied, and pin top-level ``model_provider = "openai"`` so
+ Codex actually uses the keyed provider.
+ - ``oauth`` mode: drop ``OPENAI_API_KEY`` from ``auth.json``, leave any
+ ``tokens`` blob in place, and clear our managed ``base_url`` so the
+ next launch goes back to OpenAI's default endpoint.
+ """
+ if auth_mode not in {"oauth", "api_key"}:
+ raise ValueError(f"Unsupported codex auth_mode: {auth_mode!r}")
+
+ config_path, auth_path = get_codex_config_paths(home)
+ auth_data = _load_auth(auth_path)
+ toml_data = _load_toml(config_path)
+
+ providers = toml_data.setdefault("model_providers", {})
+ if not isinstance(providers, dict):
+ providers = {}
+ toml_data["model_providers"] = providers
+ managed = providers.setdefault(MANAGED_PROVIDER_ID, {})
+ if not isinstance(managed, dict):
+ managed = {}
+ providers[MANAGED_PROVIDER_ID] = managed
+
+ if auth_mode == "api_key":
+ if not api_key:
+ raise ValueError("api_key is required when auth_mode='api_key'")
+ auth_data["OPENAI_API_KEY"] = api_key
+ toml_data["model_provider"] = MANAGED_PROVIDER_ID
+ managed.setdefault("name", "OpenAI")
+ if base_url:
+ managed["base_url"] = base_url
+ else:
+ managed.pop("base_url", None)
+ else: # oauth
+ auth_data.pop("OPENAI_API_KEY", None)
+ # Leave model_provider as-is — switching back to ChatGPT/OAuth is
+ # the user's responsibility via ``codex login``; we just stop
+ # pinning the keyed provider's overrides.
+ managed.pop("base_url", None)
+ # If our managed entry is now empty, drop it entirely so we don't
+ # leave a noisy ``[model_providers.openai]`` table behind.
+ if not managed:
+ providers.pop(MANAGED_PROVIDER_ID, None)
+ if not providers:
+ toml_data.pop("model_providers", None)
+
+ _atomic_write(auth_path, json.dumps(auth_data, indent=2) + "\n", mode=0o600)
+ _atomic_write(config_path, _dump_toml(toml_data), mode=0o600)
+
+
+def read_codex_auth_state(home: Path | None = None) -> Dict[str, Any]:
+ """Return the user-visible auth state for the Settings UI.
+
+ Reads both files and reports back what the user would see — no
+ secrets in the response (the UI receives the key length, never the
+ plaintext key).
+ """
+ config_path, auth_path = get_codex_config_paths(home)
+ auth_data = _load_auth(auth_path)
+ toml_data = _load_toml(config_path)
+ api_key = auth_data.get("OPENAI_API_KEY")
+ has_chatgpt_tokens = isinstance(auth_data.get("tokens"), dict)
+
+ providers = toml_data.get("model_providers")
+ base_url: Optional[str] = None
+ if isinstance(providers, dict):
+ managed = providers.get(MANAGED_PROVIDER_ID)
+ if isinstance(managed, dict):
+ raw = managed.get("base_url")
+ if isinstance(raw, str) and raw.strip():
+ base_url = raw.strip()
+
+ inferred_mode = "api_key" if isinstance(api_key, str) and api_key else "oauth"
+ return {
+ "auth_mode": inferred_mode,
+ "has_api_key": isinstance(api_key, str) and bool(api_key),
+ "api_key_length": len(api_key) if isinstance(api_key, str) else 0,
+ "base_url": base_url,
+ "has_chatgpt_tokens": has_chatgpt_tokens,
+ }
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index e30aa3c22..8d9515a93 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1573,6 +1573,26 @@ def backend_restart(name):
return jsonify(api.restart_backend(name))
[email protected]("/backend/codex/auth", methods=["GET"])
+def backend_codex_auth_get():
+ """Read the user-facing Codex auth state (masked secrets)."""
+ from vibe import api
+
+ return jsonify(api.get_codex_auth())
+
+
[email protected]("/backend/codex/auth", methods=["POST"])
+def backend_codex_auth_post():
+ """Persist Codex auth and reload the app-server.
+
+ Body: ``{auth_mode: 'oauth'|'api_key', api_key?: string, base_url?: string}``.
+ """
+ from vibe import api
+
+ payload = request.json or {}
+ return jsonify(api.save_codex_auth(payload))
+
+
@app.route("/browse", methods=["POST"])
def browse_directory():
"""List sub-directories of a given path for the directory picker UI."""