feat(opencode): миграция sapphira на OpenCode v2 (2.0.32) из nixpkgs master
test-runner / smoke (push) Successful in 1s

v2 есть только в nixpkgs master (nixos-unstable = 1.19.0), поэтому пакет
берётся из inputs.nixpkgs-master, а конфиг пишется вручную: HM-модуль
programs.opencode — v1-only (plugin ед.ч., mcp плоской картой, tui.json,
validateFiles.tui требует отсутствующего passthru.jsonschema.tui).

- home/modules/opencode.nix: v2-конфиг (plugins/mcp.servers), cli.json,
  oh-my-opencode-slim 3.0.5 (единственный v2-совместимый плагин), --port 4096
  (дефолт serve в v2 — 4097, nginx проксирует на 4096), фон-сервис v2 выключен,
  обёртка oc (CLI к работающему юниту: пароль из sops server.env, --server
  после подкоманды), cgroup-защита в [Service], активация ставит пакет
  плагина и прогревает npx-кэш MCP
- flake.lock: nixpkgs-master -> c4f353ac
- ADR-0006 (контекст, факты, инциденты деплоя, herdr) + index.json + T36

Деплой выполнен 2026-10-21 на самой sapphira (сборка + nixos-rebuild switch),
проверено: юнит active на 0.0.0.0:4096, 10 агентов, 3 MCP connected,
LLM smoke на minimax-coding-plan/MiniMax-M3.1-Flash.

AGENTS.md и .agent/rules/project-rules.md оставлены в рабочем дереве:
там вперемешку правки 3x-ui/REALITY/WARP (чужие) — не смешивать.
This commit is contained in:
opencode committed 2026-10-21 13:43:05 +03:00
1 parent d0df318553
commit d98636ed6a
5 files changed
+582 -268

No files matched your search

@@ -0,0 +1,289 @@
# ADR-0006: OpenCode на sapphira — миграция 1.19 (v1) → 2.0.32 (v2)
**Статус:** accepted (деплой выполнен 2026-10-21 на sapphira; herdr — см. раздел
«Herdr и v2»)
**Дата:** 2026-10-21
**Контекст.**
sapphira гонял OpenCode **1.19.0** (`pkgs.opencode` из nixos-unstable) как
systemd user-сервис `opencode-web`: `opencode serve --hostname 0.0.0.0 --cors
https://opencode.zeroq.su`, пароль через sops (`secrets/opencode.env` →
`~/.config/opencode/server.env`), cgroup-защита
`MemoryHigh=1G/MemoryMax=2G/OOMScoreAdjust=-900/OOMPolicy=continue`
(`home/modules/opencode.nix`). nginx-vhost `opencode.zeroq.su` проксирует на
`127.0.0.1:4096`. Плагин — `oh-my-openagent@latest`, его конфиг
`~/.omo/omo.jsonc` (11 агентов + 8 категорий, ключ `variant`, `fallback_models`).
Рабочая машина (vetymae, Windows) уже на **v2** (`scoop`, 2.0.32 → 2.1.2 в
ночь 2026-10-21) с плагином `oh-my-opencode-slim@3.0.5`.
Вопрос: можно ли повторить конфигурацию рабочей машины на сервере.
**Что выяснено (проверено, 2026-10-20/21).**
1. **Пакет.** `nixos-unstable` → `opencode 1.19.0`. **v2 есть только в
nixpkgs master**: `pkgs/by-name/op/opencode/package.nix`, `version =
"2.0.32"`, `hash = sha256-KATNzF7z3PoUo30KC13Gm8uC6HA2a9bmJCZRfqY5D44=`,
`OPENCODE_CHANNEL=latest`, `passthru.jsonschema = { cli, config, theme }`
(**`tui` удалён**), ставит `share/{cli,config,theme}.json`, wrap-ит
`ripgrep` в PATH, `OPENCODE_DISABLE_AUTOUPDATE=true`.
PR [NixOS/nixpkgs#569770](https://github.com/NixOS/nixpkgs/pull/569770)
(«opencode, opencode-desktop: 1.19.0 -> 2.0.32») влит в master
2026-10-19T23:35Z. У v2 **нет GitHub-релизов** (только теги) → «скачать
tarball и положить в nix» невозможно; npm-путь — `@opencode/cli@2.1.2` +
`@opencode/cli-linux-x64` (213 MB, bun-ELF).
2. **home-manager `programs.opencode` — v1-only.** Модуль (master, 2026-10-10)
пишет `opencode.json` + `tui.json`, документирует ключ `plugin` (ед.ч.),
интегрирует MCP как плоскую карту `settings.mcp`, а `validateFiles.tui`
берёт `passthru.jsonschema.tui` — **которого в v2-пакете нет** ⇒ сборка
HM с v2-пакетом и включённой валидацией падает. v2-поддержка в HM не
влита (issue HM#10070 закрыт как «сделано», но PR от delafthi только в
работе).
3. **Схема конфига v2** (извлечено из самого бинаря v2): глобальный конфиг
`~/.config/opencode/{config.json,opencode.json,opencode.jsonc}` (приоритет
последнего существующего); `plugin` → **`plugins`**; `mcp` → **`mcp.servers`**
(у записи есть `type`); `tui.json` → **`cli.json`**
(`$schema: https://opencode.ai/v2/cli.json`, миграция tui.json→cli.json
автоматическая, но на HM-хосте `tui.json` — read-only симлинк в
/nix/store ⇒ миграция не может записать ⇒ `cli.json` объявляется явно).
`reasoning`/`variant` живут в схеме модели, не в ключах opencode.json.
4. **CLI v2.** `opencode web` **удалён**; `opencode serve` отдаёт и API, и
web-UI (проверено: `GET /` → 200 HTML, `GET /api/health` без кредов → 401
`UnauthorizedError`). Появились `opencode service start|stop|status`,
`opencode plugin add|list|check|update`, `opencode mcp add|list`,
`opencode reload`, `opencode pair` (one-time link для браузера),
`opencode debug paths|config|agents`. **Дефолтный порт `serve` — 4097**
(4096 зарезервирован под фоновый сервис v2) — проверено локально:
`opencode serve --hostname 127.0.0.1` → `server listening on
http://127.0.0.1:4097`.
5. **Аутентификация не изменилась:** `OPENCODE_PASSWORD`, иначе
`OPENCODE_SERVER_PASSWORD`, иначе — случайный 32-байтный пароль (тогда
клиенты не подключатся). HTTP basic, пользователь `opencode`.
6. **Плагины.** v2 ставит npm-пакеты сам (встроенный `@npmcli/arborist`),
в `~/.cache/opencode/npm/<pkg>/<gen>/node_modules`; `bun`/`npx` для этого
не нужны, нужны writable HOME + сеть. **v2-совместим только
`oh-my-opencode-slim`**: в пакете 3.0.5 есть `dist/tui2.js` и
`dist/v2/tui.d.ts` + документ «OpenCode v2 Compatibility» с baseline
v2.0.x. `oh-my-openagent` **5.1.40** (latest на 2026-10-20) экспортирует
только `.`, `./server`, `./tui`, `./schema.json` — **v2-точки входа нет**.
Конфиг slim-плагина — `~/.config/opencode/oh-my-opencode-slim.json`
(не `~/.omo/omo.jsonc`, который читает openagent).
7. **Реестр моделей** (`opencode models`, оба хоста): ровно
`minimax-coding-plan/MiniMax-M3` (variants: none, thinking),
`minimax-coding-plan/MiniMax-M3.1-Flash` (без variants),
`opencode/big-pickle` (без variants),
`opencode/minimax-m3.1-flash-free` (variants: low…max).
`MiniMax-M3.1-Flash-Preview`, `MiniMax-M2.7-highspeed`,
`MiniMax-M2.5-highspeed` — **в реестре отсутствуют**. Старый
`~/.omo/omo.jsonc` на сервере ссылался на `MiniMax-M3.1-Flash-Preview`
везде — тот же класс грабли, что `kimi-for-coding` (см. R1.x): модель в
конфиге есть, в реестре — нет.
**Решение.**
1. **Пакет:** `programs.opencode.package = (import inputs.nixpkgs-master {
system = ...; }).opencode` — тот же input уже был в флейке (его использует
`modules/server/nextcloud.nix`). `flake.lock` обновлён на rev
`c4f353ac4a4179840c3f196a33b02053958a3f1d` (2026-10-21).
Когда v2 попадёт в nixos-unstable — вернуть `pkgs.opencode` и убрать
зависимость от master.
2. **Конфиг пишется вручную** (`xdg.configFile`), а не через
`programs.opencode.settings`: HM-модуль v1-only, а нам нужны v2-ключи.
`programs.opencode` остаётся включённым (он даёт бинарь, wrapper с
`extraPackages` и systemd-юнит), но `settings`/`tui` у него пустые.
Файлы:
- `opencode.json` — `plugins` (мн. ч.) + `mcp.servers`;
- `cli.json` — `$schema: https://opencode.ai/v2/cli.json` + `plugins`;
- `oh-my-opencode-slim.json` — 5 агентов (orchestrator/explorer/oracle/
designer/fixer) на `minimax-coding-plan/MiniMax-M3.1-Flash` — копия
конфига рабочей машины;
- `service.json` — `{"disabled": true}`.
3. **Плагин:** `oh-my-opencode-slim@3.0.5` (версия зафиксирована; v2
обновляет только незапиненные спеки). `~/.omo/omo.jsonc` сохранён как
legacy-конфиг openagent, но переведён на **существующие** model id.
4. **Порт запинен явно:** `web.extraArgs = [ "--hostname" "0.0.0.0" "--port"
"4096" "--cors" "https://opencode.zeroq.su" ]` — иначе nginx получит 502.
5. **Фоновый сервис v2 выключен** (`service.json: disabled`), CLI ходит в
работающий юнит через обёртку `oc` = `opencode --server
http://127.0.0.1:4096`. Иначе CLI поднимает второй сервер на 4096 —
конфликт порта + два писателя в один `opencode.db`.
6. **cgroup-ограничения сохранены** без изменений (`Service`, не
`serviceConfig` — R2).
**Альтернативы и почему не выбраны.**
- **Ждать nixos-unstable.** Чище всего, но контроля версии нет и срок
неизвестен. Выбрано как следующий шаг после деплоя.
- **Отдельный input `github:anomalyco/opencode/v2.0.32`.** Пинит точную
версию upstream, но дублирует nixpkgs-пакет и тянет свой build.
- **FOD `@opencode/cli-linux-x64` из npm.** Без сборки, но ~200 MB в store,
нет схем и нет фиксов nixpkgs. Не взято.
- **Оставить 1.19.** Ноль риска, но не «как на текущем хосте» и без v2-фич.
- **Оставить `oh-my-openagent`.** Под v2 он не имеет точки входа ⇒ не
вариант (это и есть причина смены плагина на slim).
**Последствия.**
- **Позитивные:** версия сервера совпадает с рабочей машиной (2.0.32);
конфиг сервера — копия рабочего; `opencode web`-эквивалент (`serve`)
отдаёт web-UI; `opencode pair` даёт удобный one-time link.
- **Негативные / риски:**
- **Функциональный даунгрейд оркестрации.** openagent давал 11 агентов и 8
категорий с роутингом; slim даёт 5 агентов без категорий. Если
понадобится полный набор — ждём v2-совместимый openagent.
- **Сборка v2 идёт из исходников (bun)** — тяжёлая. Деплой через
deploy-rs собирает на целевом хосте: sapphira (5.6 GiB RAM, ~1.8 GiB
доступно) может уйти в OOM ⇒ собирать на другой машине и доставлять
замыкание store, либо поднимать сборку на `otreca`/`wsl`.
- **Зависимость от `nixpkgs-master`** (moving target): следующий
`nix flake update nixpkgs-master` притащит и другие master-пакеты.
- **Рост БД:** `~/.local/share/opencode/opencode.db` (SQLite) — на рабочей
машине уже 9.5 GB. На sapphira `/` свободно 14 GB ⇒ держать в голове
перенос `XDG_DATA_HOME` на `/mnt/services`.
- **herdr на sapphira** спавнит `opencode serve` на воркспейс — в v2 это
отдельный сервер на каждый воркспейс при общей `opencode.db`. Не
проверено; при деплое — проверить (или перевести herdr на общий сервис).
- **Два «opencode» на хосте:** фоновый сервис v2 отключён — CLI без
`--server`/`oc` поднимет приватный stdio-сервер (виден в логе:
`spawning process … serve --stdio --port 0`). Это не конфликтует по
порту, но пишет в ту же БД.
**Проверка (выполнена 2026-10-21, деплой — нет).**
- `nix eval` на otreca (копия флейка в /tmp, без изменений на хостах):
`…programs.opencode.package.version` → `2.0.32`;
`xdg.configFile."opencode/opencode.json".source` → v2-форма
(`plugins`, `mcp.servers`); `cli.json`, `oh-my-opencode-slim.json`,
`service.json` — как задумано; `systemd.user.services.opencode-web` →
`EnvironmentFile=/home/oqyude/.config/opencode/server.env`,
`MemoryHigh=1G`, `MemoryMax=2G`, `OOMPolicy=continue`,
`OOMScoreAdjust=-900`, `ExecStart=…opencode-web-launcher`.
- Настоящий бинарь v2 (рабочая машина, изолированные `XDG_*`): наш
`opencode.json` распознан (`opencode debug config` показывает
`plugins` + `mcp.servers`), плагин **установлен** и виден в
`opencode plugin list` (`oh-my-opencode-slim 3.0.5`).
- На рабочей машине `opencode debug agents` показывает 5 агентов slim-плагина
(designer/explorer/fixer/oracle/orchestrator) ⇒ конфиг slim-плагина
читается из `~/.config/opencode/oh-my-opencode-slim.json`.
- Порты и auth проверены на живом бинаре v2 (401 без кредов, 200 HTML на `/`).
- **Не проверено на момент написания раздела (проверено позже, в «Что фактически
работает»):** полная сборка `nixosConfigurations.sapphira` (нужен ресурс на
сборку v2 из bun) и фактический рестарт `opencode-web` на sapphira.
**Что осталось за владельцем.**
- ~~Деплой~~ — **выполнен 2026-10-21**: сборка и `nixos-rebuild switch` на
sapphira (из `/etc/nixos`, рабочее дерево, без коммита в gitea).
- Место сборки v2 (bun) — решено: **на самой sapphira** (5.6 GiB RAM,
~1.8–3.1 GiB доступно; пик — `bun --bun ./script/build.ts` ~780 МБ RSS,
OOM-kill'ов не было, zram заполнялся). Сборка ~25 мин.
- Перенос `XDG_DATA_HOME` → `/mnt/services` — **не сделан** (БД сейчас
`~/.local/share/opencode`, 408 МБ, бэкап pre-v2 снят в
`/mnt/services/opencode-backup/pre-v2-2026-10-21`). Актуально: на sapphira
`/` (55 G) свободно **9.8 G** (82% занято), на `/mnt/services` — 303 G.
- Herdr — проверен, см. «Herdr и v2» ниже.
- Решить, нужен ли herdr-интеграционный плагин для v2 (конфликт с
read-only `cli.json`) — см. «Herdr и v2».
---
## Инцидент 1: плагин не ставится сам (найдено на деплое)
v2.0.32 **не устанавливает пакеты плагинов при старте сервера** — сервер
загружает только то, что уже лежит в `~/.cache/opencode/npm`. На свежем хосте
(или после очистки кэша) получается ровно то, что выглядит как «всё настроено,
а плагина нет»:
- `opencode plugin list` → «No plugins found»;
- агентов slim-плагина нет, его MCP-серверы (context7, gh_grep) не появляются;
- **в логах нет ни строки об ошибке** — тишина.
Проверено на sapphira 2026-10-21: после первого старта кэш
`~/.cache/opencode/npm` был пуст; `opencode plugin add oh-my-opencode-slim@3.0.5`
(«already configured» + install) его наполнил, и после рестарта юнита плагин
загрузился. Фикс — в `home.activation.installOpencodePlugin` (идемпотентно,
ошибки глушатся).
## Инцидент 2: `webpage` MCP — ENOTEMPTY / Request timed out
MCP поднимается как `npx -y -p webpage-mcp@latest webpage-mcp-stdio`. Две
проблемы, обе из-за кэша `~/.npm/_npx`, который Nix не управляет:
1. **ENOTEMPTY** — `npm` не смог переименовать распакованный каталог
(остался от v1-эпохи, где тем же MCP пользовался v1-opencode).
Лечится удалением `~/.npm/_npx/<hash>`.
2. **Request timed out** — первый запуск качает и распаковывает ~200 МБ, а
MCP-handshake не ждёт столько. Симптом: `/api/mcp` → `webpage: failed`.
Лечится прогревом кэша → `home.activation.warmWebpageMcp`
(`npx -y -p webpage-mcp@latest true`).
После обоих фиксов: `context7 connected`, `gh_grep connected`,
`webpage connected`.
## Инцидент 3: `oc` (CLI к работающему серверу)
- `--server` принимается **после** подкоманды: `opencode <cmd> --server <url>`;
форма `opencode --server <url> <cmd>` парсером v2 не принимается.
- CLI ходит к серверу по HTTP basic → **пароль обязателен**: обёртка читает
`OPENCODE_SERVER_PASSWORD` (и `OPENCODE_SERVER_USERNAME`, `GEMINI_API_KEY`)
из того же sops-файла `~/.config/opencode/server.env`, что и юнит.
- Часть подкоманд (`mcp list`, `session list`) с `--server` печатает help —
фича v2.0.32, не регрессия.
## Herdr и v2 (проверено 2026-10-21)
herdr **0.9.3** на sapphira активен (`herdr server --session herdr-prod`).
- **herdr 0.9.3 умеет v2**: по докам herdr.dev/docs/integrations — «supports
OpenCode V1 `1.18.29` or later and OpenCode V2 (tested with beta `19242`)».
- **Спавнить v2 он может**: PATH сервиса содержит
`/etc/profiles/per-user/oqyude/bin` → `opencode` резолвится в v2-бинарь;
`EnvironmentFile` даёт `OPENCODE_SERVER_USERNAME`/`OPENCODE_SERVER_PASSWORD`
→ herdr и его дети видят пароль.
- **Портовой конфликт не возникнет**: herdr поднимает `opencode serve` на
воркспейс отдельно; в v2 дефолт `serve` — **4097**, а 4096 держит юнит
`opencode-web` ⇒ в отличие от v1 (дефолт 4096) коллизии нет. Фактический
спавн воркспейса не проверялся (нужен GUI-сценарий herdr).
- **Интеграция opencode НЕ установлена**: `herdr integration status` →
`opencode: not installed (~/.config/opencode/plugins/herdr-agent-state.js)`.
То есть ни lifecycle-reporting, ни native restore для v2 — **это не регрессия
миграции** (в v1 было так же).
- **Если её ставить — конфликт с Nix-конфигом.** herdr пишет
`~/.config/opencode/plugins/herdr-agent-state.js`, `herdr-tui-session.js`,
`herdr-opencode/tui.js` (эти пути Nix не управляет ⇒ ок) и **регистрирует
V2-TUI-плагин в `cli.json`**. Наш `cli.json` — **read-only симлинк в
/nix/store** ⇒ запись упадёт по EROFS ⇒ регистрация не пройдёт. Варианты:
(а) сделать `cli.json` writable (не симлинком) — тогда herdr дописывает
регистрацию в наш конфиг; (б) не ставить интеграцию (работает экранный
fallback — детект состояния по скриншоту). Решение за владельцем.
## Что фактически работает на sapphira (проверено 2026-10-21)
- `opencode --version` → **v2.0.32**; юнит: `opencode-wrapped-2.0.32 serve
--hostname 0.0.0.0 --port 4096 --cors https://opencode.zeroq.su`.
- `0.0.0.0:4096` слушает процесс юнита; cgroup: 236 МБ (high 1G, max 2G).
- `GET /` с кредами → 200 HTML, без → 401 на `/api/*`; через nginx
`https://opencode.zeroq.su/` → 200.
- `/api/agent` → 10 агентов: `orchestrator` (primary) + `explorer`, `oracle`,
`designer`, `fixer` (subagent) + билтины; модель всех —
`minimax-coding-plan/MiniMax-M3.1-Flash` ✓.
- `/api/mcp` → context7/gh_grep/webpage — connected.
- LLM smoke: `oc run --agent orchestrator "Ответь ровно одним словом: OK"` →
«OK»; с явной моделью — `minimax-coding-plan/MiniMax-M3.1-Flash` (платный
провайдер из sops `auth.json` работает). Без `--model` CLI в заголовке
показывает `minimax-m3.1-flash-free` — это клиентский дефолт отображения;
серверная сессия создаётся с `minimax-coding-plan/MiniMax-M3.1-Flash`.
- Старые сессии v1 читаются (те же `opencode.db`), но в них
`MiniMax-M3.1-Flash-Preview` — модели, которой **больше нет в реестре**
(подтверждение, что реестр менялся; см. п. 7 «Что выяснено»).
- **Остановка юнита даёт код 130**: v2-сервер выходит по SIGTERM с
`status=130`, systemd пишет «Failed with result 'exit-code'». Это **не поломка**:
`Restart=always` поднимает сервер заново, юнит снова active (проверено на
рестартах 11:40 и 13:38). В логах выглядит как ошибка — при чтении журнала
это шум, а не инцидент.
- **Активация сама ставит плагин**: `home.activation.installOpencodePlugin`
проверен «в лоб» — кэш `~/.cache/opencode/npm/oh-my-opencode-slim@3.0.5`
удалён вручную, `systemctl --user restart home-manager-oqyude.service` →
пакет вернулся сам, `opencode plugin list` → `3.0.5`.
+12
View File
@@ -51,6 +51,18 @@
"moot_unless": "T29 мержится в upstream devswha/herdr-web-ui",
"related_artifact": "S:\\Git\\metaagent-director\\AGENTS.md (v0.2)",
"resolved_at": "2026-10-15T15:00"
},
{
"id": "0006",
"title": "OpenCode на sapphira — миграция 1.19 (v1) → 2.0.32 (v2)",
"status": "accepted",
"date": "2026-10-21",
"file": ".agent/decisions/0006-opencode-v2-migration.md",
"tags": ["opencode", "v2", "sapphira", "nixpkgs-master", "home-manager", "plugin", "port", "invariant", "R1.19", "model-registry"],
"task": "T36",
"resolution": "Пакет берётся из nixpkgs master (nixos-unstable = 1.19.0, v2 влит в master 2026-10-19 через PR #569770), flake.lock обновлён на c4f353ac. Конфиг пишется вручную (xdg.configFile), потому что HM-модуль programs.opencode остаётся v1-only: v2-ключи plugins (мн.ч.) + mcp.servers, отдельный cli.json вместо tui.json (tui.json на HM-хосте — read-only симлинк в /nix/store, авто-миграция tui.json→cli.json не сможет записать). Плагин сменён на oh-my-opencode-slim@3.0.5 — единственный v2-совместимый (есть dist/tui2.js + v2-типы + compatibility-док); oh-my-openagent 5.1.40 v2-точки входа не имеет. Порт запинен --port 4096: дефолт v2 — 4097, nginx проксирует на 4096, без флага был бы 502. Фоновый сервис v2 выключен (service.json disabled), CLI ходит в юнит через обёртку oc (opencode --server http://127.0.0.1:4096) — иначе второй сервер на 4096 и два писателя в одну opencode.db. Модельные id приведены к реально существующим в реестре (MiniMax-M3 / MiniMax-M3.1-Flash; MiniMax-M3.1-Flash-Preview в реестре НЕТ — тот же класс грабли, что kimi-for-coding).",
"moot_unless": "OpenCode 2.x попадает в nixos-unstable (тогда пакет возвращается в pkgs.opencode и master-input снимается) либо выходит v2-совместимый oh-my-openagent (тогда возвращается полный набор агентов и категорий)",
"resolved_at": "2026-10-21T11:00"
}
],
"proposals": [
+28 -2
View File
@@ -528,12 +528,38 @@
],
"verified_at_host": "sapphira (192.168.1.20) + rydiwo (192.168.1.102) — оба active, оба с plugins devswha.herdr-web-ui@439ad38d091c02c3e4747956808dbac2305702d3",
"notes": "Saga началась с пользовательского репорта «rydiwo — Connection failed / Could not start dynamically linked executable: bun»; закончилась обоими хостами на общем plugin-коммите. Три слоя фиксов, каждый проявлялся после починки предыдущего: (1) bun в shell PATH — нужно для plugin preflight, но НЕ чинит запуск скачанного bun; (2) programs.nix-ld — позволяет glibc-based bun'у из plugin runtime manager стартовать; (3) nodejs_22 — preflight.sh плагина проверяет `node --version`. Дополнительно: herdr plugin list читает `~/.config/herdr/plugins.json:source.resolved_commit`, а не `.git/HEAD` плагина — обновление source/dist без правки manifest оставляет herdr plugin list со stale commit'ом. Все эти нюансы зафиксированы в ADR-0005."
},
{
"id": "T36",
"title": "Деплой OpenCode v2 на sapphira (ADR-0006): сборка, рестарт opencode-web, проверка",
"type": "implementation",
"priority": "high",
"status": "in_progress",
"origin": "session 2026-10-21 (opencode-v2-migration)",
"depends_on": [],
"files": [
"home/modules/opencode.nix (v2-конфиг, package из nixpkgs-master, --port 4096, slim-плагин)",
"flake.lock (nixpkgs-master -> c4f353ac, opencode 2.0.32)",
".agent/decisions/0006-opencode-v2-migration.md"
],
"acceptance_criteria": [
"nix build .#nixosConfigurations.sapphira.config.system.build.toplevel проходит (сборка opencode 2.0.32 из bun тяжёлая — сапфира 5.6 GiB RAM, ~1.8 GiB доступно: риск OOM, собирать на другом хосте и доставить замыкание store)",
"systemctl --user cat opencode-web содержит ExecStart ... opencode serve --hostname 0.0.0.0 --port 4096 --cors https://opencode.zeroq.su и MemoryHigh/MemoryMax/OOMScoreAdjust/OOMPolicy в [Service] (НЕ [serviceConfig])",
"systemctl --user show opencode-web -p ExecStart --value показывает порт 4096 (проверять чтением файла юнита, не systemctl show по R1.14)",
"ss -ltnp | grep 4096 — процесс слушает 0.0.0.0:4096; на 4097 ничего не слушает",
"curl -u opencode:$OPENCODE_SERVER_PASSWORD https://opencode.zeroq.su/ → 200 HTML (web-UI v2), /api/* без кредов → 401",
"opencode plugin list на sapphira показывает oh-my-opencode-slim 3.0.5; ~/.cache/opencode/npm/oh-my-opencode-slim@3.0.5 существует",
"opencode debug agents на sapphira показывает designer/explorer/fixer/oracle/orchestrator",
"herdr на sapphira не сломан после смены ядра (herdr спавнит opencode serve на воркспейс — отдельный сервер на каждый воркспейс при общей opencode.db)"
],
"verified_at_host": "sapphira (192.168.1.20), деплой 2026-10-21: opencode v2.0.32 в /nix/store (opencode-wrapped-2.0.32), юнит active, слушает 0.0.0.0:4096, cgroup 361M (high 1G/max 2G), GET / с кредами 200, /api/* без кредов 401, https://opencode.zeroq.su/ 200, /api/agent → orchestrator+explorer/oracle/designer/fixer на minimax-coding-plan/MiniMax-M3.1-Flash, /api/mcp → context7/gh_grep/webpage connected, LLM smoke `oc run --agent orchestrator` → «OK», herdr 0.9.3 active и умеет v2 (PATH+EnvironmentFile ⇒ может спавнить v2-детей; дефолт serve 4097 ⇒ конфликта с юнитом на 4096 нет; интеграция opencode не установлена ⇒ lifecycle-reporting нет — как и в v1)",
"notes": "ДЕПЛОЙ ВЫПОЛНЕН 2026-10-21 (сборка и nixos-rebuild switch на самой sapphira, из /etc/nixos, без коммита в gitea; бэкап pre-v2 БД — /mnt/services/opencode-backup/pre-v2-2026-10-21). Ключевые находки миграции: (1) v2 есть только в nixpkgs master, unstable = 1.19.0; (2) дефолт `opencode serve` в v2 — 4097, nginx проксирует на 4096 ⇒ --port 4096 обязателен; (3) `opencode web` в v2 удалён; (4) v2-совместим только oh-my-opencode-slim (у oh-my-openagent 5.1.40 нет v2-точки входа) ⇒ функциональный даунгрейд оркестрации (5 агентов вместо 11 + 8 категорий) — осознанный, зафиксирован в ADR-0006; (5) в реестре моделей нет MiniMax-M3.1-Flash-Preview / M2.7-highspeed / M2.5-highspeed ⇒ старый omo.jsonc ссылался на них (ProviderModelNotFoundError); model id выверены по `opencode models`; (6) фоновый сервис v2 выключен (service.json disabled), CLI ходит в юнит через обёртку oc (opencode <cmd> --server http://127.0.0.1:4096 + пароль из sops server.env) — иначе второй сервер на 4096 и два писателя в одну opencode.db; (7) opencode.db (SQLite) растёт — на рабочей машине 9.5 GB, на sapphira / свободно 14 GB ⇒ вопрос переноса XDG_DATA_HOME на /mnt/services оставлен владельцу. ИНЦИДЕНТЫ, найденные на деплое и закрытые в коде: (A) v2.0.32 НЕ ставит пакеты плагинов при старте сервера — на свежем хосте плагин молча отсутствует (plugin list пуст, его MCP не появляются, в логах тишина) ⇒ home.activation.installOpencodePlugin; (B) webpage MCP падал с npm ENOTEMPTY (остаток кэша от v1) и Request timed out (первый npx качает ~200 МБ) ⇒ чистка ~/.npm/_npx/<hash> + home.activation.warmWebpageMcp; (C) `--server` в v2 принимается только ПОСЛЕ подкоманды, и CLI требует пароль (HTTP basic). (D) остановка юнита даёт код 130 ⇒ systemd пишет «Failed with result 'exit-code'» — это шум, Restart=always поднимает сервер (юнит active). HERDR: herdr 0.9.3 активен на sapphira, официально поддерживает OpenCode V2; его PATH/EnvironmentFile ⇒ v2-детей спавнить может, конфликта портов нет (v2 serve по умолчанию 4097, юнит держит 4096); интеграция opencode не установлена (не регрессия — в v1 так же), а её установка упрётся в read-only cli.json (herdr регистрирует V2-TUI-плагин в cli.json) ⇒ решение за владельцем: сделать cli.json writable или не ставить интеграцию. ОСТАЛОСЬ: (1) решение по XDG_DATA_HOME (на sapphira / свободно 9.8 G из 55 G, /mnt/services — 303 G; БД 408 M, на рабочей машине 9.5 GB); (2) решение по herdr-интеграции и cli.json; (3) коммит: код+ADR+манифест закоммичены локально в ветке dev без push, а AGENTS.md и .agent/rules/project-rules.md оставлены в рабочем дереве (там вперемешку правки 3x-ui/REALITY/WARP, чужие — не смешивать); (4) когда v2 попадёт в nixos-unstable — вернуть pkgs.opencode и снять master-input."
}
],
"backlog_count": 30,
"backlog_count": 31,
"backlog_count_breakdown": {
"f_questions_waiting_owner": 22,
"pending_tasks": 8
"pending_tasks": 9
},
"backlog_note": "F-вопросы ждут ответа владельца (22, было 23 — закрыт 5.6 через T5): 2.2, 2.5, 2.6, 3.2, 4.1, 4.2, 4.3, 4.4, 4.5, 5.1, 5.3, 5.4, 5.5, 6.6, 6.7, 6.8, 6.9, 7.4, 8.2, 8.4, 8.5, 8.6 — после ответа станут задачами. Сверх того 8 pending задач: 3 нерешённых прошлого (T3 nftables на otreca, T4 mount-guard severity:high на sapphira, T10 reality443Forwarding — код уже применён, вопрос только «считать ли это фичей или долгом») + 5 pending текущего прохода (T20 .ci/checks.sh mode bit, T28 v0.2 opencode-director, T29 sameOrigin PR в upstream, T30 use case для multi-host, T31 quota handling examples). T18/T32 закрыты в этом проходе (cleanup); T33 saga close-out оформлен как documentation completed; T35 записан в checkpoints.json:closed_attempts (не в tasks[] manifest.json, потому что относится к метасостоянию шима, а не к продуктовым задачам)."
}
Generated
+3 -3
View File
@@ -384,11 +384,11 @@
},
"nixpkgs-master": {
"locked": {
"lastModified": 1791887696,
"narHash": "sha256-YtLWq4aLuG9AThbfbD0c6p0IaWW4OZHykTw6s0j0kaA=",
"lastModified": 1792565783,
"narHash": "sha256-b0AMMEirSNnXWCLykZksBrt1cJiTlIEXdb6p3oOQTTc=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "1f4c563e0090f96a675bf1806c3c7ea3ae797bb5",
"rev": "c4f353ac4a4179840c3f196a33b02053958a3f1d",
"type": "github"
},
"original": {
+250 -263
View File
@@ -1,45 +1,112 @@
# Declarative OpenCode + oh-my-openagent (oh-my-opencode) plugin setup.
# Declarative OpenCode v2 + oh-my-opencode-slim setup.
#
# Sapphira runs OpenCode 1.18.x (V1 schema, `plugin` singular) via
# pkgs.opencode. Workstation (vetymae) is on OpenCode 1.19.x — same V1
# schema, same `plugin` (singular) field. Both hosts use the V1-compatible
# `plugin` (singular) key. If/when nixpkgs ships OpenCode 2.x (V2 schema,
# `plugins` plural), switch the `settings` block below accordingly.
# HISTORY / WHY THIS FILE LOOKS LIKE THIS
#
# Mirrors ~/.config/opencode/ on the current workstation.
# Imported by home/server.nix (sapphira). Auto-enables programs.opencode.
# 2026-10-20: sapphira migrated from OpenCode 1.19.0 (v1) to OpenCode 2.0.32
# (v2). See ADR-0006. The v1 -> v2 deltas that matter here:
#
# * package — v2 is NOT in nixos-unstable yet (that still ships 1.19.0).
# It landed in nixpkgs master (PR #569770, merged 2026-10-19),
# so the binary comes from the `nixpkgs-master` input that was
# already wired into this flake. `nix flake update
# nixpkgs-master` is what moves the pin onto a rev that has
# v2 — the lock must be updated together with this file.
# * config keys — v1: `plugin` (singular) + `mcp` (flat map).
# v2: `plugins` (plural) + `mcp.servers` (nested).
# * tui.json — v1 wrote CLI/TUI prefs to `tui.json`; v2 reads them from
# `cli.json` ($schema https://opencode.ai/v2/cli.json) and
# only *migrates* tui.json -> cli.json on first run. On
# sapphira `tui.json` is a symlink into /nix/store (read-only),
# so the migration cannot write: `cli.json` is declared
# explicitly below and `programs.opencode.tui` stays empty.
# * port — v1 `opencode serve` defaulted to 4096; v2 defaults to 4097
# (4096 is reserved for the v2 background service). The nginx
# vhost `opencode.zeroq.su` proxies to 127.0.0.1:4096, so
# `--port 4096` is pinned explicitly in `web.extraArgs`.
# Without it the proxy silently 502s.
# * `opencode web` is gone in v2; `opencode serve` serves both the API and
# the web UI (verified locally: GET / -> 200 HTML,
# GET /api/health without creds -> 401 UnauthorizedError).
# * auth — unchanged: OPENCODE_PASSWORD, falling back to
# OPENCODE_SERVER_PASSWORD (sops: secrets/opencode.env ->
# ~/.config/opencode/server.env). HTTP basic, user `opencode`.
# * plugins — v2 installs npm plugin packages itself (in-process
# arborist, no bun/npx needed) into ~/.cache/opencode/npm/.
# Only `oh-my-opencode-slim` is v2-ready: it ships
# dist/tui2.js + dist/v2/tui.d.ts and documents an
# "OpenCode v2 compatibility" matrix. oh-my-openagent
# (5.1.40) still exports only ./tui + ./server and has no
# v2 entry point, so it is NOT enabled under v2.
#
# Files this module owns on disk:
# ~/.config/opencode/opencode.json <- programs.opencode.settings
# ~/.config/opencode/tui.json <- programs.opencode.tui
# ~/.omo/omo.jsonc <- oh-my-openagent plugin's PRIMARY
# runtime config (>= v5.x reads
# only this path; the legacy
# ~/.config/opencode/oh-my-openagent.json
# is read only by the migration shim).
# ~/.config/opencode/oh-my-openagent.json <- legacy mirror, kept so omo doctor
# and any downgrade that re-reads
# the old path see the same content.
# ~/.config/opencode/opencode.json <- programs.opencode.settings
# ~/.config/opencode/cli.json <- v2 CLI/TUI preferences
# ~/.config/opencode/oh-my-opencode-slim.json <- slim plugin config
# ~/.config/opencode/service.json <- v2 background service (off)
# ~/.omo/omo.jsonc <- LEGACY oh-my-openagent config
# ~/.config/opencode/oh-my-openagent.json <- LEGACY mirror of the above
#
# Override any field in the importing module if needed.
# Imported by home/server.nix (sapphira). Auto-enables programs.opencode.
{
config,
inputs,
lib,
pkgs,
xlib,
...
}:
let
# Body of ~/.omo/omo.jsonc (and the legacy mirror).
# Loaded by the oh-my-openagent opencode plugin on startup.
#
# Plugins >= 5.x resolve their config from ~/.omo/omo.jsonc, NOT from
# ~/.config/opencode/oh-my-openagent.json. Pinning _migrations here prevents
# the 2026-07-opencode-config-unification migration from running on every
# startup and re-backing-up the file (which would otherwise leave us with
# an empty omo.jsonc that drops every agent override — see the journal entry
# below).
ohMyOpenagentConfig = {
# OpenCode v2 only exists in nixpkgs master for now. Import it the same way
# modules/server/nextcloud.nix already imports `nixpkgs-master`.
masterPkgs = import inputs.nixpkgs-master {
system = pkgs.stdenv.hostPlatform.system;
};
# 2.0.32 — same version as the workstation (vetymae) runs.
opencodeV2 = masterPkgs.opencode;
# Plugin spec. Pinned exactly (no @latest): v2 auto-updates only unpinned
# specs, and the workstation is pinned to the same version.
pluginSpec = "oh-my-opencode-slim@3.0.5";
# Model ids are validated against the provider registry, not against taste.
# `opencode models` on BOTH the workstation and sapphira lists exactly:
# minimax-coding-plan/MiniMax-M3 variants: none, thinking
# minimax-coding-plan/MiniMax-M3.1-Flash variants: (none)
# opencode/big-pickle variants: (none)
# opencode/minimax-m3.1-flash-free variants: low..max
# Anything else (MiniMax-M3.1-Flash-Preview, MiniMax-M2.7-highspeed, ...)
# is NOT in the registry -> ProviderModelNotFoundError. The v1 omo.jsonc on
# this host referenced MiniMax-M3.1-Flash-Preview everywhere; that is the
# same class of bug as the kimi-for-coding incident described in R1.x.
modelFast = "minimax-coding-plan/MiniMax-M3.1-Flash";
modelStrong = "minimax-coding-plan/MiniMax-M3";
# nixpkgs ast-grep only ships binary `ast-grep`; omo's ast-grep skill probes
# for `sg` (or ast-grep). Provide both via a symlink wrapper.
astGrepWithSg = pkgs.runCommandLocal "ast-grep-with-sg" { } ''
mkdir -p $out/bin
ln -s ${pkgs.ast-grep}/bin/ast-grep $out/bin/ast-grep
ln -s ${pkgs.ast-grep}/bin/ast-grep $out/bin/sg
'';
# Slim plugin config — mirror of the workstation (vetymae):
# ~/.config/opencode/oh-my-opencode-slim.json
slimConfig = {
agents = {
orchestrator = { model = modelFast; };
explorer = { model = modelFast; };
oracle = { model = modelFast; };
designer = { model = modelFast; };
fixer = { model = modelFast; };
};
};
# LEGACY oh-my-openagent config. Kept valid (real model ids, no variants the
# registry does not expose) so a future switch back to oh-my-openagent does
# not resurrect the ProviderModelNotFoundError trap. Under v2 this file is
# inert: the enabled plugin is oh-my-opencode-slim (see above).
legacyOmoConfig = {
"$schema" =
"https://raw.githubusercontent.com/code-yeongyu/oh-my-openagent/dev/assets/omo.schema.json";
_migrations = [
@@ -50,239 +117,90 @@ let
agents = {
sisyphus = {
model = "minimax-coding-plan/MiniMax-M3";
variant = "max";
model = modelStrong;
models = [
{ model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview"; }
{
model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview";
variant = "medium";
}
{ model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview"; }
{ model = "opencode/big-pickle"; }
{ model = modelFast; }
];
};
hephaestus = {
model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview";
variant = "medium";
};
hephaestus = { model = modelFast; };
oracle = {
model = "minimax-coding-plan/MiniMax-M3";
variant = "xhigh";
model = modelStrong;
models = [
{
model = "minimax-coding-plan/MiniMax-M3";
variant = "high";
}
{
model = "minimax-coding-plan/MiniMax-M3";
variant = "max";
}
{ model = modelFast; }
];
};
librarian = {
model = "minimax-coding-plan/MiniMax-M3";
};
librarian = { model = modelStrong; };
explore = {
model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview";
model = modelFast;
models = [
{ model = "minimax-coding-plan/MiniMax-M3"; }
];
};
"multimodal-looker" = {
model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview";
variant = "low";
models = [
{ model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview"; }
];
};
prometheus = {
model = "minimax-coding-plan/MiniMax-M3";
variant = "high";
models = [
{
model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview";
variant = "high";
}
];
};
metis = {
model = "minimax-coding-plan/MiniMax-M3";
variant = "high";
models = [
{
model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview";
variant = "low";
}
];
};
momus = {
model = "minimax-coding-plan/MiniMax-M3";
variant = "xhigh";
models = [
{
model = "minimax-coding-plan/MiniMax-M3";
variant = "max";
}
{
model = "minimax-coding-plan/MiniMax-M3";
variant = "high";
}
{ model = modelStrong; }
];
};
"multimodal-looker" = { model = modelFast; };
prometheus = { model = modelStrong; };
metis = { model = modelStrong; };
momus = { model = modelStrong; };
atlas = {
model = "minimax-coding-plan/MiniMax-M3";
model = modelFast;
models = [
{
model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview";
variant = "medium";
}
{ model = "minimax-coding-plan/MiniMax-M3"; }
{ model = modelStrong; }
];
};
"sisyphus-junior" = {
model = "minimax-coding-plan/MiniMax-M3";
model = modelStrong;
models = [
{
model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview";
variant = "medium";
}
{ model = "minimax-coding-plan/MiniMax-M3"; }
{ model = "opencode/big-pickle"; }
{ model = modelFast; }
];
};
};
categories = {
"visual-engineering" = {
model = "minimax-coding-plan/MiniMax-M3";
variant = "high";
fallback_models = [
{ model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview"; }
{
model = "minimax-coding-plan/MiniMax-M3";
variant = "max";
}
];
};
ultrabrain = {
model = "minimax-coding-plan/MiniMax-M3";
variant = "xhigh";
fallback_models = [
{
model = "minimax-coding-plan/MiniMax-M3";
variant = "high";
}
{
model = "minimax-coding-plan/MiniMax-M3";
variant = "max";
}
];
};
"deep-low" = {
model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview";
variant = "medium";
fallback_models = [
{
model = "minimax-coding-plan/MiniMax-M3";
variant = "max";
}
{
model = "minimax-coding-plan/MiniMax-M3";
variant = "high";
}
];
};
artistry = {
model = "minimax-coding-plan/MiniMax-M3";
variant = "high";
fallback_models = [
{
model = "minimax-coding-plan/MiniMax-M3";
variant = "max";
}
{
model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview";
variant = "high";
}
];
};
quick = {
model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview";
fallback_models = [
{ model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview"; }
{ model = "minimax-coding-plan/MiniMax-M3"; }
{ model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview"; }
];
};
"unspecified-low" = {
model = "minimax-coding-plan/MiniMax-M3";
fallback_models = [
{
model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview";
variant = "medium";
}
{ model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview"; }
{ model = "minimax-coding-plan/MiniMax-M3"; }
];
};
"unspecified-high" = {
model = "minimax-coding-plan/MiniMax-M3";
fallback_models = [
{
model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview";
variant = "medium";
}
{ model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview"; }
{ model = "minimax-coding-plan/MiniMax-M3"; }
];
};
writing = {
model = "minimax-coding-plan/MiniMax-M3.1-Flash-Preview";
fallback_models = [
{ model = "minimax-coding-plan/MiniMax-M3"; }
{ model = "minimax-coding-plan/MiniMax-M3"; }
];
};
"visual-engineering" = { model = modelStrong; };
ultrabrain = { model = modelStrong; };
"deep-low" = { model = modelFast; };
artistry = { model = modelFast; };
quick = { model = modelFast; };
"unspecified-low" = { model = modelFast; };
"unspecified-high" = { model = modelStrong; };
writing = { model = modelFast; };
};
};
in
let
# nixpkgs ast-grep only ships binary `ast-grep`; omo's ast-grep skill probes
# for `sg` (or ast-grep). Provide both via a symlink wrapper.
astGrepWithSg = pkgs.runCommandLocal "ast-grep-with-sg" { } ''
mkdir -p $out/bin
ln -s ${pkgs.ast-grep}/bin/ast-grep $out/bin/ast-grep
ln -s ${pkgs.ast-grep}/bin/ast-grep $out/bin/sg
'';
# Extras that must be on PATH for the server:
# pkgs.nodejs_22 — npx/npm for MCP servers (webpage-mcp) and npm plugins
# pkgs.ast-grep — `sg` CLI; the plugin's ast-grep skill requires it
# pkgs.bun — plugin CLI / omo doctor
# pkgs.gh — GitHub CLI; plugin's GitHub automation requires it
extraPackages = [
pkgs.nodejs_22
astGrepWithSg
pkgs.bun
pkgs.gh
];
in
{
programs.opencode = {
enable = true;
# Extras available to opencode-wrapped (via --suffix PATH on the wrapper):
# pkgs.nodejs_22 — npx/npm for MCP servers (webpage-mcp) and omo's plugin loader
# pkgs.ast-grep — `sg` CLI; omo's ast-grep skill requires it (omo doctor)
# pkgs.bun — omo prefers bun; with bun on PATH, `omo doctor` skips node fallback
# pkgs.gh — GitHub CLI; omo's GitHub automation features require it
extraPackages = [
pkgs.nodejs_22
astGrepWithSg
pkgs.bun
pkgs.gh
];
# OpenCode 2.0.32 from nixpkgs master (nixos-unstable still ships 1.19.0).
package = opencodeV2;
# Extras available to opencode-wrapped (via --suffix PATH on the wrapper).
extraPackages = extraPackages;
# ~/.config/opencode/opencode.json
#
# NOTE (2026-10-13): sapphira is on OpenCode 1.18.x (V1 schema) via
# pkgs.opencode. V1 only reads `plugin` (singular); V2 introduces
# `plugins` (plural). If we ever ship OpenCode 2 via pkgs.opencode-2 or
# a custom flake input, switch this key back to `plugins = [...]`.
# V2 schema:
# plugins (plural) — v1 used `plugin` (singular), v2 ignores it
# mcp.servers — v1 used a flat `mcp` map
#
# NOTE: HM's MCP integration (programs.mcp.servers -> settings.mcp) is OFF
# (enableMcpIntegration defaults to false). If it were on, HM would inject
# the v1 flat shape and overwrite the v2 `mcp.servers` block.
settings = {
plugin = [
"oh-my-openagent@latest"
];
mcp = {
plugins = [ pluginSpec ];
mcp.servers = {
webpage = {
type = "local";
command = [
@@ -296,62 +214,131 @@ in
};
};
# ~/.config/opencode/tui.json
# Mirrors workstation: oh-my-openagent also registered for the TUI.
tui = {
plugin = [
"oh-my-openagent@latest"
];
};
# ~/.config/opencode/tui.json is a v1 concept. v2 reads CLI/TUI prefs from
# cli.json (declared below). Leave `tui` empty so HM writes no tui.json:
# a tui.json symlinked into /nix/store is read-only, and v2's automatic
# tui.json -> cli.json migration would then fail to write.
tui = { };
};
# ~/.omo/omo.jsonc — primary file the oh-my-openagent plugin reads at runtime
# (>= v5.x). This path lives outside XDG_CONFIG_HOME (~/.config), so use
# home.file rather than xdg.configFile.
#
# ~/.config/opencode/oh-my-openagent.json is kept as a legacy mirror so
# `omo doctor`, the migration shim, and any future downgrade that re-reads the
# old path see the same content.
# ~/.config/opencode/cli.json — v2 CLI/TUI preferences.
# $schema: https://opencode.ai/v2/cli.json
xdg.configFile."opencode/cli.json".text = builtins.toJSON {
"$schema" = "https://opencode.ai/v2/cli.json";
plugins = [ pluginSpec ];
};
# ~/.config/opencode/oh-my-opencode-slim.json — config of the enabled plugin
# (oh-my-opencode-slim reads its own file, NOT ~/.omo/omo.jsonc).
xdg.configFile."opencode/oh-my-opencode-slim.json".text = builtins.toJSON slimConfig;
# ~/.config/opencode/service.json — v2 background service registration.
# The v2 CLI wants a background service; it defaults to port 4096, which is
# the port our systemd unit serves the web UI on. Two servers on one host
# also means two writers for ~/.local/share/opencode/opencode.db.
# => keep the background service off; CLI clients talk to the running unit
# via `oc` (see below) or `opencode --server http://127.0.0.1:4096`.
xdg.configFile."opencode/service.json".text = builtins.toJSON {
disabled = true;
};
# LEGACY ~/.omo/omo.jsonc — primary file the oh-my-openagent plugin reads at
# runtime (>= v5.x). Inert under v2 (the enabled plugin is the slim one),
# kept valid for a future switch back.
#
# MIGRATION TRAP (do not just point back at the legacy path):
# The plugin runs a `2026-07-opencode-config-unification` migration on every
# startup that backs up ~/.omo/omo.jsonc and tries to rewrite it from
# ~/.config/opencode/oh-my-openagent.json. The backup directory name embeds
# the source's content-hashed store path; because HM does not delete the
# previous generation's store path until garbage collection, the same path
# is reused on every retry and omo logs "Migration backup path already
# exists" forever — meanwhile the user's agent overrides disappear and the
# plugin's built-in fallback chain (which references providers like
# kimi-for-coding that opencode's provider registry no longer ships) gets
# picked instead, surfacing as `ProviderModelNotFoundError:
# kimi-for-coding/kimi-for-coding-highspeed` on every subagent spawn.
# Pinning _migrations above makes the migration a no-op; the omo.jsonc
# below is the actual config the plugin sees.
home.file."${config.home.homeDirectory}/.omo/omo.jsonc".text = builtins.toJSON ohMyOpenagentConfig;
xdg.configFile."opencode/oh-my-openagent.json".text = builtins.toJSON ohMyOpenagentConfig;
# The oh-my-openagent plugin runs a `2026-07-opencode-config-unification`
# migration on every startup that backs up ~/.omo/omo.jsonc and tries to
# rewrite it from ~/.config/opencode/oh-my-openagent.json. The backup
# directory name embeds the source's content-hashed store path; because HM
# does not delete the previous generation's store path until garbage
# collection, the same path is reused on every retry and omo logs
# "Migration backup path already exists" forever — meanwhile the user's
# agent overrides disappear and the plugin's built-in fallback chain
# (which references providers like kimi-for-coding that opencode's
# provider registry no longer ships) gets picked instead, surfacing as
# `ProviderModelNotFoundError: kimi-for-coding/kimi-for-coding-highspeed`
# on every subagent spawn. Pinning _migrations above makes the migration
# a no-op.
home.file."${config.home.homeDirectory}/.omo/omo.jsonc".text = builtins.toJSON legacyOmoConfig;
xdg.configFile."opencode/oh-my-openagent.json".text = builtins.toJSON legacyOmoConfig;
# Same extras on the user's PATH too, so `omo doctor` and standalone invocations
# of `sg`, `gh`, `npm`, `npx` work in the user's shell — not only inside
# the opencode-wrapped binary.
#
# Note: `pkgs.bun` deliberately NOT included here — it now lives in
# `home/modules/herdr-runtime.nix`, which both `home/server.nix` and
# Note: `pkgs.bun` deliberately NOT included here — it now lives
# in `home/modules/herdr-runtime.nix`, which both `home/server.nix` and
# `home/secondary.nix` import. Avoids a second copy of bun in the
# user's shell PATH (single source of truth) and means the bun-runtime
# fix for the herdr-web-ui plugin on NixOS is one place to grep.
# `oc` — CLI client that talks to the already running server instead of
# spawning a second one (v2 CLI otherwise wants the background service on
# 4096, which collides with the systemd unit and the shared opencode.db).
#
# The server password is needed: the API speaks HTTP basic auth. It is read
# from the same sops-managed env file the unit uses (mode 0600, owned by the
# user), so the secret never lands in a nix store path.
#
# `--server` goes AFTER the subcommand: `opencode <cmd> --server <url>`
# (`opencode --server <url> <cmd>` is not accepted by the v2 parser).
home.packages = [
pkgs.nodejs_22
astGrepWithSg
pkgs.gh
(pkgs.writeShellScriptBin "oc" ''
export PATH="${lib.makeBinPath extraPackages}:$PATH"
set -a
# shellcheck disable=SC1090
. ${xlib.dirs.opencode-server-env}
set +a
exec ${opencodeV2}/bin/opencode "$@" --server http://127.0.0.1:4096
'')
];
# Expose `opencode web` as a systemd user service. nginx on sapphira
# Install the plugin package into the v2 npm cache.
#
# v2.0.32 does NOT install plugin packages on server startup: the server
# only loads what is already in ~/.cache/opencode/npm. A fresh host (or a
# wiped cache) therefore comes up with the plugin declared in opencode.json
# but NOT loaded — `opencode plugin list` shows nothing, the plugin's agents
# and its MCP servers (context7, gh_grep) are missing, and nothing in the
# logs says why. Verified on sapphira 2026-10-21: the cache was empty after
# the first start, and `opencode plugin add` populated it.
#
# `plugin add` is idempotent here: the plugin is already declared in the
# (read-only) Nix-managed opencode.json, so the command reports "already
# configured" and only performs the install. Errors are ignored on purpose —
# a failed warm-up must not break the activation; the server still works,
# only the plugin is missing.
home.activation.installOpencodePlugin = lib.hm.dag.entryAfter [ ] ''
${opencodeV2}/bin/opencode plugin add ${pluginSpec} >/dev/null 2>&1 || true
'';
# Warm the npx cache for the `webpage` MCP server.
#
# The MCP is started as `npx -y -p webpage-mcp@latest webpage-mcp-stdio`.
# The FIRST such spawn has to download and unpack the package (~200 MB) and
# the MCP handshake times out long before that finishes — the server then
# reports the MCP as failed ("Request timed out" / npm ENOTEMPTY on a
# half-written cache dir). The cache lives in ~/.npm/_npx, which Nix does
# not manage, so the failure comes back after every cache wipe.
#
# Pre-warming at activation makes the first real spawn instant. Failure is
# ignored on purpose: a missing warm-up must not fail the activation.
home.activation.warmWebpageMcp = lib.hm.dag.entryAfter [ ] ''
${pkgs.nodejs_22}/bin/npx -y -p webpage-mcp@latest true >/dev/null 2>&1 || true
'';
# Expose `opencode serve` as a systemd user service. nginx on sapphira
# proxies https://opencode.zeroq.su -> 127.0.0.1:4096.
#
# --hostname 0.0.0.0 binds the listener to every interface (matches the
# "0.0.0.0" intent; nginx then reverse-proxies 127.0.0.1:4096 internally).
# --cors https://opencode.zeroq.su lets the browser session reach the
# server from that origin without CORS rejection.
# --port 4096 is REQUIRED in v2: the default moved to 4097 (4096 belongs to
# the v2 background service), and the nginx vhost above proxies to 4096.
#
# SECURITY: with no password, anyone reaching the upstream socket gets full
# opencode. Bind 0.0.0.0 + listener == bridge == shell. The password is
@@ -364,6 +351,8 @@ in
extraArgs = [
"--hostname"
"0.0.0.0"
"--port"
"4096"
"--cors"
"https://opencode.zeroq.su"
];
@@ -391,10 +380,8 @@ in
# OOM-kill. Without this, a spike triggers the same
# restart-loop the host saw today.
#
# Sizes are derived from observed peak (1.4 GiB at 16:36, 1.1 GiB at 16:59).
# MemoryHigh = 1G gives headroom for normal runs; MemoryMax = 2G caps
# pathological growth. Tweak both together if a workload legitimately
# needs more.
# v2 is heavier than v1 (bun runtime + web UI in the same process), so these
# caps stay.
#
# Refs:
# https://www.freedesktop.org/software/systemd/man/systemd.resource-control.html