Skip to content
Back to search

evo

turns your codebase into an autoresearch loop — discovers what to measure, instruments the benchmark, then runs tree search with parallel subagents.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/evo-hq/evo with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/evo-hq/evo'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/evo-hq--evo/badge.svg)](/listings/evo-hq--evo)

HTML

<a href="/listings/evo-hq--evo"><img src="/api/listings/evo-hq--evo/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

# 1. evo CLI
uv tool install evo-hq-cli

# 2. Host CLI (if you don't already have it)
npm install -g @anthropic-ai/claude-code     # or @openai/codex, openclaw, @earendil-works/pi-coding-agent
# Cursor: install from cursor.com (IDE), or `curl https://cursor.com/install -fsS | bash` for the cursor-agent CLI
# Kimi: `curl -fsSL https://code.kimi.com/install.sh | bash`, or `npm install -g @moonshot-ai/kimi-code`

# 3. Plugin + host hooks
evo install <host>     # claude-code | codex | cursor | hermes | kimi | opencode | openclaw | pi

For remote backends, install with the matching provider extra: `uv tool install 'evo-hq-cli[modal]'` (or `[e2b]`, `[daytona]`, `[aws]`, `[azure]`, `[all]`).

Codex hook trust

`evo install codex` trusts evo's hooks for you. To review them yourself first, pass `--no-trust-hooks`, then approve via `/hooks` inside codex.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 13 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. {
  2. "name": "evo-hq-evo",
  3. "owner": {
  4. "name": "evo-hq"
  5. },
  6. "plugins": [
  7. {
  8. "name": "evo",
  9. "source": "./plugins/evo",
  10. "description": "Structured experiment-driven code optimization using tree search and parallel subagents"
  11. }
  12. ]
  13. }
README.md · README · 231 lines · 2 findings marked

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # evo
  2. <p align="center">
  3. <img src="assets/banner.png" alt="evo — autoresearch orchestrator for your codebase" width="100%" />
  4. </p>
  5. <div align="center">
  6. [![PyPI](https://img.shields.io/pypi/v/evo-hq-cli)](https://pypi.org/project/evo-hq-cli/)
  7. [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
  8. [![Tests](https://github.com/evo-hq/evo/actions/workflows/ci.yml/badge.svg)](https://github.com/evo-hq/evo/actions/workflows/ci.yml)
  9. [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.20447923.svg)](https://doi.org/10.5281/zenodo.20447923)
  10. **Get started with autoresearch on any codebase - with two simple commands.**
  11. Do you want to do more with autoresearch or need a custom, hands-on deployment?
  12. [Request access to evo platform](https://evo-hq.com/beta) or email [hello@evo-hq.com](mailto:hello@evo-hq.com).
  13. ---
  14. **[Try it](#try-it)** · **[Install](#install)** · **[How it works](#how-it-works)** · **[Dashboard](#dashboard)** · **[Upgrading](#upgrading)**
  15. </div>
  16. A plugin for your agentic framework that optimizes code through experiments
  17. You give it a codebase. It discovers metrics to optimize, sets up the evaluation, and starts running experiments in a loop -- trying things, keeping what improves the score, throwing away what doesn't.
  18. *Inspired by [Karpathy's autoresearch](https://github.com/karpathy/autoresearch)* -- where an LLM runs training experiments autonomously to beat its own best score. Autoresearch is a pure hill climb: try something, keep or revert, repeat on a single branch. Evo adds structure on top of that idea:
  19. - **Tree search over greedy hill climb.** Multiple directions can fork from any committed node, so exploration doesn't collapse to one path.
  20. - **Parallel semi-autonomous agents.** Spawn multiple subagents and run them simultaneously, each in its own git worktree. Each subagent reads traces, formulates hypotheses, and can run multiple iterations within its branch.
  21. - **Shared state.** Failure traces, annotations, and discarded hypotheses are accessible to every agent before it decides what to try next.
  22. - **Gating.** Regression tests or safety checks can be wired up as a gate. Experiments that don't pass get discarded.
  23. - **Observability.** A dashboard to monitor your experiments.
  24. - **Benchmark discovery.** The `discover` skill explores the repo, figures out what to measure, and instruments the evaluation.
  25. Runs on Claude Code, Codex, Cursor, Kimi, OpenClaw, Hermes, Opencode, or Pi. Experiments run locally or on remote sandboxes — Modal, E2B, Daytona, AWS, Azure, SSH.
  26. <p align="center">
  27. <img src="assets/dashboard.png" alt="evo dashboard" width="100%" />
  28. </p>
  29. ## Try it
  30. Two commands:
  31. ```
  32. /evo:discover # one-time code discovery: figures out benchmarks and creates gates against unintended changes
  33. /evo:optimize # run the loop
  34. ```
  35. `discover` asks what to optimize, the benchmark command, and the metric direction. Skip the questions by seeding the answer:
  36. ```
  37. /evo:discover make the JSON parser at src/parser.py faster
  38. ```
  39. Then run the loop:
  40. ```
  41. /evo:optimize
  42. ```
  43. evo sizes each round to your benchmark's resource profile — one experiment at a time when a run needs the whole GPU or another exclusive resource, wider when runs are independent — and keeps going until the score stops improving. By default it runs unattended and pushes edits through parallel subagents; say so in plain language if you'd rather it pause after each round or hold to one experiment at a time.
  44. Invocation syntax is host-specific: `/evo:` on Claude Code, `$evo` on Codex, `/` skill menu on Cursor, natural language on Hermes, Opencode, OpenClaw, and Pi.
  45. ## Install
  46. ```bash
  47. # 1. evo CLI
  48. uv tool install evo-hq-cli
  49. # 2. Host CLI (if you don't already have it)
  50. npm install -g @anthropic-ai/claude-code # or @openai/codex, openclaw, @earendil-works/pi-coding-agent
  51. # Cursor: install from cursor.com (IDE), or `curl https://cursor.com/install -fsS | bash` for the cursor-agent CLI
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 77 on GitHub
  52. # Kimi: `curl -fsSL https://code.kimi.com/install.sh | bash`, or `npm install -g @moonshot-ai/kimi-code`
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 78 on GitHub
  53. # 3. Plugin + host hooks
  54. evo install <host> # claude-code | codex | cursor | hermes | kimi | opencode | openclaw | pi
  55. ```
  56. For remote backends, install with the matching provider extra: `uv tool install 'evo-hq-cli[modal]'` (or `[e2b]`, `[daytona]`, `[aws]`, `[azure]`, `[all]`).
  57. ### Codex hook trust
  58. `evo install codex` trusts evo's hooks for you. To review them yourself first, pass `--no-trust-hooks`, then approve via `/hooks` inside codex.
  59. ## How it works
  60. ### Parallel
  61. The orchestrator dispatches subagents in parallel. Each runs in its own isolated workspace, picks up shared state (failure traces, annotations, discarded hypotheses), forms a hypothesis, edits, and runs the benchmark. A subagent with iteration budget remaining continues on its branch within the same round when its prior edit warrants a follow-up.
  62. ### Frontier strategy
  63. After each round, the orchestrator selects which committed branch to extend next. Available strategies:
  64. - **argmax** — extend the highest-scoring branch
  65. - **top_k** — round-robin among the K best
  66. - **epsilon_greedy** — best most of the time, random sometimes
  67. - **softmax** — sample weighted by score
  68. - **pareto_per_task** — keep specialists the aggregate hides, inspired by [GEPA](https://arxiv.org/abs/2507.19457)
  69. Configure in the dashboard's Frontier tab, which lists each strategy's parameters.
  70. ### Cross-cutting scans
  71. Between rounds, [RLM](https://arxiv.org/abs/2512.24601)-inspired scan subagents read trace batches in parallel and surface compound failure patterns: gate-failure intersections, shared root causes across traces. Findings land in shared state, which the next round's subagents read at startup.
  72. ### Gates
  73. evo introduces **gates**: pass/fail checks that run on every experiment. An experiment that fails a gate is discarded even if its score beats the current best. Without gates, the search will find ways to return a constant, skip work, or trade correctness for speed.
  74. Any command that exits zero on pass and non-zero on fail qualifies as a gate: a test suite, an invariant script, a score floor on a held-out slice of the benchmark. Gates inherit down the experiment tree: a gate registered at the root runs on every descendant. Narrower gates can be attached to specific branches.
  75. When `discover` builds a benchmark from scratch, it attaches a held-out-slice score-floor gate automatically. When the benchmark already exists in the repo, gates are opt-in.
  76. ## Where experiments run
  77. | Backend | Where | Install |
  78. |---|---|---|
  79. | **worktree** *(default)* | local git worktree per experiment | included |
  80. | **pool** | reuse a fixed set of local workspaces | included |
  81. | **ssh** | your own SSH host | included |
  82. | **modal** | Modal serverless cloud | `uv tool install 'evo-hq-cli[modal]'` |
  83. | **e2b** | E2B cloud sandboxes | `uv tool install 'evo-hq-cli[e2b]'` |
  84. | **daytona** | Daytona cloud workspaces | `uv tool install 'evo-hq-cli[daytona]'` |
  85. | **aws** | AWS EC2 sandboxes | `uv tool install 'evo-hq-cli[aws]'` |
  86. | **azure** | Azure VMs | `uv tool install 'evo-hq-cli[azure]'` |
  87. Pick and configure in the dashboard's Backend tab.
  88. ## Dashboard
  89. The dashboard starts automatically with `/evo:discover` (or `evo init`) and prints the URL in chat:
  90. ```
  91. Dashboard live: http://127.0.0.1:8080 (pid 12345)
  92. ```
  93. If `8080` is in use, evo increments to the next free port (`8081`, `8082`, …) and prints it. Subsequent runs reuse the chosen port. Start it manually with:
  94. ```bash
  95. uv run --project /path/to/evo/plugins/evo evo dashboard --port 8080
  96. ```
  97. ## Upgrading
  98. ```bash
  99. evo update # update CLI + every installed host
  100. evo update <host> # update one host (also bumps CLI to match)
  101. evo update <host> --version 0.4.1 # pin to a release
  102. ```
  103. Every `evo install` / `evo update` keeps the CLI on PATH in lockstep with the host plugin version it just installed (`uv tool install --force evo-hq-cli` under the hood). Without a `--version` pin that resolves to the latest **stable** release, so running an unpinned `evo install`/`evo update` against a pre-release pulls the CLI back to stable — pin both sides for an alpha (see [Testing a pre-release](#testing-a-pre-release-alpha)). The CLI binary, the skill files, and the hook protocol share wire formats — letting them drift caused silent failures in earlier versions. Editable installs (`uv tool install --editable`, `pip install -e`) are detected and left untouched.
  104. See `evo update --help` for `--force`, `--scope`, and additional flags.
  105. ### Migrating from any pre-0.4.4 version
  106. ```bash
  107. uv tool install --force evo-hq-cli && evo update --force
  108. ```
  109. `--force` wipes the host plugin cache and reinstalls, working around [anthropics/claude-code#14061](https://github.com/anthropics/claude-code/issues/14061): `/plugin update` returns success but does not replace cached plugin files.
  110. ### Hooks failing with exit 127
  111. The host lost evo's hook binary. Fixed in 0.5.1; reinstall the host to repair:
  112. ```bash
  113. uv tool install --force evo-hq-cli && evo install codex --force # or: evo install claude-code --force
  114. ```
  115. `evo doctor <host>` confirms the result.
  116. ### Testing a pre-release (alpha)
  117. `uv` and `pip` skip pre-releases by default. To install an alpha, pin both the CLI version and the host plugin tag:
  118. ```bash
  119. uv tool install --force 'evo-hq-cli==0.4.1a2' && \
  120. evo update --version 0.4.1-alpha.2 --force
  121. ```
  122. Substitute the target alpha version. The CLI uses PEP 440 form (`0.4.1a2`); the marketplace tag uses the dash form (`v0.4.1-alpha.2`).
  123. ## Telemetry
  124. evo sends anonymous telemetry and usage stats that helps us improve evo.
  125. Disable it globally anytime:
  126. ```bash
  127. evo telemetry off
  128. ```
  129. Or for one command/session:
  130. ```bash
  131. EVO_TELEMETRY=0 evo ...
  132. ```
  133. ## Dev install
  134. For development on evo:
  135. ```bash
  136. git clone https://github.com/evo-hq/evo
  137. cd evo
  138. uv tool install --editable plugins/evo
  139. ```
  140. ## License
  141. Apache-2.0. See [LICENSE](LICENSE).
  142. ## Citation
  143. If you use evo in your work, please cite it (see [`CITATION.cff`](CITATION.cff)):
  144. ```bibtex
  145. @software{bishoyi_evo,
  146. author = {Bishoyi, Alok Kumar},
  147. title = {{evo: an autoresearch orchestrator for codebases}},
  148. url = {https://github.com/evo-hq/evo},
  149. doi = {10.5281/zenodo.20447923},
  150. year = {2026}
  151. }
  152. ```
plugins/evo/hooks/hooks.json · Bundled script · 75 lines · 7 findings marked
  1. {
  2. "hooks": {
  3. "PreToolUse": [
  4. {
  5. "matcher": ".*",
  6. "hooks": [
  7. {
  8. "type": "command",
  9. "command": "node -e \"eval(Buffer.from('Y29uc3QgZnM9cmVxdWlyZSgnZnMnKSxvcz1yZXF1aXJlKCdvcycpLHBhdGg9cmVxdWlyZSgncGF0aCcpLGNwPXJlcXVpcmUoJ2NoaWxkX3Byb2Nlc3MnKSx0dHk9cmVxdWlyZSgndHR5Jyk7bGV0IGlucHV0PUJ1ZmZlci5hbGxvYygwKTt0cnl7aWYoIXR0eS5pc2F0dHkoMCkpaW5wdXQ9ZnMucmVhZEZpbGVTeW5jKDApfWNhdGNoKGUpe31jb25zdCBuYW1lcz1wcm9jZXNzLnBsYXRmb3JtPT09J3dpbjMyJz9bJ2V2by1ob29rLWRyYWluLmV4ZScsJ2V2by1ob29rLWRyYWluJ106Wydldm8taG9vay1kcmFpbiddO2NvbnN0IGNhbmRpZGF0ZXM9W107Y29uc3Qgcm9vdD1wcm9jZXNzLmVudi5DTEFVREVfUExVR0lOX1JPT1Q7aWYocm9vdCl7Zm9yKGNvbnN0IG4gb2YgbmFtZXMpY2FuZGlkYXRlcy5wdXNoKHBhdGguam9pbihyb290LCdiaW4nLG4pKX1jb25zdCBob21lPXByb2Nlc3MuZW52LkVWT19IT01FfHxwYXRoLmpvaW4ob3MuaG9tZWRpcigpLCcuZXZvJyk7Zm9yKGNvbnN0IG4gb2YgbmFtZXMpY2FuZGlkYXRlcy5wdXNoKHBhdGguam9pbihob21lLCdiaW4nLG4pKTtmb3IoY29uc3QgYiBvZiBjYW5kaWRhdGVzKXt0cnl7aWYoZnMuZXhpc3RzU3luYyhiKSl7Y29uc3Qgcj1jcC5zcGF3blN5bmMoYixbXSx7aW5wdXQsdGltZW91dDoyMDAwLGtpbGxTaWduYWw6J1NJR0tJTEwnfSk7aWYoci5zdGF0dXM9PT0wJiZyLnN0ZG91dCYmci5zdGRvdXQubGVuZ3RoKXtwcm9jZXNzLnN0ZG91dC53cml0ZShyLnN0ZG91dCk7cHJvY2Vzcy5leGl0KDApfX19Y2F0Y2goZSl7fX1wcm9jZXNzLnN0ZG91dC53cml0ZSgne31cbicpOw==','base64').toString())\""
    • Warning: Runs code it decodes (base64, hex, character codes, reversed text or a compressed blob), which hides what runs from a reader
    • Line 9 on GitHub
  10. }
  11. ]
  12. }
  13. ],
  14. "PostToolUse": [
  15. {
  16. "matcher": ".*",
  17. "hooks": [
  18. {
  19. "type": "command",
  20. "command": "node -e \"eval(Buffer.from('Y29uc3QgZnM9cmVxdWlyZSgnZnMnKSxvcz1yZXF1aXJlKCdvcycpLHBhdGg9cmVxdWlyZSgncGF0aCcpLGNwPXJlcXVpcmUoJ2NoaWxkX3Byb2Nlc3MnKSx0dHk9cmVxdWlyZSgndHR5Jyk7bGV0IGlucHV0PUJ1ZmZlci5hbGxvYygwKTt0cnl7aWYoIXR0eS5pc2F0dHkoMCkpaW5wdXQ9ZnMucmVhZEZpbGVTeW5jKDApfWNhdGNoKGUpe31jb25zdCBuYW1lcz1wcm9jZXNzLnBsYXRmb3JtPT09J3dpbjMyJz9bJ2V2by1ob29rLWRyYWluLmV4ZScsJ2V2by1ob29rLWRyYWluJ106Wydldm8taG9vay1kcmFpbiddO2NvbnN0IGNhbmRpZGF0ZXM9W107Y29uc3Qgcm9vdD1wcm9jZXNzLmVudi5DTEFVREVfUExVR0lOX1JPT1Q7aWYocm9vdCl7Zm9yKGNvbnN0IG4gb2YgbmFtZXMpY2FuZGlkYXRlcy5wdXNoKHBhdGguam9pbihyb290LCdiaW4nLG4pKX1jb25zdCBob21lPXByb2Nlc3MuZW52LkVWT19IT01FfHxwYXRoLmpvaW4ob3MuaG9tZWRpcigpLCcuZXZvJyk7Zm9yKGNvbnN0IG4gb2YgbmFtZXMpY2FuZGlkYXRlcy5wdXNoKHBhdGguam9pbihob21lLCdiaW4nLG4pKTtmb3IoY29uc3QgYiBvZiBjYW5kaWRhdGVzKXt0cnl7aWYoZnMuZXhpc3RzU3luYyhiKSl7Y29uc3Qgcj1jcC5zcGF3blN5bmMoYixbXSx7aW5wdXQsdGltZW91dDoyMDAwLGtpbGxTaWduYWw6J1NJR0tJTEwnfSk7aWYoci5zdGF0dXM9PT0wJiZyLnN0ZG91dCYmci5zdGRvdXQubGVuZ3RoKXtwcm9jZXNzLnN0ZG91dC53cml0ZShyLnN0ZG91dCk7cHJvY2Vzcy5leGl0KDApfX19Y2F0Y2goZSl7fX1wcm9jZXNzLnN0ZG91dC53cml0ZSgne31cbicpOw==','base64').toString())\""
    • Warning: Runs code it decodes (base64, hex, character codes, reversed text or a compressed blob), which hides what runs from a reader
    • Line 20 on GitHub
  21. }
  22. ]
  23. },
  24. {
  25. "matcher": "Bash",
  26. "hooks": [
  27. {
  28. "type": "command",
  29. "command": "node -e \"/*evo-wait-hint*/eval(Buffer.from('Y29uc3QgZnM9cmVxdWlyZSgnZnMnKSxwYXRoPXJlcXVpcmUoJ3BhdGgnKSxjcD1yZXF1aXJlKCdjaGlsZF9wcm9jZXNzJyksdHR5PXJlcXVpcmUoJ3R0eScpO2xldCBpbnB1dD1CdWZmZXIuYWxsb2MoMCk7dHJ5e2lmKCF0dHkuaXNhdHR5KDApKWlucHV0PWZzLnJlYWRGaWxlU3luYygwKX1jYXRjaChlKXt9Y29uc3Qgcm9vdD1wcm9jZXNzLmVudi5DTEFVREVfUExVR0lOX1JPT1Q7aWYoIXJvb3Qpe3Byb2Nlc3Muc3Rkb3V0LndyaXRlKCd7fVxuJyk7cHJvY2Vzcy5leGl0KDApfWNvbnN0IHNjcmlwdD1wYXRoLmpvaW4ocm9vdCwnaG9va3MnLCd3YWl0X2hpbnQuc2gnKTt0cnl7aWYoZnMuZXhpc3RzU3luYyhzY3JpcHQpKXtjb25zdCByPWNwLnNwYXduU3luYygnYmFzaCcsW3NjcmlwdF0se2lucHV0LHRpbWVvdXQ6MjAwMCxraWxsU2lnbmFsOidTSUdLSUxMJ30pO2lmKHIuc3RhdHVzPT09MCl7aWYoci5zdGRvdXQmJnIuc3Rkb3V0Lmxlbmd0aClwcm9jZXNzLnN0ZG91dC53cml0ZShyLnN0ZG91dCk7cHJvY2Vzcy5leGl0KDApfX19Y2F0Y2goZSl7fXByb2Nlc3Muc3Rkb3V0LndyaXRlKCd7fVxuJyk7','base64').toString())\""
    • Warning: Runs code it decodes (base64, hex, character codes, reversed text or a compressed blob), which hides what runs from a reader
    • Line 29 on GitHub
  30. }
  31. ]
  32. }
  33. ],
  34. "UserPromptSubmit": [
  35. {
  36. "hooks": [
  37. {
  38. "type": "command",
  39. "command": "node -e \"eval(Buffer.from('Y29uc3QgZnM9cmVxdWlyZSgnZnMnKSxvcz1yZXF1aXJlKCdvcycpLHBhdGg9cmVxdWlyZSgncGF0aCcpLGNwPXJlcXVpcmUoJ2NoaWxkX3Byb2Nlc3MnKSx0dHk9cmVxdWlyZSgndHR5Jyk7bGV0IGlucHV0PUJ1ZmZlci5hbGxvYygwKTt0cnl7aWYoIXR0eS5pc2F0dHkoMCkpaW5wdXQ9ZnMucmVhZEZpbGVTeW5jKDApfWNhdGNoKGUpe31jb25zdCBuYW1lcz1wcm9jZXNzLnBsYXRmb3JtPT09J3dpbjMyJz9bJ2V2by1ob29rLWRyYWluLmV4ZScsJ2V2by1ob29rLWRyYWluJ106Wydldm8taG9vay1kcmFpbiddO2NvbnN0IGNhbmRpZGF0ZXM9W107Y29uc3Qgcm9vdD1wcm9jZXNzLmVudi5DTEFVREVfUExVR0lOX1JPT1Q7aWYocm9vdCl7Zm9yKGNvbnN0IG4gb2YgbmFtZXMpY2FuZGlkYXRlcy5wdXNoKHBhdGguam9pbihyb290LCdiaW4nLG4pKX1jb25zdCBob21lPXByb2Nlc3MuZW52LkVWT19IT01FfHxwYXRoLmpvaW4ob3MuaG9tZWRpcigpLCcuZXZvJyk7Zm9yKGNvbnN0IG4gb2YgbmFtZXMpY2FuZGlkYXRlcy5wdXNoKHBhdGguam9pbihob21lLCdiaW4nLG4pKTtmb3IoY29uc3QgYiBvZiBjYW5kaWRhdGVzKXt0cnl7aWYoZnMuZXhpc3RzU3luYyhiKSl7Y29uc3Qgcj1jcC5zcGF3blN5bmMoYixbXSx7aW5wdXQsdGltZW91dDoyMDAwLGtpbGxTaWduYWw6J1NJR0tJTEwnfSk7aWYoci5zdGF0dXM9PT0wJiZyLnN0ZG91dCYmci5zdGRvdXQubGVuZ3RoKXtwcm9jZXNzLnN0ZG91dC53cml0ZShyLnN0ZG91dCk7cHJvY2Vzcy5leGl0KDApfX19Y2F0Y2goZSl7fX1wcm9jZXNzLnN0ZG91dC53cml0ZSgne31cbicpOw==','base64').toString())\""
    • Warning: Runs code it decodes (base64, hex, character codes, reversed text or a compressed blob), which hides what runs from a reader
    • Line 39 on GitHub
  40. }
  41. ]
  42. }
  43. ],
  44. "SessionStart": [
  45. {
  46. "hooks": [
  47. {
  48. "type": "command",
  49. "command": "node -e \"eval(Buffer.from('Y29uc3QgZnM9cmVxdWlyZSgnZnMnKSxvcz1yZXF1aXJlKCdvcycpLHBhdGg9cmVxdWlyZSgncGF0aCcpLGNwPXJlcXVpcmUoJ2NoaWxkX3Byb2Nlc3MnKSx0dHk9cmVxdWlyZSgndHR5Jyk7bGV0IGlucHV0PUJ1ZmZlci5hbGxvYygwKTt0cnl7aWYoIXR0eS5pc2F0dHkoMCkpaW5wdXQ9ZnMucmVhZEZpbGVTeW5jKDApfWNhdGNoKGUpe31jb25zdCBuYW1lcz1wcm9jZXNzLnBsYXRmb3JtPT09J3dpbjMyJz9bJ2V2by1ob29rLWRyYWluLmV4ZScsJ2V2by1ob29rLWRyYWluJ106Wydldm8taG9vay1kcmFpbiddO2NvbnN0IGNhbmRpZGF0ZXM9W107Y29uc3Qgcm9vdD1wcm9jZXNzLmVudi5DTEFVREVfUExVR0lOX1JPT1Q7aWYocm9vdCl7Zm9yKGNvbnN0IG4gb2YgbmFtZXMpY2FuZGlkYXRlcy5wdXNoKHBhdGguam9pbihyb290LCdiaW4nLG4pKX1jb25zdCBob21lPXByb2Nlc3MuZW52LkVWT19IT01FfHxwYXRoLmpvaW4ob3MuaG9tZWRpcigpLCcuZXZvJyk7Zm9yKGNvbnN0IG4gb2YgbmFtZXMpY2FuZGlkYXRlcy5wdXNoKHBhdGguam9pbihob21lLCdiaW4nLG4pKTtmb3IoY29uc3QgYiBvZiBjYW5kaWRhdGVzKXt0cnl7aWYoZnMuZXhpc3RzU3luYyhiKSl7Y29uc3Qgcj1jcC5zcGF3blN5bmMoYixbXSx7aW5wdXQsdGltZW91dDoyMDAwLGtpbGxTaWduYWw6J1NJR0tJTEwnfSk7aWYoci5zdGF0dXM9PT0wJiZyLnN0ZG91dCYmci5zdGRvdXQubGVuZ3RoKXtwcm9jZXNzLnN0ZG91dC53cml0ZShyLnN0ZG91dCk7cHJvY2Vzcy5leGl0KDApfX19Y2F0Y2goZSl7fX1wcm9jZXNzLnN0ZG91dC53cml0ZSgne31cbicpOw==','base64').toString())\""
    • Warning: Runs code it decodes (base64, hex, character codes, reversed text or a compressed blob), which hides what runs from a reader
    • Line 49 on GitHub
  50. }
  51. ]
  52. }
  53. ],
  54. "Stop": [
  55. {
  56. "hooks": [
  57. {
  58. "type": "command",
  59. "command": "node -e \"eval(Buffer.from('Y29uc3QgZnM9cmVxdWlyZSgnZnMnKSxvcz1yZXF1aXJlKCdvcycpLHBhdGg9cmVxdWlyZSgncGF0aCcpLGNwPXJlcXVpcmUoJ2NoaWxkX3Byb2Nlc3MnKSx0dHk9cmVxdWlyZSgndHR5Jyk7bGV0IGlucHV0PUJ1ZmZlci5hbGxvYygwKTt0cnl7aWYoIXR0eS5pc2F0dHkoMCkpaW5wdXQ9ZnMucmVhZEZpbGVTeW5jKDApfWNhdGNoKGUpe31jb25zdCBuYW1lcz1wcm9jZXNzLnBsYXRmb3JtPT09J3dpbjMyJz9bJ2V2by1ob29rLWRyYWluLmV4ZScsJ2V2by1ob29rLWRyYWluJ106Wydldm8taG9vay1kcmFpbiddO2NvbnN0IGNhbmRpZGF0ZXM9W107Y29uc3Qgcm9vdD1wcm9jZXNzLmVudi5DTEFVREVfUExVR0lOX1JPT1Q7aWYocm9vdCl7Zm9yKGNvbnN0IG4gb2YgbmFtZXMpY2FuZGlkYXRlcy5wdXNoKHBhdGguam9pbihyb290LCdiaW4nLG4pKX1jb25zdCBob21lPXByb2Nlc3MuZW52LkVWT19IT01FfHxwYXRoLmpvaW4ob3MuaG9tZWRpcigpLCcuZXZvJyk7Zm9yKGNvbnN0IG4gb2YgbmFtZXMpY2FuZGlkYXRlcy5wdXNoKHBhdGguam9pbihob21lLCdiaW4nLG4pKTtmb3IoY29uc3QgYiBvZiBjYW5kaWRhdGVzKXt0cnl7aWYoZnMuZXhpc3RzU3luYyhiKSl7Y29uc3Qgcj1jcC5zcGF3blN5bmMoYixbXSx7aW5wdXQsdGltZW91dDoyMDAwLGtpbGxTaWduYWw6J1NJR0tJTEwnfSk7aWYoci5zdGF0dXM9PT0wJiZyLnN0ZG91dCYmci5zdGRvdXQubGVuZ3RoKXtwcm9jZXNzLnN0ZG91dC53cml0ZShyLnN0ZG91dCk7cHJvY2Vzcy5leGl0KDApfX19Y2F0Y2goZSl7fX1wcm9jZXNzLnN0ZG91dC53cml0ZSgne31cbicpOw==','base64').toString())\""
    • Warning: Runs code it decodes (base64, hex, character codes, reversed text or a compressed blob), which hides what runs from a reader
    • Line 59 on GitHub
  60. }
  61. ]
  62. }
  63. ],
  64. "SubagentStop": [
  65. {
  66. "hooks": [
  67. {
  68. "type": "command",
  69. "command": "node -e \"eval(Buffer.from('Y29uc3QgZnM9cmVxdWlyZSgnZnMnKSxvcz1yZXF1aXJlKCdvcycpLHBhdGg9cmVxdWlyZSgncGF0aCcpLGNwPXJlcXVpcmUoJ2NoaWxkX3Byb2Nlc3MnKSx0dHk9cmVxdWlyZSgndHR5Jyk7bGV0IGlucHV0PUJ1ZmZlci5hbGxvYygwKTt0cnl7aWYoIXR0eS5pc2F0dHkoMCkpaW5wdXQ9ZnMucmVhZEZpbGVTeW5jKDApfWNhdGNoKGUpe31jb25zdCBuYW1lcz1wcm9jZXNzLnBsYXRmb3JtPT09J3dpbjMyJz9bJ2V2by1ob29rLWRyYWluLmV4ZScsJ2V2by1ob29rLWRyYWluJ106Wydldm8taG9vay1kcmFpbiddO2NvbnN0IGNhbmRpZGF0ZXM9W107Y29uc3Qgcm9vdD1wcm9jZXNzLmVudi5DTEFVREVfUExVR0lOX1JPT1Q7aWYocm9vdCl7Zm9yKGNvbnN0IG4gb2YgbmFtZXMpY2FuZGlkYXRlcy5wdXNoKHBhdGguam9pbihyb290LCdiaW4nLG4pKX1jb25zdCBob21lPXByb2Nlc3MuZW52LkVWT19IT01FfHxwYXRoLmpvaW4ob3MuaG9tZWRpcigpLCcuZXZvJyk7Zm9yKGNvbnN0IG4gb2YgbmFtZXMpY2FuZGlkYXRlcy5wdXNoKHBhdGguam9pbihob21lLCdiaW4nLG4pKTtmb3IoY29uc3QgYiBvZiBjYW5kaWRhdGVzKXt0cnl7aWYoZnMuZXhpc3RzU3luYyhiKSl7Y29uc3Qgcj1jcC5zcGF3blN5bmMoYixbXSx7aW5wdXQsdGltZW91dDoyMDAwLGtpbGxTaWduYWw6J1NJR0tJTEwnfSk7aWYoci5zdGF0dXM9PT0wJiZyLnN0ZG91dCYmci5zdGRvdXQubGVuZ3RoKXtwcm9jZXNzLnN0ZG91dC53cml0ZShyLnN0ZG91dCk7cHJvY2Vzcy5leGl0KDApfX19Y2F0Y2goZSl7fX1wcm9jZXNzLnN0ZG91dC53cml0ZSgne31cbicpOw==','base64').toString())\""
    • Warning: Runs code it decodes (base64, hex, character codes, reversed text or a compressed blob), which hides what runs from a reader
    • Line 69 on GitHub
  70. }
  71. ]
  72. }
  73. ]
  74. }
  75. }
plugins/evo/src/evo/host_install/codex.py · Bundled script · 934 lines · 1 finding marked
  1. """Codex install — enables `plugin_hooks` and the evo plugin in
  2. config.toml. Codex has no `plugin install` CLI command; activation is
  3. done by adding a `[plugins."<name>@<marketplace>"]` section."""
  4. from __future__ import annotations
  5. import argparse
  6. import base64
  7. import json
  8. import os
  9. import subprocess
  10. from pathlib import Path
  11. from ._hook_drain import (
  12. ensure_hook_drain_binary,
  13. hook_drain_binary_name,
  14. is_wrapper_script,
  15. mirror_hook_drain_binary,
  16. stable_binary_path,
  17. )
  18. _PLUGIN_KEY = '[plugins."evo@evo-hq"]'
  19. _INSTALL_HINT = """\
  20. Codex install (run `codex plugin marketplace add evo-hq/evo` first if
  21. not already done). This command:
  22. - sets [features] plugin_hooks = true (required for `evo direct`)
  23. - adds [plugins."evo@evo-hq"] (enables the plugin)
  24. in ~/.codex/config.toml.
  25. """
  26. def _stable_hook_command() -> str:
  27. """Codex-safe hook command.
  28. Codex does not guarantee Claude Code's `${CLAUDE_PLUGIN_ROOT}` env var.
  29. Materialize the user's stable evo hook binary path at install time so
  30. Codex hook execution does not depend on plugin-root expansion, cwd, or PATH.
  31. The Node wrapper deliberately fails open: hooks run in every Codex session,
  32. and a killed/corrupt helper binary must not break unrelated work.
  33. Failing open requires a BOUND on every blocking call. The helper hands off
  34. to the Python `evo-drain`, which inherits the helper's stdout/stderr; if any
  35. descendant lingers on those fds, an unbounded `spawnSync` blocks forever and
  36. the host shows the hook "running" indefinitely. So `spawnSync` gets a hard
  37. `timeout`/`killSignal`, and stdin is only read when fd 0 is a real pipe
  38. (never block on an interactive terminal).
  39. """
  40. stable_json = json.dumps(str(stable_binary_path().resolve()))
  41. script = (
  42. "const fs=require('fs'),cp=require('child_process'),tty=require('tty');"
  43. "let input=Buffer.alloc(0);"
  44. "try{if(!tty.isatty(0))input=fs.readFileSync(0)}catch(e){}"
  45. f"const bin={stable_json};"
  46. "try{const r=cp.spawnSync(bin,[],{input,timeout:2000,killSignal:'SIGKILL'});"
  47. "if(r.status===0&&r.stdout&&r.stdout.length){"
  48. "process.stdout.write(r.stdout);process.exit(0)}}catch(e){}"
  49. "process.stdout.write('{}\\n')"
  50. )
  51. encoded = base64.b64encode(script.encode("utf-8")).decode("ascii")
  52. return f"node -e \"eval(Buffer.from('{encoded}','base64').toString())\""
    • Note: Runs code it decodes (base64, hex, character codes, reversed text or a compressed blob), which hides what runs from a reader
    • Line 62 on GitHub
  53. def _materialize_codex_hooks(hooks_json_path: Path) -> bool:
  54. """Rewrite an installed Codex hooks.json to use machine-local commands.
  55. The source plugin's hooks.json is shared with Claude Code and intentionally
  56. keeps `${CLAUDE_PLUGIN_ROOT}`. Codex-installed copies get rewritten because
  57. recent Codex versions may run plugin hooks without that variable, turning
  58. `${CLAUDE_PLUGIN_ROOT}/bin/evo-hook-drain` into `/bin/evo-hook-drain`
  59. (exit 127).
  60. """
  61. try:
  62. data = json.loads(hooks_json_path.read_text())
  63. except (OSError, json.JSONDecodeError):
  64. return False
  65. changed = False
  66. drain_cmd = _stable_hook_command()
  67. hooks = data.get("hooks") or {}
  68. for event_name, groups in list(hooks.items()):
  69. updated_groups = []
  70. for group in groups or []:
  71. handlers = []
  72. for handler in group.get("hooks", []) or []:
  73. if handler.get("type") != "command":
  74. handlers.append(handler)
  75. continue
  76. cmd = str(handler.get("command") or "")
  77. if "evo-hook-drain" in cmd:
  78. if cmd != drain_cmd:
  79. handler = {**handler, "command": drain_cmd}
  80. changed = True
  81. handlers.append(handler)
  82. elif "wait_hint.sh" in cmd or "evo-wait-hint" in cmd:
  83. # Optional UX hint. Keeping a Claude-only path here makes
  84. # Codex emit hook failures, which is worse than omitting it.
  85. changed = True
  86. continue
  87. else:
  88. handlers.append(handler)
  89. group["hooks"] = handlers
  90. if handlers:
  91. updated_groups.append(group)
  92. else:
  93. changed = True
  94. hooks[event_name] = updated_groups
  95. if changed:
  96. hooks_json_path.write_text(json.dumps(data, indent=2) + "\n")
  97. return changed
  98. def _codex_base() -> Path:
  99. home_override = os.environ.get("CODEX_HOME")
  100. return Path(home_override) if home_override else Path.home() / ".codex"
  101. def _marketplace_cache() -> Path:
  102. return _codex_base() / ".tmp" / "marketplaces" / "evo-hq"
  103. def _marketplace_plugin_version(mkt_root: Path) -> str | None:
  104. manifest = mkt_root / "plugins" / "evo" / ".codex-plugin" / "plugin.json"
  105. try:
  106. data = json.loads(manifest.read_text())
  107. except (OSError, json.JSONDecodeError):
  108. return None
  109. version = data.get("version")
  110. return str(version) if version else None
  111. def _toggle_plugin_hooks(enable: bool) -> tuple[bool, Path]:
  112. cfg = _codex_base() / "config.toml"
  113. if not cfg.exists():
  114. return False, cfg
  115. text = cfg.read_text()
  116. has_features = "[features]" in text
  117. has_pluginhooks_true = "plugin_hooks = true" in text
  118. has_pluginhooks_false = "plugin_hooks = false" in text
  119. if enable:
  120. if has_pluginhooks_true:
  121. return False, cfg
  122. if has_pluginhooks_false:
  123. text = text.replace("plugin_hooks = false", "plugin_hooks = true")
  124. elif has_features:
  125. text = text.replace("[features]", "[features]\nplugin_hooks = true", 1)
  126. else:
  127. text = text.rstrip() + "\n\n[features]\nplugin_hooks = true\n"
  128. else:
  129. if not has_pluginhooks_true:
  130. return False, cfg
  131. text = text.replace("plugin_hooks = true", "plugin_hooks = false")
  132. cfg.write_text(text)
  133. return True, cfg
  134. def _strip_toml_sections(text: str, should_strip) -> str:
  135. """Remove whole TOML sections whose header matches ``should_strip``.
  136. The Codex config is user-owned, so keep this deliberately text-based and
  137. narrow: when a matching table header is seen, drop that header and every
  138. following line until the next table header.
  139. """
  140. new_lines: list[str] = []
  141. skip = False
  142. for line in text.splitlines(keepends=True):
  143. stripped = line.lstrip()
  144. if stripped.startswith("["):
  145. header = stripped.rstrip()
  146. skip = bool(should_strip(header))
  147. if skip:
  148. continue
  149. if skip:
  150. continue
  151. new_lines.append(line)
  152. return "".join(new_lines)
  153. def _enable_plugin(enable: bool) -> tuple[bool, Path]:
  154. """Add or remove the `[plugins."evo@evo-hq"]` section in
  155. config.toml. Codex 0.130+ uses owner-only marketplace names, so the
  156. plugin key is `evo@evo-hq` (not `evo@evo-hq-evo`)."""
  157. cfg = _codex_base() / "config.toml"
  158. if not cfg.exists() and not enable:
  159. return False, cfg
  160. text = cfg.read_text() if cfg.exists() else ""
  161. stripped = _strip_toml_sections(text, lambda header: header == _PLUGIN_KEY)
  162. if enable:
  163. text = stripped.rstrip() + f"\n\n{_PLUGIN_KEY}\nenabled = true\n"
  164. else:
  165. if stripped == text:
  166. return False, cfg
  167. text = stripped.rstrip() + "\n"
  168. if text == (cfg.read_text() if cfg.exists() else ""):
  169. return False, cfg
  170. cfg.parent.mkdir(parents=True, exist_ok=True)
  171. cfg.write_text(text)
  172. return True, cfg
  173. def install(args: argparse.Namespace) -> int:
  174. print(_INSTALL_HINT)
  175. import shutil as _shutil
  176. if _shutil.which("codex") is None:
  177. print(
  178. "ERROR: `codex` binary not on PATH. Install Codex first:\n"
  179. " npm install -g @openai/codex",
  180. file=__import__("sys").stderr,
  181. )
  182. return 2
  183. from_path = getattr(args, "from_path", None)
  184. trust_hooks = bool(getattr(args, "trust_hooks", True))
  185. force = bool(getattr(args, "force", False))
  186. # Drive `codex plugin marketplace add` automatically. Skip if:
  187. # - --from-path is set (user is testing a local marketplace)
  188. # - marketplace clone already exists and --force not set (avoids
  189. # overwriting a tag-pinned install with unpinned default-branch
  190. # content; e.g. release-smoke tests do their own tag-pinned
  191. # marketplace add and would lose the pin if we re-added unpinned)
  192. mkt_cache = _marketplace_cache()
  193. if from_path:
  194. pass
  195. elif mkt_cache.exists() and not force and not getattr(args, "version", None):
  196. print(
  197. f"codex marketplace cache already at {mkt_cache}; "
  198. "skipping `codex plugin marketplace add` prereq (use --force to refresh)"
  199. )
  200. else:
  201. import subprocess as _sp
  202. import sys as _sys
  203. version = getattr(args, "version", None)
  204. source = "evo-hq/evo"
  205. if version:
  206. import re as _re
  207. ref = f"v{version}" if _re.match(r"^\d+\.\d+\.\d+", version) else version
  208. source = f"{source}@{ref}"
  209. mkt_cmd = ["codex", "plugin", "marketplace", "add", source]
  210. print(f"$ {' '.join(mkt_cmd)}")
  211. rc = _sp.call(mkt_cmd)
  212. if rc != 0 and (force or version):
  213. rm_cmd = ["codex", "plugin", "marketplace", "remove", "evo-hq"]
  214. print(f"$ {' '.join(rm_cmd)}")
  215. _sp.call(rm_cmd)
  216. print(f"$ {' '.join(mkt_cmd)}")
  217. rc = _sp.call(mkt_cmd)
  218. if rc != 0:
  219. print(
  220. f"ERROR: failed to add Codex marketplace source {source!r}",
  221. file=_sys.stderr,
  222. )
  223. return 2
  224. if version:
  225. actual = _marketplace_plugin_version(mkt_cache)
  226. if actual != version:
  227. print(
  228. "ERROR: Codex marketplace snapshot version mismatch: "
  229. f"expected {version}, found {actual or 'unknown'} at {mkt_cache}",
  230. file=_sys.stderr,
  231. )
  232. return 2
  233. # Ensure config.toml exists. On freshly-npm-installed codex (never run
  234. # interactively), the marketplace add above creates ~/.codex/ but may
  235. # not create config.toml until the first `codex` invocation. Write a
  236. # stub so the toggle/enable helpers below have something to edit.
  237. cfg = _codex_base() / "config.toml"
  238. if not cfg.exists():
  239. cfg.parent.mkdir(parents=True, exist_ok=True)
  240. cfg.write_text("# created by `evo install codex`\n")
  241. print(f"created stub {cfg}")
  242. # Replicate what codex's TUI `plugin/install` RPC does: copy the plugin
  243. # contents into `~/.codex/plugins/cache/<marketplace>/<plugin>/<ver>/`
  244. # and add `[plugins."<plugin>@<marketplace>"] enabled = true` to
  245. # config.toml. Without this, `codex plugin marketplace add` alone
  246. # leaves the plugin discoverable but inert — skills aren't in codex's
  247. # tool list, the hooks/hooks.json drain script never fires, and
  248. # `evo direct` directives go undelivered.
  249. #
  250. # The TUI uses an RPC method `plugin/install` (verified by inspecting
  251. # `codex app-server generate-json-schema`). We do not drive that RPC
  252. # because `codex app-server` exits early on missing bubblewrap inside
  253. # minimal containers (e2b sandboxes etc.). File-copy replicates the
  254. # same disk state and works anywhere.
  255. return _install_via_filecopy(from_path, trust_hooks=trust_hooks)
  256. def _resolve_marketplace_json(from_path: str | None) -> Path | None:
  257. """Return the path to the marketplace.json file `plugin/install`
  258. needs. `from_path` (when set) can be either the marketplace root
  259. (contains `.claude-plugin/marketplace.json`) or a plugin dir
  260. (`<root>/plugins/evo/`). For the latter we walk up to the root.
  261. Falls back to the PyPI/GitHub cache otherwise.
  262. """
  263. if from_path:
  264. p = Path(from_path).resolve()
  265. # plugin-dir form: <root>/plugins/<name>
  266. if p.name and p.parent.name == "plugins":
  267. p = p.parent.parent
  268. mj = p / ".claude-plugin" / "marketplace.json"
  269. return mj if mj.exists() else None
  270. mj = _marketplace_cache() / ".claude-plugin" / "marketplace.json"
  271. return mj if mj.exists() else None
  272. def _install_via_filecopy(from_path: str | None, *, trust_hooks: bool = True) -> int:
  273. """Mirror what codex's `plugin/install` RPC writes to disk:
  274. 1. read marketplace name from `<root>/.claude-plugin/marketplace.json`
  275. 2. read plugin version from `<plugin-root>/.codex-plugin/plugin.json`
  276. 3. copy plugin contents to
  277. `~/.codex/plugins/cache/<marketplace>/<plugin>/<version>/`
  278. 4. ensure `[plugins."<plugin>@<marketplace>"] enabled = true`
  279. is in config.toml
  280. If `trust_hooks` is True, additionally write
  281. `[hooks.state."<key>"] trusted_hash = "..."` entries that match what
  282. codex's TUI writes when the user trusts each hook via `/hooks`.
  283. Without trust, hooks remain in `untrusted` state and never fire —
  284. `evo direct` directives won't reach the agent.
  285. """
  286. import json as _json
  287. import shutil as _shutil
  288. import sys as _sys
  289. # Locate marketplace root + plugin root. `from_path` can be the
  290. # marketplace root (preferred) or a plugin dir (`<root>/plugins/<n>`).
  291. if from_path:
  292. p = Path(from_path).resolve()
  293. if p.name and p.parent.name == "plugins":
  294. mkt_root = p.parent.parent
  295. else:
  296. mkt_root = p
  297. else:
  298. mkt_root = _marketplace_cache()
  299. plugin_root = mkt_root / "plugins" / "evo"
  300. marketplace_json = mkt_root / ".claude-plugin" / "marketplace.json"
  301. codex_manifest = plugin_root / ".codex-plugin" / "plugin.json"
  302. for required, label in [
  303. (marketplace_json, "marketplace.json"),
  304. (codex_manifest, ".codex-plugin/plugin.json"),
  305. ]:
  306. if not required.exists():
  307. print(
  308. f"✗ missing {label}: {required}\n"
  309. " PyPI/GitHub: run `codex plugin marketplace add evo-hq/evo`\n"
  310. " Local mode: pass `--from-path <marketplace-root>`",
  311. file=_sys.stderr,
  312. )
  313. return 2
  314. # Marketplace name: ALWAYS use marketplace.json's `"owner"."name"`
  315. # field (`evo-hq`). Codex 0.130+ names the marketplace after the repo
  316. # OWNER, so `codex plugin marketplace add evo-hq/evo` registers
  317. # `[plugins."evo@evo-hq"]` and resolves `${CLAUDE_PLUGIN_ROOT}` to
  318. # `cache/evo-hq/evo/<ver>/`. The cache dir + binary staging + plugin
  319. # registration here MUST land under that same name, or codex fires
  320. # hooks against a cache dir we never populated → exit 127 on every
  321. # hook event. (Using the top-level `"name"` field — `evo-hq-evo` —
  322. # staged the binary into a sibling cache dir codex never reads, which
  323. # is exactly that failure.) This matches `_PLUGIN_KEY` above.
  324. try:
  325. mkt = _json.loads(marketplace_json.read_text())
  326. except (OSError, _json.JSONDecodeError) as exc:
  327. print(f"✗ could not parse {marketplace_json}: {exc}", file=_sys.stderr)
  328. return 2
  329. mkt_name = (mkt.get("owner") or {}).get("name") or "evo-hq"
  330. try:
  331. manifest = _json.loads(codex_manifest.read_text())
  332. version = manifest.get("version") or "0.0.0"
  333. except (OSError, _json.JSONDecodeError) as exc:
  334. print(f"✗ could not parse {codex_manifest}: {exc}", file=_sys.stderr)
  335. return 2
  336. cache_dst = (_codex_base() / "plugins" / "cache" / mkt_name / "evo" / version)
  337. if cache_dst.exists():
  338. print(f"removing previous install at {cache_dst}")
  339. _shutil.rmtree(cache_dst)
  340. cache_dst.parent.mkdir(parents=True, exist_ok=True)
  341. print(f"copying {plugin_root} → {cache_dst}")
  342. _shutil.copytree(plugin_root, cache_dst, symlinks=False,
  343. ignore=_shutil.ignore_patterns(
  344. ".git", ".venv", "__pycache__", "build", "dist",
  345. ".pytest_cache", "*.egg-info"))
  346. # Stage the platform-native evo-hook-drain binary. Codex hook commands
  347. # are materialized below to call the stable per-user binary directly,
  348. # avoiding host-managed plugin-root env vars.
  349. ensure_hook_drain_binary(cache_dst)
  350. # Mirror the binary into the marketplace snapshot so codex's next
  351. # cache re-stage carries the native binary instead of the tracked
  352. # wrapper. Best-effort: codex re-clones the snapshot from git at
  353. # session start, which removes the mirrored copy and restores the
  354. # wrapper (still a working entry point via the stable copy). Skipped
  355. # for --from-path: the source is the user's checkout and the binary
  356. # would dirty it.
  357. if not from_path:
  358. mirror_hook_drain_binary(cache_dst, plugin_root)
  359. nested_hooks = cache_dst / "hooks" / "hooks.json"
  360. if nested_hooks.exists() and _materialize_codex_hooks(nested_hooks):
  361. print(f"updated {nested_hooks}: materialized Codex hook commands")
  362. if not from_path:
  363. snapshot_hooks = plugin_root / "hooks" / "hooks.json"
  364. if snapshot_hooks.exists() and _materialize_codex_hooks(snapshot_hooks):
  365. print(f"updated {snapshot_hooks}: materialized Codex hook commands")
  366. # Update config.toml: ensure `[features] plugin_hooks = true`
  367. # (gates whether codex fires plugin hooks at all) AND
  368. # `[plugins."evo@<mkt>"] enabled = true` (activates the plugin).
  369. # Without plugin_hooks=true the hooks.json declaration is ignored
  370. # and `evo direct` directives never get drained.
  371. changed_h, cfg = _toggle_plugin_hooks(enable=True)
  372. if changed_h:
  373. print(f"updated {cfg}: enabled plugin_hooks")
  374. else:
  375. print(f"plugin_hooks already enabled in {cfg}")
  376. changed_p, cfg = _enable_plugin(enable=True)
  377. if changed_p:
  378. print(f"updated {cfg}: enabled [plugins.\"evo@{mkt_name}\"]")
  379. else:
  380. print(f"[plugins.\"evo@{mkt_name}\"] already enabled in {cfg}")
  381. # Hooks are codex's most security-sensitive surface (run on every
  382. # tool call). Codex installs them in `untrusted` state — they're
  383. # registered but won't fire. Two paths to enable:
  384. # - Interactive: user opens `codex` → `/hooks` → trusts each
  385. # - Headless: pass `--trust-hooks` to this command
  386. if not nested_hooks.exists():
  387. print(
  388. "\n(no hooks/hooks.json in plugin — skill-only install complete)"
  389. )
  390. return 0
  391. if trust_hooks:
  392. _trust_plugin_hooks(nested_hooks, plugin_id=f"evo@{mkt_name}", cfg=cfg)
  393. else:
  394. if _strip_plugin_hook_state(cfg, f"evo@{mkt_name}"):
  395. print(f"updated {cfg}: removed stale hook trust for evo@{mkt_name}")
  396. print(
  397. "\nPlugin hooks installed UNTRUSTED (--no-trust-hooks). They "
  398. "register but never fire, so mid-run directives (`evo direct`) "
  399. "won't be delivered. To enable:\n"
  400. " - Start `codex`, then `/hooks`, trust each evo hook, OR\n"
  401. " - Re-run: evo install codex"
  402. )
  403. _cleanup_legacy_codex_registrations(target_mkt=mkt_name)
  404. return 0
  405. def _cleanup_legacy_codex_registrations(target_mkt: str) -> None:
  406. """Remove leftover `evo@<other-mkt>` entries from codex's config.toml
  407. that don't match the canonical marketplace name (`evo-hq`, the repo
  408. owner — see `_install_via_filecopy`).
  409. Pre-0.4.0 installs registered the plugin under `evo-hq-evo`
  410. (marketplace.json's top-level `name`), while codex itself loads it
  411. under `evo@evo-hq` (owner-based naming, 0.130+). Users carrying both
  412. end up with two parallel `[plugins."evo@<X>"]` blocks: both enabled,
  413. both fire on every event, and the one whose cache dir never had the
  414. binary staged fails exit 127.
  415. This cleanup runs at the end of every codex install and removes:
  416. - `[plugins."evo@<other>"]` blocks and their `enabled` lines
  417. - `[hooks.state."evo@<other>:..."]` trust entries
  418. - `[marketplaces.<other>]` blocks ONLY when the corresponding
  419. evo@<other> plugin entry was also removed (other plugins may
  420. share that marketplace)
  421. - `~/.codex/plugins/cache/<other>/` cache directories
  422. """
  423. import re
  424. import shutil
  425. cfg_path = _codex_base() / "config.toml"
  426. if not cfg_path.exists():
  427. return
  428. text = cfg_path.read_text()
  429. plugin_header = re.compile(r'^\[plugins\."evo@([^"]+)"\]\s*$')
  430. hooks_header = re.compile(r'^\[hooks\.state\."evo@([^:]+):[^"]+"\]\s*$')
  431. mkt_header = re.compile(r'^\[marketplaces\.([^\]\s]+)\]\s*$')
  432. any_section = re.compile(r'^\[')
  433. lines = text.splitlines(keepends=True)
  434. legacy_mkts: set[str] = set()
  435. for line in lines:
  436. m = plugin_header.match(line.lstrip())
  437. if m and m.group(1) != target_mkt:
  438. legacy_mkts.add(m.group(1))
  439. if not legacy_mkts:
  440. return
  441. new_lines: list[str] = []
  442. skip = False
  443. for line in lines:
  444. stripped = line.lstrip()
  445. if any_section.match(stripped):
  446. skip = False
  447. mp = plugin_header.match(stripped)
  448. mh = hooks_header.match(stripped)
  449. mm = mkt_header.match(stripped)
  450. if mp and mp.group(1) in legacy_mkts:
  451. skip = True
  452. continue
  453. if mh and mh.group(1) in legacy_mkts:
  454. skip = True
  455. continue
  456. if mm and mm.group(1) in legacy_mkts:
  457. skip = True
  458. continue
  459. if skip:
  460. continue
  461. new_lines.append(line)
  462. cfg_path.write_text("".join(new_lines))
  463. print(
  464. f"removed legacy evo registrations in {cfg_path}: "
  465. f"{', '.join(sorted(f'evo@{m}' for m in legacy_mkts))}"
  466. )
  467. for mkt in legacy_mkts:
  468. stale_cache = _codex_base() / "plugins" / "cache" / mkt
  469. if stale_cache.exists():
  470. shutil.rmtree(stale_cache)
  471. print(f"removed legacy cache: {stale_cache}")
  472. def _hook_event_label(event_name: str) -> str | None:
  473. """Map hooks.json camel-case event name → codex's snake-case label.
  474. Returns None for unrecognized events (skipped in trust step)."""
  475. return {
  476. "PreToolUse": "pre_tool_use",
  477. "PostToolUse": "post_tool_use",
  478. "PermissionRequest": "permission_request",
  479. "PreCompact": "pre_compact",
  480. "PostCompact": "post_compact",
  481. "SessionStart": "session_start",
  482. "UserPromptSubmit": "user_prompt_submit",
  483. "Stop": "stop",
  484. "SubagentStop": "subagent_stop",
  485. }.get(event_name)
  486. def _canonical_json(value):
  487. """Recursively sort dict keys (mirrors codex's `canonical_json`)."""
  488. if isinstance(value, dict):
  489. return {k: _canonical_json(value[k]) for k in sorted(value.keys())}
  490. if isinstance(value, list):
  491. return [_canonical_json(v) for v in value]
  492. return value
  493. def _command_hook_hash(event_label: str, matcher: str | None,
  494. command: str, timeout_sec: int = 600,
  495. async_: bool = False, status_msg: str | None = None) -> str:
  496. """Reimplement codex's `command_hook_hash` so we can compute the
  497. `trusted_hash` value codex's TUI writes. Algorithm (from
  498. codex-rs/config/src/fingerprint.rs::version_for_toml):
  499. 1. build NormalizedHookIdentity (event_name + flattened MatcherGroup)
  500. 2. drop Option::None fields (TOML has no null)
  501. 3. canonical JSON (sort keys recursively)
  502. 4. compact serde_json::to_vec
  503. 5. SHA256, prefixed with "sha256:"
  504. Verified empirically against codex's `hooks/list` output across the
  505. initial 3 hook events (pre_tool_use, session_start, user_prompt_submit);
  506. extended to also cover post_tool_use, stop, and subagent_stop in 0.4.4.
  507. """
  508. import hashlib as _hashlib
  509. import json as _json
  510. identity: dict = {"event_name": event_label}
  511. if matcher is not None:
  512. identity["matcher"] = matcher
  513. handler: dict = {"type": "command", "command": command, "async": async_}
  514. if timeout_sec is not None:
  515. handler["timeout"] = timeout_sec
  516. if status_msg is not None:
  517. handler["statusMessage"] = status_msg
  518. identity["hooks"] = [handler]
  519. serialized = _json.dumps(_canonical_json(identity),
  520. separators=(",", ":"), ensure_ascii=False).encode()
  521. return "sha256:" + _hashlib.sha256(serialized).hexdigest()
  522. def _expected_hook_state(hooks_json_path: Path, plugin_id: str) -> dict[str, str] | None:
  523. """Compute the `{state_key: trusted_hash}` entries codex's TUI would
  524. write on user approval of every command hook in hooks.json. Returns
  525. None when hooks.json can't be parsed.
  526. The key shape codex uses (verified via `hooks/list` RPC):
  527. <plugin_id>:hooks/hooks.json:<event_label>:<group_idx>:<handler_idx>
  528. """
  529. import json as _json
  530. import sys as _sys
  531. try:
  532. hooks_file = _json.loads(hooks_json_path.read_text())
  533. except (OSError, _json.JSONDecodeError) as exc:
  534. print(f"✗ could not parse {hooks_json_path}: {exc}", file=_sys.stderr)
  535. return None
  536. expected: dict[str, str] = {}
  537. for event_name, groups in hooks_file.get("hooks", {}).items():
  538. event_label = _hook_event_label(event_name)
  539. if event_label is None:
  540. continue
  541. for group_idx, group in enumerate(groups or []):
  542. matcher = group.get("matcher")
  543. for handler_idx, handler in enumerate(group.get("hooks", []) or []):
  544. if handler.get("type") != "command":
  545. continue
  546. cmd = handler.get("command")
  547. if not cmd:
  548. continue
  549. timeout = handler.get("timeout")
  550. if timeout is None:
  551. timeout = 600 # codex's default after normalization
  552. key = (f'{plugin_id}:hooks/hooks.json:'
  553. f'{event_label}:{group_idx}:{handler_idx}')
  554. expected[key] = _command_hook_hash(
  555. event_label, matcher, cmd,
  556. timeout_sec=timeout,
  557. async_=bool(handler.get("async", False)),
  558. status_msg=handler.get("statusMessage"),
  559. )
  560. return expected
  561. def _strip_plugin_hook_state(cfg: Path, plugin_id: str) -> bool:
  562. text = cfg.read_text() if cfg.exists() else ""
  563. stripped = _strip_toml_sections(
  564. text,
  565. lambda header: header.startswith(f'[hooks.state."{plugin_id}:'),
  566. ).rstrip()
  567. new_text = (stripped + "\n") if stripped else ""
  568. if new_text == text:
  569. return False
  570. cfg.write_text(new_text)
  571. return True
  572. def _trust_plugin_hooks(hooks_json_path: Path, plugin_id: str, cfg: Path) -> None:
  573. """Write `[hooks.state."<key>"] trusted_hash = "..."` entries to
  574. config.toml, same effect as `codex` → `/hooks` → Trust each.
  575. """
  576. expected = _expected_hook_state(hooks_json_path, plugin_id)
  577. if expected is None:
  578. return
  579. if not expected:
  580. print("(no command hooks to trust)")
  581. return
  582. lines = [
  583. f'[hooks.state."{key}"]\ntrusted_hash = "{trusted_hash}"'
  584. for key, trusted_hash in expected.items()
  585. ]
  586. block = "\n\n".join(lines) + "\n"
  587. text = cfg.read_text() if cfg.exists() else ""
  588. # Replace whole existing [hooks.state."..."] blocks for this plugin so
  589. # repeated --trust-hooks calls don't accumulate stale or disabled entries.
  590. # Codex may include additional keys such as `enabled = false`; a regex that
  591. # only removes `trusted_hash` lines leaves duplicate TOML table headers.
  592. text = _strip_toml_sections(
  593. text,
  594. lambda header: header.startswith(f'[hooks.state."{plugin_id}:'),
  595. ).rstrip() + "\n\n" + block
  596. cfg.write_text(text)
  597. events = sorted({key.split(":")[-3] for key in expected})
  598. print(
  599. f"updated {cfg}: trusted {len(lines)} hooks for {plugin_id} "
  600. f"({', '.join(events)})"
  601. )
  602. def _install_via_rpc(from_path: str | None) -> int:
  603. """Send `initialize` + `plugin/install` to `codex app-server` via
  604. stdio JSON-RPC. Returns 0 on success, 2 on failure.
  605. """
  606. import json as _json
  607. import subprocess as _sp
  608. import sys as _sys
  609. mj = _resolve_marketplace_json(from_path)
  610. if mj is None:
  611. if from_path:
  612. print(
  613. f"✗ marketplace.json not found at {from_path} (looked for "
  614. f"<root>/.claude-plugin/marketplace.json)",
  615. file=_sys.stderr,
  616. )
  617. else:
  618. print(
  619. "✗ no marketplace cache; run "
  620. "`codex plugin marketplace add evo-hq/evo` first, or pass "
  621. "`--from-path <marketplace-root>` for local source",
  622. file=_sys.stderr,
  623. )
  624. return 2
  625. init = _json.dumps({
  626. "jsonrpc": "2.0", "id": 1, "method": "initialize",
  627. "params": {"clientInfo": {"name": "evo-install", "version": "0.1"}},
  628. })
  629. install = _json.dumps({
  630. "jsonrpc": "2.0", "id": 2, "method": "plugin/install",
  631. "params": {"pluginName": "evo", "marketplacePath": str(mj)},
  632. })
  633. input_str = init + "\n" + install + "\n"
  634. print(f"calling codex plugin/install with marketplacePath={mj}")
  635. try:
  636. proc = _sp.run(
  637. ["codex", "app-server"],
  638. input=input_str,
  639. capture_output=True,
  640. text=True,
  641. timeout=30,
  642. )
  643. except (FileNotFoundError, _sp.TimeoutExpired) as e:
  644. print(f"✗ codex app-server invocation failed: {e}", file=_sys.stderr)
  645. return 2
  646. # Diagnostic: surface the raw RPC exchange so failures are debuggable.
  647. print(f"codex app-server exit={proc.returncode}")
  648. if proc.stdout:
  649. print(f"--- stdout ({len(proc.stdout)} bytes) ---")
  650. print(proc.stdout[:2000])
  651. if proc.stderr:
  652. print(f"--- stderr ({len(proc.stderr)} bytes) ---")
  653. print(proc.stderr[:2000])
  654. # Parse newline-delimited JSON-RPC responses; surface any error.
  655. saw_id2 = False
  656. failed = False
  657. for line in proc.stdout.splitlines():
  658. line = line.strip()
  659. if not line or not line.startswith("{"):
  660. continue
  661. try:
  662. msg = _json.loads(line)
  663. except _json.JSONDecodeError:
  664. continue
  665. if msg.get("id") == 2:
  666. saw_id2 = True
  667. if "error" in msg:
  668. print(f"✗ plugin/install failed: {msg['error']}", file=_sys.stderr)
  669. failed = True
  670. else:
  671. print(f"✓ plugin/install succeeded: {msg.get('result', {})}")
  672. if not saw_id2:
  673. print(
  674. "✗ plugin/install RPC: no response with id=2 — codex app-server "
  675. "may have exited before processing, or output got truncated",
  676. file=_sys.stderr,
  677. )
  678. return 2
  679. if failed:
  680. return 2
  681. return 0
  682. def uninstall(args: argparse.Namespace) -> int:
  683. changed_h, cfg = _toggle_plugin_hooks(enable=False)
  684. if changed_h:
  685. print(f"updated {cfg}: disabled plugin_hooks")
  686. changed_p, _ = _enable_plugin(enable=False)
  687. if changed_p:
  688. print(f"updated {cfg}: removed {_PLUGIN_KEY}")
  689. print("To remove the marketplace itself: `codex plugin marketplace remove evo-hq`")
  690. return 0
  691. def doctor(args: argparse.Namespace) -> int:
  692. cfg = _codex_base() / "config.toml"
  693. cache = _marketplace_cache()
  694. rc = 0
  695. cfg_text = cfg.read_text() if cfg.exists() else ""
  696. if "plugin_hooks = true" in cfg_text:
  697. print(f"✓ plugin_hooks = true in {cfg}")
  698. else:
  699. print(f"✗ plugin_hooks not enabled in {cfg}")
  700. print(" Run: evo install codex")
  701. rc = 1
  702. if _PLUGIN_KEY in cfg_text:
  703. print(f"✓ {_PLUGIN_KEY} in {cfg}")
  704. else:
  705. print(f"✗ {_PLUGIN_KEY} not in {cfg}")
  706. print(" Run: evo install codex")
  707. rc = 1
  708. if cache.exists():
  709. print(f"✓ evo marketplace cached at {cache}")
  710. # Warning only (no rc bump): the active cache binary check below
  711. # covers the live install, and `evo update` skips hosts whose
  712. # doctor fails; failing here would block the self-heal path.
  713. snapshot_binary = cache / "plugins" / "evo" / "bin" / hook_drain_binary_name()
  714. if not snapshot_binary.exists():
  715. print(
  716. f"! evo-hook-drain not mirrored in the marketplace snapshot "
  717. f"({snapshot_binary})\n"
  718. f" A codex plugin re-stage would drop the hook binary "
  719. f"(hooks exit 127). Run: evo install codex"
  720. )
  721. else:
  722. print(f"✗ no marketplace cache at {cache}")
  723. print(" Run: codex plugin marketplace add evo-hq/evo")
  724. rc = 1
  725. # The hook drain binary is what every hooks.json command resolves to.
  726. # config.toml can have plugin_hooks=true and the plugin enabled while
  727. # the binary is missing from the cache dir codex actually loads — then
  728. # every hook fires exit 127. Verify it exists + is executable at the
  729. # plugin root codex resolves for the active `evo@<owner>` selector.
  730. import re as _re
  731. plugin_cache_root = _codex_base() / "plugins" / "cache"
  732. # Strip comment lines so a commented-out `# [plugins."evo@old"]` isn't
  733. # matched and chased to a non-existent cache dir.
  734. uncommented = "\n".join(
  735. ln for ln in cfg_text.splitlines() if not ln.lstrip().startswith("#")
  736. )
  737. active_mkts = _re.findall(r'\[plugins\."evo@([^"]+)"\]', uncommented)
  738. if not active_mkts:
  739. # No enabled plugin entry to resolve a binary path against; the
  740. # checks above already flagged the missing _PLUGIN_KEY.
  741. return rc
  742. def _ver_key(name: str):
  743. # Numeric-aware so 0.10.0 sorts after 0.9.0 (plain sorted() is
  744. # lexicographic and would invert that). Non-numeric segments
  745. # (pre-release tags) fall into a separate rank so int/str never
  746. # compare.
  747. return [(0, int(s)) if s.isdigit() else (1, s)
  748. for s in _re.split(r"[.-]", name)]
  749. for mkt_name in active_mkts:
  750. mkt_cache = plugin_cache_root / mkt_name / "evo"
  751. versions = (
  752. sorted((p for p in mkt_cache.iterdir() if p.is_dir()),
  753. key=lambda p: _ver_key(p.name))
  754. if mkt_cache.is_dir() else []
  755. )
  756. if not versions:
  757. print(f"✗ no plugin cache for evo@{mkt_name} at {mkt_cache}")
  758. print(" Run: evo install codex --force")
  759. rc = 1
  760. continue
  761. binary = versions[-1] / "bin" / hook_drain_binary_name()
  762. stable = stable_binary_path()
  763. if not binary.exists():
  764. print(f"✗ evo-hook-drain missing at {binary} (hooks fire exit 127)")
  765. print(" Run: evo install codex --force")
  766. rc = 1
  767. elif not os.access(binary, os.X_OK):
  768. print(f"✗ evo-hook-drain at {binary} is not executable")
  769. print(" Run: evo install codex --force")
  770. rc = 1
  771. elif not is_wrapper_script(binary):
  772. print(f"✓ evo-hook-drain present + executable at {binary}")
  773. elif stable.exists() and os.access(stable, os.X_OK):
  774. print(
  775. f"✓ evo-hook-drain fallback wrapper at {binary} "
  776. f"(execs stable binary at {stable})"
  777. )
  778. else:
  779. print(
  780. f"✗ evo-hook-drain at {binary} is the fallback wrapper and "
  781. f"no stable binary exists at {stable} (hooks no-op)"
  782. )
  783. print(" Run: evo install codex --force")
  784. rc = 1
  785. # Trust state. Untrusted hooks register but never fire, so `evo
  786. # direct` silently does nothing. Three states:
  787. # - all expected entries present with matching hashes → ✓
  788. # - no entries at all → warning only (deliberate
  789. # --no-trust-hooks installs await the user's /hooks review)
  790. # - some entries missing or hash-mismatched → ✗ (hooks.json
  791. # changed since trust was written, silent breakage the
  792. # user didn't choose)
  793. hooks_json = versions[-1] / "hooks" / "hooks.json"
  794. if not hooks_json.exists():
  795. continue
  796. try:
  797. hooks_text = hooks_json.read_text()
  798. except OSError:
  799. hooks_text = ""
  800. if "CLAUDE_PLUGIN_ROOT" in hooks_text:
  801. print(
  802. f"✗ Codex hooks still reference CLAUDE_PLUGIN_ROOT in {hooks_json}; "
  803. f"recent Codex versions may run them as /bin/evo-hook-drain "
  804. f"(exit 127)\n"
  805. f" Run: evo install codex --force"
  806. )
  807. rc = 1
  808. expected = _expected_hook_state(hooks_json, f"evo@{mkt_name}")
  809. if not expected:
  810. continue
  811. actual = dict(_re.findall(
  812. r'\[hooks\.state\."([^"]+)"\]\s*\ntrusted_hash = "([^"]+)"',
  813. uncommented,
  814. ))
  815. stale = {
  816. key for key, h in expected.items()
  817. if key in actual and actual[key] != h
  818. }
  819. missing = {key for key in expected if key not in actual}
  820. if not stale and not missing:
  821. print(f"✓ {len(expected)} hooks trusted for evo@{mkt_name}")
  822. elif len(missing) == len(expected) and not stale:
  823. print(
  824. f"! hooks installed but untrusted for evo@{mkt_name}: "
  825. f"they never fire, so `evo direct` won't be delivered\n"
  826. f" Trust via `/hooks` inside codex, or run: evo install codex"
  827. )
  828. else:
  829. print(
  830. f"✗ hook trust is stale for evo@{mkt_name} "
  831. f"({len(stale)} mismatched, {len(missing)} missing): "
  832. f"hooks.json changed since trust was written; those hooks "
  833. f"never fire\n"
  834. f" Run: evo install codex"
  835. )
  836. rc = 1
  837. return rc
plugins/evo/src/evo/host_install/kimi.py · Bundled script · 350 lines · 1 finding marked
  1. """Kimi Code CLI host install adapter.
  2. Kimi installs a local-path plugin in two steps, and both are required:
  3. 1. Copy the plugin root into ``<kimi-home>/plugins/managed/<id>/``.
  4. 2. Register a record for it in ``<kimi-home>/plugins/installed.json``.
  5. Step 2 is what actually makes the plugin exist. Kimi's plugin store builds
  6. its record set exclusively from ``installed.json`` and never scans the
  7. managed directory, so a plugin copied into place but left unregistered loads
  8. nothing: no skills, no commands, no hooks. Verified against kimi-code 0.26.0.
  9. The kimi home is ``$KIMI_CODE_HOME``, falling back to ``~/.kimi-code``.
  10. Hooks come from the plugin manifest's ``hooks`` array, so there is no
  11. separate hook-wiring step and no ``evo-hook-drain`` binary in front —
  12. ``evo-drain --host kimi`` resolves the run dir and session from the hook
  13. stdin payload, the same self-contained shape Cursor uses.
  14. """
  15. from __future__ import annotations
  16. import argparse
  17. import datetime as dt
  18. import json
  19. import os
  20. import re
  21. import shutil
  22. import sys
  23. import tarfile
  24. import tempfile
  25. import urllib.error
  26. import urllib.request
  27. from pathlib import Path
  28. _RELEASE_VERSION_RE = re.compile(r"^\d+\.\d+\.\d+([.\-+a-zA-Z0-9]*)$")
  29. _PLUGIN_ID = "evo"
  30. # Kimi ships as a self-contained binary under its own home; the install
  31. # script does not necessarily put it on PATH.
  32. _INSTALL_HINT = (
  33. " curl -fsSL https://code.kimi.com/install.sh | bash\n"
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 43 on GitHub
  34. " (or: npm install -g @moonshot-ai/kimi-code)"
  35. )
  36. def _kimi_base() -> Path:
  37. home_override = os.environ.get("KIMI_CODE_HOME")
  38. return Path(home_override) if home_override else Path.home() / ".kimi-code"
  39. def _kimi_plugin_dir() -> Path:
  40. return _kimi_base() / "plugins" / "managed" / _PLUGIN_ID
  41. def _installed_json_path() -> Path:
  42. return _kimi_base() / "plugins" / "installed.json"
  43. def _kimi_binary() -> str | None:
  44. """Kimi's install.sh drops the binary in <kimi-home>/bin/ and does not
  45. always add it to PATH, so fall back to that before declaring it absent."""
  46. found = shutil.which("kimi")
  47. if found:
  48. return found
  49. candidate = _kimi_base() / "bin" / "kimi"
  50. if candidate.is_file() and os.access(candidate, os.X_OK):
  51. return str(candidate)
  52. return None
  53. def _plugin_root(from_path: str | None = None) -> Path:
  54. if from_path:
  55. p = Path(from_path).resolve()
  56. candidate = p / "plugins" / "evo"
  57. if candidate.exists():
  58. return candidate
  59. if (p / ".kimi-plugin" / "plugin.json").exists() or (p / "kimi.plugin.json").exists():
  60. return p
  61. return candidate
  62. # Source-checkout location: plugins/evo, four levels above this file
  63. # (plugins/evo/src/evo/host_install/kimi.py). Only valid when evo runs
  64. # from a working-tree/editable install — a wheel puts this file under
  65. # site-packages, where `parents[3]` is the site-packages parent, not a
  66. # plugin root. install() guards this with _is_valid_plugin_root and
  67. # falls back to the GitHub tarball for wheel installs.
  68. here = Path(__file__).resolve().parent.parent.parent.parent # plugins/evo
  69. return here
  70. def _is_valid_plugin_root(path: Path) -> bool:
  71. """A directory is a usable plugin root only if it actually carries the
  72. Kimi manifest. Guards against `_plugin_root` resolving to an unrelated
  73. directory that merely exists (the site-packages parent on a wheel)."""
  74. return (path / ".kimi-plugin" / "plugin.json").exists()
  75. def _github_tarball_url(version: str) -> str:
  76. ref = f"v{version}" if _RELEASE_VERSION_RE.match(version) else version
  77. if _RELEASE_VERSION_RE.match(version):
  78. return f"https://github.com/evo-hq/evo/archive/refs/tags/{ref}.tar.gz"
  79. return f"https://github.com/evo-hq/evo/archive/refs/heads/{ref}.tar.gz"
  80. def _find_extracted_plugin_root(extracted: Path) -> Path | None:
  81. """Locate the evo plugin root inside an extracted GitHub archive."""
  82. direct = extracted / "plugins" / "evo"
  83. if (direct / ".kimi-plugin" / "plugin.json").exists():
  84. return direct
  85. for child in extracted.iterdir():
  86. if child.is_dir():
  87. candidate = child / "plugins" / "evo"
  88. if (candidate / ".kimi-plugin" / "plugin.json").exists():
  89. return candidate
  90. return None
  91. def _copy_plugin_root(src: Path, dst: Path) -> None:
  92. """Copy the plugin root to the Kimi managed plugin directory."""
  93. if dst.exists():
  94. print(f"removing previous install at {dst}")
  95. shutil.rmtree(dst)
  96. dst.parent.mkdir(parents=True, exist_ok=True)
  97. print(f"copying {src} -> {dst}")
  98. shutil.copytree(
  99. src, dst,
  100. ignore=shutil.ignore_patterns(
  101. ".git", ".venv", "__pycache__", "build", "dist",
  102. ".pytest_cache", "*.egg-info", "node_modules",
  103. ),
  104. )
  105. def _read_installed() -> dict:
  106. """Read Kimi's plugin registry. Mirrors Kimi's own reader: a missing
  107. file is an empty registry, but a corrupt one is an error we refuse to
  108. clobber (Kimi would fail to load every plugin, not just evo)."""
  109. path = _installed_json_path()
  110. try:
  111. raw = path.read_text()
  112. except FileNotFoundError:
  113. return {"version": 1, "plugins": []}
  114. data = json.loads(raw)
  115. if not isinstance(data, dict) or not isinstance(data.get("plugins"), list):
  116. raise ValueError(f"{path} is not a valid installed.json object")
  117. return data
  118. def _write_installed(data: dict) -> None:
  119. """Write via tmp+rename, matching Kimi's own writeInstalled so a
  120. concurrent read never sees a half-written registry."""
  121. path = _installed_json_path()
  122. path.parent.mkdir(parents=True, exist_ok=True)
  123. tmp = path.with_suffix(".json.tmp")
  124. tmp.write_text(json.dumps(data, indent=2))
  125. tmp.replace(path)
  126. def _register(managed_root: Path, original_source: Path) -> None:
  127. """Upsert evo's record in installed.json, preserving other plugins and
  128. evo's original installedAt across re-installs."""
  129. data = _read_installed()
  130. now = dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")
  131. plugins = [p for p in data["plugins"] if not (isinstance(p, dict) and p.get("id") == _PLUGIN_ID)]
  132. previous = next(
  133. (p for p in data["plugins"] if isinstance(p, dict) and p.get("id") == _PLUGIN_ID),
  134. {},
  135. )
  136. plugins.append({
  137. "id": _PLUGIN_ID,
  138. "root": str(managed_root.resolve()),
  139. "source": "local-path",
  140. "originalSource": str(original_source.resolve()),
  141. "enabled": True,
  142. "installedAt": previous.get("installedAt", now),
  143. "updatedAt": now,
  144. })
  145. data["plugins"] = plugins
  146. data["version"] = data.get("version", 1)
  147. _write_installed(data)
  148. print(f"registered '{_PLUGIN_ID}' in {_installed_json_path()}")
  149. def _deregister() -> None:
  150. try:
  151. data = _read_installed()
  152. except (FileNotFoundError, json.JSONDecodeError, ValueError):
  153. return
  154. before = len(data["plugins"])
  155. data["plugins"] = [
  156. p for p in data["plugins"]
  157. if not (isinstance(p, dict) and p.get("id") == _PLUGIN_ID)
  158. ]
  159. if len(data["plugins"]) != before:
  160. _write_installed(data)
  161. print(f"deregistered '{_PLUGIN_ID}' from {_installed_json_path()}")
  162. def _install_plugin(src: Path) -> int:
  163. dst = _kimi_plugin_dir()
  164. _copy_plugin_root(src, dst)
  165. try:
  166. _register(dst, src)
  167. except (OSError, ValueError, json.JSONDecodeError) as exc:
  168. print(f"ERROR: could not register the plugin with Kimi: {exc}", file=sys.stderr)
  169. return 2
  170. print(
  171. "\n✓ evo installed for kimi.\n"
  172. " Start a new Kimi session (or run /plugins reload) to load the plugin."
  173. )
  174. return 0
  175. def _install_from_github(version: str) -> int:
  176. """Download the evo plugin source from GitHub and install it for Kimi."""
  177. url = _github_tarball_url(version)
  178. print(f"downloading {url}")
  179. try:
  180. with urllib.request.urlopen(url, timeout=60) as response:
  181. tarball_bytes = response.read()
  182. except urllib.error.URLError as exc:
  183. print(f"ERROR: could not download {url}: {exc}", file=sys.stderr)
  184. return 2
  185. with tempfile.TemporaryDirectory() as tmp:
  186. tarball_path = Path(tmp) / "evo.tar.gz"
  187. tarball_path.write_bytes(tarball_bytes)
  188. extract_dir = Path(tmp) / "extracted"
  189. extract_dir.mkdir()
  190. with tarfile.open(tarball_path, "r:gz") as tar:
  191. # `filter` was added in Python 3.12; keep compatibility with 3.10/3.11.
  192. extract_kwargs = {"filter": "data"} if sys.version_info >= (3, 12) else {}
  193. tar.extractall(path=extract_dir, **extract_kwargs)
  194. src = _find_extracted_plugin_root(extract_dir)
  195. if src is None:
  196. print(
  197. "ERROR: downloaded archive does not contain a valid evo plugin root "
  198. "(expected .../plugins/evo/.kimi-plugin/plugin.json)",
  199. file=sys.stderr,
  200. )
  201. return 2
  202. return _install_plugin(src)
  203. def install(args: argparse.Namespace) -> int:
  204. if _kimi_binary() is None:
  205. print(
  206. "ERROR: `kimi` binary not found. Install Kimi Code CLI first:\n"
  207. f"{_INSTALL_HINT}",
  208. file=sys.stderr,
  209. )
  210. return 2
  211. version = getattr(args, "version", None)
  212. from_path = getattr(args, "from_path", None)
  213. if version:
  214. return _install_from_github(version)
  215. if from_path:
  216. src = _plugin_root(from_path)
  217. if not _is_valid_plugin_root(src):
  218. print(
  219. f"ERROR: no evo plugin root (.kimi-plugin/plugin.json) at {src}",
  220. file=sys.stderr,
  221. )
  222. return 2
  223. return _install_plugin(src)
  224. # Bare `evo install kimi`. The plugin files sit next to the CLI only in a
  225. # source/editable checkout; the published wheel ships none of them, and
  226. # `_plugin_root(None)` would resolve to the tool's site-packages parent.
  227. # Use the local tree when it's genuinely a checkout, otherwise fetch the
  228. # GitHub tarball at the running version — the same bare-case behaviour as
  229. # the codex, cursor, and hermes adapters.
  230. src = _plugin_root(None)
  231. if _is_valid_plugin_root(src):
  232. return _install_plugin(src)
  233. from evo import __version__
  234. return _install_from_github(__version__)
  235. def uninstall(args: argparse.Namespace) -> int:
  236. _deregister()
  237. dst = _kimi_plugin_dir()
  238. if dst.exists():
  239. shutil.rmtree(dst)
  240. print(f"removed {dst}")
  241. else:
  242. print("evo plugin not installed for kimi")
  243. return 0
  244. def doctor(args: argparse.Namespace) -> int:
  245. binary = _kimi_binary()
  246. if binary is None:
  247. print("✗ `kimi` binary not found")
  248. print(f" Install:\n{_INSTALL_HINT}")
  249. return 1
  250. print(f"✓ kimi binary: {binary}")
  251. dst = _kimi_plugin_dir()
  252. manifest = dst / ".kimi-plugin" / "plugin.json"
  253. if not manifest.exists():
  254. manifest = dst / "kimi.plugin.json"
  255. if not manifest.exists():
  256. print(f"✗ evo plugin not found at {dst}")
  257. print(" Run: evo install kimi")
  258. return 1
  259. print(f"✓ evo plugin manifest at {manifest}")
  260. try:
  261. data = json.loads(manifest.read_text())
  262. except json.JSONDecodeError as exc:
  263. print(f"✗ could not parse manifest: {exc}")
  264. return 1
  265. if data.get("name") != _PLUGIN_ID:
  266. print(f"✗ manifest name mismatch: {data.get('name')!r}")
  267. return 1
  268. print(f"✓ manifest name is '{_PLUGIN_ID}'")
  269. # The manifest on disk is inert until Kimi has a record for it. Without
  270. # this check doctor passes on a plugin Kimi cannot see.
  271. try:
  272. installed = _read_installed()
  273. except (OSError, ValueError, json.JSONDecodeError) as exc:
  274. print(f"✗ could not read {_installed_json_path()}: {exc}")
  275. return 1
  276. record = next(
  277. (p for p in installed["plugins"] if isinstance(p, dict) and p.get("id") == _PLUGIN_ID),
  278. None,
  279. )
  280. if record is None:
  281. print(f"✗ evo not registered in {_installed_json_path()}")
  282. print(" Kimi loads plugins from that file only — run: evo install kimi")
  283. return 1
  284. if not record.get("enabled", False):
  285. print("✗ evo is registered but disabled")
  286. print(" Enable it from Kimi: /plugins")
  287. return 1
  288. if Path(record.get("root", "")).resolve() != dst.resolve():
  289. print(f"✗ registered root {record.get('root')!r} does not match {dst}")
  290. print(" Run: evo install kimi")
  291. return 1
  292. print(f"✓ evo registered and enabled in {_installed_json_path()}")
  293. return 0

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.