Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
ae72be2
feat(codex): show Smart Router state in experimental footer
masonc08 Nov 17, 2026
ae88c65
fix(codex): keep footer available for nullable snapshots
masonc08 Nov 17, 2026
1d03365
docs(codex): distinguish native onboarding from footer preferences
masonc08 Nov 17, 2026
880b2f9
fix(codex): match Claude Smart Router state badges
masonc08 Nov 18, 2026
a2c7ffe
Merge remote-tracking branch 'origin/main' into masonc08/codex-smart-…
masonc08 Nov 18, 2026
a8c681b
fix(codex): exclude working directory from footer imports
masonc08 Nov 18, 2026
bdba928
Merge remote-tracking branch 'origin/main' into masonc08/codex-smart-…
masonc08 Nov 20, 2026
cb9fc5f
feat(codex): require stable 0.171.0 for Smart Router footer
masonc08 Nov 20, 2026
34fc74b
test(codex): close upgrade-check terminal through PTY interface
masonc08 Nov 20, 2026
baaf4ab
feat(codex): require stable 0.171.0 for routed launches
masonc08 Nov 20, 2026
347c447
chore: stack Smart Router indicator on required Codex upgrade
masonc08 Nov 20, 2026
7e264b8
fix(codex): preserve managed routing fallback after skipped upgrade
masonc08 Nov 20, 2026
9ad4f0d
Merge branch 'masonc08/codex-stable-upgrade' into masonc08/codex-smar…
masonc08 Nov 20, 2026
258edb2
docs(codex): describe managed upgrade fallback for footer launches
masonc08 Nov 20, 2026
b8341b3
fix(ci): align Codex pins and verify encrypted native task delivery
masonc08 Nov 20, 2026
d95da72
Merge branch 'masonc08/codex-stable-upgrade' into masonc08/codex-smar…
masonc08 Nov 20, 2026
57c3df6
test(codex): match native task transport and guarded toggle recovery
masonc08 Nov 20, 2026
42ffa30
fix(codex): keep footer tool out of model declarations
masonc08 Nov 20, 2026
c9a1e77
Merge branch 'masonc08/codex-stable-upgrade' into masonc08/codex-smar…
masonc08 Nov 20, 2026
b94ff30
test(codex): opt native catalog into plaintext code-mode scenario
masonc08 Nov 20, 2026
130840b
Merge branch 'masonc08/codex-stable-upgrade' into masonc08/codex-smar…
masonc08 Nov 20, 2026
1d052fe
Merge main into Codex stable upgrade
masonc08 Nov 20, 2026
2456c3b
Merge updated stable upgrade into Smart Router indicator
masonc08 Nov 20, 2026
b9f5a13
Merge main after Codex stable upgrade lands
masonc08 Nov 20, 2026
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
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,7 @@ Fields live in `~/.codex/ucode.config.toml` and `/etc/codex/managed_config.toml`
| `mcp_servers` | Ignore | Merge | Managed file; add/update the config's MCP server entries, other entries left alone. A same-name entry in `~/.codex/config.toml` of the other transport (stdio vs HTTP) is removed, since Codex would merge the two into an invalid entry |
| Smart Router and Smart Router Orchestrator hooks | Merge | Merge | Launch-only `PreToolUse`, plus `UserPromptSubmit` and compact `SessionStart` with `ENABLE_SMART_ROUTER_ORCHESTRATOR=1`; Codex combines them with its native hook sources and applies project trust; `features.hooks` is enabled for a smart-routed launch |
| Native v2 collaboration | Launch-only (-c), never written | Launch-only (-c), never written | `features.multi_agent_v2.non_code_mode_only=false` and matching `root_agent_usage_hint_text` / `subagent_usage_hint_text` override saved values for the session; only for smart routing on Codex 0.171.0 or newer. User config files, general developer instructions, and native delegation-mode controls are preserved |
| Smart Router footer | Launch-only (-c), never written | Launch-only (-c), never written | On routed Codex 0.171.0 or newer, enable `features.tui_extensions_statusline`, select `tui.status_line_provider`, and add only `mcp_servers.ug-smart-router-statusline`. The app-server owns the session-local stdio provider; the terminal client receives the feature and selection overrides. Routed launches require stable 0.171.0 or newer through the existing upgrade gate. Saved footer settings and unrelated MCP servers are preserved. The footer relies on that launch gate; do not add a second version probe |
| Smart Router native metadata | Launch-only (-c), never written | Launch-only (-c), never written | `responses_api_metadata.smart_router_recipe_name` records the configured recipe. The app-server interposer updates `smart_router_state` per main turn; spawn hooks stamp child task names. Reserve the state key for the interposer; a static config value would override turn updates |

</details>
Expand Down
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -778,6 +778,23 @@ bypass `spawn_agent` have no guaranteed marker. Reserve `smart_router_state` for
per-turn metadata; a static Codex `responses_api_metadata` entry with that name
would override dynamic values.

Routed Codex terminal sessions show `smart router` with a green `ON` or gray `OFF`
badge beside the current model, directory, and remaining context. The indicator
stays visible when routing is off, as Claude's prompt hint does. The MCP status-line
provider API ships in stable Codex 0.171.0 and still requires its experimental
feature flag, which UG supplies for that launch.

The indicator reads the same session controls as routing on each refresh, including
after `$smart-router off` and `$smart-router on`. Unreadable controls show
`smart router UNKNOWN` until a later refresh succeeds. Each launch has its own
local provider and controls file. UG enables and selects its footer for that launch
only; saved status-line settings and other MCP servers are preserved. The selected
footer replaces the normal footer's item layout for that session. This does not add
an indicator to the Codex desktop app or other app-server clients.

For validation and upgrade behavior, see
[Codex Smart Router footer](docs/codex-smart-router-statusline.md).

### Smart Router Orchestrator

Use `SMART_ROUTER_CONFIG_VERSION` at launch to select a smart-routing configuration.
Expand Down
90 changes: 90 additions & 0 deletions docs/codex-smart-router-statusline.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Codex Smart Router footer

The terminal footer uses the experimental MCP status-line provider API first
shipped in stable Codex `0.171.0`. UG registers a local stdio provider for each
routed launch and selects it in the terminal client. Both configurations are
launch-only. The provider needs no gateway credentials or network access.
Its MCP tool is visible only to the app, so it is excluded from model-facing tool declarations.

The indicator reflects the latest session controls, rather than a turn's original
routing attribution. Existing children and an ongoing main turn keep their original
attribution after a toggle. A failed controls read shows `UNKNOWN` without stopping
Codex's polling, so the next successful read can recover.

The state badge matches Claude's Smart Router banner: bold black `ON` on green,
or bold black `OFF` on gray. Claude keeps an ON/OFF hint below the prompt after its
temporary banner disappears; disabling routing does not hide that hint. Codex keeps
the badge in its persistent footer, since this API only controls the footer.

## Validation

Install the checkout in an isolated Python environment and use Codex
`0.171.0` on that environment's PATH. Do not replace the user's
installation as part of automated tests. Check both `codex --version` and `ug --version`.

Run the offline checks:

```bash
uv run pytest tests/test_codex_statusline.py tests/test_codex_smart_routing_v2.py \
tests/test_codex_metadata.py tests/test_agent_codex.py tests/test_smart_router.py \
tests/test_smart_routing_config.py tests/test_integration_contract.py
just lint
```

For a configured test workspace and an explicitly selected profile:

1. Launch `SMART_ROUTER_CONFIG_VERSION=subagent_only_v0 ug codex`. Check the
native footer shows `smart router` with a green `ON` badge alongside model and project directory.
2. Ask Codex to read a file containing an unpredictable value. Require the correct
value in its completed answer, rather than accepting a startup banner as inference.
3. Submit `$smart-router off`. After the command succeeds, require a gray `OFF`
badge in the footer without restarting the conversation. The indicator stays visible.
4. Submit `$smart-router on` and require `smart router ON` again. Complete another
file task in the same conversation.
5. Open a second session. Toggle one and check the other session's footer is unchanged.
6. Repeat with `first_prompt_and_subagent_no_orch_v0` and complete an initial prompt.
7. Repeat on Windows. Confirm both the app-server and remote terminal receive the
correct configuration, including when paths contain spaces.
8. Compare saved footer preferences and MCP registrations before and after.
Codex may add its own trust and onboarding records, such as
`tui.screen_reader_detection_done`; compare `tui.status_line` and
`tui.status_line_provider` independently of that bookkeeping.
9. With an older client and explicit routing selected, verify the upgrade gate blocks
routed launch until the upgrade succeeds. With managed routing and no explicit
selection, decline the upgrade and require a warning, a completed task, and no footer.
`--disable-smart-routing` retains ordinary launch behavior.

Existing native routing journeys can be run with pinned stable Codex through
`scripts/run_integration.py --ug-version checkout --codex-version 0.171.0
--profile <selected-profile> --workspace <test-workspace> -- -k routing_toggle`.
Those journeys verify inference and session continuity; the footer assertions above
are additional manual UI checks.

## Stable validation

On 2026-11-20, native Linux Codex `0.171.0` passed ON/OFF/ON badge rendering and
UNKNOWN/read recovery. An isolated-wheel Arclet run against the supplied workspace
completed five hidden-file tasks across two concurrent sessions and a first-prompt
launch, with installed-skill toggles, unchanged conversation identity, independent
controls, and unchanged saved footer settings and UG profile. GPT-6-Luna was selected
through ordinary user settings. Seven installation checks passed.

The initial first-prompt routing check returned HTTP 400/downstream 422 and fell
back; its delegated file tasks completed without a recorded routing decision.
Later live Arclet ON/OFF/ON and managed-routing journeys passed with correlated
child-model selection. A separate native plaintext journey verified the exact
assignment and digest at the hook and child. Native Linux and Windows routing CI
subsequently passed. Manual badge-rendering validation remains Linux-only.

## Required upgrade

Routed launches require stable Codex `0.171.0` or newer. Earlier builds, including
`0.171.0-alpha.*`, must pass the existing native upgrade flow before starting.
Declining or failing the upgrade blocks routed launch; `--disable-smart-routing`
keeps ordinary launch behavior. `UG_AUTO_UPGRADE_AGENT=1` selects automatic upgrade.
When routing comes from the managed default, an unsuccessful upgrade instead warns
and continues without routing or the footer, with no extra launch flag required.
The footer is registered after that launch gate, without a second version probe.

Upstream contract and starter:
[create-statusline](https://github.com/openai/codex/blob/rust-v0.171.0/codex-rs/skills/src/assets/samples/create-statusline/SKILL.md).
174 changes: 174 additions & 0 deletions src/ucode/smart_routing/codex_statusline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
"""Session-local MCP footer for Codex's experimental status line providers."""

from __future__ import annotations

import json
import os
import sys
from pathlib import Path, PurePosixPath, PureWindowsPath
from typing import Any, TextIO

from ucode.smart_routing.session_env import SESSION_ENV_VAR, session_routing_enabled

SERVER_NAME = "ug-smart-router-statusline"
TOOL_NAME = "statusline"
RESOURCE_URI = "ui://ug-smart-router/footer"
STATE_META_KEY = "com.openai/codex-statusline-state"
TOOL = {
"name": TOOL_NAME,
"title": "Unity Gateway Smart Router",
"description": "Show this session's Smart Router state in the Codex footer.",
"inputSchema": {"type": "object", "properties": {}},
"annotations": {"readOnlyHint": True},
"_meta": {
"ui": {"visibility": ["app"]},
"openai/ui": {"entrypoints": [{"type": "statusline", "resourceUri": RESOURCE_URI}]},
},
}


def launch_config(controls: Path) -> dict:
return {
"features.tui_extensions_statusline": True,
"tui.status_line_provider": {"server": SERVER_NAME, "tool": TOOL_NAME},
Comment thread
masonc08 marked this conversation as resolved.
Resolved
"mcp_servers": {
SERVER_NAME: {
"command": sys.executable,
"args": ["-P", "-X", "utf8", "-m", __name__],
"env": {SESSION_ENV_VAR: str(controls)},
"enabled": True,
}
},
}


def tui_config(config: dict) -> dict:
return {
key: config[key]
for key in ("features.tui_extensions_statusline", "tui.status_line_provider")
if key in config
}


def _object(value: Any) -> dict:
return value if isinstance(value, dict) else {}


def _text(value: str, color: str) -> dict:
return {"type": "text", "props": {"color": color}, "children": [value]}


def _router_indicator(label: str) -> dict:
if label == "UNKNOWN":
return _text("smart router UNKNOWN", "yellow")
badge = {
"type": "row",
"props": {"gap": 0, "background": "green" if label == "ON" else "#808080"},
"children": [
{
"type": "text",
"props": {"color": "black", "weight": "bold"},
"children": [f" {label} "],
}
],
}
return {
"type": "row",
"props": {"gap": 1},
"children": [_text("smart router", "primary"), badge],
}


def render(state: dict[str, Any]) -> dict:
controls = os.environ.get(SESSION_ENV_VAR)
try:
if not controls:
raise ValueError("No session controls")
enabled = session_routing_enabled(Path(controls), retry=False)
label = "ON" if enabled else "OFF"
except (OSError, UnicodeError, ValueError):
label = "UNKNOWN"

thread = _object(_object(state).get("thread"))
model = _object(thread.get("model"))
model_name = model.get("display_name") or model.get("id") or "Codex"
if model.get("reasoning_level"):
model_name += " " + model["reasoning_level"]
Comment thread
masonc08 marked this conversation as resolved.
Resolved
children = [_router_indicator(label), _text(model_name, "status-model")]
cwd = _object(thread.get("workspace")).get("cwd")
if cwd:
path = PureWindowsPath(cwd) if "\\" in cwd else PurePosixPath(cwd)
children.append(_text(path.name or str(path), "status-path"))
used = _object(_object(thread.get("usage")).get("context")).get("used_percentage")
if isinstance(used, (int, float)) and not isinstance(used, bool):
remaining = max(0, min(100, round(100 - used)))
children.append(_text(f"{remaining}% context left", "status-usage"))
separated: list = []
for child in children:
if separated:
separated.append("·")
separated.append(child)
return {"type": "row", "props": {"gap": 1, "wrap": "wrap"}, "children": separated}


def respond(method: str, params: dict) -> dict:
if method == "initialize":
return {
"protocolVersion": "2025-06-18",
"capabilities": {"tools": {}, "resources": {}},
"serverInfo": {"name": SERVER_NAME, "version": "1.0.0"},
}
if method == "ping":
return {}
if method == "tools/list":
return {"tools": [TOOL]}
if method == "tools/call":
if params.get("name") != TOOL_NAME:
raise ValueError("Unknown tool")
return {"content": [{"type": "text", "text": f"Footer resource: {RESOURCE_URI}"}]}
if method == "resources/list":
return {
"resources": [{"name": "footer", "uri": RESOURCE_URI, "mimeType": "application/json"}]
}
if method == "resources/templates/list":
return {"resourceTemplates": []}
if method == "resources/read":
if params.get("uri") != RESOURCE_URI:
raise ValueError("Unknown resource")
state = params.get("_meta", {}).get(STATE_META_KEY, {})
return {
"contents": [
{
"uri": RESOURCE_URI,
"mimeType": "application/json",
"text": json.dumps(render(state)),
}
]
}
raise KeyError(method)


def serve(stdin: TextIO, stdout: TextIO) -> None:
for line in stdin:
reply: dict = {"jsonrpc": "2.0", "id": None}
try:
request = json.loads(line)
if not isinstance(request, dict) or not isinstance(request.get("method"), str):
reply["error"] = {"code": -32600, "message": "Invalid request"}
elif "id" not in request:
continue
else:
reply["id"] = request["id"]
reply["result"] = respond(request["method"], request.get("params", {}))
except json.JSONDecodeError:
reply["error"] = {"code": -32700, "message": "Parse error"}
except KeyError:
reply["error"] = {"code": -32601, "message": "Method not found"}
except (TypeError, ValueError, AttributeError):
reply["error"] = {"code": -32602, "message": "Invalid parameters"}
stdout.write(json.dumps(reply) + "\n")
stdout.flush()


if __name__ == "__main__":
serve(sys.stdin, sys.stdout)
4 changes: 2 additions & 2 deletions src/ucode/smart_routing/session_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ def _read_with_retry(path: Path) -> dict[str, str]:
time.sleep(CONTROLS_READ_RETRY_SECONDS)


def session_routing_enabled(path: Path) -> bool:
overrides = _read_with_retry(path)
def session_routing_enabled(path: Path, *, retry: bool = True) -> bool:
overrides = _read_with_retry(path) if retry else _read(path)
return not all(
overrides.get(key) == "0"
for key in (ENABLE_SMART_ROUTING_ENV_VAR, ENABLE_SUBAGENT_ROUTING_ENV_VAR)
Expand Down
14 changes: 12 additions & 2 deletions src/ucode/smart_routing/v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
install_skill,
uninstall_agent_skill,
)
from ucode.smart_routing import claude_routing, orchestrator, routing, session_log
from ucode.smart_routing import claude_routing, codex_statusline, orchestrator, routing, session_log
from ucode.smart_routing.claude_hooks import (
FIRST_PROMPT_SOCKET_ENV,
ROUTE_SUBAGENT_MOD_EVENT,
Expand Down Expand Up @@ -1151,6 +1151,8 @@ def launch_codex(
overlay[f"shell_environment_policy.set.{SESSION_PYTHON_ENV_VAR}"] = os.environ[
SESSION_PYTHON_ENV_VAR
]
statusline_config = codex_statusline.launch_config(session_env_path)
config_io.deep_merge_dict(overlay, statusline_config)
config_args = codex_config_args(overlay)
Comment thread
masonc08 marked this conversation as resolved.
Resolved
if app_server_launch:
# The caller owns this app-server's address, model and clients, so run its command as is.
Expand Down Expand Up @@ -1206,7 +1208,15 @@ def launch_codex(
)
model_args = [] if has_explicit_model_arg(tool_args) else ["--model", start_model]
tui = subprocess_cross_os.popen(
[binary, *provider_args, "--remote", tui_url, *model_args, *tool_args]
[
binary,
*provider_args,
*codex_config_args(codex_statusline.tui_config(statusline_config)),

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.

other · low
what happens to a user's own tui.status_line / provider? this -c override silently replaces it on every smart-routed launch. can we keep theirs, or note it in AGENTS.md's Codex launch-only table?

"--remote",
tui_url,
*model_args,
*tool_args,
]
)
try:
returncode = tui.wait()
Expand Down
8 changes: 8 additions & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# Test suites and user journeys

`test_codex_statusline.py` covers live control-file reads, Claude-style green ON/gray
OFF badges, ON/OFF/UNKNOWN recovery, nullable snapshots, MCP advertisement and
protocol errors, and two real stdio providers using Python's `-P` flag.
`test_codex_smart_routing_v2.py` also checks the footer's POSIX/Windows app-server
registration, terminal selection, and preservation of unrelated MCP entries.
Native UI and credentialed gateway validation are separate, as described in the
[validation guide](../docs/codex-smart-router-statusline.md).

The Codex smart-routing floor is stable 0.171.0. `test_agent_codex.py` covers the
stable boundary, prerelease rejection at the minimum, and slow-probe recovery.
`test_codex_smart_routing_v2.py` and `test_cli.py` cover explicit/managed upgrade
Expand Down
9 changes: 9 additions & 0 deletions tests/integration/README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# Integration tests

The Codex footer has offline protocol, process-isolation, and launcher coverage in
`../test_codex_statusline.py` and `../test_codex_smart_routing_v2.py`. Those component
checks cover green ON/gray OFF badges, nullable snapshots, Python's `-P` provider
launch flag, and terminal config isolation. Native checks must verify badge colors
and ON/OFF text; OFF stays visible, matching Claude's persistent hint. See the
[footer validation steps](../../docs/codex-smart-router-statusline.md). A native
footer or resource read alone does not establish gateway inference or routed-child
coverage. Windows native footer rendering remains untested.

Routing CI pins stable Codex 0.171.0. Component checks in `../test_agent_codex.py`,
`../test_codex_smart_routing_v2.py`, and `../test_cli.py` cover the required version,
explicit/managed upgrades, refusal/failure, and routing disable. The managed-default
Expand Down
Loading
Loading