agenthub/deploy/cli-bridge/adapters/codex.py

127 lines
5.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""codex adapter —— 对接 `codex exec --json`,会话 id 就是 thread_id。
实测 codex-cli 0.162.0-alpha.17.2 的 stdout(WARN 之类混在 stderr):
{"type":"thread.started","thread_id":"01a135e6-669f-7b13-91f9-860557b71c36"}
{"type":"item.completed","item":{"id":"item_2","type":"agent_message","text":"你好"}}
{"type":"turn.completed","usage":{"input_tokens":15983,"output_tokens":19}}
续话用 `codex exec resume <thread_id>`(注意它不吃 `-C`/`-s`,沙箱只能走 `-c`)。
中途下达指令用 `codex queue --thread`——三家 CLI 里只有它有会话内注入。实测语义:
消息排队,**下一轮**开始时才被消费,正在跑的那一轮看不到它(要立刻生效只能 cancel + 重发)。
"""
from __future__ import annotations
import asyncio
import json
import os
from pathlib import Path
from shutil import which
name = "codex"
SANDBOX = {"readonly": "read-only", "write": "workspace-write"}
_FALLBACK = "/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex"
_version = ""
def _bin() -> str:
path = os.environ.get("CODEX_BIN") or which("codex") or _FALLBACK
if not path or not Path(path).exists():
raise RuntimeError("找不到 codex 可执行文件;用环境变量 CODEX_BIN 指定绝对路径")
return path
SANDBOX_CFG = {"readonly": 'sandbox_mode="read-only"', "write": 'sandbox_mode="workspace-write"'}
def argv(*, prompt: str, run, workdir: str, mode: str) -> list[str]:
# 实测:exec resume 不吃 -C/-s(cwd 由 bridge 设,-C 本就多余),沙箱只能走 -c。
jsonl = ["--json", "--skip-git-repo-check"]
if run.session_id:
return [_bin(), "exec", "resume", run.session_id, *jsonl, "-c", SANDBOX_CFG.get(mode, SANDBOX_CFG["readonly"]), prompt]
return [_bin(), "exec", *jsonl, "-C", workdir, "-s", SANDBOX.get(mode, "read-only"), prompt]
def _brief(value: object, limit: int = 600) -> str:
if isinstance(value, str):
return value[:limit]
return json.dumps(value, ensure_ascii=False, default=str)[:limit]
async def feed(obj: dict, run, emit) -> None:
kind = str(obj.get("type") or "")
if kind == "thread.started":
run.session_id = str(obj.get("thread_id") or run.session_id)
await emit("status", message="codex 会话 " + run.session_id, session_id=run.session_id)
elif kind == "turn.started":
await emit("status", message="turn started")
elif kind in ("turn.completed", "token_count"):
usage = obj.get("usage")
if isinstance(usage, dict):
run.usage.update(usage)
elif kind == "turn.failed":
raise RuntimeError("codex turn 失败:" + _brief(obj.get("error") or obj))
elif kind == "error":
message = _brief(obj.get("message") or obj)
run.errors.append(message)
await emit("log", text="codex error: " + message)
elif kind.startswith("item."):
await _item(obj, run, emit)
else:
await emit("log", text="codex " + (kind or "event") + ": " + _brief(obj))
async def _item(obj: dict, run, emit) -> None:
item = obj.get("item") if isinstance(obj.get("item"), dict) else {}
itype = str(item.get("type") or "")
state = str(obj.get("type") or "") # item.started | item.updated | item.completed
done = state == "item.completed"
if itype == "agent_message":
if done:
text = str(item.get("text") or "")
run.parts.append(text)
await emit("delta", text=text)
elif itype == "reasoning":
if done:
await emit("reasoning", text=str(item.get("text") or ""))
elif itype == "error": # 配置告警之类:是线索,不是正文
message = _brief(item.get("message") or item)
run.errors.append(message)
await emit("log", text="codex: " + message)
elif itype == "command_execution":
await emit("tool", name="shell", state=state, command=str(item.get("command") or "")[:500],
status=str(item.get("status") or ""), exit=item.get("exit_code"))
elif itype in ("file_change", "web_search", "mcp_tool_call", "todo_list"):
await emit("tool", name=itype, state=state, detail=_brief(item))
elif done: # 没认出来的 item 也留个痕,别静默丢掉
await emit("log", text="codex item " + (itype or "unknown") + ": " + _brief(item))
async def deliver(session_id: str, text: str) -> tuple[bool, str]:
"""agent.command 的实现:把消息排进已有 thread。
实测:返回 "Queued message <id> for thread <id>",当前这一轮不受影响,
下一次 `exec resume`(= hub 上同 session_key 的下一个 task)才会读到它。
"""
proc = await asyncio.create_subprocess_exec(
_bin(), "queue", "--thread", session_id, "--message", text,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
)
out, err = await asyncio.wait_for(proc.communicate(), timeout=30)
detail = (out + err).decode("utf-8", "replace").strip()
return proc.returncode == 0, detail[:500] or ("queued" if proc.returncode == 0 else "codex queue 失败")
async def version() -> str:
global _version
if _version:
return _version
try:
proc = await asyncio.create_subprocess_exec(_bin(), "--version",
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT)
out, _ = await asyncio.wait_for(proc.communicate(), timeout=20)
_version = out.decode("utf-8", "replace").strip()
except Exception as exc: # noqa: BLE001 - describe 不该因为版本探测挂掉
_version = "unknown (" + type(exc).__name__ + ")"
return _version