Skip to content
Back to search

opencode-harness-setup

Complete OpenCode harness setup: MCP servers, plugins, skills, RTK + Headroom token pipeline, and a REA model guard

Safety scan

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

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/digoo--opencode-harness-setup/badge.svg)](/listings/digoo--opencode-harness-setup)

HTML

<a href="/listings/digoo--opencode-harness-setup"><img src="/api/listings/digoo--opencode-harness-setup/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.

RTK

brew upgrade rtk
rtk --version        # 1.2.1

RTK ships two binaries. `rtk` is in Homebrew. **`rtk-proxy` is not** — it is a separate, separately-licensed release asset published alongside the CLI:

cd "$(mktemp -d)"
BASE=https://github.com/rtk-ai/rtk/releases/download/v1.2.1
curl -sL -o rtk-proxy.tar.gz "$BASE/rtk-proxy-aarch64-apple-darwin.tar.gz"
curl -sL -o checksums.txt "$BASE/checksums.txt"

# Verify before installing
grep "rtk-proxy-aarch64-apple-darwin" checksums.txt
shasum -a 256 rtk-proxy.tar.gz
# the two hashes must match

tar xzf rtk-proxy.tar.gz
install -m 755 rtk-proxy /opt/homebrew/bin/rtk-proxy
rtk-proxy --version

> **Do not skip the checksum step.** The proxy forwards provider credentials; a compromised > binary would receive your API keys.

Other npm packages

npm install -g context-mode@latest
npm install -g @dietrichgebert/ponytail@latest
npm install -g @caveman-ai/cli@latest
npm install -g rea-agents@latest
npm install -g @playwright/mcp@latest

> `npm update -g` can *remove* globally installed packages rather than upgrade them. Verify > with `npm list -g --depth=0` afterwards and reinstall anything missing.

---

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.

README.md · README · 2,010 lines · 1 finding marked
  1. # OpenCode Harness Setup — Complete Guide
  2. Everything needed to build a token-efficient OpenCode harness on macOS: MCP servers, plugins,
  3. skills, a two-layer compression pipeline (RTK + Headroom), and an enforced model guard for a
  4. restricted MCP server.
  5. This is the exact sequence used to produce a working setup, including the mistakes, the
  6. diagnostics, and the settings that turned out to be load-bearing.
  7. **Target**: macOS 26.7.1 (arm64) · OpenCode 2.3.2 · Node 24.22.3 (fnm) · Homebrew 7.0.10
  8. > **Custom API URL.** Every example uses `https://api.example.com/v1` as the upstream provider
  9. > endpoint. Replace it with your own OpenAI-compatible API base URL throughout. It appears in
  10. > the `rtk-proxy.toml` upstreams, the `rtk-proxy service install` flags, the `RTK_PROXY_*`
  11. > environment variables, and the OpenCode provider `baseURL`.
  12. ---
  13. ## Table of contents
  14. 1. [Architecture](#1-architecture)
  15. 2. [Prerequisites](#2-prerequisites)
  16. 3. [Step 1 — Install the token tooling](#3-step-1--install-the-token-tooling)
  17. 4. [Step 2 — Build the RTK proxy chain](#4-step-2--build-the-rtk-proxy-chain)
  18. 5. [Step 3 — Install and wire Headroom](#5-step-3--install-and-wire-headroom)
  19. 6. [Step 4 — Configure the OpenCode provider](#6-step-4--configure-the-opencode-provider)
  20. 7. [Step 5 — Install plugins and skills](#7-step-5--install-plugins-and-skills)
  21. 8. [Step 6 — Register the MCP servers](#8-step-6--register-the-mcp-servers)
  22. 9. [Step 7 — The RTK after-tool hook](#9-step-7--the-rtk-after-tool-hook)
  23. 10. [Step 8 — The REA model guard](#10-step-8--the-rea-model-guard)
  24. 11. [Step 9 — Obsidian vault and workspace docs](#11-step-9--obsidian-vault-and-workspace-docs)
  25. 12. [Step 10 — Porting the vibe-coding-toolkit](#12-step-10--porting-the-vibe-coding-toolkit)
  26. 13. [Verification](#13-verification)
  27. 14. [Troubleshooting](#14-troubleshooting)
  28. 15. [Complete file reference](#15-complete-file-reference)
  29. 16. [Every issue we hit, and its fix](#16-every-issue-we-hit-and-its-fix)
  30. 17. [Complete issue index](#17-complete-issue-index)
  31. ---
  32. ## 1. Architecture
  33. Two request paths, one upstream provider.
  34. ```text
  35. OpenCode (GPT or Claude model)
  36. |
  37. v
  38. rtk-proxy :8080 normalize (ANSI/progress/dedup) + cache-align
  39. |
  40. v
  41. https://api.example.com/v1 (the provider)
  42. Claude Code
  43. |
  44. v
  45. Headroom :8787 Kompress ONNX, mode=cache, tool-result interceptors
  46. |
  47. v
  48. rtk-proxy :8080
  49. |
  50. v
  51. https://api.example.com/v1
  52. ```
  53. Both proxies are **launchd user agents**, so they start at login and survive the editor closing.
  54. OpenCode itself is not in that chain — it is a client that points at `http://127.0.0.1:8080/v1`.
  55. ### The three compression layers
  56. | Layer | Where it runs | What it compresses | Measured |
  57. |---|---|---|---|
  58. | Headroom | proxy, before upstream | tool results (Bash output) | ~15% on large tool results |
  59. | RTK after-tool hook | in the agent, after the tool runs | any unrewritten command's output | 51,374 B to 16,108 B (69%) |
  60. | RTK source filters | in the rewritten command | `ls`, `grep`, `git`, `read`, `test` output | source-side, counted by `rtk gain` |
  61. Plus OpenCode's own `compaction` for long-session summarisation.
  62. ---
  63. ## 2. Prerequisites
  64. ```sh
  65. # Homebrew
  66. brew install git gh node fnm sqlite zstd ripgrep fd
  67. # Node via fnm (needed for the global npm packages below)
  68. curl -fsSL https://fnm.vercel.app/install | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 88 on GitHub
  69. fnm install 24
  70. fnm use 24
  71. ```
  72. Verify:
  73. ```sh
  74. opencode --version # v2.3.2
  75. gh auth status # logged in, token scopes: gist, read:org, repo, workflow
  76. node --version
  77. ```
  78. > **Path warning.** The OpenCode server does not inherit your interactive shell `PATH`, so it
  79. > cannot see binaries installed by fnm or npm into the fnm-managed Node directory. Every MCP
  80. > `command` entry must use an **absolute path**. See [Step 6](#8-step-6--register-the-mcp-servers).
  81. ---
  82. ## 3. Step 1 — Install the token tooling
  83. ### RTK
  84. ```sh
  85. brew upgrade rtk
  86. rtk --version # 1.2.1
  87. ```
  88. RTK ships two binaries. `rtk` is in Homebrew. **`rtk-proxy` is not** — it is a separate,
  89. separately-licensed release asset published alongside the CLI:
  90. ```sh
  91. cd "$(mktemp -d)"
  92. BASE=https://github.com/rtk-ai/rtk/releases/download/v1.2.1
  93. curl -sL -o rtk-proxy.tar.gz "$BASE/rtk-proxy-aarch64-apple-darwin.tar.gz"
  94. curl -sL -o checksums.txt "$BASE/checksums.txt"
  95. # Verify before installing
  96. grep "rtk-proxy-aarch64-apple-darwin" checksums.txt
  97. shasum -a 256 rtk-proxy.tar.gz
  98. # the two hashes must match
  99. tar xzf rtk-proxy.tar.gz
  100. install -m 755 rtk-proxy /opt/homebrew/bin/rtk-proxy
  101. rtk-proxy --version
  102. ```
  103. > **Do not skip the checksum step.** The proxy forwards provider credentials; a compromised
  104. > binary would receive your API keys.
  105. ### Other npm packages
  106. ```sh
  107. npm install -g context-mode@latest
  108. npm install -g @dietrichgebert/ponytail@latest
  109. npm install -g @caveman-ai/cli@latest
  110. npm install -g rea-agents@latest
  111. npm install -g @playwright/mcp@latest
  112. ```
  113. > `npm update -g` can *remove* globally installed packages rather than upgrade them. Verify
  114. > with `npm list -g --depth=0` afterwards and reinstall anything missing.
  115. ---
  116. ## 4. Step 2 — Build the RTK proxy chain
  117. ### 4.1 The proxy config
  118. `rtk-proxy` reads `rtk-proxy.toml`. Create the directory and write the file:
  119. ```sh
  120. mkdir -p ~/Library/Application\ Support/rtk-proxy
  121. ```
  122. The file `~/Library/Application Support/rtk-proxy/rtk-proxy.toml` contains:
  123. ```toml
  124. bind = "127.0.0.1:8080"
  125. anthropic_upstream = "https://api.example.com/v1"
  126. openai_upstream = "https://api.example.com/v1"
  127. ccr = true
  128. cache_align = true
  129. normalize = true
  130. compression = "balanced"
  131. relay_borrowing = true
  132. icm_ttl_secs = 604800
  133. upstream_timeout_secs = 600
  134. upstream_retries = 2
  135. ```
  136. > ### Pitfall: `rtk-proxy config set` does not persist
  137. >
  138. > ```
  139. > $ rtk-proxy config set openai_upstream https://example.com/v1
  140. > openai_upstream = https://example.com/v1 # looks like it worked
  141. > $ rtk-proxy config get openai_upstream
  142. > https://api.openai.com # unchanged
  143. > ```
  144. >
  145. > The admin endpoint acknowledges the write but the value does not survive. Use the **toml file**
  146. > or the **environment variables** `RTK_PROXY_OPENAI_UPSTREAM` / `RTK_PROXY_ANTHROPIC_UPSTREAM`.
  147. > Environment variables work when starting the process:
  148. >
  149. > ```sh
  150. > RTK_PROXY_OPENAI_UPSTREAM=https://api.example.com/v1 \
  151. > RTK_PROXY_ANTHROPIC_UPSTREAM=https://api.example.com/v1 \
  152. > rtk llm-proxy start
  153. > ```
  154. ### 4.2 Install as a launchd service
  155. ```sh
  156. rtk-proxy service install \
  157. --openai-upstream https://api.example.com/v1 \
  158. --anthropic-upstream https://api.example.com/v1 \
  159. --ccr true --cache-align true --compression balanced
  160. ```
  161. This writes:
  162. - `~/Library/LaunchAgents/app.rtk-ai.rtk-proxy.plist` — `RunAtLoad` + `KeepAlive`
  163. - `~/Library/Application Support/rtk-proxy/rtk-proxy.toml`
  164. Verify and restart:
  165. ```sh
  166. rtk-proxy service status
  167. rtk llm-proxy stop && rtk-proxy service start
  168. rtk-proxy config get
  169. ```
  170. ### 4.3 The pipeline file — this is the one that matters
  171. Without a pipeline file the daemon logs:
  172. ```text
  173. no cache-breakpoint or CCR rules — running category-A normalisation only
  174. ```
  175. and `rtk-proxy stats` reports `tokens saved: 0`.
  176. Create `~/Library/Application Support/rtk/pipeline.toml`:
  177. ```toml
  178. schema_version = 1
  179. [pipeline]
  180. extends = ["rtk:posthook", "rtk:proxy"]
  181. ```
  182. Then restart the daemon and confirm the rules changed:
  183. ```sh
  184. rtk llm-proxy stop
  185. rtk-proxy service start
  186. rtk pipeline show
  187. ```
  188. Expected output:
  189. ```text
  190. Pipeline: rtk:posthook
  191. Inherits: rtk:posthook -> rtk:proxy -> rtk:default
  192. Rules (per position; first match wins, project before user before inherited):
  193. hook.before_tool.shell
  194. rtk-rewrite [rtk:default] when always -> action=rewrite
  195. hook.after_tool.read
  196. lockfiles [rtk:posthook] ...
  197. hook.after_tool.shell
  198. term-default [rtk:posthook] when is_rtk_command=false -> use=[term]
  199. ```
  200. > ### Pitfall: `rtk:proxy` alone saves nothing
  201. >
  202. > `rtk:proxy` extends `rtk:default`, whose only proxy-layer rule is `normalize`
  203. > (`ansi`, `progress`, `dedup`). That strips escape codes — it does not compress.
  204. > The real compression method is `term`, and it only runs at `hook.after_tool`,
  205. > which the **proxy cannot reach** because the method keeps the original only in a
  206. > recall copy the proxy cannot store. RTK says so explicitly:
  207. >
  208. > ```text
  209. > W016 `term` (via cap) is skipped at proxy.request.tool_result — it keeps the
  210. > original only in a recall copy, which the proxy cannot store — use it
  211. > under hook.after_tool
  212. > ```
  213. >
  214. > So `rtk:posthook` fixes the *pipeline declaration*, but the actual compression
  215. > still requires the agent-side hook from Step 7.
  216. > ### Pitfall: `rtk pipeline explain --agent opencode` shows nothing
  217. >
  218. > The pipeline resolves rules by **agent name**, and RTK does not know `opencode`:
  219. >
  220. > ```
  221. > $ rtk pipeline explain --agent opencode --tool Bash --command "ls"
  222. > hook.after_tool.any: no rule matches these facts — output passes through
  223. > $ rtk pipeline explain --agent claude-code --tool Bash --command "ls"
  224. > hook.after_tool.shell: rule `term-default` -> [ansi, progress, dedup, base64-elide, cap]
  225. > ```
  226. >
  227. > Use `--agent claude-code` when inspecting pipeline behaviour.
  228. ---
  229. ## 5. Step 3 — Install and wire Headroom
  230. Headroom is a separate product from OpenCode's `compaction`. `compaction` summarises
  231. conversation history; **Headroom compresses tool output before it reaches the model**.
  232. Both are useful; they are not substitutes.
  233. ### 5.1 Install
  234. ```sh
  235. uv tool install --python 3.13 "headroom-ai[all]"
  236. headroom --version # 0.41.0
  237. ```
  238. Verify the compression model loads:
  239. ```sh
  240. headroom doctor
  241. ```
  242. Expected: `kompress │ ✓ pass │ ready (onnx)`.
  243. > On first request the ONNX model is loaded on a background thread. The log shows
  244. > `Kompress: DEFERRED (warming in the background after startup)` followed by
  245. > `Kompress: warmed in the background in N ms (backend onnx)`.
  246. >
  247. > Un-tuned on an 8-core arm64 Mac this took **58,861 ms**. With the ONNX tuning in
  248. > [5.7](#57-speed-up-the-kompress-warm-up) it takes **~10,000 ms**. A `degraded` kompress
  249. > status during the warm window is expected, not a fault.
  250. ### 5.2 Install as a service
  251. ```sh
  252. headroom deploy --providers manual --target claude
  253. ```
  254. This writes `~/Library/LaunchAgents/com.headroom.default.plist` and
  255. `~/.headroom/deploy/default/{manifest.json,run-headroom.sh,ensure-headroom.sh}`.
  256. ### 5.3 Point Headroom at rtk-proxy
  257. Headroom must forward to rtk-proxy, not straight to the provider. Write
  258. `~/.headroom/deploy/default/run-headroom.sh`:
  259. ```bash
  260. #!/usr/bin/env bash
  261. set -euo pipefail
  262. export HEADROOM_PORT=8787
  263. export HEADROOM_HOST=127.0.0.1
  264. export HEADROOM_MODE=cache
  265. export HEADROOM_BACKEND=anthropic
  266. export HEADROOM_EMBEDDER_RUNTIME=cpu
  267. export HEADROOM_KOMPRESS_BACKEND=onnx
  268. export HEADROOM_TELEMETRY=off
  269. export HEADROOM_ROLLOUT_CHANNEL=canary
  270. # Chain: client -> Headroom (compress) -> rtk-proxy -> provider
  271. export ANTHROPIC_TARGET_API_URL=http://127.0.0.1:8080
  272. export OPENAI_TARGET_API_URL=http://127.0.0.1:8080/v1
  273. exec /Users/<you>/.local/bin/headroom install agent run --profile default
  274. ```
  275. Copy it over the ensure script and make both executable:
  276. ```sh
  277. cp ~/.headroom/deploy/default/run-headroom.sh ~/.headroom/deploy/default/ensure-headroom.sh
  278. chmod 755 ~/.headroom/deploy/default/*.sh
  279. ```
  280. And the manifest must match, because **`base_env` overrides the run script**. Edit
  281. `~/.headroom/deploy/default/manifest.json` so `base_env` contains:
  282. ```json
  283. {
  284. "ANTHROPIC_TARGET_API_URL": "http://127.0.0.1:8080",
  285. "OPENAI_TARGET_API_URL": "http://127.0.0.1:8080/v1",
  286. "HEADROOM_KOMPRESS_ONNX_INTRA_THREADS": "8",
  287. "HEADROOM_KOMPRESS_ONNX_INTER_THREADS": "2",
  288. "HEADROOM_KOMPRESS_WARMUP_DELAY_SECONDS": "0"
  289. }
  290. ```
  291. The last three are the ONNX warm-up tuning — see [5.7](#57-speed-up-the-kompress-warm-up).
  292. Restart and verify the upstream actually changed:
  293. ```sh
  294. launchctl bootout gui/$(id -u)/com.headroom.default
  295. launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.headroom.default.plist
  296. sleep 8
  297. curl -s http://127.0.0.1:8787/readyz | grep -o '"url":"[^"]*"'
  298. # -> "url":"http://127.0.0.1:8080"
  299. ```
  300. ### 5.4 Enable tool-result interception
  301. By default Headroom only normalises. Real tool-result compression is **opt-in** and
  302. gated behind a rollout channel.
  303. Add to both `run-headroom.sh` and `ensure-headroom.sh`:
  304. ```bash
  305. export HEADROOM_ROLLOUT_CHANNEL=canary
  306. ```
  307. Add `--intercept-tool-results` to `proxy_args` in `manifest.json`:
  308. ```json
  309. "proxy_args": [
  310. "--host", "127.0.0.1",
  311. "--port", "8787",
  312. "--headroom-deployment-profile", "default",
  313. "--headroom-deployment-runtime", "python",
  314. "--mode", "cache",
  315. "--backend", "anthropic",
  316. "--intercept-tool-results",
  317. "--no-telemetry",
  318. "--no-rate-limit"
  319. ]
  320. ```
  321. Confirm the rollout resolved:
  322. ```sh
  323. headroom rollout status
  324. ```
  325. ```text
  326. Rollout channel: canary
  327. tool_result_interceptors: enabled=true decision=rollout_channel
  328. ```
  329. > ### Pitfall: Headroom compresses nothing without the flag
  330. >
  331. > The symptom is subtle: everything looks healthy, `headroom doctor` passes, `kompress` reports
  332. > `ready (onnx)`, and the proxy answers every request — but the token count never drops.
  333. >
  334. > The log shows why:
  335. >
  336. > ```text
  337. > [router] route_counts={'excluded_tool': 1} compressed=0 frozen=2 msgs=3
  338. > [router] route_counts={'ratio_too_high': 1, 'cache_miss': 1} compressed=0 frozen=976 msgs=977
  339. > ```
  340. >
  341. > `compressed=0` on every request. Two separate causes, both required:
  342. >
  343. > 1. **The rollout channel.** Tool-result interceptors are gated behind
  344. > `HEADROOM_ROLLOUT_CHANNEL=canary` (or `dev`). Without it:
  345. > ```text
  346. > Rollout channel: stable
  347. > tool_result_interceptors: enabled=false decision=not_requested
  348. > ```
  349. > 2. **The flag.** `--intercept-tool-results` must be in `proxy_args` in the manifest.
  350. > It is rejected at startup without the channel:
  351. > ```text
  352. > --intercept-tool-results Opt in to tool_result interceptors.
  353. > Requires HEADROOM_ROLLOUT_CHANNEL=canary (or dev).
  354. > ```
  355. >
  356. > Fix both, then reload the launchd agent and confirm `compressed=1` appears in the log.
  357. > ### Pitfall: pointing Headroom at the wrong provider breaks the other client
  358. >
  359. > Headroom is a **shared** proxy. Changing its upstream to serve OpenCode also changes the
  360. > upstream for every client that already pointed at Headroom.
  361. >
  362. > In this setup Claude Code was already routed through Headroom to a Kimi endpoint with a
  363. > Kimi key. Repointing Headroom at the OpenAI-compatible provider broke Claude Code
  364. > immediately, because the Kimi key was rejected by the new upstream:
  365. >
  366. > ```text
  367. > Error: Incorrect API key provided: sk-...5060.
  368. > You can find your API key at https://platform.openai.com/account/api-keys.
  369. > ```
  370. >
  371. > The mistake was changing Headroom's upstream in place. The correct approach is to keep
  372. > Headroom pointed at whatever provider its clients expect, and let each client decide where
  373. > *it* points. If you need two different upstreams, run **two** Headroom instances on
  374. > different ports — one per provider — instead of moving a shared one.
  375. >
  376. > When you do change it, audit every client that uses it before restarting:
  377. >
  378. > ```sh
  379. > grep -r "127.0.0.1:8787" ~/.claude ~/.config/opencode 2>/dev/null
  380. > ```
  381. ### 5.4.1 Two providers, two Headroom instances
  382. If two clients need different upstreams, give each its own Headroom. The deployment profile
  383. name is what keeps them apart:
  384. ```sh
  385. # profile "openai" -> port 8788
  386. headroom deploy --profile openai --port 8788 --providers manual --target opencode
  387. # profile "default" -> port 8787
  388. headroom deploy --profile default --port 8787 --providers manual --target claude
  389. ```
  390. Each profile gets its own directory (`~/.headroom/deploy/<profile>/`), its own launchd plist
  391. (`com.headroom.<profile>`), and its own `base_env`. Then point each client at its own port:
  392. ```text
  393. OpenCode -> http://127.0.0.1:8080/v1 (rtk-proxy only, no Headroom)
  394. Claude Code-> http://127.0.0.1:8787 (Headroom profile "default")
  395. ```
  396. ### 5.5 What Headroom will and will not compress
  397. `Read`, `Glob`, `Grep`, `Write`, `Edit`, `WebSearch`, `WebFetch` are **excluded by design**:
  398. lossy compression of a file read breaks byte-exact `Edit` patching. `Bash` is the intended
  399. target. Do not "fix" this by removing them from the exclusion list.
  400. ### 5.6 Measure it
  401. ```sh
  402. headroom savings
  403. ```
  404. ```text
  405. Today 0.1% saved 12,332 / 8,312,831 tokens $0.0370
  406. opencode 36 calls - 11,019 tokens saved
  407. ```
  408. To compare a payload directly, send the same body to both hops:
  409. ```sh
  410. curl -s http://127.0.0.1:8080/v1/chat/completions -H "Authorization: Bearer $KEY" \
  411. -d @body.json | jq .usage.prompt_tokens # without Headroom
  412. curl -s http://127.0.0.1:8787/v1/chat/completions -H "Authorization: Bearer $KEY" \
  413. -d @body.json | jq .usage.prompt_tokens # with Headroom
  414. ```
  415. ### 5.7 Speed up the Kompress warm-up
  416. The one-time cost is ONNX Runtime creating the session for the 261MB `kompress-v2-base`
  417. int8-wo model. ORT's defaults are conservative, so on Apple Silicon it does the work on
  418. far fewer cores than the machine has.
  419. Three environment variables fix it. Add them to the run script **and** the manifest
  420. `base_env` (see [5.3](#53-point-headroom-at-rtk-proxy) for why both are needed):
  421. ```bash
  422. # Use all cores for the model's internal work
  423. export HEADROOM_KOMPRESS_ONNX_INTRA_THREADS=8
  424. export HEADROOM_KOMPRESS_ONNX_INTER_THREADS=2
  425. # Start the background warm-up immediately instead of after a 2s delay
  426. export HEADROOM_KOMPRESS_WARMUP_DELAY_SECONDS=0
  427. ```
  428. Measured on this machine, same model, same backend:
  429. | | Warm time |
  430. |---|---|
  431. | Default | 58,861 ms |
  432. | Tuned | **10,159 ms** (5.8x) |
  433. **Why `inter` is 2 and not 8.** `HEADROOM_KOMPRESS_MAX_CONCURRENT` defaults to `1` for
  434. ONNX backends — the upstream source comment says "ONNX already owns its intra/inter-op
  435. threads". So only one model invocation runs at a time and `intra=8` cannot oversubscribe.
  436. But `intra=8` **and** `inter=8` would give ORT up to 64 threads on 8 cores. `inter=2`
  437. leaves headroom without giving up the parallel-op win.
  438. **Do not enable `HEADROOM_ONNX_ALLOW_SPINNING=1`** unless you want this. It restores ORT's
  439. spin-waiting threads, which the upstream docs explicitly warn against for a long-lived
  440. proxy:
  441. > ORT's thread pools spin-wait on every core between inferences by default, so a
  442. > long-lived proxy that keeps compression/embedding models loaded pegs all cores even
  443. > while completely idle — the machine slows to a crawl after a while (#2495).
  444. That is a bad trade for a proxy that runs 24/7 via launchd on a laptop you also use for
  445. everything else. It would not speed up the warm-up either — spinning affects the gap
  446. between inferences, not session creation.
  447. Verify the model is loaded:
  448. ```sh
  449. curl -s http://127.0.0.1:8787/debug/warmup | grep -o '"kompress":{"status":"[a-z]*"'
  450. # {"kompress":{"status":"loaded"
  451. ```
  452. After changing any of these, restart the launchd agent and watch the log:
  453. ```sh
  454. launchctl bootout gui/$(id -u)/com.headroom.default
  455. launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.headroom.default.plist
  456. sleep 15
  457. grep 'Kompress: warmed' ~/.headroom/deploy/default/runner.log | tail -n 1
  458. ```
  459. ---
  460. ## 6. Step 4 — Configure the OpenCode provider
  461. ### 6.1 The provider block
  462. `~/.config/opencode/opencode.json`:
  463. ```jsonc
  464. {
  465. "$schema": "https://opencode.ai/config.json",
  466. "permission": {
  467. "read": {
  468. "~/.config/opencode/get-shit-done/*": "allow"
  469. },
  470. "external_directory": {
  471. "~/.config/opencode/get-shit-done/*": "allow"
  472. }
  473. },
  474. "plugin": [
  475. "superpowers@git+https://github.com/obra/superpowers.git",
  476. "/opt/homebrew/lib/node_modules/context-mode",
  477. "./plugins/caveman",
  478. "./plugins/rea-guard"
  479. ],
  480. "provider": {
  481. "kpa": {
  482. "name": "KPA",
  483. "package": "@opencode/ai/providers/openai-compatible",
  484. "settings": {
  485. "baseURL": "http://127.0.0.1:8080/v1"
  486. },
  487. "models": {
  488. "gpt-5-6-luna": {
  489. "name": "GPT-5.6 Luna",
  490. "settings": {
  491. "apiKey": "{file:~/.config/opencode/secrets/provider-gpt.key}"
  492. },
  493. "limit": { "context": 1050000, "input": 922000, "output": 128000 }
  494. }
  495. }
  496. }
  497. },
  498. "mcp": {
  499. "supabase": {
  500. "type": "remote",
  501. "url": "https://mcp.supabase.com/mcp?project_ref=<ref>",
  502. "enabled": true
  503. },
  504. "serena": {
  505. "type": "local",
  506. "command": [
  507. "uvx", "--from", "git+https://github.com/oraios/serena",
  508. "serena", "start-mcp-server", "--context", "ide-assistant", "--project-from-cwd"
  509. ],
  510. "environment": { "PYTHONUNBUFFERED": "1" }
  511. },
  512. "servers": {
  513. "context7": {
  514. "type": "remote",
  515. "url": "https://mcp.context7.com/mcp"
  516. },
  517. "rea": {
  518. "type": "local",
  519. "command": [
  520. "/Users/<you>/.local/share/fnm/node-versions/v24.22.3/installation/bin/rea",
  521. "mcp"
  522. ],
  523. "disabled": false
  524. }
  525. },
  526. "context-mode": {
  527. "type": "local",
  528. "command": [
  529. "/opt/homebrew/opt/node/bin/node",
  530. "/opt/homebrew/lib/node_modules/context-mode/server.mjs",
  531. "--agent", "opencode"
  532. ],
  533. "enabled": true
  534. },
  535. "codebase-memory-mcp": {
  536. "command": ["/Users/<you>/.local/bin/codebase-memory-mcp"],
  537. "type": "local"
  538. },
  539. "playwright": {
  540. "type": "local",
  541. "command": [
  542. "/Users/<you>/.local/share/fnm/node-versions/v24.22.3/installation/bin/playwright-mcp"
  543. ],
  544. "enabled": true
  545. }
  546. },
  547. "compaction": {
  548. "auto": true,
  549. "keep": { "tokens": 15000 },
  550. "buffer": "20%"
  551. }
  552. }
  553. ```
  554. ### 6.2 Real limits, not the fallback
  555. Custom providers fall back to **200k context / 32k output** unless each model declares its own
  556. `limit`. A 1M-window model silently gets 200k. Source the real numbers from the
  557. models.dev catalog:
  558. ```sh
  559. curl -s https://models.dev/api.json -o /tmp/models.json
  560. node -e "
  561. const d=require('/tmp/models.json');
  562. for (const [p,m] of Object.entries(d)) {
  563. if (!m.models) continue;
  564. for (const id of Object.keys(m.models)) {
  565. if (id.startsWith('gpt-5-6') || id.startsWith('claude-opus-5')) {
  566. console.log(p+'/'+id, JSON.stringify(m.models[id].limit));
  567. }
  568. }
  569. }"
  570. ```
  571. ### 6.3 Secrets on disk, not in the config
  572. ```sh
  573. mkdir -p ~/.config/opencode/secrets
  574. chmod 700 ~/.config/opencode/secrets
  575. printf '%s' 'sk-...' > ~/.config/opencode/secrets/provider-gpt.key
  576. printf '%s' 'sk-...' > ~/.config/opencode/secrets/provider-claude.key
  577. chmod 600 ~/.config/opencode/secrets/*.key
  578. ```
  579. Reference with `{file:...}` so the key never appears in the config file:
  580. ```json
  581. "apiKey": "{file:~/.config/opencode/secrets/provider-gpt.key}"
  582. ```
  583. > If your existing config still references `kpalabz-gpt.key` or `kpalabz-claude.key`,
  584. > rename the files and update the `{file:...}` references to match.
  585. > ### The `permission` block
  586. >
  587. > Without it, OpenCode's TUI blocks every read of the `get-shit-done` directory
  588. > (`~/.config/opencode/get-shit-done/*`) with a confirmation prompt. The `read` and
  589. > `external_directory` entries above pre-approve both. See [Step 10](#12-step-10--porting-the-vibe-coding-toolkit) for what lives in that directory.
  590. ---
  591. ## 7. Step 5 — Install plugins and skills
  592. ### 7.1 Plugins
  593. ```jsonc
  594. "plugin": [
  595. "superpowers@git+https://github.com/obra/superpowers.git",
  596. "/opt/homebrew/lib/node_modules/context-mode",
  597. "./plugins/caveman",
  598. "./plugins/rea-guard"
  599. ]
  600. ```
  601. ```sh
  602. opencode plugin list
  603. opencode plugin check
  604. ```
  605. `superpowers` installs the `get-shit-done` framework into `~/.config/opencode/get-shit-done/`:
  606. 30+ `gsd-*` subagent definitions (`gsd-code-reviewer`, `gsd-debugger`, `gsd-executor`, …),
  607. templates for research, UI specs, and verification reports, and the `gsd-tools.cjs` CLI
  608. for git commits and intel updates. The `permission` block in `opencode.json` is what lets
  609. the agent read those templates without prompting.
  610. ### 7.2 RTK's own OpenCode plugin
  611. ```sh
  612. rtk init -g --opencode --auto-patch
  613. ```
  614. This installs `~/.config/opencode/plugins/rtk.ts` **and** the Claude Code hooks, including the
  615. `PostToolUse` hook that RTK itself reports as missing.
  616. ```sh
  617. rtk init --show
  618. ```
  619. ```text
  620. [ok] settings.json: RTK hooks configured (PreToolUse + PostToolUse)
  621. [ok] OpenCode: plugin installed (/Users/<you>/.config/opencode/plugins/rtk.ts)
  622. ```
  623. ### 7.3 Claude Code routing
  624. `~/.claude/settings.json`:
  625. ```jsonc
  626. {
  627. "env": {
  628. "ANTHROPIC_BASE_URL": "http://127.0.0.1:8787",
  629. "ANTHROPIC_API_KEY": "<your provider key>",
  630. "ANTHROPIC_MODEL": "claude-opus-5-5",
  631. "ANTHROPIC_DEFAULT_OPUS_MODEL": "claude-opus-5-5",
  632. "ANTHROPIC_DEFAULT_SONNET_MODEL": "claude-sonnet-5-5",
  633. "ANTHROPIC_DEFAULT_FABLE_MODEL": "claude-fable-5-2",
  634. "ANTHROPIC_DEFAULT_HAIKU_MODEL": "claude-haiku-5-5",
  635. "CLAUDE_CODE_SUBAGENT_MODEL": "claude-sonnet-5-5"
  636. }
  637. }
  638. ```
  639. Claude Code then flows through Headroom automatically.
  640. ### 7.4 Skills
  641. Global skills live in `~/.config/opencode/skills/`. The main ones used here:
  642. | Skill | Purpose |
  643. |---|---|
  644. | `brainstorming` | before creative work |
  645. | `writing-plans` | before multi-step implementation |
  646. | `test-driven-development` | before writing implementation code |
  647. | `systematic-debugging` | before proposing a fix |
  648. | `verification-before-completion` | before claiming done |
  649. | `requesting-code-review` | before merging |
  650. | `using-git-worktrees` | isolated feature work |
  651. | `caveman` | terse output mode |
  652. ---
  653. ## 8. Step 6 — Register the MCP servers
  654. ### 8.1 The full config
  655. ```jsonc
  656. "mcp": {
  657. "codebase-memory-mcp": {
  658. "type": "local",
  659. "command": ["/Users/<you>/.local/bin/codebase-memory-mcp"]
  660. },
  661. "context-mode": {
  662. "type": "local",
  663. "command": [
  664. "/opt/homebrew/opt/node/bin/node",
  665. "/opt/homebrew/lib/node_modules/context-mode/server.mjs",
  666. "--agent", "opencode"
  667. ],
  668. "enabled": true
  669. },
  670. "serena": {
  671. "type": "local",
  672. "command": [
  673. "uvx", "--from", "git+https://github.com/oraios/serena",
  674. "serena", "start-mcp-server", "--context", "ide-assistant", "--project-from-cwd"
  675. ],
  676. "environment": { "PYTHONUNBUFFERED": "1" }
  677. },
  678. "servers": {
  679. "context7": {
  680. "type": "remote",
  681. "url": "https://mcp.context7.com/mcp"
  682. },
  683. "supabase": {
  684. "type": "remote",
  685. "url": "https://mcp.supabase.com/mcp?project_ref=<ref>",
  686. "enabled": true
  687. },
  688. "rea": {
  689. "type": "local",
  690. "command": [
  691. "/Users/<you>/.local/share/fnm/node-versions/v24.22.3/installation/bin/rea",
  692. "mcp"
  693. ],
  694. "disabled": false
  695. }
  696. },
  697. "playwright": {
  698. "type": "local",
  699. "command": [
  700. "/Users/<you>/.local/share/fnm/node-versions/v24.22.3/installation/bin/playwright-mcp"
  701. ],
  702. "enabled": true
  703. }
  704. }
  705. ```
  706. ### 8.2 Absolute paths are mandatory
  707. ```text
  708. x rea failed: NotFound: ChildProcess.spawn (rea mcp)
  709. x playwright failed: NotFound: ChildProcess.spawn (playwright-mcp )
  710. v rea connected
  711. ```
  712. Same binary, same command — only the path changed. The OpenCode server's `PATH` does not
  713. include the fnm bin directory. Resolve it once:
  714. ```sh
  715. npm root -g
  716. ls -d ~/.local/share/fnm/node-versions/v*/installation/bin
  717. ```
  718. > If you upgrade Node through fnm, the version segment changes and every MCP pointing at
  719. > that path breaks. Re-run the command above after any Node upgrade.
  720. ### 8.3 REA has its own installer
  721. ```sh
  722. rea mcp add --agent opencode --command "rea mcp"
  723. ```
  724. It writes the config itself and keeps a backup at `opencode.json.rea.backup`. Then fix the
  725. path and verify:
  726. ```sh
  727. rea mcp doctor
  728. ```
  729. ```text
  730. healthy: true
  731. adapter: production-stdio
  732. server: { name: rea, version: 6.9.0, protocol_version: 2025-11-25 }
  733. inventory:
  734. tools: { expected: 255, observed: 255, missing: [], unexpected: [], duplicates: [] }
  735. prompts: { expected: 6, observed: 6, missing: [], unexpected: [], duplicates: [] }
  736. identity:
  737. expected_catalog_digest: 2c725b48...
  738. observed_catalog_digest: 2c725b48...
  739. ```
  740. ### 8.4 Verify everything
  741. ```sh
  742. opencode mcp list
  743. ```
  744. ```text
  745. v codebase-memory-mcp connected
  746. v context-mode connected
  747. v context7 connected
  748. v opencode_console connected
  749. v playwright connected
  750. v rea connected
  751. v serena connected
  752. v supabase connected
  753. ```
  754. ---
  755. ## 9. Step 7 — The RTK after-tool hook
  756. This is the single highest-impact change in the whole setup, and it is **not** provided by
  757. RTK's stock OpenCode plugin.
  758. ### 9.1 Why it is needed
  759. - The `term` filter (the one that actually compresses) only runs at `hook.after_tool`.
  760. - The proxy cannot reach `hook.after_tool` — it cannot store the recall copy.
  761. - RTK's stock OpenCode plugin registers `tool.execute.before` only, so nothing fires the
  762. filter in OpenCode.
  763. - Result: `rtk-proxy stats` reported `tokens saved: 0` for every request.
  764. ### 9.2 The OpenCode 2.x hook shape
  765. `ctx.tool.hook("execute.after", cb)` receives:
  766. ```text
  767. { tool, sessionID, agent, messageID, id, input, status, result }
  768. result: { output, content, metadata }
  769. ```
  770. For the **shell** tool, `result.output` is:
  771. ```json
  772. { "exitCode": 0, "output": "<the text>", "wallTimeSeconds": 12 }
  773. ```
  774. > ### Pitfall: the text is at `result.output.output`, not `result.output.stdout`
  775. >
  776. > Reading `.stdout` yields `undefined`, the handler silently returns, and nothing is
  777. > compressed — with no error anywhere. Discover the real shape with a throwaway probe plugin
  778. > that dumps `Object.keys(e)` to a file.
  779. > ### Pitfall: a syntax error in the plugin fails silently
  780. >
  781. > An orphaned doc comment left by a bad edit made the plugin fail to load. OpenCode did not
  782. > report it and the hook simply never fired. Always check the plugin parses:
  783. >
  784. > ```sh
  785. > cp ~/.config/opencode/plugins/rtk.ts /tmp/rtk-check.mts
  786. > node --input-type=module -e "import('/tmp/rtk-check.mts').then(()=>console.log('OK')).catch(e=>console.log('ERR',e.message))"
  787. > ```
  788. ### 9.3 The handler
  789. Add to `~/.config/opencode/plugins/rtk.ts`:
  790. ```ts
  791. async function handleAfterToolHook(rtkBin: string, event: any) {
  792. if (!event || event.status === "error") return
  793. if (process.env.RTK_DISABLED === "1") return
  794. const result = event.result ?? {}
  795. const output = result.output
  796. if (!output || typeof output !== "object") return
  797. // OpenCode's shell tool reports {exitCode, output, wallTimeSeconds}.
  798. const stdout = typeof output.output === "string" ? output.output : ""
  799. if (!stdout) return
  800. // rtk's `hook claude` processor keys off Claude Code's tool names.
  801. const toolName = event.tool === "shell" ? "Bash" : String(event.tool ?? "")
  802. const payload = JSON.stringify({
  803. hook_event_name: "PostToolUse",
  804. tool_name: toolName,
  805. tool_input: event.input ?? {},
  806. tool_response: { stdout, interrupted: false },
  807. })
  808. try {
  809. const answer = await new Promise<string | null>((resolve) => {
  810. const child = spawn(rtkBin, ["hook", "claude"], {
  811. encoding: "utf8",
  812. windowsHide: true,
  813. })
  814. let out = ""
  815. child.stdout?.on("data", (d) => (out += String(d)))
  816. child.on("error", () => resolve(null))
  817. child.on("close", () => resolve(out))
  818. child.stdin?.end(payload)
  819. })
  820. if (!answer) return
  821. const parsed = JSON.parse(String(answer).trim() || "{}")
  822. const updated = parsed?.hookSpecificOutput?.updatedToolOutput
  823. if (!updated || typeof updated.stdout !== "string") return
  824. if (updated.stdout === stdout) return
  825. output.output = updated.stdout
  826. } catch {
  827. // Compression is best-effort: an unusable answer leaves the output as it was.
  828. }
  829. }
  830. ```
  831. Register it in **both** entrypoints:
  832. ```ts
  833. // V2
  834. async setup(ctx: any) {
  835. const rtkBin = await ensureRtkUsable()
  836. if (!rtkBin) return
  837. await ctx?.tool?.hook?.("execute.before", (e: any) =>
  838. handleToolHook(e?.tool, e?.input, typeof e?.agent === "string" ? e.agent : undefined)
  839. )
  840. await ctx?.tool?.hook?.("execute.after", (e: any) => handleAfterToolHook(rtkBin, e))
  841. }
  842. // V1
  843. async server() {
  844. const rtkBin = await ensureRtkUsable()
  845. if (!rtkBin) return {}
  846. return {
  847. "shell.env": (input: any, output: any) => { /* existing PATH fixup */ },
  848. "tool.execute.before": (input: any, output: any) =>
  849. handleToolHook(input?.tool, output?.args),
  850. "tool.execute.after": (input: any, output: any) =>
  851. handleAfterToolHook(rtkBin, input),
  852. }
  853. }
  854. ```
  855. Requires `spawn`:
  856. ```ts
  857. import { execFile, spawn } from "node:child_process"
  858. ```
  859. ### 9.4 What the hook actually does
  860. `rtk hook claude` expects Claude Code's `PostToolUse` JSON on stdin and answers with:
  861. ```json
  862. { "hookSpecificOutput": { "hookEventName": "PostToolUse", "updatedToolOutput": { "stdout": "..." } } }
  863. ```
  864. The payload must include `tool_input.command`. Without it the handler returns empty.
  865. > ### Pitfall: rtk will not compress its own output
  866. >
  867. > The `term-default` rule has the condition `is_rtk_command = false`. When RTK's
  868. > `execute.before` hook rewrote `cat` into `rtk read`, the after-hook sees a command
  869. > RTK itself produced and **skips it** — by design, because RTK already filtered at the
  870. > source.
  871. >
  872. > So the after-hook earns its keep on commands RTK does **not** rewrite (arbitrary shell,
  873. > `awk`, `sed`, custom tools) and on any output large enough to matter.
  874. > ### Pitfall: the 512-byte floor
  875. >
  876. > RTK's `min_size = 512` guard means output under 512 bytes is left alone. That is
  877. > intentional — compressing a small result costs more than it saves.
  878. ### 9.5 Verify
  879. Build a large payload and measure:
  880. ```sh
  881. python3 -c "
  882. with open('/tmp/rtk-big/noise.txt','w') as f:
  883. for i in range(3000):
  884. f.write(f'noise record {i} alpha beta gamma delta epsilon zeta eta theta\n')
  885. "
  886. rtk hook claude < payload.json | jq -r '.hookSpecificOutput.updatedToolOutput.stdout | length'
  887. ```
  888. Observed: **51,374 to 16,108 bytes (69% reduction)**.
  889. Originals stay retrievable:
  890. ```sh
  891. rtk recall --list
  892. ```
  893. ```text
  894. HASH COMMAND LINES HIDDEN ORIG EXIT TRUNC
  895. c55d0d63dc622ff0 posthook:bash_awk 802 802 51.4K -
  896. ```
  897. ```sh
  898. rtk recall c55d0d63dc622ff0 --full
  899. ```
  900. ### 9.6 The stale-server trap
  901. The background `opencode serve --service` caches the loaded plugin. A plugin edit is not
  902. live until the server reloads.
  903. ```sh
  904. opencode run --standalone --model kpa/gpt-5-6-luna "..." # fresh server
  905. ```
  906. Or `/reload` in the TUI.
  907. ---
  908. ## 10. Step 8 — The REA model guard
  909. REA must not run with Claude or GPT models — doing so risks the account being banned.
  910. An instruction in `AGENTS.md` is advisory; a subagent can miss it. This is the enforced version.
  911. ### 10.1 The instruction layer
  912. `~/.config/opencode/AGENTS.md`, inside a marker block so plugin rewrites leave it alone:
  913. ```markdown
  914. <!-- rea-begin -->
  915. # REA MCP — model restriction
  916. REA (the `rea` MCP server) is BANNED with Claude models and GPT models. Using REA
  917. with those models risks the user's account being banned. This is a hard
  918. restriction, not a style preference.
  919. ## Rule
  920. - NEVER call any `rea` tool while the active model is a Claude model or a GPT model.
  921. - This applies to the main session and to every subagent.
  922. - If a task needs REA and the current model is Claude or GPT, switch to another model first.
  923. ## Allowed models
  924. - Any model that is not a Claude model and not a GPT model is allowed.
  925. - If unsure whether a model counts as Claude or GPT, treat it as banned and ask.
  926. ## Enforcement
  927. - Never delegate REA work to `kpa/claude-*` or `kpa/gpt-*` models.
  928. <!-- rea-end -->
  929. ```
  930. ### 10.2 The enforcement layer
  931. `~/.config/opencode/plugins/rea-guard/index.ts`:
  932. ```ts
  933. const BANNED_PATTERNS = [
  934. /^claude/i,
  935. /^gpt-/i,
  936. /^gpt[0-9]/i,
  937. /^o[134](-|$)/i, // o1, o3, o4 reasoning models
  938. /^chatgpt/i,
  939. ]
  940. function isReaTool(tool: string): boolean {
  941. return /^rea[_.]/i.test(tool)
  942. }
  943. function isBannedModel(modelID: string): boolean {
  944. if (!modelID) return false
  945. return BANNED_PATTERNS.some((re) => re.test(modelID))
  946. }
  947. export default {
  948. id: "rea-guard",
  949. async setup(ctx: any) {
  950. await ctx?.tool?.hook?.("execute.before", async (event: any) => {
  951. const tool = String(event?.tool ?? "")
  952. if (!isReaTool(tool)) return
  953. const sessionID = event?.sessionID
  954. if (!sessionID) return
  955. let modelID = ""
  956. try {
  957. const session = await ctx.session.get({ sessionID })
  958. const m = session?.model ?? session?.info?.model
  959. modelID = String(m?.id ?? m?.modelID ?? "")
  960. } catch {
  961. // Fail closed: a banned model must never reach REA because of a lookup error.
  962. throw new Error(
  963. `[rea-guard] blocked ${tool}: could not resolve the session model, and REA is banned with Claude and GPT models.`
  964. )
  965. }
  966. if (!isBannedModel(modelID)) return
  967. throw new Error(
  968. `[rea-guard] blocked ${tool}. REA is banned with Claude and GPT models (current model: ${modelID}). Switch to another model to use REA.`
  969. )
  970. })
  971. },
  972. }
  973. ```
  974. `~/.config/opencode/plugins/rea-guard/package.json`:
  975. ```json
  976. {
  977. "name": "rea-guard",
  978. "version": "1.0.0",
  979. "private": true,
  980. "type": "module",
  981. "main": "index.ts"
  982. }
  983. ```
  984. Register it:
  985. ```jsonc
  986. "plugin": [
  987. "superpowers@git+https://github.com/obra/superpowers.git",
  988. "/opt/homebrew/lib/node_modules/context-mode",
  989. "./plugins/caveman",
  990. "./plugins/rea-guard"
  991. ]
  992. ```
  993. ### 10.3 Verify
  994. ```sh
  995. opencode run --model kpa/gpt-5-6-luna "Call rea_address_name with address 0x1000."
  996. ```
  997. ```text
  998. [rea-guard] blocked rea_address_name. REA is banned with Claude and GPT models
  999. (current model: gpt-5-6-luna). Switch to another model to use REA.
  1000. ```
  1001. Test the pattern logic directly against a table of known ids — banned: `gpt-*`, `claude-*`,
  1002. `o1`/`o3`/`o4`, `chatgpt-*`; allowed: `llama`, `qwen`, `gemini`, `mistral`, `deepseek`, `grok`,
  1003. `kimi`, `glm`, `minimax`. 23 cases, all pass.
  1004. > **Note.** The guard reads the *session's selected model*, resolved server-side via
  1005. > `ctx.session.get`. It is not a provider allowlist, so it survives provider renames and
  1006. > new model names. Anything matching the banned patterns is treated as banned, including
  1007. > models you have not seen yet.
  1008. ---
  1009. ## 11. Step 9 — Obsidian vault and workspace docs
  1010. ```sh
  1011. brew install --cask obsidian
  1012. mkdir -p ~/vibecoding/vault
  1013. ```
  1014. Then open the vault in Obsidian and enable **Settings → General → Advanced → Command line
  1015. interface** if you want the `obsidian` CLI.
  1016. Workspace layout used here:
  1017. ```text
  1018. ~/vibecoding/
  1019. |-- AGENTS.md # policy: workflow, tool restrictions, shell hygiene
  1020. |-- CLAUDE.md # bridge to the shared instructions
  1021. |-- docs/ # architecture, quality, onboarding, setup, design
  1022. |-- vault/ # Obsidian
  1023. |-- vibe-toolkit/ # portable port of an upstream toolkit
  1024. `-- <project folders>/ # one folder per repo
  1025. ```
  1026. ---
  1027. ## 12. Step 10 — Porting the vibe-coding-toolkit
  1028. Upstream: <https://github.com/soumatheusgomes/vibe-coding-toolkit> — 122 blobs.
  1029. ### 12.1 Mirror the upstream for reference
  1030. Fetch the authoritative tree:
  1031. ```sh
  1032. curl -s -H "User-Agent: opencode" \
  1033. "https://api.github.com/repos/soumatheusgomes/vibe-coding-toolkit/git/trees/main?recursive=1" \
  1034. -o /tmp/gt.json
  1035. node -e "
  1036. const fs=require('fs');
  1037. const j=JSON.parse(fs.readFileSync('/tmp/gt.json','utf8'));
  1038. const blobs=j.tree.filter(t=>t.type==='blob');
  1039. console.log('blobs:', blobs.length, 'truncated:', j.truncated);
  1040. "
  1041. ```
  1042. Download each blob preserving its path. Write this to a script file and run it:
  1043. ```sh
  1044. BASE=https://raw.githubusercontent.com/soumatheusgomes/vibe-coding-toolkit/main
  1045. node -e "
  1046. const fs=require('fs');
  1047. const j=JSON.parse(fs.readFileSync('/tmp/gt.json','utf8'));
  1048. for (const t of j.tree) {
  1049. if (t.type!=='blob') continue;
  1050. const p='_upstream/'+t.path;
  1051. fs.mkdirSync(require('path').dirname(p),{recursive:true});
  1052. fs.writeFileSync('/tmp/paths.txt', t.path+'\n', {flag:'a'});
  1053. }
  1054. "
  1055. while read -r f; do
  1056. mkdir -p "_upstream/$(dirname "$f")"
  1057. curl -sL -o "_upstream/$f" "$BASE/$f"
  1058. done < /tmp/paths.txt
  1059. ```
  1060. > ### Pitfall: the `.example` and `.template` trap
  1061. >
  1062. > 25 files end in `.example` and 11 in `.template`. Any glob like `*.ts` or `*.json`
  1063. > misses all of them. A count based on the GitHub API is the only reliable check.
  1064. > Also easy to miss: `LICENSE` (no extension), `CLAUDE.md` (11 bytes),
  1065. > `.github/workflows/validate.yml`, three localised READMEs, and 10 SVG assets in
  1066. > `docs/assets/readme/` (each with a `-still.svg` twin).
  1067. ### 12.2 Port, do not copy
  1068. Port the *concept* into OpenCode's own shape. Do not copy client-specific harness internals
  1069. (Claude Code plugins, Codex config), and never copy credentials.
  1070. | Upstream concept | OpenCode equivalent |
  1071. |---|---|
  1072. | Graphify project graph | `codebase-memory-mcp` graph tools + `check_index_coverage` |
  1073. | Obsidian memory | durable notes in `docs/` + Serena memory + the environment manifest |
  1074. | Codex/Claude playbook | `opencode.json`, `plugins/`, `mcp/`, `hooks/` + `opencode plugin list` |
  1075. | Anthropic skills | OpenCode skills, `context7` for library docs |
  1076. ### 12.3 Cross-check the port with more than one model
  1077. Independent catalogs from different models catch different omissions. Have each produce a
  1078. path list, then have a third compare them against live ground truth:
  1079. ```sh
  1080. gh api "repos/OWNER/REPO/git/trees/main?recursive=1" --jq '.tree[] | select(.type=="blob") | .path'
  1081. ```
  1082. In this setup the cross-check found 26 files missing from the local mirror — the root
  1083. READMEs, LICENSE, the workflow file, 10 SVG assets, and 6 templates — because the first
  1084. catalog was built from the local mirror instead of from GitHub.
  1085. ---
  1086. ## 13. Verification
  1087. Run all of it after a fresh boot.
  1088. ```sh
  1089. echo "=== services ==="
  1090. launchctl list | grep -iE "headroom|rtk"
  1091. echo "=== ports ==="
  1092. lsof -nP -iTCP -sTCP:LISTEN | grep -E ":8080|:8787"
  1093. echo "=== chain ==="
  1094. curl -s http://127.0.0.1:8787/readyz | jq -r .checks.upstream.url
  1095. rtk-proxy config get | jq -r .openai_upstream
  1096. echo "=== mcp ==="
  1097. opencode mcp list
  1098. echo "=== plugins ==="
  1099. opencode plugin list
  1100. echo "=== models live ==="
  1101. for m in kpa/gpt-5-6-luna kpa/claude-opus-5-5 kpa/claude-haiku-5-5; do
  1102. printf '%s -> ' "$m"
  1103. opencode run --model "$m" "reply exactly OK" 2>&1 | tail -n 1
  1104. done
  1105. echo "=== savings ==="
  1106. rtk gain
  1107. headroom savings
  1108. ```
  1109. Expected chain output:
  1110. ```text
  1111. http://127.0.0.1:8080
  1112. https://api.example.com/v1
  1113. ```
  1114. Expected savings on a busy machine:
  1115. ```text
  1116. RTK Token Savings (Global Scope)
  1117. Total commands: 239
  1118. Tokens saved: 19.6K (38.0%)
  1119. headroom savings
  1120. opencode 36 calls - 11,019 tokens saved
  1121. ```
  1122. ---
  1123. ## 14. Troubleshooting
  1124. ### `rtk-proxy stats` shows `tokens saved: 0`
  1125. The proxy layer cannot compress by itself. Check in this order:
  1126. 1. `~/Library/Application Support/rtk/pipeline.toml` exists and extends `rtk:posthook`.
  1127. 2. The daemon log says `pipeline=rtk:posthook`, not `pipeline=rtk:default`.
  1128. 3. The agent-side `execute.after` hook is registered — this is where the saving happens.
  1129. ```sh
  1130. rtk pipeline show
  1131. tail -n 20 ~/Library/Application\ Support/rtk-proxy/rtk-proxy.log
  1132. ```
  1133. ### The RTK after-hook does nothing
  1134. Check in order:
  1135. 1. **Plugin syntax error.** A malformed plugin fails to load *silently*. Confirm:
  1136. ```sh
  1137. cp ~/.config/opencode/plugins/rtk.ts /tmp/rtk-check.mts
  1138. node --input-type=module -e "import('/tmp/rtk-check.mts').then(()=>console.log('OK')).catch(e=>console.log('ERR',e.message))"
  1139. ```
  1140. 2. **Wrong output path.** Must be `result.output.output`, not `result.output.stdout`.
  1141. 3. **Missing `tool_input.command`** in the payload sent to `rtk hook claude`.
  1142. 4. **Output under 512 bytes** — the `min_size` guard.
  1143. 5. **Command was rewritten by RTK** — `is_rtk_command = false` means it is skipped.
  1144. 6. **Stale server.** The background `opencode serve --service` caches the loaded plugin.
  1145. Use `/reload` in the TUI, or `opencode run --standalone` to test plugin changes.
  1146. ### MCP shows `NotFound: ChildProcess.spawn`
  1147. The OpenCode server's `PATH` lacks the fnm bin directory. Use absolute paths in `command`.
  1148. ### `rtk pipeline explain` shows no rules for `--agent opencode`
  1149. Expected. RTK knows `claude-code`, not `opencode`. Use `--agent claude-code`.
  1150. ### `rtk-proxy config set` reports success but nothing changes
  1151. Expected. The write does not persist. Edit the toml file or use the environment variables.
  1152. ### Headroom upstream still points at the old provider
  1153. The manifest's `base_env` overrides the run script. Edit **both**, then reload the launchd
  1154. agent:
  1155. ```sh
  1156. launchctl bootout gui/$(id -u)/com.headroom.default
  1157. launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.headroom.default.plist
  1158. ```
  1159. ### Headroom is healthy but saves nothing
  1160. Check the router counters in the log:
  1161. ```sh
  1162. grep -i "router" ~/.headroom/logs/proxy-8787.log | tail -n 5
  1163. ```
  1164. ```text
  1165. [router] route_counts={'excluded_tool': 1} compressed=0 frozen=2 msgs=3
  1166. ```
  1167. `compressed=0` means the interceptors never ran. Two causes, both must be fixed:
  1168. 1. `HEADROOM_ROLLOUT_CHANNEL=canary` is not set in the run script, the ensure script,
  1169. **and** the manifest `base_env`.
  1170. 2. `--intercept-tool-results` is missing from `proxy_args` in the manifest.
  1171. ```sh
  1172. headroom rollout status
  1173. # tool_result_interceptors: enabled=true decision=rollout_channel
  1174. ```
  1175. ### A client started returning "Incorrect API key provided"
  1176. You changed a shared proxy's upstream. Headroom serves every client that points at it.
  1177. Restore the upstream that client expects, or give each provider its own Headroom instance
  1178. on its own port (see 5.4.1).
  1179. ### Shell tool calls fail to parse
  1180. ```text
  1181. The tool input could not be parsed as JSON, so the call was not executed.
  1182. Invalid arguments for tool "shell": command: Missing key
  1183. ```
  1184. The command string carried nested quotes, escaped quotes, backslashes, a heredoc, `$(...)`, or
  1185. backticks. Do **not** retry with more escaping. Write the command to a script file with the
  1186. `patch` tool, then run it:
  1187. ```sh
  1188. sh /path/to/script.sh
  1189. ```
  1190. The same rule applies to `ctx_execute` with `language: "shell"` — its `code` field is still a
  1191. shell command string.
  1192. ### Everything worked, then stopped after a Node upgrade
  1193. fnm changes the version directory. Re-resolve the MCP paths:
  1194. ```sh
  1195. ls -d ~/.local/share/fnm/node-versions/v*/installation/bin
  1196. ```
  1197. and update every MCP entry that referenced the old path.
  1198. ---
  1199. ## 15. Complete file reference
  1200. ### Created or modified
  1201. | Path | Purpose |
  1202. |---|---|
  1203. | `~/.config/opencode/opencode.json` | providers, models + limits, MCPs, plugins, compaction, permission |
  1204. | `~/.config/opencode/AGENTS.md` | global policy: graph rules, caveman, shell hygiene, REA ban |
  1205. | `~/.config/opencode/get-shit-done/` | superpowers framework: gsd-* agents, templates, workflows, `gsd-tools.cjs` |
  1206. | `~/.config/opencode/plugins/rtk.ts` | RTK plugin **plus the after-tool compression hook** |
  1207. | `~/.config/opencode/plugins/rea-guard/index.ts` | REA model guard |
  1208. | `~/.config/opencode/plugins/rea-guard/package.json` | plugin manifest |
  1209. | `~/.config/opencode/secrets/*.key` | provider keys, `chmod 600` |
  1210. | `~/.claude/settings.json` | Claude Code to Headroom, models, RTK hooks |
  1211. | `~/Library/Application Support/rtk-proxy/rtk-proxy.toml` | proxy config |
  1212. | `~/Library/Application Support/rtk/pipeline.toml` | RTK pipeline (`rtk:posthook`) |
  1213. | `~/Library/LaunchAgents/app.rtk-ai.rtk-proxy.plist` | rtk-proxy autostart |
  1214. | `~/Library/LaunchAgents/com.headroom.default.plist` | Headroom autostart |
  1215. | `~/.headroom/deploy/default/manifest.json` | Headroom deployment (upstream + args) |
  1216. | `~/.headroom/deploy/default/run-headroom.sh` | Headroom env (chain + canary) |
  1217. | `~/vibecoding/AGENTS.md` | workspace policy |
  1218. | `~/vibecoding/CLAUDE.md` | bridge |
  1219. | `~/vibecoding/docs/*.md` | architecture, quality, onboarding, setup, design |
  1220. | `~/vibecoding/vibe-toolkit/` | ported toolkit (docs, prompts, templates, vendor mirror) |
  1221. | `~/vibecoding/vault/` | Obsidian vault |
  1222. ### Installed software
  1223. | Tool | Version | Form |
  1224. |---|---|---|
  1225. | OpenCode | 2.3.2 | CLI + server |
  1226. | rtk | 1.2.1 | Homebrew |
  1227. | rtk-proxy | 1.2.1 | GitHub release asset, checksum-verified |
  1228. | Headroom | 0.41.0 | `uv tool install` |
  1229. | context-mode | 2.2.1 | npm + MCP + plugin |
  1230. | ponytail | 5.3.3 | npm plugin |
  1231. | caveman | 4.1.0 | npm plugin + skills |
  1232. | superpowers | 22f0b46 | git plugin |
  1233. | rea-agents | 6.9.0 | npm + MCP |
  1234. | @playwright/mcp | 0.0.86 | npm + MCP |
  1235. | codebase-memory-mcp | 0.12.1 | binary |
  1236. | serena | 2.1.1.dev0 | `uvx` from git |
  1237. ### Measured results
  1238. | Metric | Value |
  1239. |---|---|
  1240. | RTK overall savings | 34.4K tokens (29.6%) |
  1241. | RTK after-hook on a 51KB result | 51,374 to 16,108 bytes (69%) |
  1242. | Headroom savings (OpenCode) | 11,019 tokens over 36 calls |
  1243. | Headroom on large Bash output | ~15% |
  1244. | Kompress warm-up (tuned) | 10,159 ms (was 58,861 ms) |
  1245. | REA tools available | 255 (plus 6 prompts) |
  1246. ---
  1247. ## 16. Every issue we hit, and its fix
  1248. Chronological. Each entry is a symptom you can recognise, the cause, and the fix.
  1249. ### 16.1 Shell tool calls randomly failing to parse
  1250. **Symptom**
  1251. ```text
  1252. The tool input could not be parsed as JSON, so the call was not executed.
  1253. Invalid arguments for tool "shell": command: Missing key
  1254. ```
  1255. **Cause.** The command string carried nested quotes, `\"` escapes, backslashes, a heredoc
  1256. (`<<`), `$(...)` substitution, or backticks. The harness drops or truncates those payloads.
  1257. Nothing was wrong with the command's intent.
  1258. **Fix.** Never retry with more escaping — that is what triggers it. Write the command to a
  1259. script file and run it:
  1260. ```sh
  1261. # via the patch tool: *** Add File: /tmp/job.sh
  1262. sh /tmp/job.sh
  1263. ```
  1264. Same rule for `ctx_execute` with `language: "shell"` — its `code` field is still a shell
  1265. command string.
  1266. **Prevention.** Put this in `AGENTS.md` so every agent and subagent inherits it:
  1267. ```markdown
  1268. ## Shell and output hygiene
  1269. - Keep shell commands short and simple. No heredocs. No multi-line `node -e` with nested quotes.
  1270. - For complex commands, write a script file with the write/patch tool, then run `sh /path/to/script.sh`.
  1271. - For output over roughly 20 lines, use `ctx_execute` with an `intent`, then `ctx_search` for the part that matters.
  1272. - Batch independent checks with `ctx_batch({commands, queries})`.
  1273. - Pass this guidance to every subagent before it starts shell work.
  1274. ```
  1275. ### 16.2 `rtk-proxy` saved nothing
  1276. **Symptom.** `rtk-proxy stats` reported `tokens saved: 0` across every request, while the
  1277. chain otherwise worked.
  1278. **Cause.** Two separate things.
  1279. 1. No pipeline file existed, so the daemon ran `rtk:default` and logged
  1280. `no cache-breakpoint or CCR rules — running category-A normalisation only`.
  1281. 2. Even with the pipeline fixed, the proxy **cannot** run the real compression method.
  1282. `term` keeps the original only in a recall copy the proxy cannot store, so RTK skips it
  1283. at the proxy layer (warning `W016`).
  1284. **Fix.** Part one — the pipeline file:
  1285. ```toml
  1286. schema_version = 1
  1287. [pipeline]
  1288. extends = ["rtk:posthook", "rtk:proxy"]
  1289. ```
  1290. Part two — the agent-side hook in [Step 7](#9-step-7--the-rtk-after-tool-hook).
  1291. The proxy alone will never compress; the hook is where the saving happens.
  1292. ### 16.3 `rtk-proxy config set` reported success and changed nothing
  1293. **Symptom**
  1294. ```text
  1295. $ rtk-proxy config set openai_upstream https://example.com/v1
  1296. openai_upstream = https://example.com/v1
  1297. $ rtk-proxy config get openai_upstream
  1298. https://api.openai.com
  1299. ```
  1300. **Cause.** The admin write endpoint acknowledges the request but does not persist the value.
  1301. **Fix.** Edit `~/Library/Application Support/rtk-proxy/rtk-proxy.toml` directly, or set
  1302. `RTK_PROXY_OPENAI_UPSTREAM` / `RTK_PROXY_ANTHROPIC_UPSTREAM` in the environment before
  1303. starting the daemon.
  1304. ### 16.4 The RTK after-hook silently did nothing
  1305. **Symptom.** The hook was registered, the payload looked right, and no output was compressed.
  1306. No error anywhere.
  1307. **Causes, in the order we found them.**
  1308. 1. **A syntax error in the plugin.** An orphaned doc comment left by a bad edit made the
  1309. plugin fail to load. OpenCode reported nothing.
  1310. ```sh
  1311. cp ~/.config/opencode/plugins/rtk.ts /tmp/rtk-check.mts
  1312. node --input-type=module -e "import('/tmp/rtk-check.mts').then(()=>console.log('OK')).catch(e=>console.log('ERR',e.message))"
  1313. ```
  1314. 2. **Wrong output path.** OpenCode's shell tool reports
  1315. `{exitCode, output, wallTimeSeconds}`. The text is at `result.output.output`, **not**
  1316. `result.output.stdout`. Reading `.stdout` gives `undefined` and the handler returns.
  1317. 3. **Missing `tool_input.command`** in the payload sent to `rtk hook claude`. Without it the
  1318. hook returns empty.
  1319. 4. **The tool name was `shell`, not `Bash`.** `rtk hook claude` keys off Claude Code's tool
  1320. names, so the plugin must map `shell` to `Bash` before building the payload.
  1321. 5. **Output under 512 bytes** — RTK's `min_size` guard.
  1322. 6. **The command had been rewritten by RTK itself.** `is_rtk_command = false` means RTK
  1323. skips compressing its own output, by design.
  1324. 7. **A stale server.** The background `opencode serve --service` caches the loaded plugin.
  1325. **How it was actually found.** A throwaway probe plugin that dumped
  1326. `Object.keys(event)` to a file, which revealed the real payload shape:
  1327. ```text
  1328. after {"tool":"shell","status":"completed","outputType":"string","outputLen":51374}
  1329. ```
  1330. ### 16.5 Headroom compressed nothing
  1331. **Symptom.** Everything healthy — `headroom doctor` passed, `kompress` reported
  1332. `ready (onnx)`, requests succeeded — but the token count never dropped.
  1333. **Cause.** Tool-result interception is opt-in and gated behind a rollout channel. Both parts
  1334. are required.
  1335. **Fix.**
  1336. ```bash
  1337. export HEADROOM_ROLLOUT_CHANNEL=canary
  1338. ```
  1339. ```json
  1340. "proxy_args": ["--intercept-tool-results", "..."]
  1341. ```
  1342. **Verify.**
  1343. ```sh
  1344. headroom rollout status
  1345. # tool_result_interceptors: enabled=true decision=rollout_channel
  1346. grep -i router ~/.headroom/logs/proxy-8787.log | tail -n 3
  1347. # compressed=1 <- was compressed=0
  1348. ```
  1349. ### 16.6 Repointing Headroom broke Claude Code
  1350. **Symptom.** After changing Headroom's upstream to serve OpenCode, Claude Code started
  1351. failing:
  1352. ```text
  1353. Error: Incorrect API key provided: sk-...5060.
  1354. ```
  1355. **Cause.** Headroom is a **shared** proxy. Claude Code was already routed through it with a
  1356. different provider's key. Changing the upstream changed it for every client.
  1357. **Fix.** Do not move a shared proxy between providers. Either restore the upstream that
  1358. client expects, or run two Headroom instances on two ports using separate deployment
  1359. profiles:
  1360. ```sh
  1361. headroom deploy --profile openai --port 8788 --providers manual --target opencode
  1362. headroom deploy --profile default --port 8787 --providers manual --target claude
  1363. ```
  1364. **Prevent.** Audit who points at the proxy before changing it:
  1365. ```sh
  1366. grep -r "127.0.0.1:8787" ~/.claude ~/.config/opencode 2>/dev/null
  1367. ```
  1368. ### 16.7 The manifest silently overrode the run script
  1369. **Symptom.** Edited `run-headroom.sh` to point at rtk-proxy, reloaded the service, and
  1370. `/readyz` still reported the old upstream.
  1371. **Cause.** `base_env` in `~/.headroom/deploy/default/manifest.json` takes precedence over the
  1372. script's `export` statements.
  1373. **Fix.** Edit both. Then reload:
  1374. ```sh
  1375. launchctl bootout gui/$(id -u)/com.headroom.default
  1376. launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.headroom.default.plist
  1377. sleep 8
  1378. curl -s http://127.0.0.1:8787/readyz | grep -o '"url":"[^"]*"'
  1379. ```
  1380. ### 16.8 MCP servers failed with `NotFound: ChildProcess.spawn`
  1381. **Symptom**
  1382. ```text
  1383. x rea failed: NotFound: ChildProcess.spawn (rea mcp)
  1384. x playwright failed: NotFound: ChildProcess.spawn (playwright-mcp )
  1385. ```
  1386. **Cause.** The binaries existed and worked from the shell. The OpenCode server's `PATH`
  1387. does not include the fnm-managed Node bin directory.
  1388. **Fix.** Absolute paths in every MCP `command`:
  1389. ```json
  1390. "command": ["/Users/<you>/.local/share/fnm/node-versions/v24.22.3/installation/bin/rea", "mcp"]
  1391. ```
  1392. Re-resolve after any Node upgrade — fnm changes the version segment.
  1393. ### 16.9 `rtk pipeline explain` showed no rules for OpenCode
  1394. **Symptom.**
  1395. ```text
  1396. $ rtk pipeline explain --agent opencode --tool Bash --command "ls"
  1397. hook.after_tool.any: no rule matches these facts — output passes through
  1398. ```
  1399. **Cause.** Not a bug. The pipeline resolves rules by agent name and RTK does not know
  1400. `opencode`.
  1401. **Fix.** Inspect with `--agent claude-code`.
  1402. ### 16.10 The model guard blocked everything, including allowed models
  1403. **Symptom.** REA was blocked even on a model that should have been allowed.
  1404. **Cause.** The first guard version hardcoded a provider list, so any model not on it was
  1405. treated as banned.
  1406. **Fix.** Ban by **model id pattern**, allow everything else, and resolve the real session
  1407. model server-side:
  1408. ```ts
  1409. const session = await ctx.session.get({ sessionID })
  1410. const modelID = String(session?.model?.id ?? "")
  1411. ```
  1412. And fail **closed** — if the model cannot be resolved, block the call:
  1413. ```ts
  1414. } catch {
  1415. throw new Error(`[rea-guard] blocked ${tool}: could not resolve the session model.`)
  1416. }
  1417. ```
  1418. ### 16.11 The 26-file upstream mirror gap
  1419. **Symptom.** A catalog of the upstream toolkit found 122 files. The local mirror had 96.
  1420. **Cause.** The first catalog was built from the local mirror instead of from GitHub, so it
  1421. inherited the mirror's blind spots. The missing 26 were the files a glob-based sync skips:
  1422. root READMEs (en/es/pt-BR), `LICENSE`, `CLAUDE.md`, `.gitignore`,
  1423. `.github/workflows/validate.yml`, `templates/README.md`,
  1424. `templates/environment-manifest.json.example`, `templates/product.md.template`, 5
  1425. `project-docs/*.md.template` files, and 10 SVG assets.
  1426. **Fix.** Always diff against live ground truth, never against a local copy:
  1427. ```sh
  1428. curl -s -H "User-Agent: opencode" \
  1429. "https://api.github.com/repos/OWNER/REPO/git/trees/main?recursive=1" -o /tmp/gt.json
  1430. ```
  1431. And check `truncated` in the response — the trees API truncates on large repos.
  1432. **Prevention.** Cross-check with more than one model. Three independent catalogs agreed on
  1433. 122 and found the same 26 missing; a catalog built from the local mirror was the only
  1434. outlier. See [12.3](#123-cross-check-the-port-with-more-than-one-model).
  1435. ### 16.12 `npm update -g` removed globally installed packages
  1436. **Symptom.** A package that was installed and working disappeared after an npm upgrade.
  1437. **Cause.** `npm update -g` updates packages npm knows about and can remove ones it does not.
  1438. **Fix.** Use `npm install -g <pkg>@latest` for each package. Verify afterwards:
  1439. ```sh
  1440. npm list -g --depth=0
  1441. ```
  1442. ### 16.13 Frida's install script was blocked by npm
  1443. **Symptom.** `npm install -g rea-agents` warned:
  1444. ```text
  1445. npm warn install-scripts 1 package has install scripts not yet covered by allowScripts:
  1446. npm warn install-scripts frida@17.23.2 (install: node scripts/install.js)
  1447. ```
  1448. **Cause.** npm's default is to not run install scripts. Frida's script downloads the native
  1449. binaries.
  1450. **Fix.** Only if REA's dynamic instrumentation is needed:
  1451. ```sh
  1452. npm install -g --allow-scripts=frida rea-agents@latest
  1453. ```
  1454. ### 16.14 Provider limits were silently capped
  1455. **Symptom.** A model with a 1M context window behaved as if it had 200k.
  1456. **Cause.** Custom providers fall back to 200k context / 32k output unless each model
  1457. declares its own `limit`.
  1458. **Fix.** Declare `limit` per model in `opencode.json`, sourced from models.dev.
  1459. ### 16.15 The plugin was edited but the running server kept the old code
  1460. **Symptom.** A plugin edit had no effect. `opencode run` behaved as before.
  1461. **Cause.** The background `opencode serve --service` caches loaded plugins.
  1462. **Fix.** `/reload` in the TUI, or test against a fresh server:
  1463. ```sh
  1464. opencode run --standalone --model kpa/gpt-5-6-luna "..."
  1465. ```
  1466. ### 16.16 `gh` was not the only path to GitHub
  1467. **Symptom.** Repository work drifted toward raw `curl` calls to `api.github.com`.
  1468. **Fix.** A standing rule in `AGENTS.md`:
  1469. ```markdown
  1470. Use `gh` for every GitHub call (`gh repo clone`, `gh api`, `gh pr`, `gh issue`).
  1471. Never call the GitHub REST API directly with `curl`.
  1472. ```
  1473. `gh` is already authenticated, so it also removes the need to handle tokens by hand:
  1474. ```sh
  1475. gh auth status
  1476. gh repo clone OWNER/REPO ./local-dir
  1477. gh api "repos/OWNER/REPO/git/trees/main?recursive=1" --jq '.tree[].path'
  1478. ```
  1479. ### 16.17 `verify.sh` reported failures that were not real
  1480. **Symptom.** The verification script printed:
  1481. ```text
  1482. FAIL rea-guard not loaded
  1483. FAIL rtk not loaded
  1484. ```
  1485. while `opencode plugin list` plainly showed both plugins loaded.
  1486. **Cause.** `grep -q` exits the moment it finds a match. The upstream command in the pipe
  1487. then receives `SIGPIPE` and dies. Under `set -o pipefail` the pipeline's status becomes
  1488. that failure, so a *successful* match reported as a *failed* check.
  1489. The same bug made one check pass for the wrong reason — the MCP check used
  1490. `grep -q "failed"`, which does not match, so `grep` exited 1 and the `|| ok` branch ran.
  1491. It was reporting "all connected" because the string was absent, not because it was present.
  1492. **Fix.** Capture into a variable, then match in the shell — no pipe involved:
  1493. ```bash
  1494. has() { [[ "$1" == *"$2"* ]]; }
  1495. plugin_out=$(opencode plugin list 2>&1)
  1496. has "$plugin_out" "rea-guard" && ok "rea-guard loaded" || bad "rea-guard not loaded"
  1497. ```
  1498. **Detection.** A check that fails while the underlying command clearly succeeds is a
  1499. script bug, not a system bug. Verify the command by hand before touching the system.
  1500. ### 16.18 Kompress took 59 seconds to warm
  1501. **Symptom.** After every headroom restart, the first request through the proxy stalled.
  1502. The log showed:
  1503. ```text
  1504. Kompress: DEFERRED (warming in the background after startup)
  1505. ...
  1506. Kompress: warmed in the background in 58861 ms (backend onnx)
  1507. ```
  1508. **Cause.** ONNX Runtime's default thread pool settings are conservative. On an 8-core
  1509. arm64 Mac it built the session for the 261MB int8-wo model using a fraction of the
  1510. available cores.
  1511. **Fix.** Three environment variables, in both the run script and the manifest `base_env`:
  1512. ```bash
  1513. export HEADROOM_KOMPRESS_ONNX_INTRA_THREADS=8
  1514. export HEADROOM_KOMPRESS_ONNX_INTER_THREADS=2
  1515. export HEADROOM_KOMPRESS_WARMUP_DELAY_SECONDS=0
  1516. ```
  1517. Result: **58,861 ms → 10,159 ms**.
  1518. **Trap.** The env var names are `HEADROOM_KOMPRESS_ONNX_*`, not `KOMPRESS_ONNX_*`. The
  1519. latter silently does nothing — `_env_int` returns `None` for an unset variable and the
  1520. session options are left at ORT's defaults.
  1521. **Trap.** `HEADROOM_ONNX_ALLOW_SPINNING=1` looks like a performance win and is not. It
  1522. makes ORT's idle threads spin-wait, pegging every core while the proxy sits idle. It does
  1523. not affect session creation, so it does not help the warm-up either.
  1524. ---
  1525. ## 17. Complete issue index
  1526. | # | Symptom | Root cause | Fix | Where |
  1527. |---|---|---|---|---|
  1528. | 1 | Shell call fails to parse JSON | nested quotes, escapes, heredoc, `$()` | script file, then `sh file` | [16.1](#161-shell-tool-calls-randomly-failing-to-parse) |
  1529. | 2 | `rtk-proxy` saves 0 tokens | no pipeline file + proxy cannot reach `hook.after_tool` | `pipeline.toml` + agent-side hook | [16.2](#162-rtk-proxy-saved-nothing) |
  1530. | 3 | `config set` does not persist | admin write is not durable | edit the toml, or use env vars | [16.3](#163-rtk-proxy-config-set-reported-success-and-changed-nothing) |
  1531. | 4 | RTK after-hook silent | syntax error / wrong path / missing command / wrong tool name / <512 B / stale server | 7 checks, listed in place | [16.4](#164-the-rtk-after-hook-silently-did-nothing) |
  1532. | 5 | Headroom saves nothing | interceptors need canary channel **and** the flag | both | [16.5](#165-headroom-compressed-nothing) |
  1533. | 6 | Client gets "Incorrect API key" | shared proxy's upstream was repointed | restore, or two profiles on two ports | [16.6](#166-repointing-headroom-broke-claude-code) |
  1534. | 7 | Headroom upstream unchanged | manifest `base_env` beats the script | edit both, reload launchd | [16.7](#167-the-manifest-silently-overrode-the-run-script) |
  1535. | 8 | MCP `NotFound: spawn` | server PATH lacks the fnm bin dir | absolute paths | [16.8](#168-mcp-servers-failed-with-notfound-childprocessspawn) |
  1536. | 9 | `pipeline explain` shows nothing | agent name unknown to RTK | use `--agent claude-code` | [16.9](#169-rtk-pipeline-explain-showed-no-rules-for-opencode) |
  1537. | 10 | Guard blocks allowed models | provider allowlist instead of id patterns | ban by pattern, resolve real model, fail closed | [16.10](#1610-the-model-guard-blocked-everything-including-allowed-models) |
  1538. | 11 | 26 upstream files missing | catalog built from the local mirror | diff against live ground truth | [16.11](#1611-the-26-file-upstream-mirror-gap) |
  1539. | 12 | npm package disappeared | `npm update -g` removed it | `npm install -g pkg@latest`, verify | [16.12](#1612-npm-update--g-removed-globally-installed-packages) |
  1540. | 13 | Frida install script skipped | npm blocks install scripts by default | `--allow-scripts=frida` | [16.13](#1613-fridas-install-script-was-blocked-by-npm) |
  1541. | 14 | Model capped at 200k | no `limit` declared | declare per model | [16.14](#1614-provider-limits-were-silently-capped) |
  1542. | 15 | Plugin edit ignored | server caches plugins | `/reload` or `--standalone` | [16.15](#1615-the-plugin-was-edited-but-the-running-server-kept-the-old-code) |

Lines 2,001–2,010 are not shown. The link to the file on GitHub has every line.

Ratings and comments

Sign in to rate this skill.

Sign in

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