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(codex): add subagent routing support

cyh1c94999015ed
diff --git a/config/v2_settings.py b/config/v2_settings.py
index 743e97b0a..045e4db2f 100644
--- a/config/v2_settings.py
+++ b/config/v2_settings.py
@@ -86,9 +86,9 @@ class RoutingSettings:
claude_model: Optional[str] = None
claude_reasoning_effort: Optional[str] = None
# Codex settings
+ codex_agent: Optional[str] = None
codex_model: Optional[str] = None
codex_reasoning_effort: Optional[str] = None
- # Note: Codex subagent not supported yet
@dataclass
@@ -144,6 +144,7 @@ def _parse_routing(payload: dict) -> RoutingSettings:
claude_agent=payload.get("claude_agent"),
claude_model=payload.get("claude_model"),
claude_reasoning_effort=payload.get("claude_reasoning_effort"),
+ codex_agent=payload.get("codex_agent"),
codex_model=payload.get("codex_model"),
codex_reasoning_effort=payload.get("codex_reasoning_effort"),
)
@@ -159,6 +160,7 @@ def _routing_to_dict(routing: RoutingSettings) -> dict:
"claude_agent": routing.claude_agent,
"claude_model": routing.claude_model,
"claude_reasoning_effort": routing.claude_reasoning_effort,
+ "codex_agent": routing.codex_agent,
"codex_model": routing.codex_model,
"codex_reasoning_effort": routing.codex_reasoning_effort,
}
diff --git a/core/controller.py b/core/controller.py
index cddc71cb8..1664c4ccf 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -525,6 +525,19 @@ class Controller:
)
return None, None, None
+ def get_codex_overrides(self, context: MessageContext) -> tuple[Optional[str], Optional[str], Optional[str]]:
+ """Get Codex agent, model, and reasoning effort overrides for this channel."""
+ settings_key = self._get_settings_key(context)
+ settings_manager = self.get_settings_manager_for_context(context)
+ routing = settings_manager.get_channel_routing(settings_key)
+ if routing:
+ return (
+ routing.codex_agent,
+ routing.codex_model,
+ routing.codex_reasoning_effort,
+ )
+ return None, None, None
+
async def emit_agent_message(
self,
context: MessageContext,
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 11486d9da..e4d2ce39a 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -198,7 +198,14 @@ class MessageHandler(BaseHandler):
# Check for routing-based agent to maintain session key consistency
# This ensures session IDs match between MessageHandler and SessionHandler
routing = self._get_settings_manager(context).get_channel_routing(settings_key)
- routing_agent = routing.claude_agent if routing else None
+ routing_agent = None
+ if routing:
+ if agent_name == "opencode":
+ routing_agent = getattr(routing, "opencode_agent", None)
+ elif agent_name == "claude":
+ routing_agent = getattr(routing, "claude_agent", None)
+ elif agent_name == "codex":
+ routing_agent = getattr(routing, "codex_agent", None)
matched_prefix = None
subagent_message = None
@@ -206,8 +213,9 @@ class MessageHandler(BaseHandler):
subagent_model = None
subagent_reasoning_effort = None
- if agent_name in ["opencode", "claude"]:
+ if agent_name in ["opencode", "claude", "codex"]:
from modules.agents.subagent_router import (
+ load_codex_subagent,
load_claude_subagent,
normalize_subagent_name,
parse_subagent_prefix,
@@ -233,7 +241,7 @@ class MessageHandler(BaseHandler):
subagent_name = match.get("name")
except Exception as err:
logger.warning(f"Failed to resolve OpenCode subagent: {err}")
- else:
+ elif agent_name == "claude":
try:
from pathlib import Path
@@ -247,6 +255,20 @@ class MessageHandler(BaseHandler):
subagent_reasoning_effort = subagent_def.reasoning_effort
except Exception as err:
logger.warning(f"Failed to resolve Claude subagent: {err}")
+ else:
+ try:
+ from pathlib import Path
+
+ subagent_def = load_codex_subagent(
+ normalized,
+ project_root=Path(working_path),
+ )
+ if subagent_def:
+ subagent_name = subagent_def.name
+ subagent_model = subagent_def.model
+ subagent_reasoning_effort = subagent_def.reasoning_effort
+ except Exception as err:
+ logger.warning(f"Failed to resolve Codex subagent: {err}")
if subagent_name:
matched_prefix = parsed.name
@@ -254,10 +276,10 @@ class MessageHandler(BaseHandler):
if subagent_name and subagent_message:
message = subagent_message
- if agent_name == "claude":
+ if agent_name in {"claude", "codex"}:
base_session_id = f"{base_session_id}:{subagent_name}"
composite_key = f"{base_session_id}:{working_path}"
- elif agent_name == "claude" and routing_agent and not subagent_name:
+ elif agent_name in {"claude", "codex"} and routing_agent and not subagent_name:
# Update session IDs for routing-based agent to match SessionHandler
base_session_id = f"{base_session_id}:{routing_agent}"
composite_key = f"{base_session_id}:{working_path}"
diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.py
index 64cb811a4..ec4f1eb5c 100644
--- a/core/handlers/settings_handler.py
+++ b/core/handlers/settings_handler.py
@@ -397,6 +397,7 @@ class SettingsHandler(BaseHandler):
opencode_default_config = {}
claude_agents = []
claude_models = []
+ codex_agents = []
codex_models = []
if "opencode" in registered_backends:
@@ -429,11 +430,15 @@ class SettingsHandler(BaseHandler):
if "codex" in registered_backends:
try:
- from vibe.api import codex_models as get_codex_models
+ from vibe.api import codex_agents as get_codex_agents, codex_models as get_codex_models
models_result = get_codex_models()
if models_result.get("ok"):
codex_models = models_result.get("models", [])
+ cwd = self.controller.get_cwd(context)
+ agents_result = get_codex_agents(cwd)
+ if agents_result.get("ok"):
+ codex_agents = agents_result.get("agents", [])
except Exception as e:
logger.warning(f"Failed to fetch Codex data: {e}")
@@ -446,6 +451,7 @@ class SettingsHandler(BaseHandler):
opencode_default_config=opencode_default_config,
claude_agents=claude_agents,
claude_models=claude_models,
+ codex_agents=codex_agents,
codex_models=codex_models,
)
@@ -657,6 +663,7 @@ class SettingsHandler(BaseHandler):
opencode_default_config=routing_data.opencode_default_config,
claude_agents=routing_data.claude_agents,
claude_models=routing_data.claude_models,
+ codex_agents=routing_data.codex_agents,
codex_models=routing_data.codex_models,
selected_backend=selected_backend,
selected_opencode_agent=selection.selected_opencode_agent,
@@ -665,6 +672,7 @@ class SettingsHandler(BaseHandler):
selected_claude_agent=selection.selected_claude_agent,
selected_claude_model=selection.selected_claude_model,
selected_claude_reasoning=selection.selected_claude_reasoning,
+ selected_codex_agent=selection.selected_codex_agent,
selected_codex_model=selection.selected_codex_model,
selected_codex_reasoning=selection.selected_codex_reasoning,
)
@@ -682,6 +690,7 @@ class SettingsHandler(BaseHandler):
claude_agent: Optional[str] = None,
claude_model: Optional[str] = None,
claude_reasoning_effort: Optional[str] = None,
+ codex_agent: Optional[str] = None,
codex_model: Optional[str] = None,
codex_reasoning_effort: Optional[str] = None,
notify_user: bool = True,
@@ -728,6 +737,9 @@ class SettingsHandler(BaseHandler):
claude_reasoning_effort=normalized_claude_reasoning_effort
if backend == "claude"
else (existing_routing.claude_reasoning_effort if existing_routing else None),
+ codex_agent=codex_agent
+ if backend == "codex"
+ else (existing_routing.codex_agent if existing_routing else None),
codex_model=codex_model
if backend == "codex"
else (existing_routing.codex_model if existing_routing else None),
@@ -756,6 +768,8 @@ class SettingsHandler(BaseHandler):
f"{self._t('routing.label.reasoningEffort')}: **{normalized_claude_reasoning_effort}**"
)
elif backend == "codex":
+ if codex_agent:
+ parts.append(f"{self._t('routing.label.agent')}: **{codex_agent}**")
if codex_model:
parts.append(f"{self._t('routing.label.model')}: **{codex_model}**")
if codex_reasoning_effort:
@@ -773,7 +787,8 @@ class SettingsHandler(BaseHandler):
f"opencode_agent={opencode_agent}, opencode_model={opencode_model}, "
f"claude_agent={claude_agent}, claude_model={claude_model}, "
f"claude_reasoning_effort={normalized_claude_reasoning_effort}, "
- f"codex_model={codex_model}"
+ f"codex_agent={codex_agent}, codex_model={codex_model}, "
+ f"codex_reasoning_effort={codex_reasoning_effort}"
)
except Exception as e:
diff --git a/core/modals.py b/core/modals.py
index de2aa05a1..a9ef58116 100644
--- a/core/modals.py
+++ b/core/modals.py
@@ -20,6 +20,7 @@ class RoutingModalData:
opencode_default_config: dict[str, Any]
claude_agents: list[str]
claude_models: list[str]
+ codex_agents: list[str]
codex_models: list[str]
def as_kwargs(self) -> dict[str, Any]:
@@ -32,6 +33,7 @@ class RoutingModalData:
"opencode_default_config": self.opencode_default_config,
"claude_agents": self.claude_agents,
"claude_models": self.claude_models,
+ "codex_agents": self.codex_agents,
"codex_models": self.codex_models,
}
@@ -47,5 +49,6 @@ class RoutingModalSelection:
selected_claude_agent: Optional[str] = None
selected_claude_model: Optional[str] = None
selected_claude_reasoning: Optional[str] = None
+ selected_codex_agent: Optional[str] = None
selected_codex_model: Optional[str] = None
selected_codex_reasoning: Optional[str] = None
diff --git a/docs/plans/agent-subagent-model-support.md b/docs/plans/agent-subagent-model-support.md
index 78df8fa59..9580a4a17 100644
--- a/docs/plans/agent-subagent-model-support.md
+++ b/docs/plans/agent-subagent-model-support.md
@@ -30,7 +30,7 @@
|-------|:--------:|:-----:|:----------------:|
| **OpenCode** | ✅ | ✅ | ✅ |
| **Claude Code** | ✅ | ✅ | ❌ (无 CLI 参数) |
-| **Codex** | ❌ (暂不支持) | ✅ | ✅ |
+| **Codex** | ✅ | ✅ | ✅ |
---
@@ -57,9 +57,9 @@ class RoutingSettings:
# 注:Claude 没有 reasoning_effort CLI 参数
# Codex 特定 (新增)
+ codex_agent: Optional[str] = None
codex_model: Optional[str] = None
codex_reasoning_effort: Optional[str] = None
- # 注:Codex 暂不支持 subagent
```
### 1.2 前端 ChannelConfig 类型扩展
@@ -81,6 +81,7 @@ interface ChannelConfig {
claude_agent?: string | null;
claude_model?: string | null;
// Codex (新增)
+ codex_agent?: string | null;
codex_model?: string | null;
codex_reasoning_effort?: string | null;
};
@@ -191,7 +192,6 @@ interface ChannelConfig {
<option value="xhigh">Extra High</option>
</select>
</div>
- {/* 注意:不显示 Agent - Codex 暂不支持 subagent */}
</div>
</div>
)}
@@ -201,7 +201,7 @@ interface ChannelConfig {
| 配置项 | OpenCode | Claude Code | Codex |
|--------|:--------:|:-----------:|:-----:|
-| Agent/Subagent | ✅ 显示 | ✅ 显示 | ❌ 不显示 |
+| Agent/Subagent | ✅ 显示 | ✅ 显示 | ✅ 显示 |
| Model | ✅ 显示 | ✅ 显示 | ✅ 显示 |
| Reasoning Effort | ✅ 显示 | ❌ 不显示 | ✅ 显示 |
@@ -429,9 +429,9 @@ codex exec --model o3 -c model_reasoning_effort=high "your prompt"
- Extended Thinking 只能通过 `~/.claude/settings.json` 配置
- UI 中不显示该选项
-2. **Codex 暂不支持 Subagent**
- - 官方 MCP Server 方式需要架构改动
- - 后续可考虑支持
+2. **Codex 现已支持 Subagent**
+ - 通过 `routing.codex_agent` 和前缀路由选择
+ - 支持从 Codex agent 定义继承默认 model / reasoning
3. **向后兼容**
- 所有新字段使用 Optional 类型
diff --git a/docs/plans/codex-subagent-routing.md b/docs/plans/codex-subagent-routing.md
new file mode 100644
index 000000000..59824e722
--- /dev/null
+++ b/docs/plans/codex-subagent-routing.md
@@ -0,0 +1,28 @@
+# Codex Subagent Routing Plan
+
+## Background
+
+Vibe Remote already supports subagent routing for OpenCode and Claude, but Codex routing still only exposes backend, model, and reasoning effort. Codex CLI now supports custom agents via `~/.codex/agents/` and project `.codex/agents/`, so the Vibe Remote capability gap is stale.
+
+## Goal
+
+Add end-to-end Codex subagent support that matches the existing OpenCode/Claude experience:
+
+- persisted `routing.codex_agent`
+- prefix-triggered subagent selection such as `reviewer: ...`
+- model/reasoning fallback from Codex custom agent definitions
+- agent selection in Slack, Discord, Feishu, Web UI, and API
+- remove stale documentation that claims Codex subagents are unsupported
+
+## Approach
+
+1. Extend routing data models and serialization to include `codex_agent`.
+2. Add Codex custom-agent discovery and parsing from global/project agent directories.
+3. Reuse the existing generic `subagent_*` request fields so message handling stays backend-agnostic.
+4. Update the Codex backend to load selected custom-agent instructions and defaults when starting a thread.
+5. Add tests for parsing, routing payloads, UI/API listing, and Codex turn-start overrides.
+
+## Validation
+
+- targeted pytest for subagent parsing, routing modal selection, UI API, and Codex agent payloads
+- `npm run build` in `ui/`
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 469046c88..d8e666802 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -4,9 +4,11 @@ from __future__ import annotations
import asyncio
import logging
+from pathlib import Path
from typing import Any, Dict, Optional
from modules.agents.base import AgentRequest, BaseAgent
+from modules.agents.subagent_router import SubagentDefinition, load_codex_subagent
from modules.agents.codex.event_handler import CodexEventHandler
from modules.agents.codex.session import CodexSessionManager
from modules.agents.codex.transport import CodexTransport
@@ -257,6 +259,8 @@ class CodexAgent(BaseAgent):
request: AgentRequest,
) -> str:
"""Create a new Codex thread and return its threadId."""
+ _, _, _, agent_instructions = self._resolve_codex_agent_settings(request)
+
params: Dict[str, Any] = {
"cwd": request.working_path,
"approvalPolicy": "never",
@@ -268,15 +272,24 @@ class CodexAgent(BaseAgent):
or self.controller.config.platform
)
+ instruction_parts: list[str] = []
+ if agent_instructions:
+ instruction_parts.append(agent_instructions)
+
if getattr(self.controller.config, "reply_enhancements", True):
from core.reply_enhancer import build_reply_enhancements_prompt
- params["developerInstructions"] = build_reply_enhancements_prompt(
- include_quick_replies=platform != "wechat",
- context=request.context,
- fallback_platform=platform,
+ instruction_parts.append(
+ build_reply_enhancements_prompt(
+ include_quick_replies=platform != "wechat",
+ context=request.context,
+ fallback_platform=platform,
+ )
)
+ if instruction_parts:
+ params["developerInstructions"] = "\n\n".join(part for part in instruction_parts if part)
+
resp = await transport.send_request("thread/start", params)
# thread/start returns Thread directly OR may nest under "thread"
thread_id = resp.get("id", "")
@@ -297,6 +310,58 @@ class CodexAgent(BaseAgent):
)
return thread_id
+ def _resolve_codex_agent_settings(
+ self,
+ request: AgentRequest,
+ ) -> tuple[Optional[str], Optional[str], Optional[str], Optional[str]]:
+ request_context = getattr(request, "context", None)
+ controller = getattr(self, "controller", None)
+ routing = None
+ settings_key = request.session_key
+ used_context_settings_manager = False
+
+ if request_context is not None and controller is not None and hasattr(controller, "_get_settings_key"):
+ settings_key = controller._get_settings_key(request_context)
+ manager_getter = getattr(controller, "get_settings_manager_for_context", None)
+ if callable(manager_getter):
+ try:
+ context_settings_manager = manager_getter(request_context)
+ except Exception:
+ context_settings_manager = None
+ if context_settings_manager is not None:
+ used_context_settings_manager = True
+ channel_settings = context_settings_manager.get_channel_settings(settings_key)
+ routing = channel_settings.routing if channel_settings else None
+
+ if routing is None and not used_context_settings_manager:
+ channel_settings = self.settings_manager.get_channel_settings(settings_key)
+ routing = channel_settings.routing if channel_settings else None
+
+ request_subagent = getattr(request, "subagent_name", None)
+ request_model = getattr(request, "subagent_model", None)
+ request_effort = getattr(request, "subagent_reasoning_effort", None)
+
+ effective_agent = request_subagent or (getattr(routing, "codex_agent", None) if routing else None)
+ explicit_model = request_model or (getattr(routing, "codex_model", None) if routing else None)
+ explicit_effort = request_effort or (
+ getattr(routing, "codex_reasoning_effort", None) if routing else None
+ )
+
+ agent_definition: Optional[SubagentDefinition] = None
+ if effective_agent:
+ try:
+ working_path = getattr(request, "working_path", None)
+ project_root = Path(working_path) if working_path else None
+ agent_definition = load_codex_subagent(effective_agent, project_root=project_root)
+ except Exception as exc:
+ logger.warning("Failed to load Codex subagent %s: %s", effective_agent, exc)
+
+ effective_model = explicit_model or (agent_definition.model if agent_definition else None) or self.codex_config.default_model
+ effective_effort = explicit_effort or (agent_definition.reasoning_effort if agent_definition else None)
+ developer_instructions = agent_definition.developer_instructions if agent_definition else None
+
+ return effective_agent, effective_model, effective_effort, developer_instructions
+
async def _start_or_resume_thread(
self,
transport: CodexTransport,
@@ -338,11 +403,7 @@ class CodexAgent(BaseAgent):
) -> str:
"""Build input, configure overrides, and send turn/start to Codex."""
input_items = self._build_input(request)
-
- channel_settings = self.settings_manager.get_channel_settings(request.session_key)
- routing = channel_settings.routing if channel_settings else None
- effective_model = (routing.codex_model if routing else None) or self.codex_config.default_model
- effective_effort = routing.codex_reasoning_effort if routing else None
+ _, effective_model, effective_effort, _ = self._resolve_codex_agent_settings(request)
turn_params: Dict[str, Any] = {
"threadId": thread_id,
diff --git a/modules/agents/subagent_router.py b/modules/agents/subagent_router.py
index 7c35712d6..4f81293a7 100644
--- a/modules/agents/subagent_router.py
+++ b/modules/agents/subagent_router.py
@@ -7,6 +7,11 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Iterable, Optional
+try:
+ import tomllib
+except Exception: # pragma: no cover
+ tomllib = None
+
import yaml
logger = logging.getLogger(__name__)
@@ -23,8 +28,12 @@ def _yaml_safe_load(text: str) -> dict:
@dataclass(frozen=True)
class SubagentDefinition:
name: str
+ description: Optional[str] = None
+ developer_instructions: Optional[str] = None
model: Optional[str] = None
reasoning_effort: Optional[str] = None
+ path: Optional[Path] = None
+ source: Optional[str] = None
@dataclass(frozen=True)
@@ -126,6 +135,49 @@ def load_claude_subagent(
return list_claude_subagents(search_root, project_root).get(normalized)
+def list_codex_subagents(
+ search_root: Optional[Path] = None,
+ project_root: Optional[Path] = None,
+) -> Dict[str, SubagentDefinition]:
+ """List all available Codex custom agents."""
+ definitions: Dict[str, SubagentDefinition] = {}
+
+ root = search_root or (Path.home() / ".codex")
+ global_agents_dir = root / "agents"
+ if global_agents_dir.exists() and global_agents_dir.is_dir():
+ for agent_file in sorted(global_agents_dir.glob("*.toml")):
+ definition = _parse_codex_agent_definition(agent_file, source="global")
+ if not definition:
+ continue
+ key = normalize_subagent_name(definition.name)
+ if key:
+ definitions[key] = definition
+
+ if project_root:
+ project_agents_dir = project_root / ".codex" / "agents"
+ if project_agents_dir.exists() and project_agents_dir.is_dir():
+ for agent_file in sorted(project_agents_dir.glob("*.toml")):
+ definition = _parse_codex_agent_definition(agent_file, source="project")
+ if not definition:
+ continue
+ key = normalize_subagent_name(definition.name)
+ if key:
+ definitions[key] = definition
+
+ return definitions
+
+
+def load_codex_subagent(
+ name: str,
+ search_root: Optional[Path] = None,
+ project_root: Optional[Path] = None,
+) -> Optional[SubagentDefinition]:
+ normalized = normalize_subagent_name(name)
+ if not normalized:
+ return None
+ return list_codex_subagents(search_root, project_root).get(normalized)
+
+
def _find_claude_agent_dirs(root: Path) -> Iterable[Path]:
agent_dirs = []
if (root / "agents").exists():
@@ -179,4 +231,47 @@ def _parse_claude_agent_definition(path: Path) -> Optional[SubagentDefinition]:
if not isinstance(reasoning_effort, str) or not reasoning_effort.strip():
reasoning_effort = None
- return SubagentDefinition(name=name.strip(), model=model, reasoning_effort=reasoning_effort)
+ return SubagentDefinition(name=name.strip(), model=model, reasoning_effort=reasoning_effort, path=path)
+
+
+def _parse_codex_agent_definition(path: Path, source: str) -> Optional[SubagentDefinition]:
+ if tomllib is None:
+ logger.debug("tomllib unavailable; cannot parse Codex subagent file %s", path)
+ return None
+
+ try:
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
+ except Exception as e:
+ logger.debug("Failed to parse Codex subagent definition %s: %s", path, e)
+ return None
+
+ if not isinstance(data, dict):
+ return None
+
+ name = data.get("name")
+ description = data.get("description")
+ developer_instructions = data.get("developer_instructions")
+ model = data.get("model")
+ reasoning_effort = data.get("model_reasoning_effort")
+
+ if not isinstance(name, str) or not name.strip():
+ return None
+ if not isinstance(description, str) or not description.strip():
+ return None
+ if not isinstance(developer_instructions, str) or not developer_instructions.strip():
+ return None
+
+ if not isinstance(model, str) or not model.strip():
+ model = None
+ if not isinstance(reasoning_effort, str) or not reasoning_effort.strip():
+ reasoning_effort = None
+
+ return SubagentDefinition(
+ name=name.strip(),
+ description=description.strip(),
+ developer_instructions=developer_instructions.strip(),
+ model=model,
+ reasoning_effort=reasoning_effort,
+ path=path,
+ source=source,
+ )
diff --git a/modules/im/discord.py b/modules/im/discord.py
index bfde3b04f..e6b0ff390 100644
--- a/modules/im/discord.py
+++ b/modules/im/discord.py
@@ -1378,6 +1378,7 @@ class DiscordBot(BaseIMClient):
opencode_default_config: dict,
claude_agents: list,
claude_models: list,
+ codex_agents: list,
codex_models: list,
):
interaction = trigger_id if isinstance(trigger_id, discord.Interaction) else None
@@ -1435,6 +1436,7 @@ class DiscordBot(BaseIMClient):
self.claude_reasoning = (
getattr(current_routing, "claude_reasoning_effort", None) if current_routing else None
)
+ self.codex_agent = getattr(current_routing, "codex_agent", None) if current_routing else None
self.codex_model = getattr(current_routing, "codex_model", None) if current_routing else None
self.codex_reasoning = (
getattr(current_routing, "codex_reasoning_effort", None) if current_routing else None
@@ -1727,6 +1729,38 @@ class DiscordBot(BaseIMClient):
self.add_item(reasoning_select)
if self.selected_backend == "codex":
+ codex_agent_names = _unique_agent_names(codex_agents)
+ agent_options = [
+ discord.SelectOption(
+ label=_prefixed_label(
+ "discord.labels.codexAgent",
+ self.outer._t("common.default"),
+ ),
+ value="__default__",
+ default=self.codex_agent in (None, "__default__"),
+ )
+ ]
+ agent_options += [
+ discord.SelectOption(label=a, value=a, default=a == self.codex_agent)
+ for a in codex_agent_names
+ ]
+ if len(agent_options) > 25:
+ agent_options = agent_options[:25]
+ agent_select = discord.ui.Select(
+ placeholder=self.outer._t("modal.routing.selectCodexAgent"),
+ options=agent_options,
+ min_values=1,
+ max_values=1,
+ )
+
+ async def codex_agent_callback(select_interaction: discord.Interaction):
+ if agent_select.values:
+ self.codex_agent = agent_select.values[0]
+ await select_interaction.response.defer()
+
+ agent_select.callback = codex_agent_callback
+ self.add_item(agent_select)
+
model_options = [
discord.SelectOption(
label=_prefixed_label("discord.labels.model", self.outer._t("common.default")),
@@ -1842,6 +1876,7 @@ class DiscordBot(BaseIMClient):
_normalize(self.claude_agent),
_normalize(self.claude_model),
_normalize(self.claude_reasoning),
+ _normalize(self.codex_agent),
_normalize(self.codex_model),
_normalize(self.codex_reasoning),
notify_user=True,
diff --git a/modules/im/feishu.py b/modules/im/feishu.py
index 39031793f..94f7612dc 100644
--- a/modules/im/feishu.py
+++ b/modules/im/feishu.py
@@ -1799,6 +1799,7 @@ class FeishuBot(BaseIMClient):
"claude_agent",
"claude_model",
"claude_reasoning_effort",
+ "codex_agent",
"codex_model",
"codex_reasoning_effort",
)
@@ -1857,6 +1858,7 @@ class FeishuBot(BaseIMClient):
"claude_agent": "claude_agent",
"claude_model": "claude_model",
"claude_reasoning": "claude_reasoning_effort",
+ "codex_agent": "codex_agent",
"codex_model": "codex_model",
"codex_reasoning": "codex_reasoning_effort",
}
@@ -1920,6 +1922,7 @@ class FeishuBot(BaseIMClient):
claude_agent = _val("claude_agent")
claude_model = _val("claude_model")
claude_reasoning = _val("claude_reasoning")
+ codex_agent = _val("codex_agent")
codex_model = _val("codex_model")
codex_reasoning = _val("codex_reasoning")
@@ -1934,6 +1937,7 @@ class FeishuBot(BaseIMClient):
claude_agent,
claude_model,
claude_reasoning,
+ codex_agent,
codex_model,
codex_reasoning,
is_dm=context.platform_specific.get("is_dm", False),
@@ -2306,6 +2310,7 @@ class FeishuBot(BaseIMClient):
"opencode_default_config": kwargs.get("opencode_default_config", {}),
"claude_agents": kwargs.get("claude_agents", []),
"claude_models": kwargs.get("claude_models", []),
+ "codex_agents": kwargs.get("codex_agents", []),
"codex_models": kwargs.get("codex_models", []),
}
@@ -2392,6 +2397,7 @@ class FeishuBot(BaseIMClient):
opencode_default_config = kwargs.get("opencode_default_config", {})
claude_agents = kwargs.get("claude_agents", [])
claude_models = kwargs.get("claude_models", [])
+ codex_agents = kwargs.get("codex_agents", [])
codex_models = kwargs.get("codex_models", [])
def _routing_value(field_name: str) -> Optional[str]:
@@ -2545,6 +2551,23 @@ class FeishuBot(BaseIMClient):
# ---- Codex section ----
elif selected_backend == "codex":
+ if codex_agents:
+ cx_agent_options = [{"text": {"tag": "plain_text", "content": "(Default)"}, "value": "__default__"}]
+ for agent_info in codex_agents:
+ name = agent_info if isinstance(agent_info, str) else agent_info.get("name", str(agent_info))
+ cx_agent_options.append({"text": {"tag": "plain_text", "content": name}, "value": name})
+ cx_current_agent = _routing_value("codex_agent")
+ form_elements.append({"tag": "markdown", "content": t("modal.routing.codexAgent")})
+ form_elements.append(
+ {
+ "tag": "select_static",
+ "name": "codex_agent",
+ "placeholder": {"tag": "plain_text", "content": t("modal.routing.selectCodexAgent")},
+ "options": cx_agent_options,
+ "initial_option": cx_current_agent if cx_current_agent else "__default__",
+ }
+ )
+
# Codex model selector
if codex_models:
cx_model_options = [{"text": {"tag": "plain_text", "content": "(Default)"}, "value": "__default__"}]
diff --git a/modules/im/slack.py b/modules/im/slack.py
index afb4d0ece..1b393b3db 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -1851,6 +1851,12 @@ class SlackBot(BaseIMClient):
if claude_reasoning == "__default__":
claude_reasoning = None
+ # Extract Codex model (optional)
+ codex_agent_data = values.get("codex_agent_block", {}).get("codex_agent_select", {})
+ codex_agent = codex_agent_data.get("selected_option", {}).get("value")
+ if codex_agent == "__default__":
+ codex_agent = None
+
# Extract Codex model (optional)
codex_model_data = values.get("codex_model_block", {}).get("codex_model_select", {})
codex_model = codex_model_data.get("selected_option", {}).get("value")
@@ -1884,6 +1890,7 @@ class SlackBot(BaseIMClient):
claude_agent,
claude_model,
claude_reasoning,
+ codex_agent,
codex_model,
codex_reasoning,
is_dm=isinstance(channel_id, str) and channel_id.startswith("D"),
@@ -2611,6 +2618,7 @@ class SlackBot(BaseIMClient):
opencode_default_config: dict,
claude_agents: list = None,
claude_models: list = None,
+ codex_agents: list = None,
codex_models: list = None,
selected_backend: object = _UNSET,
selected_opencode_agent: object = _UNSET,
@@ -2619,6 +2627,7 @@ class SlackBot(BaseIMClient):
selected_claude_agent: object = _UNSET,
selected_claude_model: object = _UNSET,
selected_claude_reasoning: object = _UNSET,
+ selected_codex_agent: object = _UNSET,
selected_codex_model: object = _UNSET,
selected_codex_reasoning: object = _UNSET,
) -> dict:
@@ -3030,9 +3039,15 @@ class SlackBot(BaseIMClient):
# Codex-specific options (only if codex is selected)
if effective_backend == "codex" and "codex" in registered_backends:
+ codex_agents = codex_agents or []
codex_models = codex_models or []
# Get current codex settings
+ if selected_codex_agent is _UNSET:
+ current_cx_agent = getattr(current_routing, "codex_agent", None) if current_routing else None
+ else:
+ current_cx_agent = selected_codex_agent
+
if selected_codex_model is _UNSET:
current_cx_model = current_routing.codex_model if current_routing else None
else:
@@ -3043,6 +3058,35 @@ class SlackBot(BaseIMClient):
else:
current_cx_reasoning = selected_codex_reasoning
+ cx_agent_options = [
+ {"text": {"type": "plain_text", "text": self._t("common.default")}, "value": "__default__"}
+ ]
+ for agent in codex_agents:
+ agent_id = agent.get("id", "")
+ agent_name = agent.get("name", agent_id)
+ if agent_id:
+ cx_agent_options.append(
+ {
+ "text": {"type": "plain_text", "text": agent_name[:75]},
+ "value": agent_id,
+ }
+ )
+
+ initial_cx_agent = cx_agent_options[0]
+ if current_cx_agent:
+ for opt in cx_agent_options:
+ if opt["value"] == current_cx_agent:
+ initial_cx_agent = opt
+ break
+
+ cx_agent_select = {
+ "type": "static_select",
+ "action_id": "codex_agent_select",
+ "placeholder": {"type": "plain_text", "text": self._t("modal.routing.selectCodexAgent")},
+ "options": cx_agent_options,
+ "initial_option": initial_cx_agent,
+ }
+
# Build model options
cx_model_options = [
{"text": {"type": "plain_text", "text": self._t("common.default")}, "value": "__default__"}
@@ -3136,6 +3180,13 @@ class SlackBot(BaseIMClient):
"text": f"*{self._t('modal.routing.codexSettings')}*",
},
},
+ {
+ "type": "input",
+ "block_id": "codex_agent_block",
+ "optional": True,
+ "element": cx_agent_select,
+ "label": {"type": "plain_text", "text": self._t("modal.routing.codexAgent")},
+ },
{
"type": "input",
"block_id": "codex_model_block",
@@ -3444,6 +3495,7 @@ class SlackBot(BaseIMClient):
opencode_default_config: dict,
claude_agents: list = None,
claude_models: list = None,
+ codex_agents: list = None,
codex_models: list = None,
):
"""Open a modal dialog for agent/model routing settings"""
@@ -3459,6 +3511,7 @@ class SlackBot(BaseIMClient):
opencode_default_config=opencode_default_config,
claude_agents=claude_agents,
claude_models=claude_models,
+ codex_agents=codex_agents,
codex_models=codex_models,
)
@@ -3481,6 +3534,7 @@ class SlackBot(BaseIMClient):
opencode_default_config: dict,
claude_agents: list = None,
claude_models: list = None,
+ codex_agents: list = None,
codex_models: list = None,
selected_backend: Optional[str] = None,
selected_opencode_agent: Optional[str] = None,
@@ -3489,6 +3543,7 @@ class SlackBot(BaseIMClient):
selected_claude_agent: Optional[str] = None,
selected_claude_model: Optional[str] = None,
selected_claude_reasoning: Optional[str] = None,
+ selected_codex_agent: Optional[str] = None,
selected_codex_model: Optional[str] = None,
selected_codex_reasoning: Optional[str] = None,
) -> None:
@@ -3505,6 +3560,7 @@ class SlackBot(BaseIMClient):
opencode_default_config=opencode_default_config,
claude_agents=claude_agents,
claude_models=claude_models,
+ codex_agents=codex_agents,
codex_models=codex_models,
selected_backend=selected_backend,
selected_opencode_agent=selected_opencode_agent,
@@ -3513,6 +3569,7 @@ class SlackBot(BaseIMClient):
selected_claude_agent=selected_claude_agent,
selected_claude_model=selected_claude_model,
selected_claude_reasoning=selected_claude_reasoning,
+ selected_codex_agent=selected_codex_agent,
selected_codex_model=selected_codex_model,
selected_codex_reasoning=selected_codex_reasoning,
)
diff --git a/modules/im/slack_modal.py b/modules/im/slack_modal.py
index cf644920d..10b4030e4 100644
--- a/modules/im/slack_modal.py
+++ b/modules/im/slack_modal.py
@@ -56,6 +56,7 @@ def parse_routing_modal_selection(
claude_agent = _extract_selected_value(values, "claude_agent_block", "claude_agent_select")
claude_model = _extract_selected_value(values, "claude_model_block", "claude_model_select")
claude_reasoning = _extract_selected_value(values, "claude_reasoning_block", "claude_reasoning_select")
+ codex_agent = _extract_selected_value(values, "codex_agent_block", "codex_agent_select")
codex_model = _extract_selected_value(values, "codex_model_block", "codex_model_select")
codex_reasoning = _extract_prefixed_selected_value(values, "codex_reasoning_block", "codex_reasoning_select")
@@ -72,6 +73,8 @@ def parse_routing_modal_selection(
claude_model = selected_value
elif selected_action_id == "claude_reasoning_select":
claude_reasoning = selected_value
+ elif selected_action_id == "codex_agent_select":
+ codex_agent = selected_value
elif selected_action_id == "codex_model_select":
codex_model = selected_value
elif selected_action_id.startswith("codex_reasoning_select"):
@@ -85,6 +88,7 @@ def parse_routing_modal_selection(
selected_claude_agent=_normalize_default(claude_agent),
selected_claude_model=_normalize_default(claude_model),
selected_claude_reasoning=_normalize_default(claude_reasoning),
+ selected_codex_agent=_normalize_default(codex_agent),
selected_codex_model=_normalize_default(codex_model),
selected_codex_reasoning=_normalize_default(codex_reasoning),
)
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index 71f69e78b..660cfc2d0 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -35,6 +35,7 @@ def _routing_from_dict(payload: Optional[dict]) -> RoutingSettings:
claude_agent=data.get("claude_agent"),
claude_model=data.get("claude_model"),
claude_reasoning_effort=data.get("claude_reasoning_effort"),
+ codex_agent=data.get("codex_agent"),
codex_model=data.get("codex_model"),
codex_reasoning_effort=data.get("codex_reasoning_effort"),
)
diff --git a/scripts/prepare_three_regression.py b/scripts/prepare_three_regression.py
index c5691e543..180bd1d6a 100755
--- a/scripts/prepare_three_regression.py
+++ b/scripts/prepare_three_regression.py
@@ -99,6 +99,7 @@ def _build_routing(name: str) -> dict:
"opencode_reasoning_effort": _optional(f"{prefix}_OPENCODE_REASONING_EFFORT"),
"claude_agent": _optional(f"{prefix}_CLAUDE_AGENT"),
"claude_model": _optional(f"{prefix}_CLAUDE_MODEL"),
+ "codex_agent": _optional(f"{prefix}_CODEX_AGENT"),
"codex_model": _optional(f"{prefix}_CODEX_MODEL"),
"codex_reasoning_effort": _optional(f"{prefix}_CODEX_REASONING_EFFORT"),
}
diff --git a/skills/use-vibe-remote/SKILL.md b/skills/use-vibe-remote/SKILL.md
index 935709ff9..170290c9e 100644
--- a/skills/use-vibe-remote/SKILL.md
+++ b/skills/use-vibe-remote/SKILL.md
@@ -355,25 +355,28 @@ Current Vibe Remote routing support is:
| --- | --- | --- | --- | --- |
| OpenCode | yes | yes | yes | yes |
| Claude | yes | yes | yes | yes |
-| Codex | yes | no | yes | yes |
+| Codex | yes | yes | yes | yes |
Behavior notes:
- OpenCode subagents are selected through `routing.opencode_agent` or through prefix routing such as `reviewer: ...`.
- Claude subagents are selected through `routing.claude_agent` or prefix routing.
+- Codex subagents are selected through `routing.codex_agent` or prefix routing.
- Claude reasoning is selected through `routing.claude_reasoning_effort`; common values are `low`, `medium`, and `high`, and some models also allow `max`.
-- Codex subagents are not currently supported in Vibe Remote routing.
- If a Claude reasoning value is invalid for the chosen model, Vibe Remote drops that override and falls back to the backend default.
## Subagent and Prefix Routing
If the user asks for subagents, remember:
-- OpenCode and Claude support prefix-triggered subagent selection like `planner: draft a migration plan`
+- OpenCode, Claude, and Codex support prefix-triggered subagent selection like `planner: draft a migration plan`
- when a subagent definition provides its own default model or reasoning setting, that subagent-level value overrides the channel default
- Claude subagents are discovered from markdown files under:
- `~/.claude/agents/`
- project `.claude/agents/`
+- Codex custom agents are discovered from TOML files under:
+ - `~/.codex/agents/`
+ - project `.codex/agents/`
- OpenCode subagent and model defaults come from the OpenCode runtime/config rather than only from Vibe Remote's own config
## Important Caveat: OpenCode Defaults
@@ -429,6 +432,7 @@ Example: enable a Slack channel and route it to Codex with GPT-5.4 high reasonin
"opencode_reasoning_effort": null,
"claude_agent": null,
"claude_model": null,
+ "codex_agent": null,
"codex_model": "gpt-5.4",
"codex_reasoning_effort": "high"
},
@@ -470,6 +474,7 @@ User intent:
- enable Slack channel `C...`
- backend `codex`
+- optional subagent `reviewer`
- model `gpt-5.4`
- reasoning `high`
@@ -479,6 +484,7 @@ Action:
- target `scopes.channel.slack.<channel_id>`
- set `enabled: true`
- set `routing.agent_backend = "codex"`
+- set `routing.codex_agent = "reviewer"` if requested
- set `routing.codex_model = "gpt-5.4"`
- set `routing.codex_reasoning_effort = "high"`
@@ -643,14 +649,17 @@ Important locations:
- `~/.codex/config.toml`: global Codex config
- `.codex/config.toml`: project-local Codex config
+- `~/.codex/agents/`: global Codex custom agents
+- `.codex/agents/`: project-local Codex custom agents
Relevant docs:
- config basics: `https://developers.openai.com/codex/config-basic/`
- config reference: `https://developers.openai.com/codex/config-reference/`
- CLI overview: `https://developers.openai.com/codex/cli`
+- subagents: `https://developers.openai.com/codex/subagents`
-Inside Vibe Remote, Codex scope routing currently controls backend choice, model, and reasoning effort. It does not expose Codex subagent routing.
+Inside Vibe Remote, Codex scope routing currently controls backend choice, subagent, model, and reasoning effort.
## Safety Boundaries
diff --git a/tests/e2e/test_users_and_bind.py b/tests/e2e/test_users_and_bind.py
index dcfee261e..834bdb4a4 100644
--- a/tests/e2e/test_users_and_bind.py
+++ b/tests/e2e/test_users_and_bind.py
@@ -215,3 +215,9 @@ class TestAgentModelsAPI:
status, data = _get(f"{api_url}/codex/models")
assert status == 200
assert isinstance(data, dict)
+
+ def test_codex_agents_endpoint_exists(self, api_url):
+ """GET /codex/agents should return JSON."""
+ status, data = _get(f"{api_url}/codex/agents")
+ assert status == 200
+ assert isinstance(data, dict)
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index 96d746f62..f58112524 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -37,11 +37,38 @@ setattr(_transport_module, "CodexTransport", object)
_turn_state_module = types.ModuleType("modules.agents.codex.turn_state")
setattr(_turn_state_module, "CodexTurnRegistry", object)
+_subagent_router_module = types.ModuleType("modules.agents.subagent_router")
+
+
+class _StubSubagentDefinition:
+ def __init__(
+ self,
+ name=None,
+ description=None,
+ developer_instructions=None,
+ model=None,
+ reasoning_effort=None,
+ path=None,
+ source=None,
+ ):
+ self.name = name
+ self.description = description
+ self.developer_instructions = developer_instructions
+ self.model = model
+ self.reasoning_effort = reasoning_effort
+ self.path = path
+ self.source = source
+
+
+setattr(_subagent_router_module, "SubagentDefinition", _StubSubagentDefinition)
+setattr(_subagent_router_module, "load_codex_subagent", lambda *args, **kwargs: None)
+
_STUBBED_MODULES = {
"modules": _modules_pkg,
"modules.agents": _agents_pkg,
"modules.agents.codex": _codex_pkg,
"modules.agents.base": _base_module,
+ "modules.agents.subagent_router": _subagent_router_module,
"modules.agents.codex.event_handler": _event_handler_module,
"modules.agents.codex.session": _session_module,
"modules.agents.codex.transport": _transport_module,
@@ -298,6 +325,8 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
async def test_start_thread_requests_danger_full_access(self):
agent = object.__new__(CodexAgent)
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=False))
+ agent.settings_manager = SimpleNamespace(get_channel_settings=lambda session_key: None)
+ agent.codex_config = SimpleNamespace(default_model=None)
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
agent.sessions = SimpleNamespace(set_agent_session_mapping=Mock())
request = SimpleNamespace(
@@ -305,6 +334,9 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
context=SimpleNamespace(platform="slack", platform_specific={}),
base_session_id="session-1",
session_key="channel-1",
+ subagent_name=None,
+ subagent_model=None,
+ subagent_reasoning_effort=None,
)
transport = SimpleNamespace(send_request=AsyncMock(return_value={"thread": {"id": "thread-1"}}))
@@ -321,6 +353,46 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
},
)
+ async def test_start_thread_includes_codex_agent_developer_instructions(self):
+ agent = object.__new__(CodexAgent)
+ agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=False))
+ agent.settings_manager = SimpleNamespace(get_channel_settings=lambda session_key: None)
+ agent.codex_config = SimpleNamespace(default_model=None)
+ agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
+ agent.sessions = SimpleNamespace(set_agent_session_mapping=Mock())
+ request = SimpleNamespace(
+ working_path="/tmp/work",
+ context=SimpleNamespace(platform="slack", platform_specific={}),
+ base_session_id="session-1",
+ session_key="channel-1",
+ subagent_name="reviewer",
+ subagent_model=None,
+ subagent_reasoning_effort=None,
+ )
+ transport = SimpleNamespace(send_request=AsyncMock(return_value={"thread": {"id": "thread-1"}}))
+
+ with patch.object(
+ _MODULE,
+ "load_codex_subagent",
+ return_value=SimpleNamespace(
+ developer_instructions="Focus on regressions.",
+ model="gpt-5.4-mini",
+ reasoning_effort="high",
+ ),
+ ) as load_subagent:
+ await agent._start_thread(transport, request)
+
+ load_subagent.assert_called_once_with("reviewer", project_root=Path("/tmp/work"))
+ transport.send_request.assert_awaited_once_with(
+ "thread/start",
+ {
+ "cwd": "/tmp/work",
+ "approvalPolicy": "never",
+ "sandbox": "danger-full-access",
+ "developerInstructions": "Focus on regressions.",
+ },
+ )
+
async def test_start_turn_uses_sandbox_policy_object(self):
agent = object.__new__(CodexAgent)
agent.settings_manager = SimpleNamespace(get_channel_settings=lambda session_key: None)
@@ -335,6 +407,9 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
session_key="channel-1",
base_session_id="session-1",
composite_session_id="slack:C1:T1",
+ subagent_name=None,
+ subagent_model=None,
+ subagent_reasoning_effort=None,
)
transport = SimpleNamespace(send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}))
@@ -351,6 +426,150 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
},
)
+ async def test_start_turn_uses_context_specific_settings_manager_for_routing(self):
+ agent = object.__new__(CodexAgent)
+ agent.settings_manager = SimpleNamespace(
+ get_channel_settings=lambda settings_key: SimpleNamespace(
+ routing=SimpleNamespace(codex_model="wrong-model", codex_reasoning_effort="low")
+ )
+ )
+ context_manager = SimpleNamespace(
+ get_channel_settings=lambda settings_key: SimpleNamespace(
+ routing=SimpleNamespace(codex_model="gpt-5.4", codex_reasoning_effort="high")
+ )
+ )
+ agent.controller = SimpleNamespace(
+ _get_settings_key=lambda context: "U123",
+ get_settings_manager_for_context=lambda context: context_manager,
+ )
+ agent.codex_config = SimpleNamespace(default_model="fallback-model")
+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])
+ agent._turn_registry = SimpleNamespace(
+ begin_turn_start=Mock(),
+ get_bootstrapped_turn_id=Mock(return_value=None),
+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),
+ )
+ request = SimpleNamespace(
+ session_key="discord::D123",
+ base_session_id="session-1",
+ composite_session_id="discord:D1:T1",
+ context=SimpleNamespace(platform="discord", platform_specific={"is_dm": True}),
+ subagent_name=None,
+ subagent_model=None,
+ subagent_reasoning_effort=None,
+ )
+ transport = SimpleNamespace(send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}))
+
+ await agent._start_turn(transport, request, "thread-1")
+
+ transport.send_request.assert_awaited_once_with(
+ "turn/start",
+ {
+ "threadId": "thread-1",
+ "input": [{"type": "text", "text": "hello"}],
+ "approvalPolicy": "never",
+ "sandboxPolicy": {"type": "dangerFullAccess"},
+ "model": "gpt-5.4",
+ "effort": "high",
+ },
+ )
+
+ async def test_start_turn_does_not_fall_back_to_primary_platform_when_context_manager_has_no_settings(self):
+ agent = object.__new__(CodexAgent)
+ agent.settings_manager = SimpleNamespace(
+ get_channel_settings=lambda settings_key: SimpleNamespace(
+ routing=SimpleNamespace(codex_model="wrong-model", codex_reasoning_effort="low")
+ )
+ )
+ context_manager = SimpleNamespace(get_channel_settings=lambda settings_key: None)
+ agent.controller = SimpleNamespace(
+ _get_settings_key=lambda context: "U123",
+ get_settings_manager_for_context=lambda context: context_manager,
+ )
+ agent.codex_config = SimpleNamespace(default_model="fallback-model")
+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])
+ agent._turn_registry = SimpleNamespace(
+ begin_turn_start=Mock(),
+ get_bootstrapped_turn_id=Mock(return_value=None),
+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),
+ )
+ request = SimpleNamespace(
+ session_key="discord::D123",
+ base_session_id="session-1",
+ composite_session_id="discord:D1:T1",
+ context=SimpleNamespace(platform="discord", platform_specific={"is_dm": True}),
+ subagent_name=None,
+ subagent_model=None,
+ subagent_reasoning_effort=None,
+ working_path="/tmp/work",
+ )
+ transport = SimpleNamespace(send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}))
+
+ await agent._start_turn(transport, request, "thread-1")
+
+ transport.send_request.assert_awaited_once_with(
+ "turn/start",
+ {
+ "threadId": "thread-1",
+ "input": [{"type": "text", "text": "hello"}],
+ "approvalPolicy": "never",
+ "sandboxPolicy": {"type": "dangerFullAccess"},
+ "model": "fallback-model",
+ },
+ )
+
+ async def test_start_turn_uses_codex_agent_defaults_when_routing_selects_agent(self):
+ agent = object.__new__(CodexAgent)
+ agent.settings_manager = SimpleNamespace(
+ get_channel_settings=lambda settings_key: SimpleNamespace(
+ routing=SimpleNamespace(
+ codex_agent="reviewer",
+ codex_model=None,
+ codex_reasoning_effort=None,
+ )
+ )
+ )
+ agent.codex_config = SimpleNamespace(default_model="fallback-model")
+ agent._build_input = Mock(return_value=[{"type": "text", "text": "hello"}])
+ agent._turn_registry = SimpleNamespace(
+ begin_turn_start=Mock(),
+ get_bootstrapped_turn_id=Mock(return_value=None),
+ finalize_turn_start_response=Mock(return_value=SimpleNamespace()),
+ )
+ request = SimpleNamespace(
+ session_key="channel-1",
+ base_session_id="session-1",
+ composite_session_id="slack:C1:T1",
+ working_path="/tmp/work",
+ subagent_name=None,
+ subagent_model=None,
+ subagent_reasoning_effort=None,
+ )
+ transport = SimpleNamespace(send_request=AsyncMock(return_value={"turn": {"id": "turn-1"}}))
+
+ with patch.object(
+ _MODULE,
+ "load_codex_subagent",
+ return_value=SimpleNamespace(
+ developer_instructions="Focus on regressions.",
+ model="gpt-5.4",
+ reasoning_effort="high",
+ ),
+ ) as load_subagent:
+ await agent._start_turn(transport, request, "thread-1")
+
+ load_subagent.assert_called_once_with("reviewer", project_root=Path("/tmp/work"))
+ transport.send_request.assert_awaited_once_with(
+ "turn/start",
+ {
+ "threadId": "thread-1",
+ "input": [{"type": "text", "text": "hello"}],
+ "approvalPolicy": "never",
+ "sandboxPolicy": {"type": "dangerFullAccess"},
+ "model": "gpt-5.4",
+ "effort": "high",
+ },
+ )
class CodexTransportCommandTests(unittest.IsolatedAsyncioTestCase):
async def test_transport_always_starts_app_server_with_global_bypass_flag(self):
diff --git a/tests/test_feishu_routing_card.py b/tests/test_feishu_routing_card.py
index b5244008d..4107a6309 100644
--- a/tests/test_feishu_routing_card.py
+++ b/tests/test_feishu_routing_card.py
@@ -66,6 +66,7 @@ class FeishuRoutingCardTests(unittest.IsolatedAsyncioTestCase):
opencode_agent=None,
opencode_model=None,
opencode_reasoning_effort=None,
+ codex_agent=None,
codex_model=None,
codex_reasoning_effort=None,
)
@@ -78,6 +79,7 @@ class FeishuRoutingCardTests(unittest.IsolatedAsyncioTestCase):
"opencode_agents": [],
"opencode_models": {},
"opencode_default_config": {},
+ "codex_agents": [],
"codex_models": [],
}
@@ -118,6 +120,7 @@ class FeishuRoutingCardTests(unittest.IsolatedAsyncioTestCase):
opencode_agent=None,
opencode_model=None,
opencode_reasoning_effort=None,
+ codex_agent=None,
codex_model=None,
codex_reasoning_effort=None,
)
@@ -130,6 +133,7 @@ class FeishuRoutingCardTests(unittest.IsolatedAsyncioTestCase):
"opencode_agents": [],
"opencode_models": {},
"opencode_default_config": {},
+ "codex_agents": [],
"codex_models": [],
}
diff --git a/tests/test_routing_modal_selection.py b/tests/test_routing_modal_selection.py
index 602ff04c7..5a59b26a3 100644
--- a/tests/test_routing_modal_selection.py
+++ b/tests/test_routing_modal_selection.py
@@ -22,6 +22,7 @@ def test_parse_routing_modal_selection_normalizes_default_values():
view = {
"state": {
"values": {
+ "codex_agent_block": {"codex_agent_select": {"selected_option": {"value": "__default__"}}},
"claude_model_block": {"claude_model_select": {"selected_option": {"value": "__default__"}}},
"claude_reasoning_block": {"claude_reasoning_select": {"selected_option": {"value": "__default__"}}},
"codex_reasoning_block": {"codex_reasoning_select_1": {"selected_option": {"value": "__default__"}}},
@@ -32,6 +33,26 @@ def test_parse_routing_modal_selection_normalizes_default_values():
selection = parse_routing_modal_selection(view=view, action={}, default_backend="claude")
assert selection.selected_backend == "claude"
+ assert selection.selected_codex_agent is None
assert selection.selected_claude_model is None
assert selection.selected_claude_reasoning is None
assert selection.selected_codex_reasoning is None
+
+
+def test_parse_routing_modal_selection_applies_codex_action_override():
+ view = {
+ "state": {
+ "values": {
+ "backend_block": {"backend_select": {"selected_option": {"value": "codex"}}},
+ "codex_agent_block": {"codex_agent_select": {"selected_option": {"value": "__default__"}}},
+ "codex_model_block": {"codex_model_select": {"selected_option": {"value": "gpt-5.4-mini"}}},
+ }
+ }
+ }
+ action = {"action_id": "codex_agent_select", "selected_option": {"value": "reviewer"}}
+
+ selection = parse_routing_modal_selection(view=view, action=action, default_backend="claude")
+
+ assert selection.selected_backend == "codex"
+ assert selection.selected_codex_agent == "reviewer"
+ assert selection.selected_codex_model == "gpt-5.4-mini"
diff --git a/tests/test_subagent_router.py b/tests/test_subagent_router.py
index 9e50346d6..8b4e7cacc 100644
--- a/tests/test_subagent_router.py
+++ b/tests/test_subagent_router.py
@@ -1,7 +1,9 @@
from pathlib import Path
from modules.agents.subagent_router import (
+ list_codex_subagents,
load_claude_subagent,
+ load_codex_subagent,
normalize_subagent_name,
parse_subagent_prefix,
)
@@ -44,3 +46,76 @@ def test_load_claude_subagent_from_agent_dir(tmp_path: Path):
assert definition
assert definition.name == "code-reviewer"
assert definition.model == "sonnet"
+
+
+def test_list_codex_subagents_prefers_project_override(tmp_path: Path):
+ global_agent_dir = tmp_path / ".codex" / "agents"
+ global_agent_dir.mkdir(parents=True)
+ (global_agent_dir / "reviewer.toml").write_text(
+ '\n'.join(
+ [
+ 'name = "reviewer"',
+ 'description = "Global reviewer"',
+ 'developer_instructions = "Review globally."',
+ 'model = "gpt-5.4-mini"',
+ 'model_reasoning_effort = "medium"',
+ ]
+ ),
+ encoding="utf-8",
+ )
+
+ project_root = tmp_path / "repo"
+ project_agent_dir = project_root / ".codex" / "agents"
+ project_agent_dir.mkdir(parents=True)
+ (project_agent_dir / "reviewer.toml").write_text(
+ '\n'.join(
+ [
+ 'name = "reviewer"',
+ 'description = "Project reviewer"',
+ 'developer_instructions = "Review the repo-specific changes."',
+ 'model = "gpt-5.4"',
+ 'model_reasoning_effort = "high"',
+ ]
+ ),
+ encoding="utf-8",
+ )
+
+ definitions = list_codex_subagents(search_root=tmp_path / ".codex", project_root=project_root)
+
+ reviewer = definitions["reviewer"]
+ assert reviewer.name == "reviewer"
+ assert reviewer.description == "Project reviewer"
+ assert reviewer.developer_instructions == "Review the repo-specific changes."
+ assert reviewer.model == "gpt-5.4"
+ assert reviewer.reasoning_effort == "high"
+ assert reviewer.source == "project"
+ assert reviewer.path == project_agent_dir / "reviewer.toml"
+
+
+def test_load_codex_subagent_reads_global_agent_definition(tmp_path: Path):
+ global_agent_dir = tmp_path / ".codex" / "agents"
+ global_agent_dir.mkdir(parents=True)
+ agent_file = global_agent_dir / "reviewer.toml"
+ agent_file.write_text(
+ '\n'.join(
+ [
+ 'name = "reviewer"',
+ 'description = "Checks risks"',
+ 'developer_instructions = "Focus on regressions."',
+ 'model = "gpt-5.4-mini"',
+ 'model_reasoning_effort = "low"',
+ ]
+ ),
+ encoding="utf-8",
+ )
+
+ definition = load_codex_subagent("REVIEWER", search_root=tmp_path / ".codex")
+
+ assert definition
+ assert definition.name == "reviewer"
+ assert definition.description == "Checks risks"
+ assert definition.developer_instructions == "Focus on regressions."
+ assert definition.model == "gpt-5.4-mini"
+ assert definition.reasoning_effort == "low"
+ assert definition.source == "global"
+ assert definition.path == agent_file
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index c3b6f8ff7..fbf1be6cd 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -304,6 +304,59 @@ def test_codex_models_falls_back_when_cli_cache_missing(monkeypatch, tmp_path):
assert "legacy-codex" in result["models"]
assert "gpt-5.1-codex-max" in result["models"]
assert "gpt-5.1-codex-mini" in result["models"]
+
+
+def test_codex_agents_merges_global_and_project(monkeypatch, tmp_path):
+ global_agent_dir = tmp_path / ".codex" / "agents"
+ global_agent_dir.mkdir(parents=True)
+ (global_agent_dir / "reviewer.toml").write_text(
+ '\n'.join(
+ [
+ 'name = "reviewer"',
+ 'description = "Global reviewer"',
+ 'developer_instructions = "Review carefully."',
+ 'model = "gpt-5.4-mini"',
+ 'model_reasoning_effort = "medium"',
+ ]
+ ),
+ encoding="utf-8",
+ )
+
+ project_root = tmp_path / "repo"
+ project_agent_dir = project_root / ".codex" / "agents"
+ project_agent_dir.mkdir(parents=True)
+ (project_agent_dir / "reviewer.toml").write_text(
+ '\n'.join(
+ [
+ 'name = "reviewer"',
+ 'description = "Project reviewer"',
+ 'developer_instructions = "Focus on local changes."',
+ 'model = "gpt-5.4"',
+ 'model_reasoning_effort = "high"',
+ ]
+ ),
+ encoding="utf-8",
+ )
+ (project_agent_dir / "triage.toml").write_text(
+ '\n'.join(
+ [
+ 'name = "triage"',
+ 'description = "Project triage"',
+ 'developer_instructions = "Classify issues first."',
+ ]
+ ),
+ encoding="utf-8",
+ )
+
+ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
+
+ result = api.codex_agents(str(project_root))
+
+ assert result["ok"] is True
+ assert [agent["id"] for agent in result["agents"]] == ["reviewer", "triage"]
+ assert result["agents"][0]["source"] == "project"
+ assert result["agents"][0]["description"] == "Project reviewer"
+ assert result["agents"][0]["path"] == str(project_agent_dir / "reviewer.toml")
def test_setup_opencode_permission_preserves_existing_json_fields(monkeypatch, tmp_path):
config_path = tmp_path / ".config" / "opencode" / "opencode.json"
config_path.parent.mkdir(parents=True, exist_ok=True)
diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsx
index f32e0dfbe..d7e33fb27 100644
--- a/ui/src/components/steps/ChannelList.tsx
+++ b/ui/src/components/steps/ChannelList.tsx
@@ -49,6 +49,7 @@ interface ChannelConfig {
claude_agent?: string | null;
claude_model?: string | null;
claude_reasoning_effort?: string | null;
+ codex_agent?: string | null;
codex_model?: string | null;
codex_reasoning_effort?: string | null;
};
@@ -82,6 +83,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const [pagePlatform, setPagePlatform] = useState<string>(forcedPlatform || data.platform || 'slack');
const [opencodeOptionsByCwd, setOpencodeOptionsByCwd] = useState<Record<string, any>>({});
const [claudeAgentsByCwd, setClaudeAgentsByCwd] = useState<Record<string, { id: string; name: string; path: string; source?: string }[]>>({});
+ const [codexAgentsByCwd, setCodexAgentsByCwd] = useState<Record<string, { id: string; name: string; path: string; source?: string; description?: string }[]>>({});
const [claudeModels, setClaudeModels] = useState<string[]>([]);
const [claudeReasoningOptions, setClaudeReasoningOptions] = useState<Record<string, { value: string; label: string }[]>>({});
const [codexModels, setCodexModels] = useState<string[]>([]);
@@ -294,6 +296,17 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
}
};
+ const loadCodexAgents = async (cwd: string) => {
+ try {
+ const result = await api.codexAgents(cwd);
+ if (result.ok) {
+ setCodexAgentsByCwd((prev) => ({ ...prev, [cwd]: result.agents || [] }));
+ }
+ } catch (e) {
+ console.error('Failed to load Codex agents:', e);
+ }
+ };
+
useEffect(() => {
if (platform === 'lark') {
if (larkAppId && larkAppSecret) {
@@ -331,6 +344,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const neededOpenCodeCwds = new Set<string>();
const neededClaudeCwds = new Set<string>();
+ const neededCodexCwds = new Set<string>();
channels.forEach((channel) => {
const raw = configs[channel.id];
@@ -344,6 +358,9 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
if (backend === 'claude' && config.agents?.claude?.enabled) {
neededClaudeCwds.add(effectiveCwd);
}
+ if (backend === 'codex' && config.agents?.codex?.enabled) {
+ neededCodexCwds.add(effectiveCwd);
+ }
});
neededOpenCodeCwds.forEach((cwd) => {
@@ -357,7 +374,13 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
void loadClaudeAgents(cwd);
}
});
- }, [channels, configs, config.runtime?.default_cwd, config.agents?.default_backend, config.agents?.opencode?.enabled, config.agents?.claude?.enabled]);
+
+ neededCodexCwds.forEach((cwd) => {
+ if (!codexAgentsByCwd[cwd]) {
+ void loadCodexAgents(cwd);
+ }
+ });
+ }, [channels, configs, config.runtime?.default_cwd, config.agents?.default_backend, config.agents?.opencode?.enabled, config.agents?.claude?.enabled, config.agents?.codex?.enabled]);
useEffect(() => {
if (!channels.length) return;
@@ -421,6 +444,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
claude_agent: null,
claude_model: null,
claude_reasoning_effort: null,
+ codex_agent: null,
codex_model: null,
codex_reasoning_effort: null,
},
@@ -732,6 +756,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
const effectiveCwd = channelConfig.custom_cwd || config.runtime?.default_cwd || '~/work';
const opencodeOptions = opencodeOptionsByCwd[effectiveCwd];
const claudeAgents = claudeAgentsByCwd[effectiveCwd] || [];
+ const codexAgents = codexAgentsByCwd[effectiveCwd] || [];
return (
<div key={channel.id} className="p-4 hover:bg-neutral-50/50 transition-colors">
<div className="flex items-center justify-between">
@@ -1063,7 +1088,24 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
{effectiveBackend === 'codex' && (
<div className="space-y-3">
<div className="text-xs font-medium text-muted uppercase">{t('channelList.codexSettings')}</div>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3 bg-bg/50 p-3 rounded border border-border">
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-3 bg-bg/50 p-3 rounded border border-border">
+ <div className="space-y-1">
+ <label className="text-xs text-muted">{t('channelList.agent')}</label>
+ <select
+ value={channelConfig.routing.codex_agent || ''}
+ onChange={(e) =>
+ updateConfig(channel.id, {
+ routing: { ...channelConfig.routing, codex_agent: e.target.value || null },
+ })
+ }
+ className="w-full bg-panel border border-border rounded px-3 py-2 text-sm"
+ >
+ <option value="">{t('common.default')}</option>
+ {codexAgents.map((agent) => (
+ <option key={agent.id} value={agent.id}>{agent.name}</option>
+ ))}
+ </select>
+ </div>
<div className="space-y-1">
<label className="text-xs text-muted">{t('channelList.model')}</label>
<Combobox
diff --git a/ui/src/components/steps/Summary.tsx b/ui/src/components/steps/Summary.tsx
index 985cb6eb7..c621f29b3 100644
--- a/ui/src/components/steps/Summary.tsx
+++ b/ui/src/components/steps/Summary.tsx
@@ -470,6 +470,7 @@ const buildSettingsPayload = (data: any) => {
claude_agent: cfg.routing?.claude_agent || null,
claude_model: cfg.routing?.claude_model || null,
claude_reasoning_effort: cfg.routing?.claude_reasoning_effort || null,
+ codex_agent: cfg.routing?.codex_agent || null,
codex_model: cfg.routing?.codex_model || null,
codex_reasoning_effort: cfg.routing?.codex_reasoning_effort || null,
},
diff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsx
index 77c6bdf1a..24e64914e 100644
--- a/ui/src/components/steps/UserList.tsx
+++ b/ui/src/components/steps/UserList.tsx
@@ -42,6 +42,7 @@ interface UserConfig {
claude_agent?: string | null;
claude_model?: string | null;
claude_reasoning_effort?: string | null;
+ codex_agent?: string | null;
codex_model?: string | null;
codex_reasoning_effort?: string | null;
};
@@ -308,6 +309,7 @@ export const UserList: React.FC = () => {
const [config, setConfig] = useState<any>({});
const [opencodeOptionsByCwd, setOpencodeOptionsByCwd] = useState<Record<string, any>>({});
const [claudeAgentsByCwd, setClaudeAgentsByCwd] = useState<Record<string, any[]>>({});
+ const [codexAgentsByCwd, setCodexAgentsByCwd] = useState<Record<string, any[]>>({});
const [claudeModels, setClaudeModels] = useState<string[]>([]);
const [claudeReasoningOptions, setClaudeReasoningOptions] = useState<Record<string, { value: string; label: string }[]>>({});
const [codexModels, setCodexModels] = useState<string[]>([]);
@@ -350,6 +352,13 @@ export const UserList: React.FC = () => {
} catch (e) { console.error('Failed to load Claude agents:', e); }
};
+ const loadCodexAgents = async (cwd: string) => {
+ try {
+ const result = await api.codexAgents(cwd);
+ if (result.ok) setCodexAgentsByCwd((prev) => ({ ...prev, [cwd]: result.agents || [] }));
+ } catch (e) { console.error('Failed to load Codex agents:', e); }
+ };
+
useEffect(() => {
if (config.agents?.claude?.enabled) {
api.claudeModels().then((r) => {
@@ -375,6 +384,7 @@ export const UserList: React.FC = () => {
const backend = u.routing?.agent_backend || defaultBackend;
if (backend === 'opencode' && config.agents?.opencode?.enabled && !opencodeOptionsByCwd[cwd]) loadOpenCodeOptions(cwd);
if (backend === 'claude' && config.agents?.claude?.enabled && !claudeAgentsByCwd[cwd]) loadClaudeAgents(cwd);
+ if (backend === 'codex' && config.agents?.codex?.enabled && !codexAgentsByCwd[cwd]) loadCodexAgents(cwd);
});
}, [users, config]);
@@ -447,7 +457,15 @@ export const UserList: React.FC = () => {
custom_cwd: '',
routing: {
agent_backend: null,
+ opencode_agent: null,
+ opencode_model: null,
+ opencode_reasoning_effort: null,
+ claude_agent: null,
+ claude_model: null,
claude_reasoning_effort: null,
+ codex_agent: null,
+ codex_model: null,
+ codex_reasoning_effort: null,
},
});
@@ -533,6 +551,7 @@ export const UserList: React.FC = () => {
const effectiveBackend = userConfig.routing?.agent_backend || config.agents?.default_backend || 'opencode';
const opencodeOptions = opencodeOptionsByCwd[effectiveCwd];
const claudeAgents = claudeAgentsByCwd[effectiveCwd] || [];
+ const codexAgents = codexAgentsByCwd[effectiveCwd] || [];
return (
<div key={userId} className="p-4 hover:bg-neutral-50/50 transition-colors">
{/* User header row */}
@@ -765,7 +784,18 @@ export const UserList: React.FC = () => {
{effectiveBackend === 'codex' && (
<div className="space-y-3">
<div className="text-xs font-medium text-muted uppercase">{t('channelList.codexSettings')}</div>
- <div className="grid grid-cols-1 md:grid-cols-2 gap-3 bg-bg/50 p-3 rounded border border-border">
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-3 bg-bg/50 p-3 rounded border border-border">
+ <div className="space-y-1">
+ <label className="text-xs text-muted">{t('channelList.agent')}</label>
+ <select
+ value={userConfig.routing.codex_agent || ''}
+ onChange={(e) => updateUser(userId, { routing: { ...userConfig.routing, codex_agent: e.target.value || null } })}
+ className="w-full bg-panel border border-border rounded px-3 py-2 text-sm"
+ >
+ <option value="">{t('common.default')}</option>
+ {codexAgents.map((a: any) => <option key={a.id} value={a.id}>{a.name}</option>)}
+ </select>
+ </div>
<div className="space-y-1">
<label className="text-xs text-muted">{t('channelList.model')}</label>
<Combobox
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index f8b54ee1b..d17853275 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -35,6 +35,7 @@ export type ApiContextType = {
opencodeSetupPermission: () => Promise<{ ok: boolean; message: string; config_path: string }>;
claudeAgents: (cwd?: string) => Promise<{ ok: boolean; agents?: { id: string; name: string; path: string; source?: string }[]; error?: string }>;
claudeModels: () => Promise<{ ok: boolean; models?: string[]; reasoning_options?: Record<string, { value: string; label: string }[]>; error?: string }>;
+ codexAgents: (cwd?: string) => Promise<{ ok: boolean; agents?: { id: string; name: string; path: string; source?: string; description?: string }[]; error?: string }>;
codexModels: () => Promise<{ ok: boolean; models?: string[]; error?: string }>;
getLogs: (lines?: number, source?: string) => Promise<{ logs: LogEntry[]; total: number; source: string; sources: LogSource[] }>;
getVersion: () => Promise<VersionInfo>;
@@ -173,6 +174,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
opencodeSetupPermission: () => postJson('/opencode/setup-permission', {}),
claudeAgents: (cwd) => cwd ? getJson(`/claude/agents?cwd=${encodeURIComponent(cwd)}`) : getJson('/claude/agents'),
claudeModels: () => getJson('/claude/models'),
+ codexAgents: (cwd) => cwd ? getJson(`/codex/agents?cwd=${encodeURIComponent(cwd)}`) : getJson('/codex/agents'),
codexModels: () => getJson('/codex/models'),
getLogs: (lines = 500, source) => postJson('/logs', source ? { lines, source } : { lines }),
getVersion: () => getJson('/version'),
diff --git a/vibe/api.py b/vibe/api.py
index 650d274cb..06187ade0 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -36,6 +36,7 @@ from vibe.upgrade import (
get_running_vibe_path,
get_safe_cwd,
)
+from modules.agents.subagent_router import list_codex_subagents
logger = logging.getLogger(__name__)
@@ -1031,6 +1032,34 @@ def claude_agents(cwd: Optional[str] = None) -> dict:
return {"ok": False, "error": str(e)}
+def codex_agents(cwd: Optional[str] = None) -> dict:
+ """List available Codex custom agents (global + project)."""
+ try:
+ project_root: Optional[Path] = None
+ if cwd:
+ try:
+ project_root = Path(cwd).expanduser().resolve()
+ except Exception:
+ project_root = None
+
+ definitions = list_codex_subagents(project_root=project_root)
+ agents = [
+ {
+ "id": definition.name,
+ "name": definition.name,
+ "path": str(definition.path) if definition.path else "",
+ "source": definition.source,
+ "description": definition.description,
+ }
+ for definition in definitions.values()
+ ]
+ agents.sort(key=lambda item: (0 if item.get("source") == "project" else 1, item.get("id", "")))
+ return {"ok": True, "agents": agents}
+ except Exception as e:
+ logger.error("Failed to scan Codex agents directory: %s", e)
+ return {"ok": False, "error": str(e)}
+
+
def claude_models() -> dict:
"""Best-effort merged list of Claude Code model options.
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index ddae857ed..e6dad2887 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -78,6 +78,7 @@
"backend": "Backend",
"opencodeAgent": "OpenCode agent",
"claudeAgent": "Claude agent",
+ "codexAgent": "Codex agent",
"model": "Model",
"reasoningEffort": "Reasoning effort"
}
@@ -168,6 +169,8 @@
"claudeAgent": "Claude Agent",
"selectClaudeAgent": "Select Claude agent",
"codexSettings": "Codex Settings",
+ "codexAgent": "Codex Agent",
+ "selectCodexAgent": "Select Codex agent",
"codexReasoningEffort": "Reasoning Effort",
"tip": "Select (Default) to use the backend's configured defaults."
},
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 183be54dd..066334553 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -78,6 +78,7 @@
"backend": "后端",
"opencodeAgent": "OpenCode Agent",
"claudeAgent": "Claude Agent",
+ "codexAgent": "Codex Agent",
"model": "模型",
"reasoningEffort": "推理强度"
}
@@ -168,6 +169,8 @@
"claudeAgent": "Claude Agent",
"selectClaudeAgent": "选择 Claude Agent",
"codexSettings": "Codex 设置",
+ "codexAgent": "Codex Agent",
+ "selectCodexAgent": "选择 Codex Agent",
"codexReasoningEffort": "推理强度",
"tip": "选择“(默认)”以使用后端的配置默认值。"
},
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index aecd8a11e..ec941beb4 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -674,6 +674,21 @@ def claude_agents():
return jsonify(api.claude_agents(cwd))
[email protected]("/codex/agents", methods=["GET"])
+def codex_agents():
+ from vibe import api
+
+ cwd = request.args.get("cwd")
+ if cwd:
+ expanded = Path(cwd).expanduser()
+ if not expanded.is_absolute():
+ cwd = str(get_working_dir() / cwd)
+ else:
+ cwd = str(expanded)
+
+ return jsonify(api.codex_agents(cwd))
+
+
@app.route("/claude/models", methods=["GET"])
def claude_models():
from vibe import api
@@ -907,6 +922,7 @@ if _os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):
claude_agent=modal_values.get("claude_agent"),
claude_model=modal_values.get("claude_model"),
claude_reasoning_effort=modal_values.get("claude_reasoning_effort"),
+ codex_agent=modal_values.get("codex_agent"),
codex_model=modal_values.get("codex_model"),
codex_reasoning_effort=modal_values.get("codex_reasoning_effort"),
)
@@ -948,6 +964,7 @@ if _os.environ.get("E2E_TEST_MODE", "").lower() in ("true", "1", "yes"):
claude_agent=modal_values.get("claude_agent"),
claude_model=modal_values.get("claude_model"),
claude_reasoning_effort=modal_values.get("claude_reasoning_effort"),
+ codex_agent=modal_values.get("codex_agent"),
codex_model=modal_values.get("codex_model"),
codex_reasoning_effort=modal_values.get("codex_reasoning_effort"),
)