codex_runtime_switch.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. """Shared logic for the /codex-runtime slash command (CLI and gateway call into this module)."""
  2. from __future__ import annotations
  3. import functools
  4. import logging
  5. from dataclasses import dataclass
  6. from typing import Optional
  7. logger = logging.getLogger(__name__)
  8. VALID_RUNTIMES = ("auto", "codex_app_server")
  9. # Human-friendly synonyms accepted by parse_args.
  10. _ARG_SYNONYMS = {
  11. "on": "codex_app_server", "codex": "codex_app_server", "enable": "codex_app_server",
  12. "off": "auto", "default": "auto", "disable": "auto", "hermes": "auto"}
  13. _HERMES_TOOLS_CALLBACK_NOTE = (
  14. "Hermes tool callback registered: codex can now use "
  15. "web_search, web_extract, vision_analyze, "
  16. "image_generate, skill_view, skills_list, text_to_speech, "
  17. "kanban_* (worker + orchestrator) via MCP.",
  18. " (delegate_task, memory, session_search, todo run "
  19. "only on the default Hermes runtime — they need the "
  20. "agent loop context.)")
  21. @dataclass
  22. class CodexRuntimeStatus:
  23. """Result of a /codex-runtime invocation; callers render it per surface (Rich panel / text)."""
  24. success: bool
  25. new_value: Optional[str] = None
  26. old_value: Optional[str] = None
  27. message: str = ""
  28. requires_new_session: bool = False
  29. def parse_args(arg_string: str) -> tuple[Optional[str], list[str]]:
  30. """Parse the slash-command argument string into ``(value, errors)``.
  31. No args → ``(None, [])`` (show current state); a runtime name or synonym → that runtime.
  32. """
  33. raw = (arg_string or "").strip().lower()
  34. if not raw:
  35. return None, []
  36. value = _ARG_SYNONYMS.get(raw, raw)
  37. if value in VALID_RUNTIMES:
  38. return value, []
  39. return None, [f"Unknown runtime {raw!r}. Use one of: auto, codex_app_server, on, off"]
  40. def get_current_runtime(config: dict) -> str:
  41. """Current ``model.openai_runtime``; 'auto' for unset / empty / unrecognized values."""
  42. if not isinstance(config, dict):
  43. return "auto"
  44. model_cfg = config.get("model") or {}
  45. if not isinstance(model_cfg, dict):
  46. return "auto"
  47. value = str(model_cfg.get("openai_runtime") or "").strip().lower()
  48. return value if value in VALID_RUNTIMES else "auto"
  49. def get_configured_codex_binary(config: dict) -> str:
  50. """``model.codex_bin`` (one argv element, never shell-parsed) or bare ``codex`` from PATH.
  51. Gateway/service/Kanban-worker processes often run with a minimal PATH that lacks the codex
  52. CLI (e.g. a desktop-bundled ``.../Codex.app/Contents/Resources/codex``), so users need a
  53. config-level override for every codex spawn site (#61360)."""
  54. model_cfg = config.get("model") if isinstance(config, dict) else None
  55. value = model_cfg.get("codex_bin") if isinstance(model_cfg, dict) else None
  56. return str(value or "").strip() or "codex"
  57. def set_runtime(config: dict, new_value: str) -> str:
  58. """Persist *new_value* into the config dict in place; returns the previous value."""
  59. if new_value not in VALID_RUNTIMES:
  60. raise ValueError(f"invalid runtime {new_value!r}; must be one of {VALID_RUNTIMES}")
  61. old = get_current_runtime(config)
  62. if not isinstance(config.get("model"), dict):
  63. config["model"] = {}
  64. config["model"]["openai_runtime"] = new_value
  65. return old
  66. def check_codex_binary_ok(codex_bin: str = "codex") -> tuple[bool, Optional[str]]:
  67. """Best-effort codex CLI install/version check → ``(ok, version_or_message)``."""
  68. try:
  69. from agent.transports.codex_app_server import check_codex_binary
  70. return check_codex_binary(codex_bin=codex_bin)
  71. except Exception as exc: # pragma: no cover
  72. return False, f"codex check failed: {exc}"
  73. def _migration_lines(config: dict) -> list[str]:
  74. """Run the ~/.codex/config.toml migration and describe it; failures are non-fatal."""
  75. lines: list[str] = []
  76. try:
  77. from hermes_cli.codex_runtime_plugin_migration import HERMES_TOOLS_MCP_SERVER_NAME, migrate
  78. mig_report = migrate(config)
  79. # The hermes-tools callback is internal plumbing — surfaced separately below.
  80. user_servers = [s for s in mig_report.migrated if s != HERMES_TOOLS_MCP_SERVER_NAME]
  81. if user_servers:
  82. lines.append(f"Migrated {len(user_servers)} MCP server(s): {', '.join(user_servers)}")
  83. if mig_report.migrated_plugins:
  84. lines.append(
  85. f"Migrated {len(mig_report.migrated_plugins)} native "
  86. f"Codex plugin(s): {', '.join(mig_report.migrated_plugins)}")
  87. elif mig_report.plugin_query_error:
  88. lines.append(f"Codex plugin discovery skipped: {mig_report.plugin_query_error}")
  89. if mig_report.wrote_permissions_default:
  90. lines.append(
  91. f"Default sandbox: {mig_report.wrote_permissions_default} "
  92. f"(no approval prompt on every write)")
  93. if HERMES_TOOLS_MCP_SERVER_NAME in mig_report.migrated:
  94. lines.extend(_HERMES_TOOLS_CALLBACK_NOTE)
  95. lines.append(f" (config: {mig_report.target_path})")
  96. for err in mig_report.errors:
  97. lines.append(f"⚠ MCP migration: {err}")
  98. except Exception as exc:
  99. lines.append(f"⚠ MCP migration skipped: {exc}")
  100. return lines
  101. def apply(
  102. config: dict, new_value: Optional[str], *, persist_callback=None) -> CodexRuntimeStatus:
  103. """Entry point for CLI and gateway. ``config`` is mutated in place when ``new_value`` is set
  104. (None = show current state); ``persist_callback(config)`` writes it, skipped when None."""
  105. current = get_current_runtime(config)
  106. codex_bin = get_configured_codex_binary(config)
  107. # Cached per apply() call: the enable path would otherwise spawn `codex --version` up to 3x.
  108. _check_binary_cached = functools.cache(check_codex_binary_ok)
  109. if new_value is None:
  110. ok, ver = _check_binary_cached(codex_bin)
  111. msg = (
  112. f"openai_runtime: {current}\n"
  113. f"codex CLI: {'OK ' + ver if ok else 'not available — ' + (ver or 'install with `npm i -g @openai/codex`')}"
  114. )
  115. return CodexRuntimeStatus(success=True, new_value=current, old_value=current, message=msg)
  116. # Re-enabling codex_app_server falls through to the migration: the config value is already
  117. # correct but the world state (managed block in ~/.codex/config.toml, hermes-tools MCP
  118. # callback, plugin discovery) may be stale — a common footgun when users pre-set
  119. # `openai_runtime: codex_app_server` by hand. The migration is idempotent so re-running is
  120. # cheap and safe. Re-setting `auto` returns immediately (disabling never touches ~/.codex/).
  121. reapplying_enable = new_value == current == "codex_app_server"
  122. if new_value == current and not reapplying_enable:
  123. return CodexRuntimeStatus(
  124. success=True, new_value=current, old_value=current,
  125. message=f"openai_runtime already set to {current}")
  126. # Switching ON: verify codex CLI before persisting — an opt-in toggle that silently fails on
  127. # the first turn is the worst possible UX.
  128. if new_value == "codex_app_server":
  129. ok, ver_or_msg = _check_binary_cached(codex_bin)
  130. if not ok:
  131. return CodexRuntimeStatus(
  132. success=False, new_value=None, old_value=current,
  133. message=(
  134. "Cannot enable codex_app_server runtime: "
  135. f"{ver_or_msg or 'codex CLI not available'}\n"
  136. "Install with: npm i -g @openai/codex"))
  137. if not reapplying_enable:
  138. set_runtime(config, new_value)
  139. if persist_callback is not None:
  140. try:
  141. persist_callback(config)
  142. except Exception as exc:
  143. logger.exception("failed to persist openai_runtime change")
  144. return CodexRuntimeStatus(
  145. success=False, new_value=new_value, old_value=current,
  146. message=f"updated config in memory but persist failed: {exc}")
  147. msg_lines = [
  148. f"openai_runtime already set to {current} — re-applying migration"
  149. if reapplying_enable
  150. else f"openai_runtime: {current} → {new_value}"]
  151. if new_value == "codex_app_server":
  152. ok, ver = _check_binary_cached(codex_bin)
  153. if ok:
  154. msg_lines.append(f"codex CLI: {ver}")
  155. # Migrate Hermes' MCP servers + Codex's curated plugins into ~/.codex/config.toml so the
  156. # spawned codex subprocess sees the same tool surface AND can call back into Hermes.
  157. msg_lines.extend(_migration_lines(config))
  158. msg_lines.append(
  159. "OpenAI/Codex turns now run through `codex app-server` "
  160. "(terminal/file ops/patching inside Codex; "
  161. "Hermes tools available via MCP callback).")
  162. msg_lines.append(
  163. "Effective on next session — current cached agent keeps "
  164. "the prior runtime to preserve prompt cache.")
  165. else:
  166. msg_lines.append("OpenAI/Codex turns will use the default Hermes runtime.")
  167. msg_lines.append("Effective on next session.")
  168. return CodexRuntimeStatus(
  169. success=True, new_value=new_value, old_value=current,
  170. message="\n".join(msg_lines), requires_new_session=True)