test-runner / smoke (push) Canceled after 0s
herdr-демон v0.9.3 запускает агента как голый `opencode` (src/detect/mod.rs: `Agent::OpenCode => "opencode"`) и вписывает токен в шелл панели (src/app/agents.rs: `start_agent`). Конфиг-хука на замену executable у herdr нет (`herdr --default-config` без `agent.*`). На 2-4 вкладках это даёт 1.6-3.2 ГиБ opencode-инстансов поверх 5.6 ГиБ sapphira. Решение: PATH-шим в herdr-юните. `opencodeAttachShim` (`pkgs.writeShellScriptBin "opencode"`) кладётся первым в `systemd.user.services.herdr.Service.Environment` под `lib.mkIf config.programs.opencode.web.enable` и превращает голый вызов в `opencode attach http://127.0.0.1:4096 --dir "$PWD"`. Реальные подкоманды шим пропускает насквозь, resume после рестарта демона (`opencode --session <id>`, src/agent_resume.rs) — в attach-with-session. На rydiwo, где opencode.nix не импортирован, шим не ставится (опция на default `false`). Env (EnvironmentFile с OPENCODE_SERVER_USERNAME/PASSWORD и GEMINI_API_KEY) тот же sops-файл, что у `opencode-web.service` — `opencode attach` берёт basic-auth из env автоматически. systemd НЕ разворачивает `$PATH` в `Environment=` (проверено на sapphira 2026-10-15: `PATH=/x:$PATH` хранится литералом), PATH выписан целиком из реально существующих каталогов. R2 (Service ≠ serviceConfig) соблюдён. Доказательства (sapphira): • `nix build .#nixosConfigurations.sapphira.config.system.build.toplevel` — rc=0 • отрендеренный herdr.service: `Environment=PATH=<shim>/bin:…`, `EnvironmentFile` и `ExecStart` не изменены • шим-перехват: `opencode --help` → attach help; `opencode serve --help` → passthrough • живой сервер: 3 сессии в opencode.db с `directory=/tmp/attach-smoke` созданы через `run/attach --attach` • `opencode attach` в pty держит связь Документация (ADR-0006, T34): .agent/decisions/0006-herdr-shared- opencode-serve.md. R1.16 в project-rules.md, инвариант 13 в AGENTS.md, T34 в tasks/manifest.json. nixos-rebuild switch НЕ выполнен — на ваше усмотрение после ревью. Главный риск (открыто): opencode #55076 — общий сервер при resume может не вернуть permissions/step-limits (та самая причина, по которой предыдущая редакция herdr.nix обходила shared service). Митигация лежит на сервере (OPENCODE_CONFIG_CONTENT cap или выделенный serve), не в этом модуле. Мониторить; при рецидиве — менять на opencode-web или поднимать выделенный.
173 lines
8.7 KiB
Nix
173 lines
8.7 KiB
Nix
# Unattended herdr (https://herdr.dev) agent orchestrator running as a
|
|
# systemd USER service on sapphira. Matches the orchestrator's per-UID
|
|
# design: Unix sockets live in $XDG_CONFIG_HOME/herdr/ with mode 0600,
|
|
# owner-only. See .agent/context/research-herdr-2026-10.md for the full
|
|
# architecture assessment.
|
|
#
|
|
# Why user service, not system:
|
|
# - herdr stores Unix sockets (API + client) in $XDG_CONFIG_HOME/herdr/
|
|
# with mode 0600 and owner-only access. A system service would run
|
|
# under a different uid, so the human user could not reach the API
|
|
# without sudo and there is no benefit to running it as a dedicated
|
|
# uid (herdr itself holds no secrets — see "Credentials" below).
|
|
# - herdr's design is per-UID: one server per user, configurable session
|
|
# namespaces via --session. A system service would fight the tool.
|
|
# - The existing opencode-web service on sapphira (home/modules/opencode.nix)
|
|
# is already a user service; this module mirrors that pattern exactly.
|
|
#
|
|
# Why --session herdr-prod:
|
|
# - herdr's default session name is fixed at $XDG_CONFIG_HOME/herdr/;
|
|
# using --session namespaced it under sessions/herdr-prod/. This lets
|
|
# a TUI `herdr` client run interactively on sapphira (e.g. for ad-hoc
|
|
# debugging) without colliding with the unattended server's sockets.
|
|
# (Background: herdr issue #4544 — default socket path is fixed, so
|
|
# parallel/automated herdr workloads land on the user's live server.)
|
|
#
|
|
# Children OpenCode instances (integration-managed, see integrations docs):
|
|
# - herdr launches the built-in opencode agent by typing the bare token
|
|
# `opencode` into the pane's shell. Left alone, every workspace tab hence
|
|
# starts a full opencode process with its own in-process server
|
|
# (~0.8 GiB per tab).
|
|
# - This module instead puts a PATH shim (`opencodeAttachShim` below) first
|
|
# in the unit's PATH, so each pane becomes a thin client of the single
|
|
# long-running shared server (opencode-web.service, 127.0.0.1:4096). See
|
|
# .agent/decisions/0006-herdr-shared-opencode-serve.md.
|
|
# - Children inherit the parent env, so EnvironmentFile below covers both
|
|
# herdr and its opencode clients — including OPENCODE_SERVER_USERNAME /
|
|
# OPENCODE_SERVER_PASSWORD, which `opencode attach` reads automatically
|
|
# for the server's basic auth.
|
|
# - RISK (opencode #55076): the shared server may resume killed sessions
|
|
# without their original permissions/step limits. That mitigation lives
|
|
# with the server (opencode-web), not here; see ADR-0006 "Risks".
|
|
#
|
|
# Credentials:
|
|
# - herdr stores NO secrets. Per herdr docs/integrations/, each agent
|
|
# (OpenCode, Claude, Codex, etc.) reads its own config from its own
|
|
# XDG paths (~/.config/opencode/, ~/.claude/, ~/.codex/, ...). herdr
|
|
# only propagates the parent process env to child panes. So the
|
|
# EnvironmentFile below is the same one used by opencode-web
|
|
# (modules/users.nix:117-122), and the sops-managed OpenCode auth/
|
|
# account JSON files (modules/users.nix:128-141) are read by the
|
|
# spawned OpenCode children on their own — no extra wiring here.
|
|
{
|
|
config,
|
|
lib,
|
|
pkgs,
|
|
xlib,
|
|
...
|
|
}:
|
|
let
|
|
# Address of the shared `opencode serve` provided by programs.opencode.web
|
|
# (home/modules/opencode.nix:361-370). opencode's built-in default port for
|
|
# `opencode web` is 4096; this literal must match that service.
|
|
sharedServeUrl = "http://127.0.0.1:4096";
|
|
|
|
# Only hosts that actually run the shared server get the shim (sapphira).
|
|
# rydiwo (home/secondary.nix) does not import opencode.nix, so there the
|
|
# option is at its default `false` and herdr keeps its stock behaviour.
|
|
sharedServeEnabled = config.programs.opencode.web.enable;
|
|
|
|
# A `PATH` entry named `opencode` that redirects herdr's launch to the shared
|
|
# server instead of letting every pane spawn its own full opencode instance.
|
|
#
|
|
# Why a PATH shim (and not a plugin or daemon patch): herdr's daemon builds
|
|
# the pane command as the bare token `opencode`
|
|
# (src/detect/mod.rs: `Agent::OpenCode => "opencode"`) and types it into the
|
|
# pane's shell (src/app/agents.rs: `start_agent`). `$PATH` is therefore the
|
|
# only interception point that neither forks herdr nor patches the
|
|
# herdr-web-ui plugin — and it survives `herdr plugin update`, which would
|
|
# clobber a plugin-side patch (cf. ADR-0005 maintenance debt).
|
|
#
|
|
# On daemon restart herdr resumes an agent as `opencode --session <id>`
|
|
# (src/agent_resume.rs). The shim forwards argv, so that path becomes
|
|
# `opencode attach <url> --dir $PWD --session <id>` against the same server.
|
|
#
|
|
# Real subcommands (if the user ever runs `opencode serve` etc. inside a
|
|
# herdr pane) are passed through untouched.
|
|
opencodeAttachShim = pkgs.writeShellScriptBin "opencode" ''
|
|
set -eu
|
|
case "''${1:-}" in
|
|
serve|web|attach|run|acp|mcp|providers|auth|agent|models|debug|session|export|import|plugin|plug|db|github|pr|completion|upgrade|uninstall|stats)
|
|
exec ${pkgs.opencode}/bin/opencode "$@"
|
|
;;
|
|
esac
|
|
exec ${pkgs.opencode}/bin/opencode attach ${sharedServeUrl} --dir "$PWD" "$@"
|
|
'';
|
|
|
|
# Base PATH for the herdr unit. systemd does NOT expand variables inside
|
|
# `Environment=` (verified on sapphira 2026-10-15: `PATH=/x:$PATH` is stored
|
|
# literally), so the full PATH must be spelled out. Only directories that
|
|
# actually resolve are kept — `~/.nix-profile/bin` and
|
|
# `/nix/var/nix/profiles/default/bin` are dangling symlinks on sapphira.
|
|
basePath = "/run/wrappers/bin:${config.home.profileDirectory}/bin:/run/current-system/sw/bin";
|
|
in
|
|
{
|
|
# Install herdr binary. nixpkgs already installs bash/fish/zsh shell
|
|
# completions via installShellCompletion in the package's postInstall
|
|
# (verified: pkgs/by-name/he/herdr/package.nix).
|
|
home.packages = [ pkgs.herdr ];
|
|
|
|
# systemd user service: headless `herdr server` running in the
|
|
# dedicated `herdr-prod` session namespace.
|
|
#
|
|
# Why Type=simple (not notify): upstream herdr does not implement
|
|
# sd_notify (no such call in src/platform/unix_common.rs:338-365).
|
|
# Readiness is implied by socket creation in
|
|
# $XDG_CONFIG_HOME/herdr/sessions/herdr-prod/ (mode 0600, owner oqyude).
|
|
#
|
|
# Why Restart=always (not on-failure): herdr issue #4920 — the server
|
|
# can shut down after the last client detaches on some paths.
|
|
# Restart=always guarantees the unattended daemon stays up; systemd
|
|
# de-bounces spurious exits via RestartSec.
|
|
systemd.user.services.herdr = {
|
|
Unit = {
|
|
Description = "herdr agent orchestrator (production session, sapphira)";
|
|
Documentation = [
|
|
"https://herdr.dev/docs/"
|
|
"https://herdr.dev/docs/socket-api/"
|
|
"https://herdr.dev/docs/session-state/"
|
|
];
|
|
# Spawned children may open Tailscale / LAN sockets (e.g. for the
|
|
# built-in opencode integration that needs to reach other hosts).
|
|
# Wait for routable network so they don't race NetworkManager-wait-online.
|
|
After = [ "network-online.target" ];
|
|
Wants = [ "network-online.target" ];
|
|
};
|
|
Service = {
|
|
Type = "simple";
|
|
ExecStart = "${lib.getExe pkgs.herdr} server --session herdr-prod";
|
|
Restart = "always";
|
|
RestartSec = "5s";
|
|
# EnvironmentFile is decrypted by sops-nix (modules/users.nix:117-122)
|
|
# to xlib.dirs.opencode-server-env. Contains OPENCODE_SERVER_PASSWORD
|
|
# and any other env vars the spawned `opencode serve` children need.
|
|
# herdr propagates parent process env to child panes (verified:
|
|
# src/session.rs:171-187), so this single EnvironmentFile covers
|
|
# both the orchestrator and its integration-managed OpenCode
|
|
# instances. herdr itself stores NO secrets.
|
|
EnvironmentFile = xlib.dirs.opencode-server-env;
|
|
# Only set where the shared server exists: prepend the `opencode` shim so
|
|
# herdr panes attach to it instead of spawning their own instance. On
|
|
# hosts without the server the option stays unset and herdr's children
|
|
# inherit the manager PATH unchanged.
|
|
Environment = lib.mkIf sharedServeEnabled [
|
|
"OPENCODE_ATTACH_URL=${sharedServeUrl}"
|
|
"PATH=${lib.makeBinPath [ opencodeAttachShim ]}:${basePath}"
|
|
];
|
|
# Memory protection, same pattern as opencode-web
|
|
# (home/modules/opencode.nix:407-412). sapphira has 5.6 GiB RAM
|
|
# with ~1 GiB baseline; herdr's cgroup covers itself AND its
|
|
# spawned opencode subprocesses, so the budget is available
|
|
# headroom minus a 1.5 GiB cushion for the rest of the host.
|
|
# Sizes are conservative; bump together if a workload legitimately
|
|
# needs more.
|
|
MemoryHigh = "2G";
|
|
MemoryMax = "4G";
|
|
OOMScoreAdjust = -900;
|
|
OOMPolicy = "continue";
|
|
};
|
|
Install = {
|
|
WantedBy = [ "default.target" ];
|
|
};
|
|
};
|
|
} |