Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/app/api/ws/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ class ChatSendPayload(BaseModel):
force_override_bot_model_type: Optional[str] = Field(
None, description="Override model type"
)
model_options: Optional[Dict[str, str]] = Field(
model_options: Optional[Dict[str, Any]] = Field(
None,
description="Model selection options, such as reasoning or speed.",
)
Expand Down
4 changes: 2 additions & 2 deletions backend/app/schemas/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ class TaskCreate(BaseModel):
force_override_bot_model_type: Optional[str] = (
None # Model type: 'public', 'user', 'group'
)
model_options: Optional[dict[str, str]] = None
model_options: Optional[dict[str, Any]] = None
# API key name field
api_key_name: Optional[str] = None # API key name used for this request

Expand Down Expand Up @@ -185,7 +185,7 @@ class TaskDetail(BaseModel):
subtasks: Any = None
model_id: Optional[str] = None
force_override_bot_model_type: Optional[str] = None
model_options: Optional[dict[str, str]] = None
model_options: Optional[dict[str, Any]] = None
is_group_chat: bool = False # Whether this is a group chat task
is_group_owner: bool = False # Whether current user is the owner (for group chats)
member_count: Optional[int] = None # Number of members (for group chats)
Expand Down
2 changes: 1 addition & 1 deletion backend/app/services/chat/storage/task_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class TaskCreationParams:
None # Model type: 'public', 'user', 'group'
)
# Model selection options, such as reasoning or speed.
model_options: Optional[Dict[str, str]] = None
model_options: Optional[Dict[str, Any]] = None
is_group_chat: bool = False
git_url: Optional[str] = None
git_repo: Optional[str] = None
Expand Down
36 changes: 36 additions & 0 deletions backend/app/services/chat/trigger/unified.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,17 @@

logger = logging.getLogger(__name__)
SELECTED_KB_PRELOAD_SKILL = "wegent-knowledge"
SERVICE_TIER_ALIASES = {
"fast": "priority",
"priority": "priority",
"快速": "priority",
"运行快速": "priority",
"standard": "default",
"default": "default",
"普通": "default",
"标准": "default",
"运行标准": "default",
}


def _reasoning_from_model_options(payload: Any) -> Optional[Dict[str, Any]]:
Expand Down Expand Up @@ -65,6 +76,23 @@ def _reasoning_from_model_options(payload: Any) -> Optional[Dict[str, Any]]:
return result or None


def _service_tier_from_model_options(payload: Any) -> Optional[str]:
"""Convert UI speed options into Codex service tier values."""
if payload is None:
return None
model_options = getattr(payload, "model_options", None)
if not isinstance(model_options, dict):
return None

speed = model_options.get("speed") or model_options.get("service_tier")
if isinstance(speed, dict):
speed = speed.get("value") or speed.get("speed") or speed.get("service_tier")
if not speed:
return None

return SERVICE_TIER_ALIASES.get(str(speed).strip().lower())


def _build_executor_attachment_payload(context: Any) -> dict[str, Any]:
"""Serialize an attachment context for executor-side downloading."""
return {
Expand Down Expand Up @@ -319,6 +347,14 @@ async def build_execution_request(
request.model_config["think_config"],
)

selected_service_tier = _service_tier_from_model_options(payload)
if selected_service_tier:
request.model_config["service_tier"] = selected_service_tier
logger.info(
"[build_execution_request] Applied selected service tier: %s",
selected_service_tier,
)

# Store reasoning_config in ExecutionRequest for downstream access
request.reasoning_config = (
selected_reasoning_config or request.model_config.get("reasoning")
Expand Down
27 changes: 27 additions & 0 deletions backend/tests/services/chat/test_reasoning_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,30 @@ def test_model_options_reasoning_object_maps_effort_and_summary(self):
"effort": "high",
"summary": "concise",
}

@pytest.mark.parametrize(
("speed", "service_tier"),
[
("fast", "priority"),
("快速", "priority"),
("standard", "default"),
("标准", "default"),
],
)
def test_model_options_speed_maps_to_service_tier(self, speed, service_tier):
"""Test UI speed options map to Codex service tier values."""
from app.services.chat.trigger.unified import _service_tier_from_model_options

payload = MagicMock()
payload.model_options = {"speed": speed}

assert _service_tier_from_model_options(payload) == service_tier

def test_model_options_speed_object_maps_to_service_tier(self):
"""Test object-shaped UI speed maps to Codex service tier values."""
from app.services.chat.trigger.unified import _service_tier_from_model_options

payload = MagicMock()
payload.model_options = {"speed": {"value": "fast"}}

assert _service_tier_from_model_options(payload) == "priority"
14 changes: 14 additions & 0 deletions docs/en/user-guide/ai-devices/local-device-support.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,20 @@ curl -fL -o wegent-executor \
chmod +x wegent-executor
```

#### Use Device-Local CLI Configuration

By default, the executor uses the Claude/Codex model and provider configuration issued by Wegent. If a device already has local Codex CLI login or provider configuration, set this environment variable to let Codex use the device-local configuration:

```bash
WEGENT_LOCAL_CLI_CONFIG_RUNTIMES=codex
```

When the variable is empty or unset, all runtimes keep using the system-issued configuration. The currently supported value is:

- `codex`: Codex uses device-local configuration, and Wegent no longer injects the Codex provider.

This setting only affects the current device, which is useful when different devices should mix system-issued configuration and local Codex CLI configuration differently. Claude keeps using Wegent-issued configuration.

### Building a Device Image

The repository provides `docker/device/Dockerfile` for cloud device or local device base images. The image installs `code-server`, the `weiboplat.wecoder-agent` extension, Claude Code CLI, `ttyd`, Node.js 22, Python, Git, and copies `executor/dist/wegent-executor` to `/app/executor` and `~/.wegent-executor/bin/wegent-executor`.
Expand Down
14 changes: 14 additions & 0 deletions docs/zh/user-guide/ai-devices/local-device-support.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,20 @@ curl -fL -o wegent-executor \
chmod +x wegent-executor
```

#### 使用设备本机 CLI 配置

默认情况下,executor 会使用 Wegent 下发的 Claude/Codex 模型和 provider 配置。如果某台设备已经在本机配置好了 Codex CLI 登录或 provider,可以通过环境变量让 Codex 使用本机配置:

```bash
WEGENT_LOCAL_CLI_CONFIG_RUNTIMES=codex
```

该变量为空或未设置时,所有 runtime 都继续使用系统下发配置。当前仅支持以下值:

- `codex`:Codex 使用设备本机配置,不再注入 Wegent Codex provider。

该配置只影响当前设备,适合不同设备分别使用系统下发配置或本机 Codex CLI 配置的场景。Claude 仍保持 Wegent 下发的配置行为。

### 构建设备镜像

仓库提供 `docker/device/Dockerfile` 用于构建云设备或本地设备基础镜像。该镜像会安装 `code-server`、`weiboplat.wecoder-agent` 扩展、Claude Code CLI、`ttyd`、Node.js 22、Python、Git,并把 `executor/dist/wegent-executor` 放到 `/app/executor` 和 `~/.wegent-executor/bin/wegent-executor`。
Expand Down
43 changes: 20 additions & 23 deletions executor/agents/codex/codex_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,36 +200,23 @@ async def _start_codex_client(self) -> None:
await self._codex.__aenter__()

async def _open_thread(self) -> None:
from openai_codex import ApprovalMode

assert self.codex_config is not None
thread_id = self._session_store.load(
self.task_id,
self._bot_id,
self.new_session,
)
developer_instructions = self._build_developer_instructions()
thread_kwargs = self._build_thread_kwargs(developer_instructions)
try:
if thread_id:
self._thread = await self._codex.thread_resume(
thread_id,
approval_mode=ApprovalMode.deny_all,
config=self.codex_config.thread_config,
cwd=self.project_path,
developer_instructions=developer_instructions,
model=self.codex_config.model,
model_provider=self.codex_config.model_provider,
sandbox=self._sandbox_full_access(),
**thread_kwargs,
)
else:
self._thread = await self._codex.thread_start(
approval_mode=ApprovalMode.deny_all,
config=self.codex_config.thread_config,
cwd=self.project_path,
developer_instructions=developer_instructions,
model=self.codex_config.model,
model_provider=self.codex_config.model_provider,
sandbox=self._sandbox_full_access(),
**thread_kwargs,
service_name="wegent",
)
except Exception:
Expand All @@ -239,17 +226,27 @@ async def _open_thread(self) -> None:
"Failed to resume Codex thread %s, starting a new one", thread_id
)
self._thread = await self._codex.thread_start(
approval_mode=ApprovalMode.deny_all,
config=self.codex_config.thread_config,
cwd=self.project_path,
developer_instructions=developer_instructions,
model=self.codex_config.model,
model_provider=self.codex_config.model_provider,
sandbox=self._sandbox_full_access(),
**thread_kwargs,
service_name="wegent",
)
self._session_store.save(self.task_id, self._bot_id, self._thread.id)

def _build_thread_kwargs(self, developer_instructions: str) -> dict[str, Any]:
from openai_codex import ApprovalMode

assert self.codex_config is not None
kwargs = {
"approval_mode": ApprovalMode.deny_all,
"config": self.codex_config.thread_config,
"cwd": self.project_path,
"developer_instructions": developer_instructions,
"model": self.codex_config.model,
"sandbox": self._sandbox_full_access(),
}
if self.codex_config.model_provider:
kwargs["model_provider"] = self.codex_config.model_provider
return kwargs

async def _notify_client_created(self) -> None:
if not self.on_client_created_callback:
return
Expand Down
94 changes: 79 additions & 15 deletions executor/agents/codex/config_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,43 @@

from executor.agents.env_value import resolve_env_value
from executor.config import config
from executor.config.local_cli_config import use_local_cli_config
from shared.logger import setup_logger

OPENAI_RESPONSES_PROTOCOL = "openai-responses"
RESPONSES_WIRE_API = "responses"
DEFAULT_PROVIDER_NAME = "wecode openai"
CODEX_REASONING_EFFORTS = {"none", "minimal", "low", "medium", "high", "xhigh"}
CODEX_REASONING_SUMMARIES = {"auto", "concise", "detailed"}
DEFAULT_REASONING_EFFORT = "medium"
REASONING_EFFORT_ALIASES = {
"": DEFAULT_REASONING_EFFORT,
"none": DEFAULT_REASONING_EFFORT,
"off": DEFAULT_REASONING_EFFORT,
"false": DEFAULT_REASONING_EFFORT,
"disabled": DEFAULT_REASONING_EFFORT,
"关闭": DEFAULT_REASONING_EFFORT,
"低": "low",
"中": "medium",
"中等": "medium",
"高": "high",
"超高": "xhigh",
"最高": "xhigh",
"extra_high": "xhigh",
"ultra": "xhigh",
"x-high": "xhigh",
}
Comment on lines +25 to +41

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Keep “reasoning unset/off” separate from the fallback path.

Lines 207-223 currently turn both omitted reasoning and explicit disable values (none, off, disabled, 关闭) into model_reasoning_effort=medium. That means every Codex thread now gets an explicit reasoning override, even when the caller wanted no override or explicitly turned reasoning off. It also contradicts Line 22, where "none" is still treated as a valid Codex effort.

Suggested fix
 def _normalize_reasoning(value: Any) -> dict[str, str]:
+    if value is None:
+        return {}
+
     if isinstance(value, str):
         effort = value
         summary = None
     elif isinstance(value, dict):
         effort = value.get("effort") or value.get("reasoning")
         summary = value.get("summary")
         if isinstance(effort, dict):
             summary = summary or effort.get("summary")
             effort = effort.get("effort") or effort.get("reasoning")
     else:
-        return {"effort": DEFAULT_REASONING_EFFORT}
+        return {}

     effort_value = _normalize_reasoning_effort(effort)
-    result: dict[str, str] = {"effort": effort_value}
+    result: dict[str, str] = {}
+    if effort_value is not None:
+        result["effort"] = effort_value
     if summary:
         summary_value = str(summary).lower()
         if summary_value in CODEX_REASONING_SUMMARIES:
             result["summary"] = summary_value
     return result


-def _normalize_reasoning_effort(value: Any) -> str:
+def _normalize_reasoning_effort(value: Any) -> Optional[str]:
     normalized = str(value or "").strip().lower()
+    if normalized in {"", "off", "false", "disabled", "关闭"}:
+        return None
     aliased = REASONING_EFFORT_ALIASES.get(normalized, normalized)
-    if aliased in CODEX_REASONING_EFFORTS and aliased != "none":
+    if aliased in CODEX_REASONING_EFFORTS:
         return aliased
     return DEFAULT_REASONING_EFFORT

Also applies to: 196-223

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@executor/agents/codex/config_builder.py` around lines 25 - 41,
REASONING_EFFORT_ALIASES currently maps omitted/explicit-off keys
("none","off","disabled","关闭") to DEFAULT_REASONING_EFFORT causing explicit
overrides; change those entries to a distinct sentinel (e.g., None or "unset")
instead of DEFAULT_REASONING_EFFORT in REASONING_EFFORT_ALIASES, and update the
logic that computes model_reasoning_effort to treat that sentinel as "no
override" (leave unset) while still falling back to DEFAULT_REASONING_EFFORT
only when the alias is the empty string or truly missing; reference
REASONING_EFFORT_ALIASES, DEFAULT_REASONING_EFFORT and the code paths that
assign model_reasoning_effort to implement this separation.

SERVICE_TIER_ALIASES = {
"fast": "priority",
"priority": "priority",
"快速": "priority",
"运行快速": "priority",
"standard": "default",
"default": "default",
"普通": "default",
"标准": "default",
"运行标准": "default",
}

logger = setup_logger("codex_config_builder")

Expand All @@ -30,7 +60,7 @@ class CodeXConfig:

codex_bin: str
model: str
model_provider: str
model_provider: Optional[str]
config_overrides: tuple[str, ...]
thread_config: dict[str, Any]
effort: Optional[str]
Expand All @@ -57,6 +87,21 @@ def build_codex_config(model_config: dict[str, Any]) -> CodeXConfig:
if not model:
raise ValueError("CodeXAgent requires model_config.model_id")

local_config = use_local_cli_config("codex")
reasoning = _normalize_reasoning(model_config.get("reasoning"))
service_tier = _normalize_service_tier(model_config.get("service_tier"))
if local_config:
overrides = [f"model={model}"]
return CodeXConfig(
codex_bin=_resolve_codex_binary(config.CODEX_BINARY_PATH),
model=model,
model_provider=None,
config_overrides=tuple(overrides),
thread_config=_build_thread_config(reasoning, service_tier),
effort=reasoning.get("effort"),
summary=reasoning.get("summary"),
)

base_url = str(model_config.get("base_url") or "").strip()
if not base_url:
raise ValueError("CodeXAgent requires model_config.base_url")
Expand All @@ -69,7 +114,6 @@ def build_codex_config(model_config: dict[str, Any]) -> CodeXConfig:

model_provider = _resolve_model_provider(model_config)
wire_api = _resolve_wire_api(model_config)
reasoning = _normalize_reasoning(model_config.get("reasoning"))

overrides = [
"forced_login_method=api",
Expand All @@ -81,23 +125,30 @@ def build_codex_config(model_config: dict[str, Any]) -> CodeXConfig:
f"model_providers.{model_provider}.experimental_bearer_token={api_key}",
]

thread_config: dict[str, Any] = {}
if reasoning.get("effort"):
thread_config["model_reasoning_effort"] = reasoning["effort"]
if reasoning.get("summary"):
thread_config["model_reasoning_summary"] = reasoning["summary"]

return CodeXConfig(
codex_bin=_resolve_codex_binary(config.CODEX_BINARY_PATH),
model=model,
model_provider=model_provider,
config_overrides=tuple(overrides),
thread_config=thread_config,
thread_config=_build_thread_config(reasoning, service_tier),
effort=reasoning.get("effort"),
summary=reasoning.get("summary"),
)


def _build_thread_config(
reasoning: dict[str, str], service_tier: Optional[str]
) -> dict[str, Any]:
thread_config: dict[str, Any] = {}
if reasoning.get("effort"):
thread_config["model_reasoning_effort"] = reasoning["effort"]
if reasoning.get("summary"):
thread_config["model_reasoning_summary"] = reasoning["summary"]
if service_tier:
thread_config["service_tier"] = service_tier
return thread_config


def _resolve_model_provider(model_config: dict[str, Any]) -> str:
provider = (
model_config.get("codex_model_provider")
Expand Down Expand Up @@ -153,15 +204,28 @@ def _normalize_reasoning(value: Any) -> dict[str, str]:
summary = summary or effort.get("summary")
effort = effort.get("effort") or effort.get("reasoning")
else:
return {}
return {"effort": DEFAULT_REASONING_EFFORT}

result: dict[str, str] = {}
if effort:
effort_value = str(effort).lower()
if effort_value in CODEX_REASONING_EFFORTS:
result["effort"] = effort_value
effort_value = _normalize_reasoning_effort(effort)
result: dict[str, str] = {"effort": effort_value}
if summary:
summary_value = str(summary).lower()
if summary_value in CODEX_REASONING_SUMMARIES:
result["summary"] = summary_value
return result


def _normalize_reasoning_effort(value: Any) -> str:
normalized = str(value or "").strip().lower()
aliased = REASONING_EFFORT_ALIASES.get(normalized, normalized)
if aliased in CODEX_REASONING_EFFORTS and aliased != "none":
return aliased
return DEFAULT_REASONING_EFFORT


def _normalize_service_tier(value: Any) -> Optional[str]:
if isinstance(value, dict):
value = value.get("value") or value.get("speed") or value.get("service_tier")
if not value:
return None
return SERVICE_TIER_ALIASES.get(str(value).strip().lower())
Loading
Loading