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
1 change: 1 addition & 0 deletions desktop/src-tauri/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ pub fn project(
"hermes",
"hooks",
"plugin",
"plugin_runtime",
"profile",
"package",
"skill",
Expand Down
21 changes: 21 additions & 0 deletions desktop/src-tauri/tests/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,24 @@ fn memory_protocol_checks_survive_projection_without_private_details() {
assert!(!output.contains("secret-token"));
}
}

#[test]
fn codex_doctor_report_projects_every_check_it_emits() {
// Python's test_desktop_fixture_holds_every_codex_doctor_check keeps this fixture in step with Codex doctor.
let fixture = include_bytes!("fixtures/doctor-codex.json");
let report = project(DiagnosticKind::Integrations, fixture, 1).unwrap();
let source: serde_json::Value = serde_json::from_slice(fixture).unwrap();
let emitted = source["hosts"]["codex"]["checks"].as_object().unwrap();

assert_eq!(report.hosts.len(), 1);
let projected: Vec<_> = report.hosts[0]
.checks
.iter()
.map(|check| check.field.as_str())
.collect();
assert_eq!(projected.len(), emitted.len());
assert!(projected.contains(&"plugin_runtime"));
let output = serde_json::to_string(&report).unwrap();
assert!(!output.contains("plugin environment is ready"));
assert!(!output.contains("/usr/bin/codex"));
}
76 changes: 76 additions & 0 deletions desktop/src-tauri/tests/fixtures/doctor-codex.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
{
"ok": false,
"hosts": {
"codex": {
"status": "failed",
"checks": {
"codex": {
"ok": true,
"status": "ok",
"detail": "/usr/bin/codex"
},
"mcp_full_profile": {
"ok": false,
"status": "degraded",
"detail": "Full-profile tools unavailable: generate_experience; upgrade the Server and refresh the plugin, then open a new Codex session"
},
"plugin": {
"ok": true,
"status": "ok",
"detail": "powercontext@powercontext enabled=True"
},
"plugin_runtime": {
"ok": true,
"status": "ok",
"detail": "plugin environment is ready"
},
"mcp_configuration": {
"ok": true,
"status": "ok",
"detail": "native HTTP MCP enabled with environment overrides; auth_status=unsupported"
},
"authorization": {
"ok": true,
"status": "ok",
"detail": "no host authorization is configured; the native probe will verify an unauthenticated connection",
"checks": {
"current_process": "not_configured",
"setup_managed": "not_configured",
"desktop_restart": "not_applicable"
}
},
"mcp_tools": {
"ok": true,
"status": "ok",
"detail": "Codex native MCP initialized and discovered 2 tools"
},
"service_support": {
"ok": true,
"status": "ok",
"detail": "native personal service adapter is supported"
},
"service_registration": {
"ok": true,
"status": "ok",
"detail": "not_installed (optional)"
},
"server_liveness": {
"ok": false,
"status": "failed",
"detail": "cannot reach http://127.0.0.1:18765"
},
"server_readiness": {
"ok": false,
"status": "skipped",
"detail": "not checked because Server liveness failed"
},
"server_memory_protocol": {
"ok": false,
"status": "skipped",
"detail": "not checked because Server liveness failed"
}
},
"ok": false
}
}
}
17 changes: 15 additions & 2 deletions docs/en/docs/integrations/codex.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,21 @@ powercontext setup codex
powercontext doctor codex
```

The command adds the repository as a Codex marketplace, installs the PowerContext plugin, and creates the user data
directory. It is safe to run again. Pass the same `--ref` used to install the PowerContext tool.
The command adds the repository as a Codex marketplace, installs the PowerContext plugin, builds the plugin's Python
environment, and creates the user data directory. It is safe to run again. Pass the same `--ref` used to install the
PowerContext tool.

The plugin's hooks and its MCP credential helper run through `uv` from `PATH`, so setup needs `uv` and, on a first
install, access to the package index. Building the environment at setup keeps the first session from building it
while Codex starts the hooks and MCP together. If the plugin is installed or updated by other means, `powercontext
doctor codex` reports `plugin_runtime` as degraded until you rerun setup.

PowerContext's MCP server is optional to Codex, so an unavailable Server never blocks a session. Codex waits for
optional servers for one second by default (`mcp_optional_startup_grace_ms`) before it lists a session's first tools;
on a slow or busy machine that first turn can run without PowerContext's MCP tools. For non-interactive runs such as
`codex exec`, where the first turn may be the only one, set `mcp_optional_startup_grace_ms = 0` at the top level of
Codex's `config.toml`, not under a server table, to wait up to the server's `startup_timeout_sec` (10 seconds by
default) instead.

When refreshing setup, client endpoint declarations in the setup `.env` file or process environment supersede saved
client settings and the previously installed MCP URL. Without a new declaration, setup reuses saved endpoints.
Expand Down
13 changes: 11 additions & 2 deletions docs/zh/docs/integrations/codex.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,17 @@ powercontext setup codex
powercontext doctor codex
```

该命令会把仓库添加为 Codex marketplace,安装 PowerContext 插件,并创建用户数据目录。重复执行是安全的。
`--ref` 应与安装 PowerContext 工具时使用的 ref 一致。
该命令会把仓库添加为 Codex marketplace,安装 PowerContext 插件,构建插件的 Python 环境,并创建用户数据目录。
重复执行是安全的。`--ref` 应与安装 PowerContext 工具时使用的 ref 一致。

插件的 Hook 和 MCP 凭据助手都通过 `PATH` 中的 `uv` 运行,因此 setup 需要 `uv`,首次安装时还需要能访问包索引。
在 setup 时构建环境,可避免首次会话在 Codex 同时启动 Hook 和 MCP 时才去构建。如果插件通过其他方式安装或更新,
在重新执行 setup 之前,`powercontext doctor codex` 会把 `plugin_runtime` 报告为 degraded。

PowerContext 的 MCP server 对 Codex 是可选的,因此 Server 不可用时不会阻塞会话。Codex 默认只等待可选 server 一秒
(`mcp_optional_startup_grace_ms`),然后列出会话首轮可用的工具;在较慢或负载较高的机器上,首轮可能没有 PowerContext
的 MCP 工具。对 `codex exec` 等非交互运行,首轮可能就是唯一一轮,可在 Codex 的 `config.toml` 顶层(而非某个
server 表下)设置 `mcp_optional_startup_grace_ms = 0`,改为最多等待该 server 的 `startup_timeout_sec`(默认 10 秒)。

刷新安装时,setup `.env` 文件或进程环境中新声明的客户端地址会覆盖保存的客户端设置和之前安装的 MCP 地址。
未提供新地址时,setup 复用保存的地址。文件与进程中声明的地址冲突时,仍需显式选择:使用 `--server-url`,
Expand Down
87 changes: 82 additions & 5 deletions src/powercontext/cli/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,15 +342,84 @@ def doctor(
)


def _codex_plugin_root(marketplace: str, plugin_version: str) -> Path:
"""Return the directory where Codex installed this plugin version."""

if any(part in {"", ".", ".."} or "/" in part or "\\" in part for part in (marketplace, plugin_version)):
raise SetupError("Invalid Codex plugin cache location") # noqa: TRY003
codex_home = Path(os.environ.get("CODEX_HOME", str(Path.home() / ".codex"))).expanduser()
return codex_home / "plugins" / "cache" / marketplace / PLUGIN_NAME / plugin_version


def _sync_codex_plugin_runtime(plugin_root: Path, *options: str, timeout: float) -> subprocess.CompletedProcess[str]:
"""Run `uv sync` on the plugin's own `.venv`, the environment the MCP header helper uses."""

# Never sync into another project's environment named by the caller's shell.
environment = {
name: value for name, value in os.environ.items() if name not in {"UV_PROJECT_ENVIRONMENT", "VIRTUAL_ENV"}
}
return subprocess.run( # noqa: S603 - the hooks and the MCP helper run the same uv from PATH.
["uv", "sync", "--frozen", "--quiet", *options, "--project", str(plugin_root)], # noqa: S607
check=False,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
env=environment,
timeout=timeout,
)


def _prepare_codex_plugin_runtime(plugin_root: Path) -> None:
"""Build the installed plugin's Python environment before Codex first starts it.

Codex starts the MCP header helper with a filtered environment and the hooks with the session's environment, both
through `uv run` at session start. Left to that moment, both build the environment: uv replaces it when the two
request different interpreters, failing the helper mid-import, and a cold build delays the optional MCP server
past the point where Codex lists the first turn's tools.
"""

retry = "the plugin is installed; rerun setup once uv can install its dependencies"
try:
completed = _sync_codex_plugin_runtime(plugin_root, timeout=300)
except (OSError, subprocess.SubprocessError) as error:
raise SetupError(f"Cannot prepare the Codex plugin runtime with uv ({retry}): {error}") from error # noqa: TRY003
if completed.returncode != 0:
detail = completed.stderr.strip() or completed.stdout.strip() or f"exit code {completed.returncode}"
raise SetupError(f"Preparing the Codex plugin runtime with uv failed ({retry}): {detail}") # noqa: TRY003


def _codex_plugin_runtime_diagnostic(plugin: dict[str, Any]) -> Diagnostic:
"""Report whether the installed plugin's environment is ready without building it."""

rerun = "rerun `powercontext setup codex`"
if which("uv") is None:
return Diagnostic(
status=DiagnosticStatus.FAILED,
detail=f"uv is not on PATH; the plugin's hooks and MCP credential helper need it; install uv and {rerun}",
)
try:
root = _codex_plugin_root(_required_string(plugin, "marketplaceName"), _required_string(plugin, "version"))
completed = _sync_codex_plugin_runtime(root, "--check", timeout=60)
except (SetupError, OSError, subprocess.SubprocessError) as error:
return Diagnostic(status=DiagnosticStatus.FAILED, detail=f"cannot check the plugin environment: {error}")
if completed.returncode == 0:
return Diagnostic(status=DiagnosticStatus.OK, detail="plugin environment is ready")
return Diagnostic(
status=DiagnosticStatus.DEGRADED,
detail=(
"plugin environment is not built; the next Codex session builds it while starting and may begin "
f"without PowerContext MCP tools; {rerun}"
),
)


def _codex_endpoint_updates(marketplace: str, plugin_version: str, server_url: str) -> dict[Path, bytes]:
"""Keep the installed native MCP and Hook endpoint and saved credential source identical."""

from powercontext.cli.authorization import credential_path

if any(part in {"", ".", ".."} or "/" in part or "\\" in part for part in (marketplace, plugin_version)):
raise SetupError("Invalid Codex plugin cache location") # noqa: TRY003
codex_home = Path(os.environ.get("CODEX_HOME", str(Path.home() / ".codex"))).expanduser()
path = codex_home / "plugins" / "cache" / marketplace / PLUGIN_NAME / plugin_version / ".mcp.json"
path = _codex_plugin_root(marketplace, plugin_version) / ".mcp.json"
try:
config = json.loads(path.read_text(encoding="utf-8"))
entry = config["mcpServers"][PLUGIN_NAME]
Expand Down Expand Up @@ -1323,6 +1392,10 @@ class CodexInstaller:
def install(self, source):
if _codex_path_executable() is None:
raise SetupError("Codex CLI is not installed or is not on PATH.") # noqa: TRY003
if which("uv") is None:
raise SetupError( # noqa: TRY003
"uv is not installed or is not on PATH; the Codex plugin's hooks and MCP helper need it."
)
marketplace_source, local = _normalize_marketplace_source(source.location)
arguments = ["plugin", "marketplace", "add", marketplace_source]
if not local:
Expand All @@ -1338,10 +1411,12 @@ def install(self, source):
)
if plugin is None or plugin.get("enabled") is not False:
plugin = _run_codex_json("plugin", "add", f"{PLUGIN_NAME}@{marketplace}")
plugin_version = _required_string(plugin, "version")
_prepare_codex_plugin_runtime(_codex_plugin_root(marketplace, plugin_version))
return {
"marketplace": marketplace,
"plugin": _required_string(plugin, "name"),
"plugin_version": _required_string(plugin, "version"),
"plugin_version": plugin_version,
"data_dir": str(powercontext_data_dir()),
}

Expand Down Expand Up @@ -1423,6 +1498,8 @@ def verify(self) -> dict[str, Diagnostic]:
detail="not checked because the PowerContext plugin is unavailable",
)
return diagnostics
# Before the MCP probe below, whose helper run would build the environment itself.
diagnostics["plugin_runtime"] = _codex_plugin_runtime_diagnostic(plugin)
Comment thread
hidb4ai marked this conversation as resolved.
Resolved

try:
servers = _run_codex_mcp_list()
Expand Down
Loading
Loading