hyperhive/nix/agent-modules/matrix.nix

298 lines
14 KiB
Nix

# Per-agent matrix integration: the `hyperhive.matrix.*` +
# `hyperhive.matrixAccounts` options, the long-running
# hive-matrix-daemon, its token-arrival path trigger, and the
# auto-injected stdio MCP bridge entry.
{
pkgs,
lib,
config,
...
}:
let
userName = config.hyperhive.user.name;
# Single source of truth for the default matrix homeserver URL, shared
# by the `hyperhive.matrix.url` option default and the daemon-unit guard
# that decides whether to set a unit-level HIVE_MATRIX_URL (so the two
# cannot drift). Matches the daemon's own built-in default
# (`paths::DEFAULT_HOMESERVER`).
matrixUrlDefault = "http://localhost:8008";
# Rasterize the operator-set agent icon (`hyperhive.icon`, an SVG) to a
# 512x512 PNG so the matrix daemon can upload it as each account's avatar
# over the live authenticated Client (see hive-matrix-mcp::client::sync_avatar).
# Only forced when an icon is configured — the `HIVE_ICON_PNG` daemon-env
# entry is gated on `hyperhive.icon != null`, so this binding stays lazy
# when no icon is set.
iconPng = pkgs.runCommand "hive-agent-icon.png" { nativeBuildInputs = [ pkgs.librsvg ]; } ''
rsvg-convert -f png -w 512 -h 512 ${config.hyperhive.icon} -o $out
'';
in
{
options.hyperhive.matrix.enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Enable per-agent matrix integration via `hive-matrix-mcp`.
When true (the default), the harness:
- runs `hive-matrix-daemon` as a systemd unit that holds a
matrix-sdk Client + sync against the homeserver at
`HIVE_MATRIX_URL` (default `http://localhost:8008` the
in-host tuwunel from `nix/host-modules/hive-matrix.nix`). The
daemon auto-skips when `<state>/matrix-token` is missing,
and a `systemd.paths` watcher restarts it the moment
hive-c0re provisions the token (same path-trigger shape
as `forge-avatar-sync`).
- exposes the matrix tool surface (send_message, send_dm,
send_reaction, send_reply, mark_read, list_rooms,
list_room_members, read_room) to claude via an auto-injected
`extraMcpServers.matrix` entry. Claude spawns the stdio
`hive-matrix-mcp` bridge per turn, which forwards each tool
call to the daemon over `/run/hive-matrix/socket`.
- wakes the agent on incoming room events via a short teaser
Wake signal (`[matrix] <sender> in <room>: <first 100c>`)
to the hyperhive control socket; the full event stays
unread server-side until `read_room` consumes it.
Set to `false` for agents that should NOT have matrix tools at
all (e.g. agents on a host without `hyperhive.matrix.enable` on
the meta side). When token file is absent the daemon and MCP
both no-op cleanly anyway, so `false` is rarely necessary.
'';
};
options.hyperhive.matrix.url = lib.mkOption {
type = lib.types.str;
default = matrixUrlDefault;
example = "https://matrix.darkest.space";
description = ''
Matrix homeserver URL the agent's `hive-matrix-daemon` connects
to. At runtime hive-c0re forwards the isolation-aware URL
(`matrix.<domain>` via the gateway) so isolated agents reach
the homeserver without crossing host loopback. Override
per-agent when an agent should talk to an external homeserver
instead (e.g. a federation-only setup or a remote hive's
tuwunel reached via a vpn).
'';
};
options.hyperhive.matrixAccounts = lib.mkOption {
type = lib.types.attrsOf (
lib.types.submodule {
options = {
tokenFile = lib.mkOption {
type = lib.types.str;
example = "/agents/dmatrix/state/matrix-token-ccc";
description = ''
Path to this account's bearer-token file. The daemon reads
the token from here to restore the matrix session; how the
file gets populated is the provisioner's concern (an
operator-supplied secret for an external account). The
daemon skips an extra account whose token file is absent.
'';
};
sessionDir = lib.mkOption {
type = lib.types.str;
example = "/agents/dmatrix/state/matrix-sdk-state-ccc";
description = ''
Per-account matrix-sdk sqlite store directory (crypto keys
+ event cache). Must differ between accounts so their
sessions do not collide.
'';
};
homeserver = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "https://matrix.example.org";
description = ''
Homeserver URL for this account. When null (the default),
the account falls back to `hyperhive.matrix.url`. Set it for
an account on a different homeserver than the agent's
default (e.g. an external public-matrix account).
'';
};
};
}
);
default = { };
example = lib.literalExpression ''
{
ccc = {
tokenFile = "/agents/dmatrix/state/matrix-token-ccc";
sessionDir = "/agents/dmatrix/state/matrix-sdk-state-ccc";
homeserver = "https://matrix.example.org";
};
}
'';
description = ''
Declare *additional* matrix accounts served by the single
`hive-matrix-daemon` (one matrix-sdk Client + sync loop each),
beyond the agent's built-in hive-internal account. The
attribute name keys each account (unique by construction) and is
the handle the matrix MCP tools target via their `account`
argument.
The **hive-internal account is always present and is the primary**:
it is named `main`, synthesized by the daemon from
`hyperhive.matrix.url` + `<state>/matrix-token` +
`<state>/matrix-sdk-state`, and is the account a tool call acts as
when it omits `account`. You never declare it here --- this option
is only for the extras (e.g. an external public-matrix account).
Leave empty (the default) for the common single-account case: the
agent then has only `main`. When non-empty, the extras are
serialized to the daemon's `HIVE_MATRIX_ACCOUNTS` environment
variable and the daemon appends them after `main`. Requires
`hyperhive.matrix.enable` (there is no `main` to extend otherwise).
'';
};
config = {
assertions = [
# Extra matrix accounts only make sense alongside the hive-internal
# `main` account they extend, which exists only when matrix is
# enabled.
{
assertion = config.hyperhive.matrixAccounts == { } || config.hyperhive.matrix.enable;
message =
"hyperhive.matrixAccounts requires hyperhive.matrix.enable = true "
+ "(the extras extend the hive-internal `main` account, which only "
+ "exists when matrix is enabled).";
}
# `main` is reserved for the synthesized hive-internal account; a
# declared extra by that name would silently collide with it.
{
assertion = !builtins.hasAttr "main" config.hyperhive.matrixAccounts;
message =
"hyperhive.matrixAccounts cannot contain a key named \"main\" "
+ "--- that name is reserved for the hive-internal account.";
}
# Token files must land at the `matrix-token*` name the daemon
# path-watcher globs (`/agents/*/state/matrix-token*`), or the account
# never gets picked up live (it loads only on a full daemon restart).
# Enforce the basename prefix so a deviating name (e.g.
# `matrix-catgirl-token`) is caught at build time, not silently.
{
assertion = lib.all (a: lib.hasPrefix "matrix-token" (baseNameOf a.tokenFile)) (
lib.attrValues config.hyperhive.matrixAccounts
);
message =
"every hyperhive.matrixAccounts.<name>.tokenFile basename must start with "
+ "\"matrix-token\" so the daemon path-watcher glob "
+ "(/agents/*/state/matrix-token*) picks it up live. Offending: "
+ lib.concatStringsSep ", " (
lib.mapAttrsToList (n: a: "${n}=${baseNameOf a.tokenFile}") (
lib.filterAttrs (
_n: a: !lib.hasPrefix "matrix-token" (baseNameOf a.tokenFile)
) config.hyperhive.matrixAccounts
)
)
+ ".";
}
];
# Auto-inject the matrix stdio MCP bridge alongside the bash entry
# from ./mcp.nix. `lib.mkDefault` so the operator's own agent.nix
# can override the entry.
hyperhive.extraMcpServers = lib.mkIf config.hyperhive.matrix.enable {
matrix = lib.mkDefault {
command = "${config.hyperhive.packages.hive-matrix-mcp}/bin/hive-matrix-mcp";
args = [ ];
# Same socket path the hive-matrix-daemon service binds
# via its `RuntimeDirectory = "hive-matrix"`. Keeps the
# bridge + daemon in sync without baking the path into
# the Rust default — the env override wins for both.
env.HIVE_MATRIX_SOCKET = "/run/hive-matrix/socket";
allowedTools = [ "*" ];
};
};
# Long-running matrix-sdk client + sync per agent. Holds the unix
# socket the stdio `hive-matrix-mcp` bridge connects to + emits
# hyperhive wake signals on incoming room events via
# `/run/hive/mcp.sock`. See
# `docs/persistence.md::Matrix per-agent daemon + token-arrival
# trigger` for the socket-path / first-boot-ordering rationale.
systemd.services.hive-matrix-daemon = lib.mkIf config.hyperhive.matrix.enable {
description = "long-running matrix-sdk Client + MCP daemon socket";
wantedBy = [ "multi-user.target" ];
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
environment = {
HIVE_MATRIX_SOCKET = "/run/hive-matrix/socket";
RUST_LOG = "info";
}
# Homeserver URL: by default the daemon inherits the host-forwarded
# HIVE_MATRIX_URL (set by hive-c0re to `matrix.<domain>` via the
# gateway, since agents run in private netns and can't reach host
# loopback directly), falling back to the daemon's built-in
# localhost default if the forward is absent. A per-agent
# `hyperhive.matrix.url` override (non-default) is set unit-level
# so it wins over the forwarded value; at the default we
# deliberately DON'T set it so the forwarded value isn't shadowed.
// lib.optionalAttrs (config.hyperhive.matrix.url != matrixUrlDefault) {
HIVE_MATRIX_URL = config.hyperhive.matrix.url;
}
# Multi-account: serialize the *extra* accounts to the JSON the
# daemon parses (`accounts::configured`). Only set when extras are
# declared; the daemon always synthesizes the primary `main`
# (hive-internal) account itself from the per-agent paths and
# prepends it, so we emit extras only. Each entry is in the
# daemon's `AccountCfg` serde shape: name (the attr key) /
# token_file / state_dir / optional homeserver.
// lib.optionalAttrs (config.hyperhive.matrixAccounts != { }) {
HIVE_MATRIX_ACCOUNTS = builtins.toJSON (
lib.mapAttrsToList (
name: a:
{
inherit name;
token_file = a.tokenFile;
state_dir = a.sessionDir;
}
// lib.optionalAttrs (a.homeserver != null) { inherit (a) homeserver; }
) config.hyperhive.matrixAccounts
);
}
# Rasterized agent icon path for the daemon's avatar sync. Only set
# when an icon is configured; absent → the daemon skips avatar setting
# (hive-matrix-mcp::client::sync_avatar returns early on unset env).
// lib.optionalAttrs (config.hyperhive.icon != null) {
HIVE_ICON_PNG = "${iconPng}";
};
serviceConfig = {
ExecStart = "${config.hyperhive.packages.hive-matrix-daemon}/bin/hive-matrix-daemon";
SyslogIdentifier = "hive-matrix-daemon";
Restart = "on-failure";
RestartSec = 5;
User = userName;
Group = userName;
RuntimeDirectory = "hive-matrix";
# Keep /run/hive-matrix across restarts. With the default
# `RuntimeDirectoryPreserve=no`, a `switch-to-configuration`
# restart races the outgoing instance's stop-time cleanup
# (which deletes the dir) against the incoming instance's
# start (which creates it + binds the socket inside it). The
# cleanup can win and delete the dir out from under the fresh
# daemon, which then fails to mkdir under root-owned /run and
# exits — looping on Restart=on-failure until the next boot.
# `yes` stops systemd removing it on stop; it still creates it
# on first start, and it lives on tmpfs so it's gone at
# container reboot regardless. See hive-bash-daemon (./mcp.nix).
RuntimeDirectoryPreserve = "yes";
};
};
# Re-fire the daemon when the matrix token appears (hive-c0re
# provisions it after agent containers come up). Without this
# the daemon would exit 0 silently on first boot and the MCP
# would have no backend until next restart. See
# `docs/persistence.md` (same section as above).
systemd.paths.hive-matrix-daemon = lib.mkIf config.hyperhive.matrix.enable {
description = "trigger hive-matrix-daemon when a matrix token appears";
wantedBy = [ "multi-user.target" ];
# `matrix-token*` (not just `matrix-token`) so a secondary
# multi-account token (e.g. `matrix-token-ccc`) landing also
# re-fires the daemon to pick up the freshly-provisioned account.
pathConfig.PathExistsGlob = "/agents/*/state/matrix-token*";
};
};
}