33 Commits

Author SHA1 Message Date
3861962566 feat(herdr): enable kitty graphics 2026-08-29 23:45:40 -04:00
4361d9b9b6 feat(shell): add yazi 2026-08-29 23:35:18 -04:00
4493790d72 feat(desktop): use ghostty as terminal 2026-08-29 23:24:48 -04:00
7d5a0d4759 build(flake): follow monorepo nixpkgs 2026-08-29 23:17:06 -04:00
f7164dd172 feat(nvim): soft-wrap prose buffers 2026-08-29 21:36:34 -04:00
81a729ea06 feat(direnv): add repo-root flake shorthand 2026-08-29 19:31:08 -04:00
dc74538cfe refactor(registry): narrow assembly output 2026-08-29 17:06:18 -04:00
28d8eb7ca9 refactor(flake): inline assembly wiring 2026-08-29 17:06:07 -04:00
42b1578efa refactor(guest): assemble guest modules 2026-08-29 17:05:44 -04:00
4f105c81c2 refactor(guest): clean guest module implementation 2026-08-29 17:05:44 -04:00
0abd3121fb refactor(guest): simplify guest options 2026-08-29 17:05:44 -04:00
d88ee49aaf refactor(host): simplify host assembly 2026-08-29 17:05:43 -04:00
647b20b934 refactor(flake): split assembly by concept 2026-08-29 17:05:43 -04:00
6f0f586fb6 refactor(shell): use default modules for grouped tools 2026-08-29 17:05:43 -04:00
be4a060e94 docs(nix): record flake conventions 2026-08-29 17:05:43 -04:00
1ba3bdf8d6 refactor(flake): move assembly code out of lib 2026-08-29 17:05:43 -04:00
abac67afb4 refactor(modules): organize module tree 2026-08-28 08:40:15 -04:00
f767b613a0 refactor(reverse-proxy): move module under services 2026-08-28 00:11:29 -04:00
105960ea3b refactor(modules): move base modules under modules 2026-08-27 23:48:35 -04:00
200930035a docs(agents): clarify writing guidance 2026-08-26 18:42:51 -04:00
64c1db71e4 fix(pi): correct tool lookup patch 2026-08-26 16:33:44 -04:00
17326fa65b refactor(agents): reduce local AI tooling 2026-08-26 15:55:43 -04:00
09d8e72065 docs: add technical writing guide 2026-08-26 15:55:16 -04:00
32ef8edbed chore(agents): disable global skills 2026-08-26 09:28:18 -04:00
a0604c708e refactor(flake): remove project-level checks 2026-08-26 09:15:09 -04:00
8eb873f57b chore(agents): update skills flake 2026-08-26 09:00:13 -04:00
48d9d3280f feat(registry): validate unique addresses and routes 2026-08-25 22:29:56 -04:00
f45aa44ead refactor(registry): add stable uid registry 2026-08-25 21:45:56 -04:00
622d09818f refactor(registry): remove legacy endpoint helpers 2026-08-25 00:26:32 -04:00
cb59b18703 feat(fish): add shell shortcut registry 2026-08-24 23:54:54 -04:00
45c6d01b1f refactor(reverse-proxy): use route registry 2026-08-24 21:58:54 -04:00
c267a2ec5c refactor(network): use address registry 2026-08-23 23:28:04 -04:00
6f963920ec feat(registry): add generic fleet namespace 2026-08-23 22:37:53 -04:00
96 changed files with 2157 additions and 4807 deletions

195
AGENTS.md
View File

@@ -1,105 +1,110 @@
# dotfiles-nixos # dotfiles-nixos
One flake that builds every machine the user owns. One flake builds every machine I own.
The domain model (Host, Module, Skeleton, Auto-loader, Enable convention, overlays) lives in `~/Documents/ai-artifacts/projects/dotfiles/003-dotfiles-context.md`.
## Conventions ## Repository Conventions
- Comments posted to Gitea (pull requests, issues, reviews) go out under the operator's account, so sign every one to make clear the author is the agent, not the operator. - Use `docs/technical-writing.md` and `docs/dictionary.md` while authoring any file.
End the comment with a `— Claude` sign-off. Apply them to comments, user-facing descriptions, commit prose, pull-request prose, and Markdown documentation.
(A dedicated bot account may replace this later. - Comments posted to the forge under the operator's account must end with `— Pi`.
Until then, the sign-off is the only marker.) The sign-off identifies the agent as the author instead of the operator.
- Commit messages follow Conventional Commits, specified in `docs/conventional-commits.md`. - Commit messages follow Conventional Commits, defined in `docs/conventional-commits.md`.
Scope is the module or host the change belongs to (`fish`, `nvim`, `neogaia`), omitted for repo-wide changes. Use a scope for the changed module or host, such as `fish`, `nvim`, or `neogaia`.
Keep messages free of Gitea-specific references: this repository is mirrored to GitHub, where issue and pull-request numbers resolve to unrelated things. - Keep commit messages about the Git history, not the forge workflow.
- When a graphical application is added, give it a `window-rewrite` icon mapping in `modules/desktop/waybar.nix`. Do not reference issue or pull-request numbers unless the commit itself requires a stable external reference.
Without one its windows fall back to the generic default glyph on the workspace indicator instead of showing a recognisable per-application icon. - During pull-request development, add follow-up commits instead of amending existing commits.
Match on the window class, which `hyprctl clients -j | jq -r '.[].class' | sort -u` lists for the running session. Preserve review history until the pull request is ready to merge.
- Use `gitea-axi` for Gitea issues, pull requests, labels, reviews, comments, and milestones.
It resolves this repository from the `origin` remote inside the checkout.
## Dotfiles Conventions
### Desktop
- When adding a graphical application, add a `window-rewrite` icon mapping in `modules/desktop/session/waybar.nix`.
The workspace indicator uses this mapping to show an application icon instead of the generic default glyph.
Match the mapping on the window class.
Run `hyprctl clients -j | jq -r '.[].class' | sort -u` to list classes in the running session.
- Set Hyprland session environment variables in `modules/desktop/session/hyprland/default.nix` with `env = KEY,VALUE`.
`home.sessionVariables` do **not** reach the Hyprland session because UWSM does not source `hm-session-vars.sh`.
Source cursor values from `config.stylix.cursor`.
Set `XCURSOR_*` and `HYPRCURSOR_*` to the same theme for Bibata.
- Configure the Steam desktop client as an XWayland application.
SDL Wayland selectors do not make the visible client native Wayland.
Keep fractional scaling sharp with Hyprland's `xwayland.force_zero_scaling` and Steam's `STEAM_FORCE_DESKTOPUI_SCALING`.
### Firefox
- Manage Firefox search engines through `programs.firefox.search` with `force = true`.
Hide built-in engines with `<engine>.metaData.hidden = true` because omission does not remove them.
Use current engine ids, such as `default = "ddg"` instead of `"DuckDuckGo"`.
Decode the built `search.json.mozlz4` with `mozlz4a -d <search.json.mozlz4>` to check the result.
- Avoid Home Manager Firefox extension settings unless the whole profile can use the legacy extension-storage backend.
Any non-empty `profiles.<name>.extensions.settings.<id>.settings` sets `extensions.webextensions.ExtensionStorageIDB.enabled = false` for the whole profile.
### Neovim
- Nixvim's flake input follows the root nixpkgs source, but its Home Manager module does not reuse the host's `pkgs` instance.
Keep `programs.nixvim.nixpkgs.useGlobalPackages = true`.
That setting makes Nixvim use the shared package set without warning that its source default changed.
### AI Tooling
- Use produced literals for Herdr key names that include shifted punctuation.
For example, use `prefix+<` instead of `prefix+shift+comma`.
- Treat `~/.pi/agent/skills` as generated output from Home Manager.
Do not edit skills in that directory.
A new file created there stays outside the repo.
Shared global skills come from the `skills` flake through `modules/agents/skills.nix`.
Update the `skills` flake input, then rebuild.
- Keep generated `.agents/skills/.gitignore` files from ignoring symlinked skills.
Pi skill discovery honors `.gitignore`, `.ignore`, and `.fdignore` inside scanned skill directories.
An ignored symlinked skill does not load even when `.agents/skills/<name>/SKILL.md` exists.
- Write directly to flake-managed Pi extension, prompt, and skill directories only for throwaway development or local experiments.
Home Manager activation can overwrite or hide unmanaged files in those directories.
Promote finished work into the dotfiles module before treating it as deployed.
## Gotchas ## Gotchas
- Guest modules are host-agnostic wiring, while host files own deployment-specific service configuration such as served volumes and host paths. - Guest modules are host-agnostic wiring, while host files own deployment-specific service configuration such as served volumes and host paths.
For example, `guests/copyparty.nix` should expose options and translate them into guest mounts/service settings, while `hosts/pikachu/default.nix` chooses `/inbox`, `/media`, and their backing paths. For example, `guests/copyparty.nix` should expose options and translate them into guest mounts/service settings, while `hosts/pikachu/default.nix` chooses `/inbox`, `/media`, and their backing paths.
- `sops.secrets.<name>.owner` must name a user known on the decrypting host. Guest addresses and routes are host-level configuration because a guest module can be used on multiple hosts.
For guest-only service users, do not set the owner to the guest uid unless the host also declares that user. - The registry collector reads only top-level host `config.registry` declarations.
Use a host-visible owner plus a shared group mode when an identity-mapped guest service can read through its group. Registry declarations inside guest interiors live under `config.containers.<guest>.config.registry`.
- Actual Budget's NixOS service runs `actual-server` with `WorkingDirectory = services.actual.settings.dataDir`, and the `actual-server` CLI wrapper sets `ACTUAL_CONFIG_PATH=./config.json` when that current directory contains `config.json`, overriding the NixOS module's generated config path before the server loads configuration. The collected registry does not include those guest-interior declarations.
When migrating old community-script state to the normal upstream `/data` shape, move or rewrite a copied `/data/config.json` so it cannot shadow the declarative module settings. Publish guest values from host-side code, or extend the collector to recurse into guests.
- Subagent completion delivery is non-blocking through immediate spawn, milestone notifications, retained terminal entries, and `subagent_list` or `subagent_result` retrieval. See http://git.alexion.dev/alexion/dotfiles/issues/65.
`subagent_wait` intentionally blocks the parent tool call until its condition or timeout, so do not use it merely to keep background work alive during an interactive workflow. - A NixOS module function argument default such as `registry ? config.registry` does not safely handle an unprovided module argument.
- Nixvim's flake input following the root nixpkgs source does not make its Home Manager module reuse the host's `pkgs` instance. The module system still queries `_module.args.registry`.
Keep `programs.nixvim.nixpkgs.useGlobalPackages = true` so Nixvim uses the shared package set without warning that its source default was affected. Evaluation fails when that argument is absent.
- This host has no `python` or `python3` command on its ordinary `PATH`. For an optional special-argument fallback, bind module arguments through `@args`.
For ad hoc Python, use Nix explicitly, such as `nix shell nixpkgs#python3 -c python3 <script>`. Test `args ? <name>` inside the module body.
- ADR bodies are immutable records of decisions as they were made, while frontmatter is mutable.
When a decision changes or its premise proves wrong, preserve the original body, update its status, and add a new ADR that supersedes it. - `chaotic-nyx` must **not** follow this flake's `nixpkgs`.
Filename migrations preserve references in immutable bodies through frontmatter aliases rather than rewriting those bodies. Chaotic builds its packages against its own pinned `nixpkgs`.
- This repo pins no Nix formatter, and its committed `.nix` files are not clean under current `nixfmt-rfc-style`. Its overlay defaults to `onTopOf = "flake-nixpkgs"`, the cache-friendly path.
Running `nixfmt` across a file reflows untouched code (for example `lib.nix`'s `deriveMac` list and multi-line assertion messages) and injects churn unrelated to the change. That setup lets `nyx-cache.chaotic.cx` serve the CachyOS kernel instead of building it from source.
Format only the lines being written or changed, matching the surrounding style by hand. Chaotic packages do not see this flake's `unstable` or `stable` overlays.
- This repo is developed on `neogaia`, which now runs the NixOS it builds.
Flakes and the chaotic substituter come from this flake's own `nix.settings`, so no `NIX_CONFIG` export or per-command `--extra-experimental-features` is needed, and building a toplevel with `boot.kernelPackages = linuxPackages_cachyos` fetches the kernel from `nyx-cache` rather than compiling it.
Both were true only while the machine still ran CachyOS against a distro Nix daemon.
- Git identity is declared in the flake by `modules/git.nix`, which writes `alexion <contact@alexion.dev>` — the identity all history uses — on any host enabling `modules.git`.
Every new host has to enable it, so that a host reads as a full checklist of what it carries.
It is deployed on `neogaia` and verified: a commit in a repository outside this checkout is authored `alexion <contact@alexion.dev>` with no override.
Verify it that way rather than from this checkout, whose `.git/config` carries the same identity and would mask a broken module.
`~/.gitconfig` (a second global file that outranks the flake-managed `~/.config/git/config`) currently holds only a `tea` credential helper and no `user.*`, so it does not shadow the identity, but it is undeclared and will not survive a reimage.
- The primary build/verify seam is `nix flake check`, which builds project-level checks plus `checks.x86_64-linux.<host>` system toplevels.
Cheap targeted host checks use `nix eval .#nixosConfigurations.<host>.config...`.
- chaotic-nyx must **not** follow our `nixpkgs`, and its packages are built against chaotic's own pinned nixpkgs (its overlay defaults to `onTopOf = "flake-nixpkgs"`, the cache-friendly path).
That is what lets the `nyx-cache.chaotic.cx` binary cache hit instead of compiling the CachyOS kernel from source.
The tradeoff is that chaotic packages do not see our `unstable`/`stable` overlays.
- The remote is self-hosted Gitea (`git.alexion.dev`), and the forge CLI is `gitea-axi` rather than `tea`.
`gitea-axi` resolves the repository from the `origin` remote and discovers credentials from a `tea` login whose host matches the remote, so both are implicit inside a checkout.
It is installed on `neogaia` by `modules.agents.tools.gitea-axi`, and verified: `gitea-axi` run from this checkout renders the `alexion/dotfiles` dashboard authenticated, so the claude-code `SessionStart` hook that runs it now resolves to a real binary rather than a missing one.
The package wraps the binary so `git` and `tea` are reachable without being on `PATH`, while still preferring the operator's own where present.
Credentials: `~/.config/tea/config.yml` holds a token-bearing login named `alexion`, which `gitea-axi` uses and which also opens pull requests directly with `nix run nixpkgs#tea -- pr create --login alexion --repo alexion/dotfiles --base main --head <branch> ...`.
The `--repo` flag is required on that path, since `tea` resolves `origin` only for a login whose SSH host matches.
The same token reads PR discussion, which `tea` itself does poorly: `tea pr <n> --comments` prints only the body, and `-f comments` returns no comments field at all.
Use the API instead, taking the token from `.logins[] | select(.name=="alexion") | .token`.
Review comments are **not** at `/issues/<n>/comments` — that endpoint holds only top-level discussion and is usually empty.
Inline comments need two calls: `/pulls/<n>/reviews` for the review ids, then `/pulls/<n>/reviews/<id>/comments` for the bodies, whose `path` and `diff_hunk` fields say what each one is attached to.
A review row with an empty `body` is the normal shape when the operator left only inline comments.
- `~/.claude/skills` and `~/.pi/agent/skills` are home-manager-generated (`recursive = true`), so editing a skill in place fails and a new file created there silently escapes the repo.
Shared global skills come from the `skills` flake through `modules/agents/skills.nix`, applied by a rebuild.
Claude-specific legacy skills, when kept, live under `modules/agents/claude-code/skills/<name>/`.
- Pi skill discovery honors `.gitignore`, `.ignore`, and `.fdignore` inside scanned skill directories.
A generated `.agents/skills/.gitignore` entry that ignores a symlinked skill also prevents Pi from loading that skill, even when `.agents/skills/<name>/SKILL.md` exists and the symlink target is valid.
- nixpkgs `vimPlugins.nord-nvim` is `shaunsingh/nord.nvim` (no `require("nord").setup()`).
The config wants `gbprod/nord.nvim`, which is packaged as `vimPlugins.gbprod-nord`.
- `nixos-generate-config --show-hardware-config` needs root on this machine even just to print: unprivileged it dies at `Failed to retrieve subvolume info for /`, because the root filesystem is btrfs.
- This repo's claude-code module sets sudo's credential cache to per-user (`timestamp_type=global`, 60-minute window), so an authentication made in one real terminal counts for the agent's commands.
A `PreToolUse` hook refuses privileged commands while the cache is cold, so a cold cache announces itself instead of stalling.
A privileged-command failure *without* that message is the sandbox, not the cache.
- Host GPUs: `neogaia` is Intel, `zeus` (the desktop) is **AMD**, and `raichu` (a headless server) is the only Nvidia machine.
The corrected fact also lives in artifact `006-dotfiles-hyprland-compositor-adr.md`.
- This repo's `programs.firefox` `search` (with `force = true`) writes `search.json.mozlz4`.
Omission alone does not prune a built-in engine, since Firefox reconciles its app-provided engines back in, so remove one by listing it with `<engine>.metaData.hidden = true`.
Engines are referenced by their current id, so the default is `default = "ddg"`, not `"DuckDuckGo"`.
Decode the built file with `mozlz4a -d <search.json.mozlz4>` to check the result.
- Any non-empty Home Manager Firefox `profiles.<name>.extensions.settings.<id>.settings` causes Home Manager to set `extensions.webextensions.ExtensionStorageIDB.enabled = false` globally for that profile.
This repo's Stylix Firefox `colorTheme` settings trigger it, so every extension in the profile uses the legacy extension-storage backend regardless of how it is installed.
- `home.sessionVariables` do **not** reach the Hyprland session, since UWSM does not source `hm-session-vars.sh`.
The cursor is therefore set through Hyprland's own `env = KEY,VALUE` in `modules/desktop/hyprland/hyprland.nix`, sourced from `config.stylix.cursor`.
Bibata ships XCursor format only (no `hyprcursor/` dir), rendered through Hyprland's XCursor fallback, so `XCURSOR_*` and `HYPRCURSOR_*` naming the same theme are both safe.
- `neogaia` is a wifi laptop with a btrfs root and no ZFS pools, so it cannot honestly carry `modules.network`, `modules.zfs`, or a networked/pool-mounted guest.
Enabling networkd takes over its DNS, its CachyOS `zfs-kernel` build is marked broken, and it has no bridge or pool to attach to.
Verify these against it ad hoc through `nixosConfigurations.neogaia.extendModules` (forcing a ZFS-capable `boot.kernelPackages` for the zfs case) plus `nix eval` of the derived values, never by committing the enablement.
Committed networked and pool-mounted guests belong on a wired storage host such as `pikachu`, not on `neogaia`.
- Herdr key names for shifted punctuation are not interchangeable with the physical base key plus `shift`.
The tab rename binding must use the produced literal, such as `prefix+<`, rather than `prefix+shift+comma`.
- Flake-managed Pi extension, prompt, and skill directories may still be written directly for throwaway development or local experiments.
The risk is that a later Home Manager activation can overwrite or hide those unmanaged files, so finished work must be promoted into the dotfiles module before it counts as deployed.
- Pi's tool discovery checks `~/.pi/agent/bin` before `PATH`, and downloaded generic Linux binaries there can be unusable on NixOS with the stub-ld error.
This flake patches Pi to validate local tool binaries before selecting them, so it falls back to usable `fd`/`rg` from `PATH` instead.
Stale unpatched launchers are the remaining failure mode for broken `@` autocomplete.
- Nix flake evaluation ignores untracked files in this checkout.
Keep a new auto-loaded module staged or committed until it is removed, otherwise `nix flake check` and `nixos-rebuild --flake` evaluate without it and report its options as missing.
- The current Steam desktop client is an XWayland application.
Its CEF windows do not support Ozone and Steam composites them into an SDL surface with X11 extensions, so SDL Wayland selectors do not make the visible client native Wayland.
Keep fractional scaling sharp with Hyprland's `xwayland.force_zero_scaling` and Steam's own `STEAM_FORCE_DESKTOPUI_SCALING` instead.
- AdGuard's LAN wildcard rewrite for `*.alexion.dev` points names at the reverse-proxy guest, including non-HTTP ports.
Keep `git.alexion.dev:2022` working by proxying that TCP stream through the reverse-proxy guest to Gitea.
- Remote deploy helpers that run target-side `sudo` over SSH need a TTY. - Remote deploy helpers that run target-side `sudo` over SSH need a TTY.
Use `ssh -t` unless the target command is guaranteed not to prompt for sudo credentials. Use `ssh -t` unless the target command cannot prompt for sudo credentials.
- This host has no `python` or `python3` command on its ordinary `PATH`.
For one-off Python commands, use Nix explicitly, such as `nix shell nixpkgs#python3 -c python3 <script>`.
- `nixos-generate-config --show-hardware-config` needs root on this machine, even when it only prints.
Without root, it fails with `Failed to retrieve subvolume info for /`.
The root filesystem uses btrfs.
- Nix flake evaluation ignores untracked files in this checkout.
Stage or commit new auto-loaded modules before evaluating the flake.
Otherwise, `nix flake check` and `nixos-rebuild --flake` cannot see those modules.
They can then report missing options that exist only in the working tree.
- `sops.secrets.<name>.owner` must name a user known on the decrypting host.
Do not set the owner to a guest-only service user unless the host also declares that user.
Use a host-visible owner plus a shared group mode when the guest service can read the decrypted secret file through its group.
- Actual Budget's NixOS service runs `actual-server` with `WorkingDirectory = services.actual.settings.dataDir`.
The `actual-server` CLI wrapper sets `ACTUAL_CONFIG_PATH=./config.json` when the working directory contains `config.json`.
That environment variable overrides the config path generated by the NixOS module.
During migration from old community-script state, move or rewrite a copied `/data/config.json`.
Otherwise, the copied file shadows the declarative module settings.

View File

@@ -1,91 +0,0 @@
{
config,
lib,
inputs,
...
}:
# The shared foundation both the host base and the guest-base build on: the
# primary user, home-manager, and the fresher/pinned package overlays.
let
inherit (lib) mkOption types;
user = config.user;
# Args to instantiate an extra nixpkgs source on the base platform.
pinArgs = prev: {
inherit (prev.stdenv.hostPlatform) system;
config.allowUnfree = true;
};
in
{
imports = [ inputs.home-manager.nixosModules.home-manager ];
options.user = {
name = mkOption {
type = types.str;
default = "alexion";
description = ''
The primary interactive user this system is built for. Drives both the
system account and the home-manager user in lockstep.
'';
};
description = mkOption {
type = types.str;
default = "Alexion";
description = "Human-readable description (GECOS field) for the primary user.";
};
};
config = {
# Reach fresher packages with `unstable.<name>` or pin with `stable.<name>`.
nixpkgs.overlays = [
(_final: prev: {
unstable = import inputs.nixpkgs-unstable (pinArgs prev);
stable = import inputs.nixpkgs-stable (pinArgs prev);
})
];
nixpkgs.config.allowUnfree = true;
# Flakes, so `nixos-rebuild switch` works from the console and a direnv
# `use flake` resolves inside a guest.
nix.settings.experimental-features = [
"nix-command"
"flakes"
];
# Primary user.
# The wheel group is the way in, since root is locked.
# No password is set here, since that is host-only.
# A guest therefore has none and is reached by SSH key or `machinectl`.
users.users.${user.name} = {
isNormalUser = true;
description = user.description;
extraGroups = [
"wheel"
"storage"
];
};
# The shared write group.
# Its gid is fixed, so a host and every guest carry the same number.
# An identity-mapped container write then lands on the pool as this group, sparing every service the permission juggling.
# 10000 clears the system-group ids assigned automatically and leaves headroom above the primary user, so nothing else claims it.
users.groups.storage.gid = 10000;
# home-manager as a NixOS module: one build produces the system and user
# environment together, sharing the system's pkgs and installing user
# packages into the system profile.
home-manager = {
useGlobalPkgs = true;
useUserPackages = true;
extraSpecialArgs = {
inherit inputs;
my = inputs.self.lib;
};
users.${user.name} = {
home.username = user.name;
home.homeDirectory = "/home/${user.name}";
home.stateVersion = "26.05";
};
};
};
}

59
docs/dictionary.md Normal file
View File

@@ -0,0 +1,59 @@
# Technical Writing and Domain Dictionary
This dictionary defines project-specific controlled vocabulary, prohibited terms, and domain allowlists.
It applies to comments, user-facing descriptions, commit prose, pull-request prose, and Markdown documentation in this repository.
ASD-STE100 Simplified Technical English partly informs these rules.
This repository uses those ideas as a local style discipline.
It does not claim formal ASD-STE100 compliance.
## Strictly Banned Fluff and Latin Terms
Do not use these Latin abbreviations, conversational filler words, and subjective qualifiers.
Remove them or use the approved replacements.
| Disapproved Term | Approved Replacement | Notes |
| :--- | :--- | :--- |
| `i.e.` | `that is` | Latin abbreviation. Unclear to non-native speakers. |
| `e.g.` | `for example` | Latin abbreviation. |
| `etc.` | `and so forth`, `and others` | Latin abbreviation. Vague and non-exhaustive. |
| `vs.` / `versus` | `compared to`, `against` | Latin abbreviation. |
| `via` | `by using`, `through`, `with` | Latin term. Prefer direct prepositions. |
| `ad hoc` | `one-off`, `for this case` | Latin term. Prefer direct wording. |
| `simply` | omit | Subjective filler. Code and concepts are not inherently simple. |
| `just` | omit | Minimizing filler word. |
| `obviously` | omit | Subjective qualifier. |
| `clearly` | omit | Subjective qualifier. |
| `easily` | omit | Subjective qualifier. |
| `properly` | `correctly`, or specify exact behavior | Vague and subjective. State the exact condition. |
| `as necessary` | specify exact condition | Ambiguous. Define the condition explicitly. |
| `very` / `quite` | omit | Empty intensifiers. |
| `basically` | omit | Conversational filler. |
| `actually` | omit | Conversational filler. |
| `really` | omit | Empty intensifier. |
| `furthermore` / `moreover` | `also`, `and` | Overly formal transitional filler. |
## Technical and Domain Allowed Language
Use only approved project-specific terms as controlled vocabulary in documentation and comments.
Add a term here when repeated project prose needs it.
Use the simplest accurate word when a term is not listed.
| Approved Domain Term | Category | Description and Permitted Context |
| :--- | :--- | :--- |
| agent | Agent tooling | An AI coding assistant acting in the operator's environment. |
| operator | Agent tooling | The human driving the development process. Use when distinguishing the human from the agent acting on their behalf. |
| guest | dotfiles | A systemd-nspawn container managed by this flake. Use for configured containers under `guests/`. |
| host | dotfiles | A machine with a NixOS configuration built by this flake. |
| module | dotfiles | In this repository, a self-contained configuration under `modules/`. Use for one program, service, or subsystem. |
| registry | dotfiles | A typed configuration namespace whose entries can be collected across hosts and reused by other configuration. |
| Conventional Commits | Git | A commit-message format defined in `docs/conventional-commits.md`. |
| forge | Git | A web service that hosts Git repositories, pull requests, issues, and code review comments. Use when the exact provider does not matter. |
| flake | Nix | A Nix project with pinned inputs and declared outputs. Use for the repository-level build unit defined by `flake.nix`. |
| assembly file | Nix | A Nix file under `flake/` that constructs flake outputs or arguments passed to NixOS modules. |
| assembly function | Nix | A project function in `flake/` that creates modules, systems, or output values. |
| library file | Nix | A Nix file that defines reusable project functions instead of a NixOS module or flake output. |
| library function | Nix | A pure project function exposed under `util`. |
| NixOS module | Nix | A Nix file evaluated by `nixosSystem` for a NixOS configuration. |
| overlay | Nix | A function that modifies a Nix package set by adding or replacing packages. |
| workspace | Window management | A named or numbered group of windows in a graphical session. Some desktop environments call this a virtual desktop. |

View File

@@ -171,7 +171,7 @@ Then populate that file, which needs no existing identity because encrypting onl
$ nix run nixpkgs#sops -- secrets/newhost.yaml $ nix run nixpkgs#sops -- secrets/newhost.yaml
``` ```
A host with `modules.ssh.enable` expects one entry per key type, named `ssh-host-<type>-key`, each holding a private key generated with `ssh-keygen -t <type> -N "" -f /tmp/<type>`. A host with `modules.network.ssh.enable` expects one entry per key type, named `ssh-host-<type>-key`, each holding a private key generated with `ssh-keygen -t <type> -N "" -f /tmp/<type>`.
The build fails at evaluation if a declared secret is absent from the file, so a host that enables the daemon without these will not install. The build fails at evaluation if a declared secret is absent from the file, so a host that enables the daemon without these will not install.
Commit the matching public halves beside the host's configuration in plaintext, since publishing them is their purpose. Commit the matching public halves beside the host's configuration in plaintext, since publishing them is their purpose.

270
docs/nix.md Normal file
View File

@@ -0,0 +1,270 @@
# Nix Conventions
This document records local Nix style and design conventions.
Use these conventions when changing this flake.
Read this document with `docs/dictionary.md`.
## Names
### Reserve `lib` for `nixpkgs.lib`
Use `lib` only for the base `nixpkgs.lib` value.
Do not use `lib` for project functions.
Use `util` for library functions passed through module arguments.
Use `flake.mk<Name>` for assembly functions used by flake outputs.
Avoid:
```nix
specialArgs = {
lib = util;
};
```
Use:
```nix
specialArgs = {
inherit util;
};
```
Then call library functions through `util` inside modules:
```nix
{
lib,
util,
...
}:
{
networking.networkmanager.unmanaged = [ "interface-name:${util.bridgeName 10}" ];
}
```
### Name project function namespaces by role
Put pure project functions under `util`.
Put functions that create systems or output values under `flake`.
This keeps data-only functions separate from functions that carry flake context.
Avoid:
```nix
util.mkHosts { root = self + "/hosts"; }
```
Use:
```nix
flake.mkHosts { root = self + "/hosts"; }
```
## File Placement
### Put files in the directory that owns their role
Choose the file location before writing a Nix file.
Put assembly files under `flake/`.
Put library files under `lib/`.
Put modules under `modules/`.
Put host configurations under `hosts/<name>/`.
Put host-side guest wiring under `guests/`.
Put registry definitions under `registry/`.
Keep `flake.nix` focused on inputs and output wiring.
Do not add root-level Nix files other than `flake.nix`.
A module is self-contained configuration under `modules/`.
A module configures one program, service, or subsystem.
Files under `hosts/`, `guests/`, and `modules/` return NixOS modules.
### Use `default.nix` for module directories with support files
Use `default.nix` as the primary module when a module directory owns support files.
Keep sibling files for data or code read by that primary module.
Avoid:
```text
modules/shell/fish/fish.nix
modules/shell/fish/config.fish
```
Use:
```text
modules/shell/fish/default.nix
modules/shell/fish/config.fish
```
### Use non-module `default.nix` files only for directory assembly
Outside `modules/`, use `default.nix` to connect files in its directory.
Do not define primary assembly functions in `default.nix`.
Put primary assembly functions in named files.
Avoid:
```text
flake/default.nix # defines mkHost
```
Use:
```text
flake/default.nix # imports ./host.nix
flake/host.nix # defines mkHosts
```
### Keep assembly files focused on one concept
Give each assembly file under `flake/` one top-level concept.
Keep helper functions private to that file when no other file needs them.
Export the constructor for the concept when another assembly file needs it.
Name that constructor `mk<Concept>`.
Avoid:
```nix
{
inherit collectNixFiles mkHost mkHosts;
}
```
Use:
```nix
{
inherit mkHosts;
}
```
## Function Arguments
### Use closed interfaces for assembly files and library files
Use exact function argument patterns for assembly files and library files.
The caller owns the argument set for these files.
The imported file names each accepted attribute.
The imported file rejects stale or accidental extra attributes.
Avoid:
```nix
{
inputs,
lib,
self,
...
}:
```
Use:
```nix
{
inputs,
lib,
self,
}:
```
### Pass function arguments explicitly
Pass only the values an assembly file or library file needs.
Bind `lib` to the base `nixpkgs.lib` value at the call site.
Use `inherit` only for values that keep the same name.
Avoid:
```nix
import ./flake inputs
```
Use:
```nix
let
inherit (nixpkgs) lib;
in
import ./flake { inherit lib inputs self; }
```
### Keep NixOS module interfaces open
Files under `hosts/`, `guests/`, and `modules/` return NixOS modules.
`nixosSystem` owns their argument shape.
Name each argument the module uses.
Keep `...` so the module accepts standard arguments and special arguments.
Avoid:
```nix
{
config,
lib,
pkgs,
registry,
}:
```
Use:
```nix
{
config,
lib,
pkgs,
registry,
...
}:
```
## `let` Bindings
### Use role-specific binding names
A `let` binding name must explain the value's role in the expression.
Avoid names that describe only the value's type.
Avoid:
```nix
let
names = lib.attrNames hosts;
in
lib.genAttrs names mkHost
```
Use:
```nix
let
hostNames = lib.attrNames hosts;
in
lib.genAttrs hostNames mkHost
```
## Standard Library Calls
### Qualify standard library calls in flake assembly
Use qualified standard library calls inside assembly files.
Use `lib.mapAttrs` instead of inheriting `mapAttrs` from `lib`.
This keeps the source of each function visible.
Avoid:
```nix
let
inherit (lib) mapAttrs;
in
mapAttrs f attrs
```
Use:
```nix
lib.mapAttrs f attrs
```

109
docs/technical-writing.md Normal file
View File

@@ -0,0 +1,109 @@
# Technical Writing
This guide defines writing rules for comments, user-facing descriptions, commit prose, pull-request prose, and Markdown documentation.
These rules apply throughout this repository.
ASD-STE100 Simplified Technical English partly informs these rules.
This repository uses those ideas as a local style discipline.
It does not claim formal ASD-STE100 compliance.
Read the local dictionary with this guide.
In this guide, “the dictionary” means `docs/dictionary.md`.
The dictionary defines banned terms and the strict domain allowlist.
## Structural Conciseness and Grammar Rules
- **Clear and concise style:** Use direct, concise writing.
Use simple present tense for factual descriptions.
Do not use uncertainty words such as `could`, `might`, and `should` unless uncertainty is the subject.
Use each domain word with the meaning assigned in the dictionary.
Avoid: `The tool should usually handle the input correctly.`
Use: `The tool validates the input.`
- **Avoid jargon and inflated language:** Use common technical words.
Avoid unnecessary jargon in three categories:
1. Linguistic and grammatical meta-jargon.
Avoid: `modal auxiliaries`
Use: `uncertain words`
2. Inflated corporate phrasing.
Avoid: `utilize`
Use: `use`
Avoid: `commence`
Use: `start`
3. Unapproved domain inventions.
Do not use project-specific terms unless the dictionary defines them.
General technical words do not need dictionary entries.
Add a common word to the dictionary when it has a project-specific meaning.
If a term is vague or overloaded, choose one precise term.
List avoided alternatives in the dictionary.
Choose the simplest word that accurately communicates the meaning.
- **Sentence length limits:** Code comments, user-facing descriptions, and procedural instructions have a 20-word limit.
Descriptive Markdown paragraphs have a 25-word limit.
Do not put multiple sentences on one physical line.
Wrap a sentence across multiple physical lines when readability requires it.
Split long sentences into multiple concise sentences.
Avoid: `The command configures the service with the generated settings and restarts it after the file changes.`
Use: `The command configures the service with the generated settings.`
Use: `It restarts the service after the file changes.`
- **Active voice:** Always use active voice.
The subject must perform the action.
Do not use passive voice.
Avoid: `Stale entries are invalidated by the cache.`
Use: `The cache invalidates stale entries.`
- **Imperative mood:** Procedural instructions and task steps must start with an imperative verb.
Summary fragments for declarations use third-person singular.
Avoid: `The token should be validated before use.`
Use for a task step: `Validate the token before use.`
Use for a declaration summary: `Validates the token before use.`
- **Noun clusters:** Do not write more than three consecutive nouns without a preposition or hyphen.
Avoid: `session cache entry lookup`
Use: `lookup of session cache entries`
- **One idea per sentence:** Express only one instruction or core concept per sentence.
Do not combine multiple operations in one compound sentence.
Avoid: `Validate the input and restart the service when validation succeeds.`
Use: `Validate the input.`
Use: `Restart the service when validation succeeds.`
- **Code token exemption:** Text in Markdown backticks, URLs, and code blocks counts as one word.
Sentence-length limits and noun-cluster limits do not apply to these tokens.
Example: `curl --fail --silent https://example.com/health` counts as one word.
- **Cause and time precision:** Use `because` for causality.
Use `since` only for passage of time.
Use `as` only for simultaneous action.
Avoid: `Since the token is expired, validation fails.`
Use: `Because the token is expired, validation fails.`
## In-Code Documentation Conventions
- **Declaration coverage and exemptions:** Document public interfaces, configuration options, fields, and non-trivial public methods.
Omit comments on obvious declarations when the name and context are self-explanatory.
Avoid: `Enable this option.`
Use: `Enables automatic cleanup after a successful run.`
- **Declaration non-redundancy:** Comments must explain purpose, preconditions, invariants, or non-obvious consequences.
Do not repeat information that the name, type, path, or parameter list already conveys.
Avoid: `The timeout option sets the timeout.`
Use: `Controls how long the command waits before it reports failure.`
- **Multi-line declaration comments:** Start multi-line declaration comments with one summary sentence.
Put a blank line between the summary and detail paragraphs.
Use detail paragraphs for preconditions, invariants, examples, and non-obvious consequences.
Avoid:
```text
The caller must load the signing key before calling this method.
Validates the token and returns false for expired tokens.
```
Use:
```text
Validates the token.
The caller must load the signing key before calling this method.
Expired tokens return false instead of an error.
```
- **Code symbol references:** Enclose identifiers, paths, commands, option names, and file names in Markdown backticks.
Avoid: Run npm test before editing package.json.
Use: Run `npm test` before editing `package.json`.
- **Boolean descriptions:** Start boolean descriptions with the behavior verb.
Use `True if` only when the value reports state instead of enabling behavior.
Avoid: `Flag that specifies whether retries are enabled.`
Use: `Enables retry behavior.`
Use for state: `True if the token is expired.`

29
flake.lock generated
View File

@@ -404,6 +404,21 @@
"type": "github" "type": "github"
} }
}, },
"monorepo": {
"inputs": {
"nixpkgs": "nixpkgs_2"
},
"locked": {
"lastModified": 1788059616,
"narHash": "sha256-HBYT3h0vXRsvmgPOhUW3kgPTkgdl73PEwRTJQ5X48aM=",
"path": "/home/alexion/dev",
"type": "path"
},
"original": {
"path": "/home/alexion/dev",
"type": "path"
}
},
"nixos-hardware": { "nixos-hardware": {
"inputs": { "inputs": {
"nixpkgs": [ "nixpkgs": [
@@ -542,8 +557,12 @@
"firefox-addons": "firefox-addons", "firefox-addons": "firefox-addons",
"gitea-axi": "gitea-axi", "gitea-axi": "gitea-axi",
"home-manager": "home-manager_3", "home-manager": "home-manager_3",
"monorepo": "monorepo",
"nixos-hardware": "nixos-hardware", "nixos-hardware": "nixos-hardware",
"nixpkgs": "nixpkgs_2", "nixpkgs": [
"monorepo",
"nixpkgs"
],
"nixpkgs-stable": "nixpkgs-stable", "nixpkgs-stable": "nixpkgs-stable",
"nixpkgs-unstable": "nixpkgs-unstable", "nixpkgs-unstable": "nixpkgs-unstable",
"nixvim": "nixvim", "nixvim": "nixvim",
@@ -562,11 +581,11 @@
] ]
}, },
"locked": { "locked": {
"lastModified": 1785695024, "lastModified": 1787455371,
"narHash": "sha256-DLLk6X5zu3cRT50p18uHVdwjGVtiS0t/661M34q02zU=", "narHash": "sha256-MJ0bX4/cksSbGl7v9o0l+Wy1xAEa3BgzG7Hs8EEGde0=",
"ref": "refs/heads/main", "ref": "refs/heads/main",
"rev": "9b2a6bcd583d7d6bf7e5377c3632f601692df209", "rev": "9a1d21da4d3e70165ff772967d639df244dcc2ea",
"revCount": 54, "revCount": 55,
"type": "git", "type": "git",
"url": "https://git.alexion.dev/alexion/skills" "url": "https://git.alexion.dev/alexion/skills"
}, },

430
flake.nix
View File

@@ -2,8 +2,10 @@
description = "Alexion's NixOS configuration — one flake for every host"; description = "Alexion's NixOS configuration — one flake for every host";
inputs = { inputs = {
# Base channel. monorepo.url = "path:/home/alexion/dev";
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
# Base package set shared with the monorepo.
nixpkgs.follows = "monorepo/nixpkgs";
# Fresher packages, reachable per-package as `unstable.<name>`. # Fresher packages, reachable per-package as `unstable.<name>`.
nixpkgs-unstable.url = "github:nixos/nixpkgs/nixpkgs-unstable"; nixpkgs-unstable.url = "github:nixos/nixpkgs/nixpkgs-unstable";
@@ -76,14 +78,9 @@
{ self, nixpkgs, ... }@inputs: { self, nixpkgs, ... }@inputs:
let let
inherit (nixpkgs) lib; inherit (nixpkgs) lib;
my = import ./lib { inherit lib inputs self; };
in in
{ {
# Helper functions for discovering and building hosts. inherit (import ./flake { inherit lib inputs self; }) nixosConfigurations;
lib = my;
# Every host under hosts/ is discovered and built.
nixosConfigurations = my.mkHosts (self + "/hosts");
# A project shell for agent-local resources that should travel with this # A project shell for agent-local resources that should travel with this
# checkout rather than the operator's global profile. # checkout rather than the operator's global profile.
@@ -98,414 +95,13 @@
]; ];
}; };
# `nix flake check` builds host toplevels and project-level checks. # `nix flake check` builds every discovered host toplevel.
checks.x86_64-linux = checks.x86_64-linux = lib.mapAttrs (
let name: host:
pkgs = nixpkgs.legacyPackages.x86_64-linux; if host.config.warnings == [ ] then
serviceIdentities = import ./lib/service-identities.nix { inherit lib; }; host.config.system.build.toplevel
serviceIdentityTestsPass = lib.all (result: result) (lib.attrValues serviceIdentities.tests); else
in throw "Host ${name} has evaluation warnings:\n${lib.concatStringsSep "\n" host.config.warnings}"
(lib.mapAttrs ( ) self.nixosConfigurations;
name: host:
if host.config.warnings == [] then
host.config.system.build.toplevel
else
throw "Host ${name} has evaluation warnings:\n${lib.concatStringsSep "\n" host.config.warnings}"
) self.nixosConfigurations)
// {
service-identities = pkgs.runCommand "service-identities-check" { } ''
${lib.optionalString (!serviceIdentityTestsPass) "exit 1"}
touch $out
'';
copyparty-reverse-proxy-trust-config =
let
pikachuConfig = self.nixosConfigurations.pikachu.config;
serviceConfig = pikachuConfig.containers.copyparty.config.systemd.services.copyparty.serviceConfig;
configScript = builtins.readFile serviceConfig.ExecStartPre;
plainConfig =
(lib.nixosSystem {
system = "x86_64-linux";
specialArgs.my = self.lib;
modules = [
./modules/services/copyparty.nix
{
modules.services.copyparty = {
enable = true;
passwordFile = "/run/password";
volumes."/" = {
path = "/srv/files";
access.A = [ "alexion" ];
};
};
}
];
}).config;
plainScript = builtins.readFile plainConfig.systemd.services.copyparty.serviceConfig.ExecStartPre;
in
pkgs.runCommand "copyparty-reverse-proxy-trust-config-check" { } ''
${
lib.optionalString (
!(
lib.hasInfix " rproxy: 1" configScript
&& lib.hasInfix " xff-hdr: x-forwarded-for" configScript
&& lib.hasInfix " xff-src: 10.23.20.109/32" configScript
&& !(lib.hasInfix "rproxy" plainScript)
&& !(lib.hasInfix "xff-hdr" plainScript)
&& !(lib.hasInfix "xff-src" plainScript)
)
) "exit 1"
}
touch $out
'';
copyparty-reverse-proxy-trust-requires-source =
let
testConfig =
(lib.nixosSystem {
system = "x86_64-linux";
specialArgs.my = self.lib;
modules = [
./modules/services/copyparty.nix
{
modules.services.copyparty = {
enable = true;
passwordFile = "/run/password";
reverseProxy.enable = true;
volumes."/" = {
path = "/srv/files";
access.A = [ "alexion" ];
};
};
}
];
}).config;
hasFailedTrustedSourcesAssertion = lib.any (
assertion:
assertion.assertion == false
&& assertion.message == "modules.services.copyparty.reverseProxy.trustedSources must name at least one trusted proxy source when reverse-proxy support is enabled."
) testConfig.assertions;
in
pkgs.runCommand "copyparty-reverse-proxy-trust-requires-source-check" { } ''
${lib.optionalString (!hasFailedTrustedSourcesAssertion) "exit 1"}
touch $out
'';
reverse-proxy-basic-route =
let
testConfig =
(lib.nixosSystem {
system = "x86_64-linux";
specialArgs.my = self.lib;
modules = [
./modules/reverse-proxy.nix
{
modules.reverse-proxy = {
enable = true;
routes."budget.alexion.dev" = {
path = "/";
backend = "http://10.23.20.42:5006";
};
};
}
];
}).config;
vhost = testConfig.services.nginx.virtualHosts."budget.alexion.dev";
in
pkgs.runCommand "reverse-proxy-basic-route-check" { } ''
${
lib.optionalString (
!(vhost.forceSSL && vhost.enableACME && vhost.locations."/".proxyPass == "http://10.23.20.42:5006")
) "exit 1"
}
touch $out
'';
reverse-proxy-actualbudget-guest-route =
let
testConfig = self.nixosConfigurations.pikachu.config;
route = testConfig.modules.reverse-proxy.routes.actualbudget;
vhost = testConfig.containers.reverse-proxy.config.services.nginx.virtualHosts."budget.alexion.dev";
in
pkgs.runCommand "reverse-proxy-actualbudget-guest-route-check" { } ''
${
lib.optionalString (
!(
route.host == "budget.alexion.dev"
&& route.backend == null
&& route.endpoint == "pikachu-actualbudget"
&& route.port == 5006
&& route.tls
&& route.aliases == [ ]
&& route.path == "/"
&& !route.websockets
&& vhost.locations."/".proxyPass == "http://10.23.20.42:5006"
)
) "exit 1"
}
touch $out
'';
generic-registry-fleet-view =
let
hosts = {
alpha = lib.nixosSystem {
system = "x86_64-linux";
specialArgs.registry = registry;
modules = [
self.lib.registry.module
{
registry.address.alpha.service = "10.0.0.5";
system.stateVersion = "26.11";
}
];
};
beta = lib.nixosSystem {
system = "x86_64-linux";
specialArgs.registry = registry;
modules = [
self.lib.registry.module
(
{ registry, ... }:
{
environment.etc."registry-address-check".text = registry.address.alpha.service;
system.stateVersion = "26.11";
}
)
];
};
};
registry = self.lib.registry.collect { inherit hosts; };
betaConfig = hosts.beta.config;
in
pkgs.runCommand "generic-registry-fleet-view-check" { } ''
${
lib.optionalString (
!(
registry.address.alpha.service == "10.0.0.5"
&& betaConfig.environment.etc."registry-address-check".text == "10.0.0.5"
&& !(registry.address ? alpha-service)
)
) "exit 1"
}
touch $out
'';
network-endpoint-fleet-registry =
let
hostEndpointConfig =
lib.nixosSystem {
system = "x86_64-linux";
specialArgs.my = self.lib;
modules = [
./modules/network.nix
{
modules.network.endpoint.address = "10.23.50.146";
}
];
};
guestEndpointConfig =
lib.nixosSystem {
system = "x86_64-linux";
specialArgs.my = self.lib;
modules = [
inputs.sops-nix.nixosModules.sops
./modules/network.nix
./modules/reverse-proxy.nix
(self.lib.guest { name = "copyparty"; })
{
modules.network.vlans = [ 20 ];
guests.copyparty = {
enable = true;
vlan = 20;
endpoint.address = "10.23.20.126";
};
}
];
};
fleetEndpoints = self.lib.networkEndpoints.collectFleetEndpoints {
neogaia = hostEndpointConfig;
pikachu = guestEndpointConfig;
};
in
pkgs.runCommand "network-endpoint-fleet-registry-check" { } ''
${
lib.optionalString (
!(
fleetEndpoints.neogaia.address == "10.23.50.146"
&& fleetEndpoints."pikachu-copyparty".address == "10.23.20.126"
&& !(fleetEndpoints ? pikachu)
&& guestEndpointConfig.config.containers.copyparty.config.systemd.network.networks."20-eth0".networkConfig.DHCP == "yes"
)
) "exit 1"
}
touch $out
'';
reverse-proxy-fleet-routes =
let
routeHost =
lib.nixosSystem {
system = "x86_64-linux";
specialArgs.my = self.lib;
modules = [
./modules/reverse-proxy.nix
{
modules.reverse-proxy.routes.app = {
host = "worker.alexion.dev";
backend = "http://10.23.20.126:3923";
};
}
];
};
endpoints = self.lib.networkEndpoints.collectFleetEndpoints {
pikachu = self.nixosConfigurations.pikachu;
};
fleetRoutes = self.lib.reverseProxyRoutes.collectFleetRoutes {
inherit routeHost;
pikachu = self.nixosConfigurations.pikachu;
} endpoints;
testConfig =
(self.nixosConfigurations.pikachu.extendModules {
specialArgs.reverseProxyFleetRoutes = fleetRoutes;
}).config;
vhosts = testConfig.containers.reverse-proxy.config.services.nginx.virtualHosts;
in
pkgs.runCommand "reverse-proxy-fleet-routes-check" { } ''
${
lib.optionalString (
!(
fleetRoutes ? routeHost-app
&& fleetRoutes ? pikachu-actualbudget
&& vhosts."worker.alexion.dev".locations."/".proxyPass == "http://10.23.20.126:3923"
&& vhosts."budget.alexion.dev".locations."/".proxyPass == "http://10.23.20.42:5006"
&& vhosts."files.alexion.dev".locations."/".proxyPass == "http://10.23.20.126:3923"
)
) "exit 1"
}
touch $out
'';
reverse-proxy-endpoint-backends =
let
endpointHost =
lib.nixosSystem {
system = "x86_64-linux";
specialArgs.my = self.lib;
modules = [
./modules/network.nix
{
modules.network.endpoint.address = "10.23.50.146";
}
];
};
routeHost =
lib.nixosSystem {
system = "x86_64-linux";
specialArgs.my = self.lib;
modules = [
./modules/reverse-proxy.nix
{
modules.reverse-proxy.routes.app = {
host = "worker.alexion.dev";
endpoint = "worker";
port = 8080;
};
}
];
};
guestRouteHost =
lib.nixosSystem {
system = "x86_64-linux";
specialArgs.my = self.lib;
modules = [
inputs.sops-nix.nixosModules.sops
./modules/network.nix
./modules/reverse-proxy.nix
(self.lib.guest { name = "files"; })
{
networking.hostName = "pikachu";
modules.network.vlans = [ 20 ];
guests.files = {
enable = true;
vlan = 20;
endpoint.address = "10.23.20.126";
reverseProxy = {
enable = true;
host = "files.alexion.dev";
port = 3923;
};
};
}
];
};
endpoints = self.lib.networkEndpoints.collectFleetEndpoints {
worker = endpointHost;
pikachu = guestRouteHost;
};
fleetRoutes = self.lib.reverseProxyRoutes.collectFleetRoutes {
inherit routeHost;
pikachu = guestRouteHost;
} endpoints;
testConfig =
(lib.nixosSystem {
system = "x86_64-linux";
specialArgs.my = self.lib;
modules = [
./modules/reverse-proxy.nix
{
modules.reverse-proxy = {
enable = true;
routes = fleetRoutes;
};
}
];
}).config;
vhosts = testConfig.services.nginx.virtualHosts;
in
pkgs.runCommand "reverse-proxy-endpoint-backends-check" { } ''
${
lib.optionalString (
!(
vhosts."worker.alexion.dev".locations."/".proxyPass == "http://10.23.50.146:8080"
&& fleetRoutes."pikachu-files".endpoint == "pikachu-files"
&& vhosts."files.alexion.dev".locations."/".proxyPass == "http://10.23.20.126:3923"
)
) "exit 1"
}
touch $out
'';
reverse-proxy-secondary-path-requires-root =
let
testConfig =
(lib.nixosSystem {
system = "x86_64-linux";
specialArgs.my = self.lib;
modules = [
./modules/reverse-proxy.nix
{
modules.reverse-proxy = {
enable = true;
routes.raichu-files = {
host = "files.alexion.dev";
path = "/raichu";
backend = "http://10.23.20.10:3923";
};
};
}
];
}).config;
hasFailedRootAssertion = lib.any (
assertion:
assertion.assertion == false
&& assertion.message == "modules.reverse-proxy.routes for files.alexion.dev must include a primary / route."
) testConfig.assertions;
in
pkgs.runCommand "reverse-proxy-secondary-path-requires-root-check" { } ''
${lib.optionalString (!hasFailedRootAssertion) "exit 1"}
touch $out
'';
};
}; };
} }

53
flake/default.nix Normal file
View File

@@ -0,0 +1,53 @@
{
lib,
inputs,
self,
}:
let
util = import ../lib { inherit lib; };
registry = import ./registry.nix {
inherit lib;
hosts = self.nixosConfigurations;
root = self + "/registry";
};
modules = import ./module.nix {
inherit util;
root = self + "/modules";
};
guestModules = import ./guest.nix {
inherit
inputs
lib
registry
specialArgs
util
;
repositoryModules = modules;
root = self + "/guests";
};
specialArgs = {
inherit
inputs
self
util
;
registry = registry.collected;
};
in
{
nixosConfigurations = import ./host.nix {
inherit
inputs
lib
specialArgs
guestModules
;
registryModule = registry.module;
repositoryModules = modules;
root = self + "/hosts";
};
}

279
flake/guest.nix Normal file
View File

@@ -0,0 +1,279 @@
{
inputs,
lib,
root,
specialArgs,
repositoryModules,
registry,
util,
}:
let
mkGuest =
name:
{ config, lib, ... }:
let
cfg = config.guests.${name};
directoryMounts = lib.filterAttrs (_: mount: mount.directory != null) cfg.mounts;
directoryScript = lib.concatStringsSep "\n" (
lib.mapAttrsToList (
_: mount:
''
${config.system.path}/bin/install -d \
${lib.optionalString (mount.owner != null) "-o ${lib.escapeShellArg (toString mount.owner)}"} \
${lib.optionalString (mount.group != null) "-g ${lib.escapeShellArg mount.group}"} \
${lib.optionalString (mount.mode != null) "-m ${lib.escapeShellArg mount.mode}"} \
${lib.escapeShellArg mount.directory}
''
) directoryMounts
);
in
{
options.guests.${name} = {
enable = lib.mkEnableOption "the ${name} guest, run in its own nested container";
vlan = lib.mkOption {
type = lib.types.ints.between 1 4094;
example = 10;
description = ''
The tagged VLAN this guest lives on. The guest attaches to its host's
`br-vlan<id>` bridge for that VLAN. The id must be one of the host's
`modules.network.vlans.ids`.
'';
};
mac = lib.mkOption {
type = lib.types.str;
default = util.deriveMac "${config.networking.hostName}.${name}";
defaultText = lib.literalMD "a stable address derived from the host name and guest option path";
example = "bc:24:11:00:00:01";
description = ''
The guest's MAC address on its VLAN, pinned inside the guest by its
own networkd. Set it to reuse an existing address so a router's DHCP
reservation keeps working. Left unset, a stable address is derived
from the host name and guest option path in the locally-administered range.
'';
};
address = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "10.23.20.126";
description = ''
Expected IP address assigned outside NixOS for this guest.
Left null, this guest contributes no address to the address registry.
'';
};
reverseProxy = {
enable = lib.mkEnableOption "a reverse-proxy route for this guest";
route = lib.mkOption {
type = registry.types.route;
description = "Route registry entry published for this guest.";
};
};
mounts = lib.mkOption {
type = lib.types.attrsOf (
lib.types.submodule {
options = {
directory = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "/srv/media";
description = "Host directory bind-mounted into the guest.";
};
file = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "/run/secrets/service-password";
description = "Host file bind-mounted into the guest.";
};
readOnly = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Mount the host path read-only inside the guest.";
};
owner = lib.mkOption {
type = lib.types.nullOr (
lib.types.oneOf [
lib.types.str
lib.types.ints.positive
]
);
default = null;
description = "Owner assigned to the host directory before the guest starts.";
};
group = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = "Group assigned to the host directory before the guest starts.";
};
mode = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "0770";
description = "Mode assigned to the host directory before the guest starts.";
};
};
}
);
default = { };
example = lib.literalExpression ''
{
"/data/media" = { directory = "/srv/media"; };
"/data/config" = { directory = "/srv/config/jellyfin"; };
}
'';
description = ''
Host paths bind-mounted into the guest, keyed by the path they appear
at inside the guest, so a guest sees exactly the data it should at any
granularity — a single folder, a whole pool, or a decrypted secret.
Mounts are read-write unless `readOnly` is set.
'';
};
interior = lib.mkOption {
type = lib.types.deferredModule;
default = { };
description = "NixOS module imported into the guest interior.";
};
limits = {
memory = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "2G";
description = ''
Cap on the guest's memory, applied to its unit as `MemoryMax`.
Accepts systemd size suffixes such as `512M` or `2G`. Left null,
the guest's memory is uncapped.
'';
};
cpu = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "150%";
description = ''
Cap on the guest's CPU, applied to its unit as `CPUQuota`, where
`100%` is one full core. Left null, the guest's CPU is uncapped.
'';
};
tasksMax = lib.mkOption {
type = lib.types.nullOr lib.types.ints.positive;
default = null;
example = 512;
description = ''
Cap on the number of processes and threads the guest may spawn,
applied to its unit as `TasksMax`. Left null, the task count is
uncapped.
'';
};
};
};
config = lib.mkIf cfg.enable {
assertions =
let
hasDirectorySettings = mount: mount.owner != null || mount.group != null || mount.mode != null;
hasCompleteDirectorySettings = mount: mount.owner != null && mount.group != null && mount.mode != null;
hasOneSource = mount: (mount.directory != null) != (mount.file != null);
mountsWithInvalidSource = lib.attrNames (lib.filterAttrs (_: mount: !hasOneSource mount) cfg.mounts);
fileMountsWithHostSettings = lib.attrNames (
lib.filterAttrs (_: mount: mount.file != null && hasDirectorySettings mount) cfg.mounts
);
directoryMountsWithPartialHostSettings = lib.attrNames (
lib.filterAttrs (_: mount: mount.directory != null && hasDirectorySettings mount && !hasCompleteDirectorySettings mount) cfg.mounts
);
in
[
{
assertion = mountsWithInvalidSource == [ ];
message = ''
guests.${name} mounts ${lib.concatStringsSep ", " mountsWithInvalidSource} must set exactly one of `directory` or `file`.
'';
}
{
assertion = fileMountsWithHostSettings == [ ];
message = ''
guests.${name} file mounts ${lib.concatStringsSep ", " fileMountsWithHostSettings} must not set `owner`, `group`, or `mode`.
'';
}
{
assertion = directoryMountsWithPartialHostSettings == [ ];
message = ''
guests.${name} directory mounts ${lib.concatStringsSep ", " directoryMountsWithPartialHostSettings} must set `owner`, `group`, and `mode` together.
'';
}
{
assertion = lib.elem cfg.vlan config.modules.network.vlans.ids;
message = ''
guests.${name}.vlan = ${toString cfg.vlan} is not among its host's modules.network.vlans.ids (${lib.concatMapStringsSep ", " toString config.modules.network.vlans.ids}). Declare the VLAN on the host or correct the guest's placement.
'';
}
];
registry.address.${config.networking.hostName}.${name} =
lib.mkIf (cfg.address != null) cfg.address;
registry.route.${config.networking.hostName}.${name} =
lib.mkIf cfg.reverseProxy.enable cfg.reverseProxy.route;
systemd.services."container@${name}" =
let
bridgeDevice = "sys-subsystem-net-devices-${lib.replaceStrings [ "-" ] [ "\\x2d" ] (util.bridgeName cfg.vlan)}.device";
in
{
after = [ bridgeDevice ];
wants = [ bridgeDevice ];
serviceConfig = lib.filterAttrs (_: v: v != null) {
MemoryMax = cfg.limits.memory;
CPUQuota = cfg.limits.cpu;
TasksMax = cfg.limits.tasksMax;
};
preStart = lib.mkIf (directoryMounts != { }) directoryScript;
};
containers.${name} = {
autoStart = true;
privateNetwork = lib.mkDefault true;
hostBridge = util.bridgeName cfg.vlan;
privateUsers = lib.mkDefault "no";
bindMounts = lib.mapAttrs (_: mount: {
hostPath = if mount.directory != null then mount.directory else mount.file;
isReadOnly = mount.readOnly;
}) cfg.mounts;
inherit specialArgs;
config = {
imports = [
inputs.sops-nix.nixosModules.sops
inputs.stylix.nixosModules.stylix
repositoryModules
registry.module
cfg.interior
{
modules.guest.enable = true;
networking.useNetworkd = true;
networking.useHostResolvConf = false;
systemd.network.networks."20-eth0" = {
matchConfig.Name = "eth0";
linkConfig.MACAddress = cfg.mac;
networkConfig.DHCP = "yes";
};
}
];
};
};
};
};
in
let
files = util.collectNixFiles root;
guestFiles = lib.filterAttrs (file: type: type == "regular" && lib.hasSuffix ".nix" file) (builtins.readDir root);
names = map (file: lib.removeSuffix ".nix" file) (lib.attrNames guestFiles);
in
{
imports = files ++ map mkGuest names;
}

45
flake/host.nix Normal file
View File

@@ -0,0 +1,45 @@
{
inputs,
lib,
root,
specialArgs,
repositoryModules,
guestModules,
registryModule,
}:
let
mkHost =
{
root,
name,
}:
lib.nixosSystem {
inherit specialArgs;
modules = [
inputs.chaotic.nixosModules.default
inputs.disko.nixosModules.disko
inputs.sops-nix.nixosModules.sops
inputs.stylix.nixosModules.stylix
repositoryModules
guestModules
# TODO: refactor
registryModule (root + "/${name}")
{
networking.hostName = name;
modules.host.enable = true;
}
];
};
in
let
directories = lib.filterAttrs (_name: type: type == "directory") (builtins.readDir root);
names = lib.attrNames directories;
in
lib.genAttrs names (
name:
mkHost { inherit root name; }
)

7
flake/module.nix Normal file
View File

@@ -0,0 +1,7 @@
{
root,
util,
}:
{
imports = util.collectNixFiles root;
}

197
flake/registry.nix Normal file
View File

@@ -0,0 +1,197 @@
{ hosts, lib, root }:
let
checkType = lib.types.submodule {
options = {
assertion = lib.mkOption {
type = lib.types.functionTo lib.types.bool;
description = ''
Predicate run against this registry's flattened collected entries.
'';
};
message = lib.mkOption {
type = lib.types.str;
description = ''
Error message shown when this registry validation check fails.
'';
};
};
};
predicates = {
uniqueValue = value: entries: builtins.length (lib.unique (map value entries)) == builtins.length entries;
};
registryLib = lib // {
registry = (lib.registry or { }) // {
inherit predicates;
};
};
registryDefinitionModule = {
options = {
type = lib.mkOption {
type = lib.types.raw;
description = ''
NixOS option type for one registry entry.
'';
};
replicate = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Whether collected entries are merged and published under every host key.
'';
};
checks = lib.mkOption {
type = lib.types.listOf checkType;
default = [ ];
description = ''
Validation checks for this registry's flattened collected entries.
'';
};
};
};
registryName = fileName: lib.removeSuffix ".nix" fileName;
registryOption = registry: lib.mkOption {
type = lib.types.attrsOf (lib.types.attrsOf registry.type);
default = { };
description = ''
Lazily collected fleet-visible registry entries, nested by host and entry name.
'';
};
mkRegistry = path:
let
evaluated = lib.evalModules {
specialArgs.lib = registryLib;
modules = [
registryDefinitionModule
path
];
};
in
{
inherit (evaluated.config) type replicate checks;
};
definitions = lib.mapAttrs' (
name: type:
let
path = root + "/${name}";
in
lib.nameValuePair (registryName name) (mkRegistry path)
) (lib.filterAttrs (name: type: type == "regular" && lib.hasSuffix ".nix" name) (builtins.readDir root));
flattenRegistryEntries = registryName: data:
lib.concatLists (
lib.mapAttrsToList (
host: entries:
lib.mapAttrsToList (entry: value: {
path = "registry.${registryName}.${host}.${entry}";
inherit host entry value;
}) entries
) data
);
rawDeclarations = registryName: hosts:
lib.mapAttrs (_hostName: host: host.config.registry.${registryName} or { }) hosts;
replicatedEntries = registryName: raw:
let
entries = lib.concatLists (
lib.concatLists (
lib.mapAttrsToList (
_evalHost: hostDeclarations:
lib.mapAttrsToList (
hostName: declarations:
lib.mapAttrsToList (entryName: value: {
path = "registry.${registryName}.${hostName}.${entryName}";
inherit entryName value;
}) declarations
) hostDeclarations
) raw
)
);
in
lib.foldl' (
acc: entry:
if lib.hasAttr entry.entryName acc then
if acc.${entry.entryName}.value == entry.value then
acc
else
throw "conflicting replicated registry entry ${entry.path} does not match ${acc.${entry.entryName}.path}"
else
acc // {
${entry.entryName} = entry;
}
) { } entries;
replicatedData = registryName: hosts: raw:
let
entries = lib.mapAttrs (_entryName: entry: entry.value) (replicatedEntries registryName raw);
in
lib.mapAttrs (_hostName: _host: entries) hosts;
validationAssertions = data:
lib.concatLists (
lib.mapAttrsToList (
registryName: registry:
let
entries = flattenRegistryEntries registryName data.${registryName};
in
map (check: {
assertion = check.assertion entries;
inherit (check) message;
}) registry.checks
) definitions
);
assertValid = data:
let
assertions = validationAssertions data;
failures = lib.filter (assertion: !assertion.assertion) assertions;
in
assert lib.assertMsg (lib.all (assertion: assertion.assertion) assertions) (
lib.concatMapStringsSep "\n" (assertion: assertion.message) failures
);
data;
join = registry: host: entry:
lib.filterAttrs (_name: value: value != null) (
lib.mapAttrs (registryName: _registry: (registry.${registryName}.${host} or { }).${entry} or null) definitions
);
collectData =
{ hosts }:
let
raw = lib.mapAttrs (registryName: _registry: rawDeclarations registryName hosts) definitions;
data = lib.mapAttrs (
registryName: registry:
if registry.replicate or false then
replicatedData registryName hosts raw.${registryName}
else
lib.mapAttrs (hostName: host: host.config.registry.${registryName}.${hostName} or { }) hosts
) definitions;
in
assertValid data;
withOperations = registry:
registry
// {
join = host: entry: join registry host entry;
};
in
{
types = lib.mapAttrs (_name: definition: definition.type) definitions;
module = {
options.registry = lib.mapAttrs (_name: registry: registryOption registry) definitions;
};
collected = withOperations (collectData { inherit hosts; });
}

View File

@@ -1,31 +0,0 @@
{
my,
inputs,
lib,
...
}:
# The guest-base: the slim foundation every nested guest's interior stands on.
# It imports the full modules tree so any module is available to enable inside a
# guest, and stands on the same shared base a host does.
{
imports = my.collectNixFiles (inputs.self + "/modules") ++ [
(inputs.self + "/base.nix")
# The modules tree reaches for these option namespaces, so they must be
# declared for the tree to evaluate even where a guest leaves them off.
inputs.sops-nix.nixosModules.sops
inputs.stylix.nixosModules.stylix
];
# A nested container has no per-host `default.nix` to pin its release.
system.stateVersion = "26.05";
# The baseline toolset and SSH access, so any guest shelled into is a workable
# environment without per-guest wiring.
modules.toolkit.enable = lib.mkDefault true;
modules.ssh.enable = lib.mkDefault true;
# A guest carries no host identity, so it presents a self-generated host key
# rather than restoring one from secrets.
modules.ssh.hostKeys.restore = lib.mkDefault false;
}

View File

@@ -1,7 +1,6 @@
{ {
config, config,
lib, lib,
my,
... ...
}: }:
let let
@@ -9,18 +8,6 @@ let
dataDir = "/data"; dataDir = "/data";
in in
{ {
imports = [
(my.guest {
name = "actualbudget";
interior = {
modules.services.actualbudget = {
enable = true;
inherit dataDir;
};
};
})
];
options.guests.actualbudget = { options.guests.actualbudget = {
dataPath = lib.mkOption { dataPath = lib.mkOption {
type = lib.types.nullOr lib.types.str; type = lib.types.nullOr lib.types.str;
@@ -39,7 +26,13 @@ in
]; ];
guests.actualbudget = { guests.actualbudget = {
mounts.${dataDir}.hostPath = cfg.dataPath; interior = {
modules.services.actualbudget = {
enable = true;
inherit dataDir;
};
};
mounts.${dataDir}.directory = cfg.dataPath;
limits = { limits = {
memory = lib.mkDefault "2G"; memory = lib.mkDefault "2G";
cpu = lib.mkDefault "200%"; cpu = lib.mkDefault "200%";

View File

@@ -1,12 +1,10 @@
{ {
config, config,
lib, lib,
my,
... ...
}: }:
let let
cfg = config.guests.copyparty; cfg = config.guests.copyparty;
serviceUid = my.serviceUid "copyparty";
volumeType = lib.types.submodule { volumeType = lib.types.submodule {
options = { options = {
@@ -35,26 +33,6 @@ let
}; };
in in
{ {
imports = [
(my.guest {
name = "copyparty";
interior = {
modules.services.copyparty = {
enable = true;
inherit (cfg) accountName stateDir;
passwordFile = "/run/secrets/${cfg.passwordSecret}";
reverseProxy = {
enable = cfg.reverseProxy.enable;
inherit (cfg.reverseProxy) trustedSources;
};
volumes = lib.mapAttrs (_urlPath: volume: {
inherit (volume) path access flags;
}) cfg.volumes;
};
};
})
];
options.guests.copyparty = { options.guests.copyparty = {
accountName = lib.mkOption { accountName = lib.mkOption {
type = lib.types.str; type = lib.types.str;
@@ -107,19 +85,33 @@ in
]; ];
guests.copyparty = { guests.copyparty = {
secrets = [ cfg.passwordSecret ]; interior.modules.services.copyparty = {
enable = true;
inherit (cfg) accountName stateDir;
passwordFile = "/run/secrets/${cfg.passwordSecret}";
reverseProxy = {
enable = cfg.reverseProxy.enable;
inherit (cfg.reverseProxy) trustedSources;
};
volumes = lib.mapAttrs (_urlPath: volume: {
inherit (volume) path access flags;
}) cfg.volumes;
};
mounts = mounts =
{ {
${cfg.stateDir} = { ${cfg.stateDir} = {
hostPath = cfg.statePath; directory = cfg.statePath;
create = { owner = config.registry."stable-uid".${config.networking.hostName}.copyparty;
owner = serviceUid; group = "storage";
group = "storage"; mode = "0770";
mode = "0770"; };
}; ${"/run/secrets/${cfg.passwordSecret}"} = {
file = config.sops.secrets.${cfg.passwordSecret}.path;
readOnly = true;
}; };
} }
// lib.mapAttrs' (_urlPath: volume: lib.nameValuePair volume.path { inherit (volume) hostPath; }) cfg.volumes; // lib.mapAttrs' (_urlPath: volume: lib.nameValuePair volume.path { directory = volume.hostPath; }) cfg.volumes;
limits = { limits = {
memory = lib.mkDefault "2G"; memory = lib.mkDefault "2G";
cpu = lib.mkDefault "200%"; cpu = lib.mkDefault "200%";

View File

@@ -1,11 +0,0 @@
args@{ my, ... }:
# A sample guest whose interior runs an OCI container on Podman.
# The image is pulled at runtime, so the guest builds with no build-time fetch.
my.guest {
name = "nesting-sample";
interior = {
virtualisation.oci-containers.containers.hello = {
image = "docker.io/library/hello-world";
};
};
} args

View File

@@ -1,41 +1,58 @@
{ {
config, config,
lib, lib,
my,
reverseProxyFleetRoutes ? config.modules.reverse-proxy.routes,
... ...
}: }:
let let
giteaSshBackend = "10.23.20.45:2022"; giteaSshBackend = "10.23.20.45:2022";
legacyBackend = "http://10.23.20.32";
legacyHosts = [
"games.alexion.dev"
"git.alexion.dev"
"music.alexion.dev"
"photos.alexion.dev"
"plex.alexion.dev"
"servers.alexion.dev"
"todo.alexion.dev"
"wings.alexion.dev"
];
legacyRoutes = lib.listToAttrs (
map (host: {
name = "legacy-${lib.replaceStrings [ "." ] [ "-" ] host}";
value = {
inherit host;
backend = legacyBackend;
};
}) legacyHosts
);
in in
{ {
imports = [ config = lib.mkIf config.guests.reverse-proxy.enable {
(my.guest { guests.reverse-proxy = {
name = "reverse-proxy";
interior = { interior = {
modules.reverse-proxy = { modules.services.reverse-proxy.enable = true;
enable = true;
routes = reverseProxyFleetRoutes // legacyRoutes; services.nginx.virtualHosts = {
"games.alexion.dev" = {
forceSSL = true;
enableACME = true;
locations."/".proxyPass = "http://10.23.20.32";
};
"git.alexion.dev" = {
forceSSL = true;
enableACME = true;
locations."/".proxyPass = "http://10.23.20.32";
};
"music.alexion.dev" = {
forceSSL = true;
enableACME = true;
locations."/".proxyPass = "http://10.23.20.32";
};
"photos.alexion.dev" = {
forceSSL = true;
enableACME = true;
locations."/".proxyPass = "http://10.23.20.32";
};
"plex.alexion.dev" = {
forceSSL = true;
enableACME = true;
locations."/".proxyPass = "http://10.23.20.32";
};
"servers.alexion.dev" = {
forceSSL = true;
enableACME = true;
locations."/".proxyPass = "http://10.23.20.32";
};
"todo.alexion.dev" = {
forceSSL = true;
enableACME = true;
locations."/".proxyPass = "http://10.23.20.32";
};
"wings.alexion.dev" = {
forceSSL = true;
enableACME = true;
locations."/".proxyPass = "http://10.23.20.32";
};
}; };
networking.firewall.allowedTCPPorts = [ 2022 ]; networking.firewall.allowedTCPPorts = [ 2022 ];
@@ -47,11 +64,7 @@ in
} }
''; '';
}; };
})
];
config = lib.mkIf config.guests.reverse-proxy.enable {
guests.reverse-proxy = {
limits = { limits = {
memory = lib.mkDefault "1G"; memory = lib.mkDefault "1G";
cpu = lib.mkDefault "100%"; cpu = lib.mkDefault "100%";

View File

@@ -1,5 +0,0 @@
args@{ my, ... }:
# The tracer-bullet guest: the thinnest complete path from discovery to a
# running nested container. Its interior is just the guest-base — the baseline
# toolset and SSH access — so it proves the concept without carrying a service.
my.guest { name = "sample"; } args

View File

@@ -31,45 +31,22 @@
# So wifi can be joined from the console. # So wifi can be joined from the console.
networking.networkmanager.enable = true; networking.networkmanager.enable = true;
registry.address.neogaia.self = "10.23.50.146";
# So setup can be driven over the network. # So setup can be driven over the network.
# The matching host public keys sit beside this file in plaintext, since # The matching host public keys sit beside this file in plaintext, since
# publishing them is their purpose. # publishing them is their purpose.
modules.ssh.enable = true; modules.network.ssh.enable = true;
modules.ssh.hostKeys.sopsFile = ../../secrets/neogaia.yaml; modules.network.ssh.hostKeys.sopsFile = ../../secrets/neogaia.yaml;
modules.ssh.userKey.sopsFile = ../../secrets/neogaia.yaml; modules.network.ssh.userKey.sopsFile = ../../secrets/neogaia.yaml;
modules.toolkit.enable = true; modules.shell.herdr.enable = true;
# The walking-skeleton guest, enabled like any module: proves the guest path
# end to end through this host's `nix flake check`.
# Modest caps keep the skeleton guest from starving the laptop.
guests.sample.enable = true;
guests.sample.limits = {
memory = "1G";
cpu = "100%";
tasksMax = 512;
};
# The nesting guest, run with `nesting` on: proves an interior OCI container
# on Podman builds end to end through this host's `nix flake check`.
guests.nesting-sample.enable = true;
guests.nesting-sample.nesting = true;
guests.nesting-sample.limits = {
memory = "1G";
cpu = "100%";
tasksMax = 512;
};
modules.agents.claude-code.enable = true;
modules.agents.herdr.enable = true;
modules.agents.tools.gitea-axi.enable = true; modules.agents.tools.gitea-axi.enable = true;
modules.agents.pi.enable = true; modules.agents.pi.enable = true;
modules.agents.pi.subagents.maxConcurrent = 8;
modules.agents.pi.subagents.recentTerminalTtlMs = 15 * 60 * 1000;
modules.desktop.enable = true; modules.desktop.enable = true;
modules.desktop.obsidian.enable = true; modules.desktop.apps.obsidian.enable = true;
modules.desktop.steam.enable = true; modules.desktop.apps.steam.enable = true;
time.timeZone = "America/New_York"; time.timeZone = "America/New_York";
i18n.defaultLocale = "en_GB.UTF-8"; i18n.defaultLocale = "en_GB.UTF-8";

View File

@@ -1,4 +1,9 @@
{ config, pkgs, ... }: {
config,
pkgs,
registry,
...
}:
# pikachu — AZW ME Pro server. # pikachu — AZW ME Pro server.
# Disk layout is in ./disk.nix. # Disk layout is in ./disk.nix.
# `fileSystems` for the root disk are derived from it. # `fileSystems` for the root disk are derived from it.
@@ -57,7 +62,7 @@
}; };
networking.useDHCP = false; networking.useDHCP = false;
modules.network.vlans = [ 20 ]; modules.network.vlans.ids = [ 20 ];
boot.zfs.forceImportRoot = false; boot.zfs.forceImportRoot = false;
@@ -67,23 +72,24 @@
pools.pikachu = { }; pools.pikachu = { };
}; };
modules.ssh.enable = true; registry.address.pikachu.self = "10.23.10.102";
modules.ssh.hostKeys.sopsFile = ../../secrets/pikachu.yaml;
modules.ssh.userKey.sopsFile = ../../secrets/pikachu.yaml;
modules.git.enable = true; modules.network.ssh.enable = true;
modules.toolkit.enable = true; modules.network.ssh.hostKeys.sopsFile = ../../secrets/pikachu.yaml;
modules.network.ssh.userKey.sopsFile = ../../secrets/pikachu.yaml;
guests.actualbudget = { guests.actualbudget = {
enable = true; enable = true;
vlan = 20; vlan = 20;
mac = "BC:24:11:C1:CD:28"; mac = "BC:24:11:C1:CD:28";
dataPath = "/pikachu/data/actualbudget"; dataPath = "/pikachu/data/actualbudget";
endpoint.address = "10.23.20.42"; address = "10.23.20.42";
reverseProxy = { reverseProxy = {
enable = true; enable = true;
host = "budget.alexion.dev"; route = {
port = 5006; domain = "budget.alexion.dev";
port = 5006;
};
}; };
}; };
@@ -91,7 +97,7 @@
enable = true; enable = true;
vlan = 20; vlan = 20;
mac = "02:98:64:5a:07:4f"; mac = "02:98:64:5a:07:4f";
endpoint.address = "10.23.20.109"; address = "10.23.20.109";
}; };
guests.copyparty = { guests.copyparty = {
@@ -99,12 +105,14 @@
vlan = 20; vlan = 20;
mac = "02:23:20:39:23:01"; mac = "02:23:20:39:23:01";
statePath = "/pikachu/data/copyparty"; statePath = "/pikachu/data/copyparty";
endpoint.address = "10.23.20.126"; address = "10.23.20.126";
reverseProxy = { reverseProxy = {
enable = true; enable = true;
host = "files.alexion.dev"; route = {
port = 3923; domain = "files.alexion.dev";
trustedSources = [ "${config.modules.network.endpoints."reverse-proxy".address}/32" ]; port = 3923;
};
trustedSources = [ "${registry.address.${config.networking.hostName}."reverse-proxy"}/32" ];
}; };
volumes = { volumes = {
"/inbox" = { "/inbox" = {

View File

@@ -1,109 +1,9 @@
{ { lib }:
lib,
inputs,
self,
}:
let let
inherit (lib) files = import ./files.nix { inherit lib; };
attrNames network = import ./network.nix { inherit lib; };
filterAttrs
genAttrs
flatten
hasSuffix
mapAttrsToList
;
serviceIdentityRegistry = import ./service-identities.nix { inherit lib; };
registryLib = import ./registry.nix { inherit lib; };
registry = registryLib.load {
dir = self + "/registry";
args = { inherit lib; };
};
networkEndpoints = import ./network-endpoints.nix { inherit lib; };
reverseProxyRoutes = import ./reverse-proxy-routes.nix { inherit lib; };
collectNixFiles =
dir:
flatten (
mapAttrsToList (
name: type:
let
path = dir + "/${name}";
in
if type == "directory" then
collectNixFiles path
else if type == "regular" && hasSuffix ".nix" name then
[ path ]
else
[ ]
) (builtins.readDir dir)
);
specialArgs =
let
networkFleetEndpoints = self.lib.networkEndpoints.collectFleetEndpoints self.nixosConfigurations;
in
{
inherit inputs networkFleetEndpoints self;
my = self.lib;
registry = self.lib.registry.collect { hosts = self.nixosConfigurations; };
reverseProxyFleetRoutes = self.lib.reverseProxyRoutes.collectFleetRoutes self.nixosConfigurations networkFleetEndpoints;
};
bridgeName = id: "br-vlan${toString id}";
guests = import ./guests.nix {
inherit
lib
self
specialArgs
bridgeName
reverseProxyRoutes
;
};
mkHost =
{
hostName,
system ? "x86_64-linux",
}:
inputs.nixpkgs.lib.nixosSystem {
inherit system specialArgs;
modules =
(collectNixFiles (self + "/modules"))
++ (collectNixFiles (self + "/guests"))
++ [
inputs.chaotic.nixosModules.default
inputs.disko.nixosModules.disko
inputs.sops-nix.nixosModules.sops
inputs.stylix.nixosModules.stylix
registry.module
(self + "/system.nix")
(self + "/hosts/${hostName}")
{ networking.hostName = hostName; }
];
};
mkHosts =
hostsDir:
let
hostNames = attrNames (filterAttrs (_name: type: type == "directory") (builtins.readDir hostsDir));
in
genAttrs hostNames (hostName: mkHost { inherit hostName; });
in in
{ {
inherit inherit (files) collectNixFiles;
collectNixFiles inherit (network) bridgeName deriveMac;
mkHost
mkHosts
bridgeName
registry
networkEndpoints
reverseProxyRoutes
;
inherit (guests) deriveMac guest;
inherit (serviceIdentityRegistry) serviceUid;
serviceIdentities = serviceIdentityRegistry.identities;
} }

22
lib/files.nix Normal file
View File

@@ -0,0 +1,22 @@
{ lib }:
let
collectNixFiles =
dir:
lib.flatten (
lib.mapAttrsToList (
name: type:
let
path = dir + "/${name}";
in
if type == "directory" then
collectNixFiles path
else if type == "regular" && lib.hasSuffix ".nix" name then
[ path ]
else
[ ]
) (builtins.readDir dir)
);
in
{
inherit collectNixFiles;
}

View File

@@ -1,379 +0,0 @@
{
lib,
self,
specialArgs,
bridgeName,
reverseProxyRoutes,
}:
let
inherit (lib) escapeShellArg mapAttrsToList;
deriveMac =
name:
let
hash = builtins.hashString "sha256" name;
octet = i: builtins.substring (i * 2) 2 hash;
in
lib.concatStringsSep ":" ([ "02" ] ++ map octet [ 0 1 2 3 4 ]);
guest =
{
name,
interior ? { },
}:
{ config, lib, ... }:
let
optionPath = [ "guests" ] ++ lib.splitString "." name;
cfg = lib.getAttrFromPath optionPath config;
machineName = lib.replaceStrings [ "." ] [ "-" ] name;
networked = cfg.vlan != null;
userMounts = lib.mapAttrs (_guestPath: m: {
inherit (m) hostPath;
isReadOnly = m.readOnly;
}) cfg.mounts;
secretMounts = lib.listToAttrs (
map (
name:
let
path = config.sops.secrets.${name}.path;
in
lib.nameValuePair path {
hostPath = path;
isReadOnly = true;
}
) cfg.secrets
);
mountCollisions = lib.attrNames (builtins.intersectAttrs userMounts secretMounts);
limitConfig = lib.filterAttrs (_: v: v != null) {
MemoryMax = cfg.limits.memory;
CPUQuota = cfg.limits.cpu;
TasksMax = cfg.limits.tasksMax;
};
createdMounts = lib.filterAttrs (_guestPath: m: m.create != null) cfg.mounts;
mountCreateScript = lib.concatStringsSep "\n" (
mapAttrsToList (
_guestPath: m:
let
create = m.create;
in
''
${config.system.path}/bin/install -d -o ${escapeShellArg (toString create.owner)} -g ${escapeShellArg create.group} -m ${escapeShellArg create.mode} ${escapeShellArg m.hostPath}
''
) createdMounts
);
guestNet =
{ lib, ... }:
{
config = lib.mkIf networked {
networking.useNetworkd = true;
networking.useHostResolvConf = false;
systemd.network.networks."20-eth0" = {
matchConfig.Name = "eth0";
linkConfig.MACAddress = cfg.mac;
networkConfig = lib.mkIf (cfg.address == null) { DHCP = "yes"; };
address = lib.mkIf (cfg.address != null) [ cfg.address ];
};
};
};
in
{
options = lib.setAttrByPath optionPath {
enable = lib.mkEnableOption "the ${name} guest, run in its own nested container";
backend = lib.mkOption {
type = lib.types.enum [
"container"
"microvm"
];
default = "container";
description = ''
How the guest is realized. `container` runs the guest as a
systemd-nspawn nested container. `microvm` is reserved for a future
hard-isolation backend and is not built yet.
'';
};
vlan = lib.mkOption {
type = lib.types.nullOr (lib.types.ints.between 1 4094);
default = null;
example = 10;
description = ''
The tagged VLAN this guest lives on. The guest attaches to its host's
`br-vlan<id>` bridge for that VLAN. Left null, the guest keeps a
private network with no bridge attachment. The id must be one of the
host's `modules.network.vlans`.
'';
};
mac = lib.mkOption {
type = lib.types.str;
default = deriveMac name;
defaultText = lib.literalMD "a stable address derived from the guest's namespace path";
example = "bc:24:11:00:00:01";
description = ''
The guest's MAC address on its VLAN, pinned inside the guest by its
own networkd. Set it to reuse an existing address so a router's DHCP
reservation keeps working. Left unset, a stable address is derived
from the guest's namespace path in the locally-administered range.
'';
};
address = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "10.0.10.5/24";
description = ''
The guest's static address, in CIDR form, on its VLAN. Left null, the
guest takes its address by DHCP, keeping IP management at the router.
'';
};
endpoint = {
address = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "10.23.20.126";
description = ''
Expected IP address assigned outside NixOS for this guest's
network endpoint. Left null, this guest contributes no endpoint to
the fleet endpoint registry.
'';
};
};
reverseProxy = reverseProxyRoutes.mkRouteOptions {
subject = "guest route";
enableDefault = false;
};
mounts = lib.mkOption {
type = lib.types.attrsOf (
lib.types.submodule {
options = {
hostPath = lib.mkOption {
type = lib.types.str;
example = "/srv/media";
description = "The path on the host bind-mounted into the guest.";
};
readOnly = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Mount the path read-only. Read-write by default, since a
service must write to the pool data it owns.
'';
};
create = lib.mkOption {
type = lib.types.nullOr (lib.types.submodule {
options = {
type = lib.mkOption {
type = lib.types.enum [ "directory" ];
default = "directory";
description = "Host path type to create before the guest starts.";
};
owner = lib.mkOption {
type = lib.types.oneOf [
lib.types.str
lib.types.ints.positive
];
description = "Owner assigned to the created host path.";
};
group = lib.mkOption {
type = lib.types.str;
description = "Group assigned to the created host path.";
};
mode = lib.mkOption {
type = lib.types.str;
example = "0770";
description = "Mode assigned to the created host path.";
};
};
});
default = null;
description = ''
Opt-in host path creation before the guest starts. Existing
paths are left enabled unless this is set, so served storage
roots can still be required to exist explicitly.
'';
};
};
}
);
default = { };
example = lib.literalExpression ''
{
"/data/media" = { hostPath = "/srv/media"; };
"/data/config" = {
hostPath = "/srv/config/jellyfin";
readOnly = true;
};
}
'';
description = ''
Host paths bind-mounted into the guest, keyed by the path they appear
at inside the guest, so a guest sees exactly the data it should at any
granularity — a single folder or a whole pool. Each mount is
read-write unless `readOnly` is set.
'';
};
secrets = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
example = [ "jellyfin-api-key" ];
description = ''
Names of the secrets this guest needs. The host is the sole
decryptor: it decrypts each named secret from its own sops files and
bind-mounts the plaintext file into the guest read-only at
`/run/secrets/<name>`, the same path it would occupy on a host, so a
service reads its credentials at a predictable location. The guest
names the files it wants and receives exactly those. It holds no age
key and decrypts nothing itself. Ownership carries across unchanged,
since the container maps ids one to one, so a secret owned by a uid on
the host is owned by that same uid inside the guest.
'';
};
limits = {
memory = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "2G";
description = ''
Cap on the guest's memory, applied to its unit as `MemoryMax`.
Accepts systemd size suffixes such as `512M` or `2G`. Left null,
the guest's memory is uncapped.
'';
};
cpu = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "150%";
description = ''
Cap on the guest's CPU, applied to its unit as `CPUQuota`, where
`100%` is one full core. Left null, the guest's CPU is uncapped.
'';
};
tasksMax = lib.mkOption {
type = lib.types.nullOr lib.types.ints.positive;
default = null;
example = 512;
description = ''
Cap on the number of processes and threads the guest may spawn,
applied to its unit as `TasksMax`. Left null, the task count is
uncapped.
'';
};
};
nesting = lib.mkOption {
type = lib.types.bool;
default = false;
description = ''
Grant the guest's interior the prerequisites to run Podman or other
OCI containers of its own. Off by default, so a guest cannot nest
containers. On, the guest's container gains the network-administration
capability its container runtime uses to build bridges and firewall
rules, along with the tun and fuse device nodes such a runtime reaches
for, so the interior's `virtualisation.oci-containers` works with
Podman as its default runtime.
'';
};
autoStart = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Start the guest at boot. On by default. Disabled, the guest stays
defined and can be started on demand, but does not come up at boot.
'';
};
};
config = lib.mkIf cfg.enable {
sops.secrets = lib.genAttrs cfg.secrets (_: { });
modules.network.endpoints.${machineName} = lib.mkIf (cfg.endpoint.address != null) {
inherit (cfg.endpoint) address;
};
modules.reverse-proxy.routes.${machineName} = lib.mkIf cfg.reverseProxy.enable (
reverseProxyRoutes.routeFields (
cfg.reverseProxy
// lib.optionalAttrs (cfg.reverseProxy.backend == null && cfg.reverseProxy.endpoint == null) {
endpoint = "${config.networking.hostName}-${machineName}";
}
)
);
assertions = [
{
assertion = mountCollisions == [ ];
message = ''
guests.${name} maps a mount at ${lib.concatStringsSep ", " mountCollisions}, colliding with a secret bind-mounted at the same path. Rename the mount or the secret so each in-guest path is used once.
'';
}
{
assertion = cfg.backend == "container";
message = ''
guests.${name}.backend = "${cfg.backend}" is not implemented. Only the "container" backend is built; "microvm" is reserved for future work.
'';
}
{
assertion = !networked || lib.elem cfg.vlan config.modules.network.vlans;
message = ''
guests.${name}.vlan = ${toString cfg.vlan} is not among its host's modules.network.vlans (${lib.concatMapStringsSep ", " toString config.modules.network.vlans}). Declare the VLAN on the host or correct the guest's placement.
'';
}
];
systemd.services."container@${machineName}" = lib.mkIf (cfg.backend == "container") (
lib.mkMerge [
{
serviceConfig = limitConfig;
preStart = lib.mkIf (createdMounts != { }) mountCreateScript;
}
(lib.mkIf networked (
let
bridgeDevice = "sys-subsystem-net-devices-${lib.replaceStrings [ "-" ] [ "\\x2d" ] (bridgeName cfg.vlan)}.device";
in
{
after = [ bridgeDevice ];
wants = [ bridgeDevice ];
}
))
]
);
containers.${machineName} = lib.mkIf (cfg.backend == "container") {
autoStart = cfg.autoStart;
privateNetwork = lib.mkDefault true;
hostBridge = lib.mkIf networked (bridgeName cfg.vlan);
privateUsers = lib.mkDefault "no";
additionalCapabilities = lib.optionals cfg.nesting [ "CAP_NET_ADMIN" ];
allowedDevices = lib.optionals cfg.nesting [
{
node = "/dev/net/tun";
modifier = "rwm";
}
{
node = "/dev/fuse";
modifier = "rwm";
}
];
bindMounts = userMounts // secretMounts;
inherit specialArgs;
config = {
imports = [
(self + "/guest.nix")
guestNet
interior
];
};
};
};
};
in
{
inherit deriveMac guest;
}

View File

@@ -1,42 +0,0 @@
{ lib }:
let
endpointOptions = {
address = lib.mkOption {
type = lib.types.str;
example = "10.23.20.126";
description = "Expected IP address assigned outside NixOS for this network endpoint.";
};
};
endpointType = lib.types.submodule {
options = endpointOptions;
};
endpointFields = endpoint: {
inherit (endpoint) address;
};
collectFleetEndpoints =
hosts:
lib.concatMapAttrs (
hostName: host:
let
cfg = host.config.modules.network;
hostEndpoint = lib.optionalAttrs (cfg.endpoint.address != null) {
${hostName} = endpointFields cfg.endpoint;
};
guestEndpoints = lib.mapAttrs' (
endpointName: endpoint: lib.nameValuePair "${hostName}-${endpointName}" (endpointFields endpoint)
) cfg.endpoints;
in
hostEndpoint // guestEndpoints
) hosts;
in
{
inherit
collectFleetEndpoints
endpointFields
endpointOptions
endpointType
;
}

12
lib/network.nix Normal file
View File

@@ -0,0 +1,12 @@
{ lib }:
{
bridgeName = id: "br-vlan${toString id}";
deriveMac =
name:
let
hash = builtins.hashString "sha256" name;
octet = i: builtins.substring (i * 2) 2 hash;
in
lib.concatStringsSep ":" ([ "02" ] ++ map octet [ 0 1 2 3 4 ]);
}

View File

@@ -1,53 +0,0 @@
{ lib }:
let
inherit (lib)
filterAttrs
hasSuffix
mapAttrs
mapAttrs'
mkOption
nameValuePair
removeSuffix
types
;
registryName = fileName: removeSuffix ".nix" fileName;
registryOption = registry: mkOption {
type = types.attrsOf (types.attrsOf registry.type);
default = { };
description = ''
Lazily collected fleet-visible registry entries, nested by host and entry name.
'';
};
in
{
load =
{
dir,
args ? { },
}:
let
definitions = mapAttrs' (
name: type:
let
path = dir + "/${name}";
in
nameValuePair (registryName name) (import path args)
) (filterAttrs (name: type: type == "regular" && hasSuffix ".nix" name) (builtins.readDir dir));
in
{
inherit definitions;
module = {
options.registry = mapAttrs (_name: registry: registryOption registry) definitions;
};
collect =
{ hosts }:
mapAttrs (
registryName: _registry:
mapAttrs (hostName: host: host.config.registry.${registryName}.${hostName} or { }) hosts
) definitions;
};
}

View File

@@ -1,129 +0,0 @@
{ lib }:
let
mkRouteOptions =
{
name ? null,
subject ? "route",
enableDefault ? true,
}:
{
enable = lib.mkOption {
type = lib.types.bool;
default = enableDefault;
description = "Whether this reverse-proxy ${subject} is active.";
};
host = lib.mkOption (
{
type = lib.types.str;
description = "Primary hostname served by this reverse-proxy ${subject}.";
}
// lib.optionalAttrs (name != null) {
default = name;
defaultText = lib.literalMD "the route attribute name";
}
);
aliases = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Additional hostnames served by this reverse-proxy ${subject}.";
};
path = lib.mkOption {
type = lib.types.str;
default = "/";
description = "URL path prefix proxied by this reverse-proxy ${subject}.";
};
backend = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = "Full HTTP backend URL that receives proxied traffic.";
};
endpoint = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = "Fleet network endpoint key used to derive the backend URL.";
};
port = lib.mkOption {
type = lib.types.nullOr (lib.types.ints.between 1 65535);
default = null;
example = 3923;
description = "Backend TCP port used with the fleet network endpoint.";
};
scheme = lib.mkOption {
type = lib.types.str;
default = "http";
description = "Backend URL scheme used with the fleet network endpoint.";
};
tls = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Whether to serve this reverse-proxy ${subject} with ACME-backed TLS.";
};
websockets = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Whether to enable websocket proxy headers for this reverse-proxy ${subject}.";
};
};
routeFields = route: {
inherit (route)
host
aliases
path
backend
endpoint
port
scheme
tls
websockets
;
};
endpointBackend = endpoints: route:
let
endpoint = endpoints.${route.endpoint} or (
throw "Unknown reverse-proxy endpoint `${route.endpoint}`. Known endpoints: ${lib.concatStringsSep ", " (lib.attrNames endpoints)}"
);
in
"${route.scheme}://${endpoint.address}:${toString route.port}";
resolvedRouteFields = endpoints: route:
let
routeWithBackend =
if route.backend != null then
route
else if route.endpoint != null && route.port != null then
route // { backend = endpointBackend endpoints route; }
else
throw "Reverse-proxy route `${route.host}${route.path}` needs either backend or endpoint plus port.";
in
routeFields routeWithBackend;
collectFleetRoutes =
hosts: endpoints:
lib.concatMapAttrs (
hostName: host:
lib.mapAttrs' (
routeName: route: lib.nameValuePair "${hostName}-${routeName}" (resolvedRouteFields endpoints route)
) host.config.modules.reverse-proxy.routes
) hosts;
in
{
inherit collectFleetRoutes mkRouteOptions resolvedRouteFields routeFields;
routeType = lib.types.submodule (
{ name, ... }:
{
options = mkRouteOptions { inherit name; };
}
);
}

View File

@@ -1,59 +0,0 @@
{ lib }:
let
defaultIdentities = {
actualbudget = 20001;
copyparty = 20002;
};
duplicateUidMessage = duplicates: ''
Duplicate stable service UID allocation(s): ${lib.concatStringsSep ", " (
map (entry: "${toString entry.uid} is assigned to ${lib.concatStringsSep ", " entry.names}") duplicates
)}
'';
mk = identities:
let
names = lib.attrNames identities;
namesByUid = lib.foldl' (
acc: name:
let
uid = toString identities.${name};
in
acc // {
${uid} = (acc.${uid} or [ ]) ++ [ name ];
}
) { } names;
duplicates = lib.mapAttrsToList (uid: namesForUid: {
uid = lib.toInt uid;
names = namesForUid;
}) (lib.filterAttrs (_uid: namesForUid: builtins.length namesForUid > 1) namesByUid);
checkedIdentities =
assert lib.assertMsg (duplicates == [ ]) (duplicateUidMessage duplicates);
identities;
in
rec {
inherit checkedIdentities;
serviceUid = name:
if builtins.hasAttr name checkedIdentities then
checkedIdentities.${name}
else
throw "Unknown stable service identity `${name}`. Known identities: ${lib.concatStringsSep ", " (lib.attrNames checkedIdentities)}";
};
default = mk defaultIdentities;
tests = {
actualbudgetUid = default.serviceUid "actualbudget" == 20001;
copypartyUid = default.serviceUid "copyparty" == 20002;
missingLookupFails = !(builtins.tryEval (default.serviceUid "missing-service")).success;
duplicateUidFails = !(builtins.tryEval (mk {
first = 20003;
second = 20003;
}).checkedIdentities).success;
};
in
default // {
identities = default.checkedIdentities;
inherit tests;
}

View File

@@ -13,51 +13,73 @@ These are common instructions for Alexion's agents across all scenarios.
- NEVER ask the user a question using the `AskUserQuestion` tool. - NEVER ask the user a question using the `AskUserQuestion` tool.
Ask in plain prose, in your own message, instead, with no exceptions. Ask in plain prose, in your own message, instead, with no exceptions.
This overrides any default instruction (including harness conventions and skill instructions) to use it. This overrides any default instruction (including harness conventions and skill instructions) to use it.
- Never manually modify CHANGELOG.md files or any files that are marked as auto-generated. - Never manually modify `CHANGELOG.md` files or files marked as auto-generated.
Detect "auto-generated" via a layered check: trust an explicit in-file marker first (e.g. `AUTO-GENERATED, DO NOT EDIT`). Detect auto-generated files with a layered check.
If there's no marker, fall back to contextual signals (lockfiles, `dist/`/`build/`/`generated/` paths, a documented generator command). Trust an explicit in-file marker first, for example `AUTO-GENERATED, DO NOT EDIT`.
If it's still ambiguous, ask before editing rather than guessing. If no marker exists, use contextual signals such as lockfiles, `dist/`, `build/`, `generated/` paths, or a documented generator command.
- When writing or substantially editing long Markdown files, put each full sentence in its own line. If the answer stays ambiguous, ask before editing.
Preserve normal Markdown structure, but avoid wrapping multiple sentences onto one physical line. - In authored prose, do not put multiple sentences on one physical line.
Apply this to any prose you author, regardless of file length; "long" is not a real threshold. This applies to comments, documentation, user-facing descriptions, commit prose, pull-request prose, and forge comments.
Only format what you're actually writing or changing. A sentence can wrap across multiple physical lines when needed.
Never reflow an entire pre-existing paragraph or file just because you touched something nearby. - Keep Markdown formatting changes local.
- When making technical decisions, do not give much weight to development cost. Only format prose you write or change.
Instead, prefer quality, simplicity, robustness, scalability and long term maintainability. Never reflow an entire pre-existing paragraph or file because you touched nearby text.
This is specifically about implementation time. - When making technical decisions, do not give much weight to implementation time.
Human cost/benefit heuristics ("not worth N extra days of engineering") don't transfer to an AI agent that codes far faster than a human. Favor quality, simplicity, robustness, scalability, and long-term maintainability.
This is not a license to override standard anti-overengineering guardrails (avoid premature abstraction, no speculative config, etc.); those still apply to unnecessary complexity. Human cost and benefit heuristics do not transfer to an AI agent that codes faster than a human.
It means: don't discount a more robust or maintainable approach just because it would take a human a long time to build. Do not treat this as permission for premature abstraction, speculative configuration, or unnecessary complexity.
- File names should always be lower case, unless there's a valid reason. Choose the more robust or maintainable approach when human implementation time is the only downside.
Established ecosystem or tool conventions count as a valid reason automatically (e.g. `README.md`, `LICENSE`, `CHANGELOG.md`, `Makefile`, `Dockerfile`, `.github/` files), without needing to ask each time. - Use lowercase file names unless a valid reason requires uppercase.
Established ecosystem or tool conventions count as valid reasons.
Examples include `README.md`, `LICENSE`, `CHANGELOG.md`, `Makefile`, `Dockerfile`, and `.github/` files.
- Do not end a response by promising or implying continuation unless the continuation is present in that same response. - Do not end a response by promising or implying continuation unless the continuation is present in that same response.
If a workflow should continue, perform the next step before ending the turn. Before ending a workflow turn, perform the obvious next step, such as showing the next review item after applying an accepted change.
If the workflow is paused, say that plainly instead of using a dangling transition like "continuing" or "next". If the workflow is paused, say that plainly instead of using a dangling transition like "continuing" or "next".
- When you discover that a belief you held about an objective fact or convention of the current project was wrong, write it down so it isn't relearned next time. - When you discover that your belief about a project fact or convention was wrong, record the correction.
This applies whether the user corrected you or you caught the mistake yourself, and only to things that are true regardless of who is operating the project (a wrong build command, a wrong file path, a convention you guessed at instead of checking) — not personal working-style preferences or one-off task details. Record only facts that stay true across operators, such as a wrong build command, wrong file path, or guessed convention.
Record it in that project's own AGENTS.md, not this global file, under a dedicated `## Gotchas` section (create the section if the file doesn't have one yet). Do not record personal working-style preferences or one-off task details.
If the project has nested AGENTS.md files, use the one nearest to where the mistake occurred, falling back to the project's top-level AGENTS.md. Record the correction in the nearest project `AGENTS.md`, not this global file.
Append to an existing AGENTS.md immediately, without asking; if no AGENTS.md exists yet for the project, ask before creating one. Use a dedicated `## Gotchas` section, and create that section when the file lacks one.
Briefly mention the edit in your response rather than making it silently. If no project `AGENTS.md` exists, ask before creating one.
If an existing entry is later found to be wrong or stale, correct or remove it the same way. Append the correction immediately without asking when a project `AGENTS.md` exists.
Briefly mention the edit in your response.
If an existing entry is wrong or stale, correct or remove it the same way.
## Comments ## Comments
- Write comments only where they earn their place, and keep them concise. - Write comments only where they earn their place.
Assume the reader can read code: comment the "why", not the "what", and explain "what" only when it is genuinely non-obvious. Keep comments concise.
A comment must be self-contained to its file — accurate to a reader looking at that file alone. Assume the reader can read code.
Do not write about history ("used to be X", "now moved here") or future state, about how a value is consumed elsewhere, or to justify the choice against alternatives; state the positive reason a thing exists, keeping any real stakes as a present-tense consequence. Explain why, not what.
The only permitted cross-file mention is a bare pointer explaining why something is *absent* here (e.g. a value another tool derives, which this file therefore does not declare), never narrating what the other file or tool does. Explain what only when it is genuinely non-obvious.
Do not use a project's domain-model or ubiquitous-language capitalized terms as glossary references; describe things in plain language, using ordinary lowercase nouns. - Keep comments self-contained to their file.
Never reference agent-facing state (anything under `.agents/`, `.claude/`, `AGENTS.md`, or `CLAUDE.md`). Write comments for a reader who sees only that file.
A file-top header is one concise purpose line, added only where the filename or path does not already say it — never a feature inventory of the code below. Do not explain how another file or tool consumes a value.
For a placeholder, say so plainly plus any actionable present-tense directive ("Placeholder: regenerate with <tool> on the target machine"), never "placeholder for <missing feature>". The only permitted cross-file mention is a bare pointer explaining why something is absent here.
User-facing documentation strings (an option's `description`, a generated help string) are documentation rather than comments, so they may describe behaviour more fully — but the self-contained rule and the bans on glossary terms and agent-state references still apply. - Do not narrate history or future state in comments.
- Start each sentence of a comment on its own line, as with Markdown prose. Avoid phrases such as "used to be", "now moved here", and "will be".
A sentence needing more than one line is first a prompt to ask whether it should be two sentences. State the present reason a thing exists.
Only when it genuinely cannot be split does it wrap, and then it wraps normally at the right margin. - Do not justify a choice against alternatives in comments.
Never break a line early at a comma or clause boundary to make it read as a unit. State the positive reason the choice exists.
Never use a semicolon, in a comment or in authored prose. Include present consequences when they matter.
Recast as two sentences instead. - Do not reference agent-facing state in comments.
Only reformat comments you are actually writing or changing. This includes `.agents/`, `.claude/`, `AGENTS.md`, and `CLAUDE.md`.
- Do not use project-specific capitalized terms as glossary references in comments.
Use plain lowercase nouns unless the code requires the exact term.
- Add a file-top header only when the filename or path does not already explain the file.
The header must be one concise purpose line.
Do not write a feature inventory.
- Write placeholders plainly.
Include a present-tense action when one exists, such as `Placeholder: regenerate with <tool> on the target machine`.
Do not write `placeholder for <missing feature>`.
- Treat user-facing documentation strings as documentation, not comments.
They can describe behavior more fully than code comments.
They still must stay self-contained and avoid agent-state references.
- Start each sentence of a comment on its own physical line.
A comment sentence can wrap when needed.
Prefer splitting long comment sentences before wrapping them.
Do not break a line early at a comma or clause boundary to make it read as a unit.
Do not use semicolons in comments or authored prose.
Recast semicolon clauses as separate sentences.
Only reformat comments you write or change.

View File

@@ -1,141 +0,0 @@
import { existsSync, readdirSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { basename, join } from "node:path";
import type { ContextMode } from "./types.ts";
import type { Diagnostics } from "./config.ts";
export interface AgentDefinition {
name: string;
description: string;
body: string;
context?: ContextMode;
model?: string;
thinking?: string;
tools?: string;
allowedContexts?: ContextMode[];
hidden?: boolean;
source: string;
}
export function loadAgents(cwd: string, projectTrusted: boolean, diagnostics: Diagnostics, agentDir = defaultAgentDir()): Map<string, AgentDefinition> {
const user = loadTier(join(agentDir, "agents"), "user", diagnostics);
const project = projectTrusted ? loadTier(join(cwd, ".pi", "agents"), "project", diagnostics) : new Map<string, AgentDefinition>();
return new Map([...user, ...project]);
}
function loadTier(dir: string, tier: string, diagnostics: Diagnostics): Map<string, AgentDefinition> {
const agents = new Map<string, AgentDefinition>();
if (!existsSync(dir)) return agents;
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
const path = join(dir, entry.name);
const parsed = parseAgent(path, diagnostics);
if (!parsed) continue;
if (agents.has(parsed.name)) {
diagnostics.warnings.push(`Duplicate ${tier} agent '${parsed.name}' ignored at ${path}`);
continue;
}
const stem = basename(entry.name, ".md");
if (stem !== parsed.name) diagnostics.warnings.push(`${tier} agent file '${entry.name}' name '${parsed.name}' does not match filename`);
agents.set(parsed.name, parsed);
}
return agents;
}
export function parseAgent(path: string, diagnostics: Diagnostics): AgentDefinition | undefined {
try {
const text = readFileSync(path, "utf8");
const match = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/u.exec(text);
if (!match) {
diagnostics.warnings.push(`Agent ${path} missing YAML frontmatter`);
return undefined;
}
const frontmatter = parseFrontmatter(match[1]);
const name = stringField(frontmatter, "name");
const description = stringField(frontmatter, "description");
if (!name || !/^[a-z0-9-]+$/.test(name)) {
diagnostics.warnings.push(`Agent ${path} has invalid name`);
return undefined;
}
if (!description) {
diagnostics.warnings.push(`Agent ${path} has invalid description`);
return undefined;
}
const context = contextField(frontmatter.context);
const allowedContexts = contextsField(frontmatter.allowedContexts);
if (frontmatter.context !== undefined && !context) diagnostics.warnings.push(`Agent ${path} has invalid context`);
if (frontmatter.allowedContexts !== undefined && !allowedContexts) diagnostics.warnings.push(`Agent ${path} has invalid allowedContexts`);
if (context && allowedContexts && !allowedContexts.includes(context)) diagnostics.warnings.push(`Agent ${path} context is outside allowedContexts`);
return {
name,
description,
body: match[2].trim(),
context,
model: stringField(frontmatter, "model"),
thinking: stringField(frontmatter, "thinking"),
tools: stringField(frontmatter, "tools"),
allowedContexts,
hidden: booleanField(frontmatter, "hidden"),
source: path,
};
} catch (error) {
diagnostics.warnings.push(`Failed to load agent ${path}: ${error instanceof Error ? error.message : String(error)}`);
return undefined;
}
}
function parseFrontmatter(text: string): Record<string, unknown> {
const result: Record<string, unknown> = {};
const lines = text.split(/\r?\n/u);
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i];
if (!line.trim() || line.trimStart().startsWith("#")) continue;
const scalar = /^(\w+):\s*(.*?)\s*$/u.exec(line);
if (!scalar) continue;
const [, key, raw] = scalar;
if (raw !== "") {
result[key] = parseScalar(raw);
continue;
}
const values: string[] = [];
while (i + 1 < lines.length) {
const item = /^\s+-\s*(.*?)\s*$/u.exec(lines[i + 1]);
if (!item) break;
values.push(String(parseScalar(item[1])));
i += 1;
}
result[key] = values;
}
return result;
}
function parseScalar(raw: string): string | boolean {
const unquoted = raw.replace(/^['"]|['"]$/gu, "");
if (unquoted === "true") return true;
if (unquoted === "false") return false;
return unquoted;
}
function stringField(record: Record<string, unknown>, key: string): string | undefined {
const value = record[key];
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}
function booleanField(record: Record<string, unknown>, key: string): boolean | undefined {
const value = record[key];
return typeof value === "boolean" ? value : undefined;
}
function contextField(value: unknown): ContextMode | undefined {
return value === "independent" || value === "fork" ? value : undefined;
}
function contextsField(value: unknown): ContextMode[] | undefined {
if (!Array.isArray(value)) return undefined;
const contexts = value.map(contextField);
return contexts.every(Boolean) ? (contexts as ContextMode[]) : undefined;
}
function defaultAgentDir(): string {
return process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
}

View File

@@ -1,139 +0,0 @@
import assert from "node:assert/strict";
import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { loadAgents } from "./agents.ts";
import { BUILT_IN_TOOL_PROFILES, loadConfig, resolveSpawn, type Diagnostics } from "./config.ts";
function fixture() {
const root = mkdtempSync(join(tmpdir(), "subagents-config-"));
const agentDir = join(root, "agent");
const cwd = join(root, "project");
mkdirSync(agentDir, { recursive: true });
mkdirSync(cwd, { recursive: true });
return { root, agentDir, cwd };
}
function diagnostics(): Diagnostics {
return { warnings: [] };
}
test("missing config files and agent directories are normal", () => {
const { cwd, agentDir } = fixture();
const diag = diagnostics();
const config = loadConfig(cwd, true, diag, agentDir);
const agents = loadAgents(cwd, true, diag, agentDir);
assert.equal(config.defaultContext, "independent");
assert.equal(config.defaultTools, "read-only");
assert.equal(config.recentTerminalTtlMs, 300000);
assert.equal(agents.size, 0);
assert.deepEqual(diag.warnings, []);
});
test("global and trusted project config merge in order", () => {
const { cwd, agentDir } = fixture();
mkdirSync(join(cwd, ".pi"), { recursive: true });
writeFileSync(join(agentDir, "subagents.json"), JSON.stringify({ defaultTools: "global-profile", recentTerminalTtlMs: 1000, toolProfiles: { "global-profile": { activeTools: ["read"] } } }));
writeFileSync(join(cwd, ".pi", "subagents.json"), JSON.stringify({ defaultTools: "project-profile", recentTerminalTtlMs: 2000, toolProfiles: { "project-profile": { activeTools: ["ls"] } } }));
const config = loadConfig(cwd, true, diagnostics(), agentDir);
assert.equal(config.defaultTools, "project-profile");
assert.equal(config.recentTerminalTtlMs, 2000);
assert.deepEqual(config.toolProfiles["global-profile"].activeTools, ["read"]);
assert.deepEqual(config.toolProfiles["project-profile"].activeTools, ["ls"]);
});
test("recent terminal ttl preserves zero and rejects invalid values", () => {
const { cwd, agentDir } = fixture();
writeFileSync(join(agentDir, "subagents.json"), JSON.stringify({ recentTerminalTtlMs: 0 }));
const zeroDiag = diagnostics();
const zeroConfig = loadConfig(cwd, true, zeroDiag, agentDir);
assert.equal(zeroConfig.recentTerminalTtlMs, 0);
assert.deepEqual(zeroDiag.warnings, []);
writeFileSync(join(agentDir, "subagents.json"), JSON.stringify({ recentTerminalTtlMs: -1 }));
const invalidDiag = diagnostics();
const invalidConfig = loadConfig(cwd, true, invalidDiag, agentDir);
assert.equal(invalidConfig.recentTerminalTtlMs, 300000);
assert.ok(invalidDiag.warnings.some((warning) => warning.includes("Invalid global recentTerminalTtlMs ignored")));
});
test("project config is ignored when project is untrusted", () => {
const { cwd, agentDir } = fixture();
mkdirSync(join(cwd, ".pi"), { recursive: true });
writeFileSync(join(cwd, ".pi", "subagents.json"), JSON.stringify({ defaultTools: "project-profile", toolProfiles: { "project-profile": { activeTools: ["ls"] } } }));
const config = loadConfig(cwd, false, diagnostics(), agentDir);
assert.equal(config.defaultTools, "read-only");
assert.equal(config.toolProfiles["project-profile"], undefined);
});
test("agents load with project precedence over user", () => {
const { cwd, agentDir } = fixture();
mkdirSync(join(agentDir, "agents"), { recursive: true });
mkdirSync(join(cwd, ".pi", "agents"), { recursive: true });
writeFileSync(join(agentDir, "agents", "review.md"), "---\nname: review\ndescription: User review\ntools: read-only\n---\nuser body\n");
writeFileSync(join(cwd, ".pi", "agents", "review.md"), "---\nname: review\ndescription: Project review\ntools: full-tools\n---\nproject body\n");
const agents = loadAgents(cwd, true, diagnostics(), agentDir);
assert.equal(agents.get("review")?.description, "Project review");
assert.equal(agents.get("review")?.body, "project body");
});
test("duplicate same-tier definitions and invalid frontmatter produce diagnostics", () => {
const { cwd, agentDir } = fixture();
const dir = join(agentDir, "agents");
mkdirSync(dir, { recursive: true });
writeFileSync(join(dir, "one.md"), "---\nname: same\ndescription: One\n---\none\n");
writeFileSync(join(dir, "two.md"), "---\nname: same\ndescription: Two\n---\ntwo\n");
writeFileSync(join(dir, "bad.md"), "---\nname: Bad Name\n---\nbad\n");
const diag = diagnostics();
const agents = loadAgents(cwd, true, diag, agentDir);
assert.equal(agents.size, 1);
assert.ok(diag.warnings.some((warning) => warning.includes("Duplicate user agent 'same'")));
assert.ok(diag.warnings.some((warning) => warning.includes("invalid name")));
});
test("named spawn resolves overrides, frontmatter, config, and defaults", () => {
const { cwd, agentDir } = fixture();
mkdirSync(join(agentDir, "agents"), { recursive: true });
writeFileSync(join(agentDir, "subagents.json"), JSON.stringify({ defaultTools: "local-review", toolProfiles: { "local-review": { activeTools: ["read"] } } }));
writeFileSync(join(agentDir, "agents", "review.md"), "---\nname: review\ndescription: Review\ncontext: independent\nmodel: inherit\nthinking: high\ntools: local-review\n---\nagent body\n");
const diag = diagnostics();
const config = loadConfig(cwd, true, diag, agentDir);
const agents = loadAgents(cwd, true, diag, agentDir);
const resolved = resolveSpawn({ agent: "review", prompt: "check this", label: "Review migration", thinking: "low" }, config, agents);
assert.equal(resolved.prompt, "check this");
assert.equal(resolved.label, "Review migration");
assert.equal(resolved.context, "independent");
assert.equal(resolved.model, "inherit");
assert.equal(resolved.thinking, "low");
assert.equal(resolved.tools, "local-review");
assert.deepEqual(resolved.toolProfile.activeTools, ["read"]);
assert.equal(resolved.agentBody, "agent body");
});
test("built-in tool profile names cannot be overridden", () => {
const { cwd, agentDir } = fixture();
writeFileSync(join(agentDir, "subagents.json"), JSON.stringify({ toolProfiles: { "read-only": { activeTools: ["bash"] } } }));
const diag = diagnostics();
const config = loadConfig(cwd, true, diag, agentDir);
assert.deepEqual(config.toolProfiles["read-only"], BUILT_IN_TOOL_PROFILES["read-only"]);
assert.ok(diag.warnings.some((warning) => warning.includes("Ignoring global override for built-in tool profile 'read-only'")));
});

View File

@@ -1,182 +0,0 @@
import { existsSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import type { ContextMode, SpawnRequest, ToolProfile } from "./types.ts";
import type { AgentDefinition } from "./agents.ts";
export interface Diagnostics {
warnings: string[];
}
export interface SubagentsConfig {
defaultContext: ContextMode;
defaultTools: string;
maxConcurrent: number;
recentTerminalTtlMs: number;
ui: {
enabled: boolean;
defaultExpanded: boolean;
};
toolProfiles: Record<string, ToolProfile>;
}
export interface ResolvedSpawnRequest extends SpawnRequest {
prompt: string;
context: ContextMode;
tools: string;
toolProfile: ToolProfile;
agentBody?: string;
}
export const BUILT_IN_TOOL_PROFILES: Record<string, ToolProfile> = {
none: { activeTools: [] },
"read-only": { activeTools: ["read", "grep", "find", "ls"] },
"read-only-with-safe-bash": { activeTools: ["read", "grep", "find", "ls", "bash"] },
"full-tools": { activeTools: null },
};
const DEFAULT_CONFIG: SubagentsConfig = {
defaultContext: "independent",
defaultTools: "read-only",
maxConcurrent: 3,
recentTerminalTtlMs: 5 * 60 * 1000,
ui: { enabled: true, defaultExpanded: false },
toolProfiles: { ...BUILT_IN_TOOL_PROFILES },
};
export function loadConfig(cwd: string, projectTrusted: boolean, diagnostics: Diagnostics, agentDir = defaultAgentDir()): SubagentsConfig {
let config = cloneConfig(DEFAULT_CONFIG);
config = mergeConfig(config, readConfig(join(agentDir, "subagents.json"), diagnostics, "global"), diagnostics, "global");
if (projectTrusted) {
config = mergeConfig(config, readConfig(join(cwd, ".pi", "subagents.json"), diagnostics, "project"), diagnostics, "project");
}
if (!config.toolProfiles[config.defaultTools]) {
diagnostics.warnings.push(`Unknown defaultTools profile '${config.defaultTools}', using read-only`);
config.defaultTools = "read-only";
}
return config;
}
export function resolveSpawn(request: SpawnRequest, config: SubagentsConfig, agents: Map<string, AgentDefinition>): ResolvedSpawnRequest {
const prompt = typeof request.prompt === "string" ? request.prompt.trim() : "";
if (!prompt) throw new Error("prompt is required");
const agent = request.agent ? agents.get(request.agent) : undefined;
if (request.agent && !agent) throw new Error(`unknown subagent agent: ${request.agent}`);
const context = request.context ?? agent?.context ?? config.defaultContext;
if (context !== "independent" && context !== "fork") throw new Error(`unsupported context: ${context}`);
if (agent?.allowedContexts && !agent.allowedContexts.includes(context)) {
throw new Error(`agent '${agent.name}' does not allow ${context} context`);
}
const tools = request.tools ?? agent?.tools ?? config.defaultTools;
const toolProfile = config.toolProfiles[tools];
if (!toolProfile) throw new Error(`unknown tool profile: ${tools}`);
return {
...request,
prompt,
agent: agent?.name ?? request.agent,
context,
model: request.model ?? agent?.model,
thinking: request.thinking ?? agent?.thinking,
tools,
toolProfile,
agentBody: agent?.body,
};
}
function readConfig(path: string, diagnostics: Diagnostics, label: string): Partial<SubagentsConfig> | undefined {
if (!existsSync(path)) return undefined;
try {
const parsed = JSON.parse(readFileSync(path, "utf8"));
return normalizeConfig(parsed, diagnostics, label);
} catch (error) {
diagnostics.warnings.push(`Invalid ${label} subagents.json: ${error instanceof Error ? error.message : String(error)}`);
return undefined;
}
}
function normalizeConfig(raw: unknown, diagnostics: Diagnostics, label: string): Partial<SubagentsConfig> | undefined {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
diagnostics.warnings.push(`Invalid ${label} subagents.json: root must be an object`);
return undefined;
}
const input = raw as Record<string, unknown>;
const config: Partial<SubagentsConfig> = {};
if (input.defaultContext === "independent" || input.defaultContext === "fork") config.defaultContext = input.defaultContext;
else if (input.defaultContext !== undefined) diagnostics.warnings.push(`Invalid ${label} defaultContext ignored`);
if (typeof input.defaultTools === "string") config.defaultTools = input.defaultTools;
else if (input.defaultTools !== undefined) diagnostics.warnings.push(`Invalid ${label} defaultTools ignored`);
if (typeof input.maxConcurrent === "number" && Number.isInteger(input.maxConcurrent) && input.maxConcurrent > 0) config.maxConcurrent = input.maxConcurrent;
else if (input.maxConcurrent !== undefined) diagnostics.warnings.push(`Invalid ${label} maxConcurrent ignored`);
if (typeof input.recentTerminalTtlMs === "number" && Number.isInteger(input.recentTerminalTtlMs) && input.recentTerminalTtlMs >= 0) {
config.recentTerminalTtlMs = input.recentTerminalTtlMs;
} else if (input.recentTerminalTtlMs !== undefined) diagnostics.warnings.push(`Invalid ${label} recentTerminalTtlMs ignored`);
if (input.ui !== undefined) config.ui = normalizeUi(input.ui, diagnostics, label);
if (input.toolProfiles !== undefined) config.toolProfiles = normalizeProfiles(input.toolProfiles, diagnostics, label);
return config;
}
function normalizeUi(raw: unknown, diagnostics: Diagnostics, label: string): SubagentsConfig["ui"] | undefined {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
diagnostics.warnings.push(`Invalid ${label} ui ignored`);
return undefined;
}
const input = raw as Record<string, unknown>;
return {
enabled: typeof input.enabled === "boolean" ? input.enabled : DEFAULT_CONFIG.ui.enabled,
defaultExpanded: typeof input.defaultExpanded === "boolean" ? input.defaultExpanded : DEFAULT_CONFIG.ui.defaultExpanded,
};
}
function normalizeProfiles(raw: unknown, diagnostics: Diagnostics, label: string): Record<string, ToolProfile> {
const profiles: Record<string, ToolProfile> = {};
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
diagnostics.warnings.push(`Invalid ${label} toolProfiles ignored`);
return profiles;
}
for (const [name, value] of Object.entries(raw as Record<string, unknown>)) {
if (name in BUILT_IN_TOOL_PROFILES) {
diagnostics.warnings.push(`Ignoring ${label} override for built-in tool profile '${name}'`);
continue;
}
const profile = normalizeProfile(value);
if (!profile) {
diagnostics.warnings.push(`Invalid ${label} tool profile '${name}' ignored`);
continue;
}
profiles[name] = profile;
}
return profiles;
}
function normalizeProfile(raw: unknown): ToolProfile | undefined {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
const activeTools = (raw as { activeTools?: unknown }).activeTools;
if (!Array.isArray(activeTools) || !activeTools.every((tool) => typeof tool === "string")) return undefined;
return { activeTools };
}
function mergeConfig(base: SubagentsConfig, override: Partial<SubagentsConfig> | undefined, diagnostics: Diagnostics, label: string): SubagentsConfig {
if (!override) return base;
const merged = cloneConfig(base);
if (override.defaultContext) merged.defaultContext = override.defaultContext;
if (override.defaultTools) merged.defaultTools = override.defaultTools;
if (override.maxConcurrent) merged.maxConcurrent = override.maxConcurrent;
if (override.recentTerminalTtlMs !== undefined) merged.recentTerminalTtlMs = override.recentTerminalTtlMs;
if (override.ui) merged.ui = { ...merged.ui, ...override.ui };
if (override.toolProfiles) merged.toolProfiles = { ...merged.toolProfiles, ...override.toolProfiles };
for (const key of Object.keys(merged.toolProfiles)) {
if (key in BUILT_IN_TOOL_PROFILES) merged.toolProfiles[key] = BUILT_IN_TOOL_PROFILES[key];
}
return merged;
}
function cloneConfig(config: SubagentsConfig): SubagentsConfig {
return { ...config, ui: { ...config.ui }, toolProfiles: { ...config.toolProfiles } };
}
function defaultAgentDir(): string {
return process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
}

View File

@@ -1,326 +0,0 @@
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";
import { loadAgents } from "./agents.ts";
import { loadConfig, resolveSpawn, type Diagnostics } from "./config.ts";
import { SubprocessRpcRunner } from "./runner.ts";
import { Supervisor } from "./supervisor.ts";
import { milestoneNotification } from "./status.ts";
import type { SpawnRequest, SubagentStatus } from "./types.ts";
import { widget } from "./ui.ts";
let supervisor: Supervisor | undefined;
let lastDiagnostics: Diagnostics = { warnings: [] };
let lastStatuses: SubagentStatus[] = [];
let uiExpanded = false;
export default function subagents(pi: ExtensionAPI) {
const getSupervisor = (ctx: ExtensionContext): Supervisor => {
if (supervisor) return supervisor;
const diagnostics: Diagnostics = { warnings: [] };
const cwd = cwdOf(ctx);
const config = loadConfig(cwd, isProjectTrusted(ctx), diagnostics);
lastDiagnostics = diagnostics;
uiExpanded = config.ui.defaultExpanded;
supervisor = new Supervisor(new SubprocessRpcRunner(), cwd, {
maxConcurrent: config.maxConcurrent,
recentTerminalTtlMs: config.recentTerminalTtlMs,
onMilestone: (status, event) => {
pi.appendEntry("subagent_milestone", { event, status });
const notification = milestoneNotification(status, event);
if (notification) ctx.ui?.notify?.(notification.message, notification.level);
},
onChange: (statuses) => {
lastStatuses = statuses;
updateUi(ctx, config.ui.enabled);
},
});
updateUi(ctx, config.ui.enabled);
return supervisor;
};
const resolve = (ctx: ExtensionContext, request: SpawnRequest): SpawnRequest => {
const diagnostics: Diagnostics = { warnings: [] };
const cwd = cwdOf(ctx);
const trusted = isProjectTrusted(ctx);
const config = loadConfig(cwd, trusted, diagnostics);
const agents = loadAgents(cwd, trusted, diagnostics);
lastDiagnostics = diagnostics;
const resolved = resolveSpawn(request, config, agents);
if (resolved.context === "fork") resolved.parentSessionFile = ctx.sessionManager.getSessionFile();
return resolved;
};
pi.registerTool({
name: "subagent_spawn",
label: "Spawn subagent",
description: "Start one ad hoc independent subagent and return immediately with its child id",
parameters: Type.Object({
prompt: Type.String({ description: "Prompt for the delegated subagent" }),
label: Type.Optional(Type.String({ description: "Human-readable label for this work item" })),
agent: Type.Optional(Type.String({ description: "Named agent definition to use" })),
context: Type.Optional(Type.Union([Type.Literal("independent"), Type.Literal("fork")])),
model: Type.Optional(Type.String({ description: "Optional model selector for the child" })),
thinking: Type.Optional(Type.String({ description: "Optional thinking level for the child" })),
tools: Type.Optional(Type.String({ description: "Tool profile name" })),
}),
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
const accepted = getSupervisor(ctx).spawn(resolve(ctx, params as SpawnRequest));
ctx.ui?.notify?.(`Started subagent ${accepted.label}`, "info");
return textResult(accepted);
},
});
pi.registerTool({
name: "subagent_batch",
label: "Spawn subagent batch",
description: "Start multiple subagents and return immediately with accepted child ids and per-entry failures",
parameters: Type.Object({
subagents: Type.Array(
Type.Object({
prompt: Type.String({ description: "Prompt for the delegated subagent" }),
label: Type.Optional(Type.String({ description: "Human-readable label for this work item" })),
agent: Type.Optional(Type.String({ description: "Named agent definition to use" })),
context: Type.Optional(Type.Union([Type.Literal("independent"), Type.Literal("fork")])),
model: Type.Optional(Type.String({ description: "Optional model selector for the child" })),
thinking: Type.Optional(Type.String({ description: "Optional thinking level for the child" })),
tools: Type.Optional(Type.String({ description: "Tool profile name" })),
}),
),
}),
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
const requests = Array.isArray((params as { subagents?: unknown }).subagents) ? ((params as { subagents: SpawnRequest[] }).subagents) : [];
const accepted: SpawnRequest[] = [];
const failed: Array<{ index: number; error: string }> = [];
requests.forEach((request, index) => {
try {
accepted.push(resolve(ctx, request));
} catch (error) {
failed.push({ index, error: error instanceof Error ? error.message : String(error) });
}
});
const result = getSupervisor(ctx).spawnBatch(accepted);
return textResult({ accepted: result.accepted, failed: [...failed, ...result.failed] });
},
});
pi.registerTool({
name: "subagent_list",
label: "List subagents",
description: "List active and terminal subagents for this parent session until terminal entries are cleared",
parameters: Type.Object({}),
async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
return textResult(getSupervisor(ctx).list());
},
});
pi.registerTool({
name: "subagent_status",
label: "Get subagent status",
description: "Get current lifecycle status for one subagent",
parameters: Type.Object({
id: Type.String({ description: "Subagent id returned by subagent_spawn" }),
}),
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
return textResult(getSupervisor(ctx).status(String((params as { id: unknown }).id)));
},
});
pi.registerTool({
name: "subagent_result",
label: "Get subagent result",
description: "Return still-running before completion and the final answer after completion",
parameters: Type.Object({
id: Type.String({ description: "Subagent id returned by subagent_spawn" }),
}),
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
return textResult(getSupervisor(ctx).result(String((params as { id: unknown }).id)));
},
});
pi.registerTool({
name: "subagent_wait",
label: "Wait for subagents",
description: "Block until multiple subagents are terminal or a timeout expires. Prefer setting timeoutMs so the parent turn cannot hang forever",
parameters: Type.Object({
ids: Type.Array(Type.String({ description: "Subagent id returned by subagent_spawn or subagent_batch" })),
timeoutMs: Type.Optional(Type.Number({ description: "Maximum milliseconds to wait. Omit or use 0 to wait indefinitely" })),
mode: Type.Optional(Type.Union([Type.Literal("all"), Type.Literal("any")], { description: "Wait for all ids by default, or return after any id is terminal" })),
}),
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
const input = params as { ids?: unknown; timeoutMs?: unknown; mode?: unknown };
const ids = Array.isArray(input.ids) ? input.ids.map(String) : [];
const timeoutMs = typeof input.timeoutMs === "number" && Number.isFinite(input.timeoutMs) ? input.timeoutMs : undefined;
const mode = input.mode === "any" ? "any" : "all";
return textResult(await getSupervisor(ctx).wait(ids, { timeoutMs, mode, signal }));
},
});
pi.registerTool({
name: "subagent_cancel",
label: "Cancel subagent",
description: "Cancel a running subagent",
parameters: Type.Object({
id: Type.String({ description: "Subagent id returned by subagent_spawn" }),
}),
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
return textResult(await getSupervisor(ctx).cancel(String((params as { id: unknown }).id)));
},
});
pi.registerTool({
name: "subagent_clear",
label: "Clear terminal subagents",
description: "Remove terminal subagents from the current-session visible work set. Omitting ids clears all terminal children",
parameters: Type.Object({
ids: Type.Optional(Type.Array(Type.String({ description: "Subagent id returned by subagent_spawn or subagent_batch" }))),
}),
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
const input = params as { ids?: unknown };
const ids = Array.isArray(input.ids) ? input.ids.map(String) : undefined;
return textResult({ cleared: getSupervisor(ctx).clearTerminal(ids) });
},
});
pi.registerCommand("subagent-spawn", {
description: "Start an ad hoc independent subagent",
handler: async (args, ctx) => {
const accepted = getSupervisor(ctx).spawn(resolve(ctx, parseSpawnArgs(args)));
ctx.ui.notify(`Started subagent ${accepted.label}`, "info");
},
});
pi.registerCommand("subagent-batch", {
description: "Start ad hoc independent subagents split by |",
handler: async (args, ctx) => {
const requests = args
.split("|")
.map((prompt) => prompt.trim())
.filter(Boolean)
.map((prompt) => resolve(ctx, { prompt }));
ctx.ui.notify(JSON.stringify(getSupervisor(ctx).spawnBatch(requests), null, 2), "info");
},
});
pi.registerCommand("subagent-list", {
description: "Show subagent status records",
handler: async (_args, ctx) => {
ctx.ui.notify(JSON.stringify(getSupervisor(ctx).list(), null, 2), "info");
},
});
pi.registerCommand("subagent-clear", {
description: "Clear terminal subagent records. Pass ids to clear selected terminal records only",
handler: async (args, ctx) => {
const ids = args.trim().split(/\s+/u).filter(Boolean);
ctx.ui.notify(JSON.stringify({ cleared: getSupervisor(ctx).clearTerminal(ids.length > 0 ? ids : undefined) }, null, 2), "info");
},
});
pi.registerCommand("subagent-status", {
description: "Show a subagent status by id",
handler: async (args, ctx) => {
ctx.ui.notify(JSON.stringify(getSupervisor(ctx).status(args.trim()), null, 2), "info");
},
});
pi.registerCommand("subagent-result", {
description: "Show a subagent result by id",
handler: async (args, ctx) => {
ctx.ui.notify(JSON.stringify(getSupervisor(ctx).result(args.trim()), null, 2), "info");
},
});
pi.registerCommand("subagent-wait", {
description: "Wait for subagent ids separated by spaces",
handler: async (args, ctx) => {
const { ids, timeoutMs, mode } = parseWaitArgs(args);
ctx.ui.notify(JSON.stringify(await getSupervisor(ctx).wait(ids, { timeoutMs, mode }), null, 2), "info");
},
});
pi.registerCommand("subagent-ui", {
description: "Toggle the bundled subagent status inspector",
handler: async (_args, ctx) => {
uiExpanded = !uiExpanded;
updateUi(ctx, true);
ctx.ui.notify(`Subagent inspector ${uiExpanded ? "expanded" : "collapsed"}`, "info");
},
});
pi.registerCommand("subagent-diagnostics", {
description: "Show subagent configuration diagnostics from the last load",
handler: async (_args, ctx) => {
ctx.ui.notify(JSON.stringify(lastDiagnostics, null, 2), "info");
},
});
pi.registerCommand("subagent-cancel", {
description: "Cancel a running subagent by id",
handler: async (args, ctx) => {
ctx.ui.notify(JSON.stringify(await getSupervisor(ctx).cancel(args.trim()), null, 2), "info");
},
});
pi.on("session_shutdown", async () => {
await supervisor?.shutdown();
supervisor = undefined;
});
}
function updateUi(ctx: ExtensionContext, enabled: boolean) {
if (!ctx.hasUI) return;
ctx.ui.setWidget("subagents", enabled ? widget(lastStatuses, uiExpanded) : undefined);
}
function parseSpawnArgs(args: string): SpawnRequest {
const parts = args.trim().split(/\s+/u);
const request: Partial<SpawnRequest> = {};
while (parts.length >= 2 && parts[0].startsWith("--")) {
const flag = parts.shift();
const value = parts.shift();
if (flag === "--agent") request.agent = value;
else if (flag === "--label") request.label = value;
else if (flag === "--context" && (value === "independent" || value === "fork")) request.context = value;
else if (flag === "--tools") request.tools = value;
else if (flag === "--model") request.model = value;
else if (flag === "--thinking") request.thinking = value;
}
return { ...request, prompt: parts.join(" ") || args } as SpawnRequest;
}
function parseWaitArgs(args: string): { ids: string[]; timeoutMs?: number; mode?: "all" | "any" } {
const parts = args.trim().split(/\s+/u).filter(Boolean);
let timeoutMs: number | undefined;
let mode: "all" | "any" | undefined;
const ids: string[] = [];
while (parts.length > 0) {
const part = parts.shift();
if (!part) continue;
if (part === "--timeout-ms" && parts[0]) {
const parsed = Number(parts.shift());
if (Number.isFinite(parsed)) timeoutMs = parsed;
} else if (part === "--mode" && (parts[0] === "all" || parts[0] === "any")) {
mode = parts.shift() as "all" | "any";
} else {
ids.push(part);
}
}
return { ids, timeoutMs, mode };
}
function isProjectTrusted(ctx: ExtensionContext): boolean {
const value = (ctx as unknown as { isProjectTrusted?: () => boolean }).isProjectTrusted?.();
return value === true;
}
function cwdOf(ctx: ExtensionContext): string {
const sessionCwd = (ctx as unknown as { sessionManager?: { getCwd?: () => string }; cwd?: string }).sessionManager?.getCwd?.();
return sessionCwd ?? (ctx as unknown as { cwd?: string }).cwd ?? process.cwd();
}
function textResult(value: unknown) {
return {
content: [{ type: "text" as const, text: JSON.stringify(value, null, 2) }],
details: value,
};
}

View File

@@ -1,118 +0,0 @@
import assert from "node:assert/strict";
import childProcess from "node:child_process";
import { EventEmitter } from "node:events";
import { fileURLToPath } from "node:url";
import test from "node:test";
import type { RunnerEvents } from "./types.ts";
class FakeStream extends EventEmitter {
setEncoding(_encoding: BufferEncoding): void {}
write(_chunk: string, callback?: (error?: Error | null) => void): boolean {
callback?.();
return true;
}
end(): void {}
}
function events(): RunnerEvents {
return {
accepted: () => {},
running: () => {},
settling: () => {},
completed: () => {},
failed: () => {},
};
}
test("child RPC process forwards structured activity before collecting the final result", async (t) => {
const running: unknown[] = [];
const completed: Array<{ result: string; stopReason?: string }> = [];
const fakeChild = new EventEmitter() as EventEmitter & {
stdout: FakeStream;
stderr: FakeStream;
stdin: FakeStream;
killed: boolean;
pid?: number;
kill(signal?: NodeJS.Signals): boolean;
};
fakeChild.stdout = new FakeStream();
fakeChild.stderr = new FakeStream();
fakeChild.stdin = new FakeStream();
fakeChild.killed = false;
fakeChild.kill = () => {
fakeChild.killed = true;
return true;
};
t.mock.method(fakeChild.stdin, "write", (chunk, callback?: (error?: Error | null) => void) => {
const request = JSON.parse(String(chunk)) as { id: string; type: string };
callback?.();
if (request.type === "get_last_assistant_text") {
queueMicrotask(() => {
fakeChild.stdout.emit("data", `${JSON.stringify({ id: request.id, type: "response", success: true, data: { text: "final answer" } })}\n`);
});
}
return true;
});
t.mock.method(childProcess, "spawn", () => fakeChild as unknown as childProcess.ChildProcessWithoutNullStreams);
const { SubprocessRpcRunner } = await import("./runner.ts");
const runner = new SubprocessRpcRunner();
await runner.start("child-1", { prompt: "work", label: "Review migration" }, "/tmp", {
...events(),
running: (event) => running.push(event),
completed: (result, stopReason) => completed.push({ result, stopReason }),
});
const firstActivity = { type: "message_start", role: "assistant", message: { id: "msg-1" } };
const secondActivity = { type: "tool_execution_start", tool: "read", input: { path: "runner.ts" } };
const settledActivity = { type: "agent_settled" };
fakeChild.stdout.emit("data", `${JSON.stringify(firstActivity)}\n${JSON.stringify(secondActivity)}\n${JSON.stringify(settledActivity)}\n`);
await new Promise((resolve) => setImmediate(resolve));
assert.deepEqual(running, [firstActivity, secondActivity, settledActivity]);
assert.deepEqual(completed, [{ result: "final answer", stopReason: "agent_settled" }]);
});
test("child RPC process disables discovery while explicitly loading subagents extension", async (t) => {
const calls: Array<{ command: string; args: string[] }> = [];
const fakeChild = new EventEmitter() as EventEmitter & {
stdout: FakeStream;
stderr: FakeStream;
stdin: FakeStream;
killed: boolean;
pid?: number;
kill(signal?: NodeJS.Signals): boolean;
};
fakeChild.stdout = new FakeStream();
fakeChild.stderr = new FakeStream();
fakeChild.stdin = new FakeStream();
fakeChild.killed = false;
fakeChild.kill = () => {
fakeChild.killed = true;
return true;
};
const spawn = t.mock.method(childProcess, "spawn", (command, args) => {
calls.push({ command: String(command), args: Array.isArray(args) ? args.map(String) : [] });
return fakeChild as unknown as childProcess.ChildProcessWithoutNullStreams;
});
const { SubprocessRpcRunner } = await import("./runner.ts");
const runner = new SubprocessRpcRunner();
await runner.start("child-1", { prompt: "work", label: "Review migration" }, "/tmp", events());
assert.equal(spawn.mock.callCount(), 1);
const args = calls[0].args;
const noExtensionsIndex = args.indexOf("--no-extensions");
const extensionIndex = args.indexOf("--extension");
const nameIndex = args.indexOf("--name");
assert.notEqual(noExtensionsIndex, -1, "child args keep automatic extension discovery disabled");
assert.notEqual(nameIndex, -1, "child args include a process name");
assert.equal(args[nameIndex + 1], "subagent Review migration");
assert.notEqual(extensionIndex, -1, "child args explicitly load the subagents extension entry");
assert.equal(args[extensionIndex + 1], fileURLToPath(new URL("./index.ts", import.meta.url)));
assert.ok(noExtensionsIndex < extensionIndex);
});

View File

@@ -1,218 +0,0 @@
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { fileURLToPath } from "node:url";
import type { ChildHandle, ChildRunner, RunnerEvents, SpawnRequest } from "./types.ts";
interface PendingResponse {
resolve(value: unknown): void;
reject(error: Error): void;
command: string;
}
interface RpcLine {
id?: string;
type?: string;
command?: string;
success?: boolean;
data?: unknown;
error?: string;
message?: string;
}
class RpcChildHandle implements ChildHandle {
private buffer = "";
private nextRequest = 0;
private settled = false;
private finishing = false;
private cancelling = false;
private killed = false;
private readonly pending = new Map<string, PendingResponse>();
constructor(
private readonly child: ChildProcessWithoutNullStreams,
private readonly events: RunnerEvents,
) {
child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
child.stdout.on("data", (chunk) => this.onStdout(chunk));
child.stderr.on("data", (chunk) => this.events.running(`stderr: ${String(chunk).trim().slice(0, 200)}`));
child.on("error", (error) => this.fail(error.message));
child.on("close", (code, signal) => {
for (const pending of this.pending.values()) {
pending.reject(new Error(`RPC process closed before ${pending.command} response`));
}
this.pending.clear();
if (!this.settled) this.fail(`RPC process closed with code ${code ?? "null"} signal ${signal ?? "null"}`);
});
}
async prompt(message: string): Promise<void> {
await this.send("prompt", { message });
}
async cancel(): Promise<void> {
if (this.cancelling) return;
this.cancelling = true;
try {
await Promise.race([this.send("abort", {}), delay(200)]);
} catch {}
this.terminate();
}
private onStdout(chunk: string) {
this.buffer += chunk;
while (true) {
const newline = this.buffer.indexOf("\n");
if (newline === -1) return;
const line = this.buffer.slice(0, newline).replace(/\r$/, "");
this.buffer = this.buffer.slice(newline + 1);
if (line.trim() === "") continue;
this.onLine(line);
}
}
private onLine(line: string) {
let payload: RpcLine;
try {
payload = JSON.parse(line);
} catch {
this.events.running(`non-json rpc output: ${line.slice(0, 200)}`);
return;
}
if (payload.type === "response" && payload.id) {
const pending = this.pending.get(payload.id);
if (!pending) return;
this.pending.delete(payload.id);
if (payload.success) pending.resolve(payload.data);
else pending.reject(new Error(payload.error ?? payload.message ?? `${pending.command} failed`));
return;
}
if (payload.type === "agent_started") {
this.events.running(payload as Record<string, unknown>);
return;
}
if (payload.type === "agent_settled") {
this.events.running(payload as Record<string, unknown>);
this.finish().catch((error) => this.fail(error instanceof Error ? error.message : String(error)));
return;
}
if (payload.type) this.events.running(payload as Record<string, unknown>);
}
private async finish() {
if (this.settled || this.finishing) return;
this.finishing = true;
this.events.settling();
const result = await this.send("get_last_assistant_text", {});
const text = typeof result === "string" ? result : result && typeof result === "object" && "text" in result ? String((result as { text: unknown }).text) : "";
this.settled = true;
this.events.completed(text, "agent_settled");
this.terminate();
}
private terminate() {
if (this.killed) return;
this.killed = true;
this.child.stdin.end();
if (this.child.killed) return;
if (process.platform !== "win32" && this.child.pid) {
try {
process.kill(-this.child.pid, "SIGTERM");
} catch {
this.child.kill("SIGTERM");
}
setTimeout(() => {
if (this.child.killed || !this.child.pid) return;
try {
process.kill(-this.child.pid, "SIGKILL");
} catch {
this.child.kill("SIGKILL");
}
}, 2_000).unref();
return;
}
this.child.kill("SIGTERM");
}
private fail(error: string) {
if (this.settled) return;
this.settled = true;
this.events.failed(error);
}
private send(command: string, body: Record<string, unknown>): Promise<unknown> {
const id = `subagent-${++this.nextRequest}`;
return new Promise((resolve, reject) => {
this.pending.set(id, { resolve, reject, command });
this.child.stdin.write(`${JSON.stringify({ id, type: command, ...body })}\n`, (error) => {
if (!error) return;
this.pending.delete(id);
reject(error);
});
});
}
}
export class SubprocessRpcRunner implements ChildRunner {
async start(id: string, request: SpawnRequest, cwd: string, events: RunnerEvents): Promise<ChildHandle> {
const args = [process.argv[1], "--mode", "rpc", "--no-extensions", "--extension", subagentsExtensionPath(), "--name", `subagent ${request.label ?? id}`, ...contextArgs(request), ...toolArgs(request), ...modelArgs(request)];
const child = spawn(process.execPath, args, {
cwd,
env: childEnvironment(),
stdio: ["pipe", "pipe", "pipe"],
detached: process.platform !== "win32",
});
const handle = new RpcChildHandle(child, events);
events.accepted();
void handle.prompt(independentPrompt(request)).catch((error) => events.failed(error instanceof Error ? error.message : String(error)));
return handle;
}
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function subagentsExtensionPath(): string {
return fileURLToPath(new URL("./index.ts", import.meta.url));
}
function contextArgs(request: SpawnRequest): string[] {
if (request.context !== "fork" || !request.parentSessionFile) return [];
return ["--fork", request.parentSessionFile];
}
function toolArgs(request: SpawnRequest): string[] {
const activeTools = request.toolProfile?.activeTools;
if (activeTools === undefined || activeTools === null) return [];
if (activeTools.length === 0) return ["--no-tools"];
return ["--tools", activeTools.join(",")];
}
function modelArgs(request: SpawnRequest): string[] {
const args: string[] = [];
if (request.model && request.model !== "inherit") args.push("--model", request.model);
if (request.thinking) args.push("--thinking", request.thinking);
return args;
}
function childEnvironment(): NodeJS.ProcessEnv {
const env = { ...process.env };
delete env.PI_SESSION_ID;
delete env.PI_SESSION_FILE;
delete env.PI_PROVIDER;
delete env.PI_MODEL;
delete env.PI_REASONING_LEVEL;
return env;
}
function independentPrompt(request: SpawnRequest): string {
const base = request.agentBody ? `${request.agentBody}\n\n` : "";
if (request.context === "fork") {
return `${base}You are running as a delegated subagent in fork context.\nUse the inherited parent session context, then return a concise final answer for the parent agent.\n\nTask:\n${request.prompt}`;
}
return `${base}You are running as a delegated subagent in independent context.\nDo not assume access to the parent conversation transcript.\nReturn a concise final answer for the parent agent.\n\nTask:\n${request.prompt}`;
}

View File

@@ -1,58 +0,0 @@
import { SUBAGENT_STATES, SUBAGENT_TERMINAL_STATES } from "./types.ts";
import type { ChildRecord, SpawnAccepted, SubagentResult, SubagentState, SubagentStatus } from "./types.ts";
export function toAccepted(status: SubagentStatus): SpawnAccepted {
return {
id: status.id,
label: status.label,
context: status.context,
tools: status.tools,
state: status.state,
hint: `Use subagent_status or subagent_result with id ${status.id}`,
};
}
export function cloneStatus(status: SubagentStatus): SubagentStatus {
return {
...status,
currentActivity: status.currentActivity ? { ...status.currentActivity } : undefined,
activityHistory: status.activityHistory.map((event) => ({ ...event })),
elapsedMs: elapsedMs(status),
};
}
export function cloneResult(record: ChildRecord): SubagentResult {
const status = cloneStatus(record.status);
const terminal = isTerminalState(status.state);
return {
id: status.id,
label: status.label,
state: status.state,
running: !terminal,
resultAvailable: status.resultAvailable,
result: record.result,
error: status.error,
completedAt: status.completedAt,
elapsedMs: status.elapsedMs,
};
}
export function isTerminalState(state: SubagentState): boolean {
return (SUBAGENT_TERMINAL_STATES as readonly string[]).includes(state);
}
export function milestoneNotification(status: SubagentStatus, event: string): { message: string; level: "info" | "error" } | undefined {
if (!isSubagentState(event) || !isTerminalState(event)) return undefined;
return { message: `Subagent ${status.label} ${event}`, level: event === "completed" ? "info" : "error" };
}
export function isSubagentState(value: string): value is SubagentState {
return (SUBAGENT_STATES as readonly string[]).includes(value);
}
export function elapsedMs(status: Pick<SubagentStatus, "startedAt" | "completedAt">): number {
const start = Date.parse(status.startedAt);
const end = status.completedAt ? Date.parse(status.completedAt) : Date.now();
if (!Number.isFinite(start) || !Number.isFinite(end)) return 0;
return Math.max(0, end - start);
}

View File

@@ -1,469 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import { milestoneNotification } from "./status.ts";
import { Supervisor } from "./supervisor.ts";
import type { ChildHandle, ChildRunner, RunnerEvents, SpawnRequest } from "./types.ts";
import { widget } from "./ui.ts";
class FakeHandle implements ChildHandle {
cancelCalls = 0;
async cancel(): Promise<void> {
this.cancelCalls += 1;
}
}
class FakeRunner implements ChildRunner {
starts: Array<{ id: string; request: SpawnRequest; events: RunnerEvents; handle: FakeHandle }> = [];
autoAccept = true;
async start(id: string, request: SpawnRequest, _cwd: string, events: RunnerEvents): Promise<ChildHandle> {
const handle = new FakeHandle();
this.starts.push({ id, request, events, handle });
if (this.autoAccept) events.accepted(`session-${id}`);
return handle;
}
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
async function spawnStarted(supervisor: Supervisor, prompt = "work") {
const accepted = supervisor.spawn({ prompt });
await sleep(0);
return accepted;
}
test("cancel is idempotent and reaches cancelled", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
const accepted = await spawnStarted(supervisor);
const first = await supervisor.cancel(accepted.id);
const second = await supervisor.cancel(accepted.id);
assert.equal(first.state, "cancelled");
assert.equal(second.state, "cancelled");
assert.equal(runner.starts[0].handle.cancelCalls, 1);
});
test("startup timeout reaches timed_out", async () => {
const runner = new FakeRunner();
runner.autoAccept = false;
const supervisor = new Supervisor(runner, "/tmp", { timeouts: { startMs: 5 } });
const accepted = await spawnStarted(supervisor);
await sleep(20);
const status = supervisor.status(accepted.id);
assert.equal(status.state, "timed_out");
assert.equal(status.stopReason, "start_timeout");
assert.equal(runner.starts[0].handle.cancelCalls, 1);
});
test("runtime timeout reaches timed_out", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp", { timeouts: { runMs: 5 } });
const accepted = await spawnStarted(supervisor);
await sleep(20);
const status = supervisor.status(accepted.id);
assert.equal(status.state, "timed_out");
assert.equal(status.stopReason, "run_timeout");
assert.equal(runner.starts[0].handle.cancelCalls, 1);
});
test("activity exposes ordered transcript events while status and list keep only summaries", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
const accepted = await spawnStarted(supervisor);
runner.starts[0].events.running({ type: "message_started", role: "assistant" });
runner.starts[0].events.running({
type: "message_delta",
role: "assistant",
assistantMessageEvent: { type: "content_delta", delta: "private transcript body" },
});
runner.starts[0].events.running({ type: "tool_started", tool: "read", input: { path: "secret-notes.md" } });
runner.starts[0].events.running({ type: "tool_completed", tool: "read", output: "secret file contents" });
type ActivityStatus = ReturnType<Supervisor["status"]> & {
activityHistory: Array<{ type: string; summary: string }>;
currentActivity: { summary: string };
};
const activity = supervisor.activity(accepted.id);
const status = supervisor.status(accepted.id) as ActivityStatus;
const listed = supervisor.list().find((item) => item.id === accepted.id) as ActivityStatus | undefined;
assert.deepEqual(
activity.map((event) => event.type),
["queued", "starting", "prompt accepted", "message_started", "message_delta", "tool_started", "tool_completed"],
);
assert.deepEqual(activity[4], {
type: "message_delta",
summary: "assistant message content_delta",
at: activity[4].at,
role: "assistant",
tool: undefined,
phase: "content_delta",
text: "private transcript body",
input: undefined,
output: undefined,
error: undefined,
payload: {
type: "message_delta",
role: "assistant",
assistantMessageEvent: { type: "content_delta", delta: "private transcript body" },
},
});
assert.deepEqual(activity[5], {
type: "tool_started",
summary: "read secret-notes.md",
at: activity[5].at,
role: undefined,
tool: "read",
phase: "started",
text: undefined,
input: { path: "secret-notes.md" },
output: undefined,
error: undefined,
payload: { type: "tool_started", tool: "read", input: { path: "secret-notes.md" } },
});
assert.equal(activity[6].output, "secret file contents");
assert.ok(Array.isArray(status.activityHistory), "status should expose structured activityHistory");
assert.deepEqual(status.activityHistory.map((event) => event.type), activity.map((event) => event.type));
assert.deepEqual(status.activityHistory.map((event) => event.summary), activity.map((event) => event.summary));
assert.equal(status.currentActivity.summary, "read");
assert.equal(listed?.currentActivity.summary, "read");
assert.doesNotMatch(JSON.stringify(status), /private transcript body|secret file contents/u);
assert.doesNotMatch(JSON.stringify(listed), /private transcript body|secret file contents/u);
});
test("status activity history keeps only the 100 most recent summaries", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
const accepted = await spawnStarted(supervisor);
for (let index = 0; index < 150; index += 1) {
runner.starts[0].events.running(`tick ${index}`);
}
const history = supervisor.status(accepted.id).activityHistory;
assert.equal(history.length, 100);
assert.equal(history[0].summary, "tick 50");
assert.equal(history[99].summary, "tick 149");
});
test("process failure reaches failed with diagnostics", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
const accepted = await spawnStarted(supervisor);
runner.starts[0].events.failed("process closed with code 1");
const status = supervisor.status(accepted.id);
assert.equal(status.state, "failed");
assert.equal(status.error, "process closed with code 1");
});
test("shutdown cancels running children", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
const accepted = await spawnStarted(supervisor);
await supervisor.shutdown();
const status = supervisor.status(accepted.id);
assert.equal(status.state, "cancelled");
assert.equal(status.stopReason, "shutdown");
assert.equal(runner.starts[0].handle.cancelCalls, 1);
});
test("completed children ignore later cancel", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
const accepted = await spawnStarted(supervisor);
runner.starts[0].events.completed("done", "agent_settled");
await supervisor.cancel(accepted.id);
const result = supervisor.result(accepted.id);
assert.equal(result.state, "completed");
assert.equal(result.result, "done");
assert.equal(runner.starts[0].handle.cancelCalls, 0);
});
test("explicit labels are reused across accepted status list and result surfaces", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
const label = "Review risky migration";
const accepted = supervisor.spawn({ prompt: "inspect the migration plan", label } as SpawnRequest & { label: string });
await sleep(0);
runner.starts[0].events.completed("done", "agent_settled");
assert.deepEqual(
{
accepted: accepted.label,
status: supervisor.status(accepted.id).label,
list: supervisor.list().find((status) => status.id === accepted.id)?.label,
result: (supervisor.result(accepted.id) as { label?: string }).label,
},
{
accepted: label,
status: label,
list: label,
result: label,
},
);
});
test("ad hoc fallback labels are prompt-derived and reused by widget and result surfaces", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
const prompt = " Audit\n\tguest enablement plan ";
const label = "Audit guest enablement plan";
const accepted = supervisor.spawn({ prompt });
await sleep(0);
runner.starts[0].events.completed("done", "agent_settled");
const statuses = supervisor.list();
const inspectorLines = widget(statuses, true)().render(240);
assert.deepEqual(
{
accepted: accepted.label,
childRequest: runner.starts[0].request.label,
status: supervisor.status(accepted.id).label,
list: statuses.find((status) => status.id === accepted.id)?.label,
result: supervisor.result(accepted.id).label,
},
{
accepted: label,
childRequest: label,
status: label,
list: label,
result: label,
},
);
assert.ok(inspectorLines.some((line) => line.includes(`completed 0s ${label} result: available`)), inspectorLines.join("\n"));
assert.doesNotMatch(accepted.label, /^ad-hoc sg-/u);
});
test("milestone notifications use the stored label", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
const accepted = supervisor.spawn({ prompt: "work", label: "Review migration" });
await sleep(0);
runner.starts[0].events.completed("done", "agent_settled");
assert.deepEqual(milestoneNotification(supervisor.status(accepted.id), "completed"), {
message: "Subagent Review migration completed",
level: "info",
});
assert.equal(milestoneNotification(supervisor.status(accepted.id), "running"), undefined);
});
test("shutdown clears recent terminal expiry timer", async () => {
const runner = new FakeRunner();
let changes = 0;
const supervisor = new Supervisor(runner, "/tmp", {
recentTerminalTtlMs: 5,
onChange: () => {
changes += 1;
},
});
await spawnStarted(supervisor);
await supervisor.shutdown();
const afterShutdown = changes;
await sleep(15);
assert.equal(changes, afterShutdown);
});
test("batch spawn returns explicit labels on accepted child requests and statuses while preserving failures", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
const result = supervisor.spawnBatch([
{ prompt: "one", label: "Review docs" },
{ prompt: "" },
{ prompt: "two", label: "Check tests" },
]);
await sleep(0);
assert.deepEqual(result.accepted.map((accepted) => accepted.label), ["Review docs", "Check tests"]);
assert.equal(result.failed.length, 1);
assert.equal(result.failed[0].index, 1);
assert.deepEqual(runner.starts.map((start) => start.request.label), ["Review docs", "Check tests"]);
assert.deepEqual(result.accepted.map((accepted) => supervisor.status(accepted.id).label), ["Review docs", "Check tests"]);
});
test("maxConcurrent preserves queued records", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp", { maxConcurrent: 1 });
const result = supervisor.spawnBatch([{ prompt: "one" }, { prompt: "two" }]);
await sleep(0);
assert.equal(result.accepted.length, 2);
assert.equal(runner.starts.length, 1);
assert.equal(supervisor.status(result.accepted[1].id).state, "queued");
runner.starts[0].events.completed("done", "agent_settled");
await sleep(0);
assert.equal(runner.starts.length, 2);
});
test("clearTerminal returns only removed terminal ids", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
const first = await spawnStarted(supervisor, "one");
const second = await spawnStarted(supervisor, "two");
const running = await spawnStarted(supervisor, "three");
runner.starts[0].events.completed("one done", "agent_settled");
runner.starts[1].events.completed("two done", "agent_settled");
assert.deepEqual(supervisor.clearTerminal(), [first.id, second.id]);
assert.throws(() => supervisor.status(first.id), /unknown subagent id/);
assert.throws(() => supervisor.status(second.id), /unknown subagent id/);
assert.equal(supervisor.status(running.id).state, "running");
});
test("terminal records expire after ttl while active children remain", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp", { recentTerminalTtlMs: 5 });
const completed = await spawnStarted(supervisor, "one");
const failed = await spawnStarted(supervisor, "two");
const running = await spawnStarted(supervisor, "three");
runner.starts[0].events.completed("one done", "agent_settled");
runner.starts[1].events.failed("two failed");
assert.equal(supervisor.result(completed.id).result, "one done");
assert.equal(supervisor.result(failed.id).error, "two failed");
assert.equal(supervisor.status(running.id).state, "running");
await sleep(20);
const listedIds = supervisor.list().map((status) => status.id);
assert.equal(listedIds.includes(completed.id), false);
assert.equal(listedIds.includes(failed.id), false);
assert.equal(listedIds.includes(running.id), true);
assert.throws(() => supervisor.status(completed.id), /unknown subagent id/);
assert.throws(() => supervisor.status(failed.id), /unknown subagent id/);
assert.throws(() => supervisor.result(completed.id), /unknown subagent id/);
assert.throws(() => supervisor.result(failed.id), /unknown subagent id/);
assert.equal(supervisor.status(running.id).state, "running");
});
test("zero recent terminal ttl does not hide terminal statuses", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp", { recentTerminalTtlMs: 0 });
const accepted = await spawnStarted(supervisor);
runner.starts[0].events.completed("done", "agent_settled");
assert.equal(supervisor.list().some((status) => status.id === accepted.id), true);
assert.equal(supervisor.result(accepted.id).result, "done");
});
test("wait blocks until multiple subagents are terminal", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
const first = await spawnStarted(supervisor, "one");
const second = await spawnStarted(supervisor, "two");
const waiting = supervisor.wait([first.id, second.id], { timeoutMs: 100 });
runner.starts[0].events.completed("one done", "agent_settled");
await sleep(0);
assert.equal(await Promise.race([waiting.then(() => "done"), sleep(10).then(() => "pending")]), "pending");
runner.starts[1].events.failed("two failed");
const result = await waiting;
assert.equal(result.timedOut, false);
assert.equal(result.ready, true);
assert.deepEqual(result.ids, [first.id, second.id]);
assert.equal(result.pending.length, 0);
assert.deepEqual(result.results.map((item) => item.state), ["completed", "failed"]);
assert.equal(result.results[0].result, "one done");
assert.equal(result.results[1].error, "two failed");
});
test("wait returns pending statuses on timeout", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
const first = await spawnStarted(supervisor, "one");
const second = await spawnStarted(supervisor, "two");
runner.starts[0].events.completed("one done", "agent_settled");
const result = await supervisor.wait([first.id, second.id], { timeoutMs: 5 });
assert.equal(result.timedOut, true);
assert.equal(result.ready, false);
assert.deepEqual(result.results.map((item) => item.state), ["completed", "running"]);
assert.deepEqual(result.pending.map((item) => item.id), [second.id]);
});
test("wait any returns after the first terminal subagent", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
const first = await spawnStarted(supervisor, "one");
const second = await spawnStarted(supervisor, "two");
const waiting = supervisor.wait([first.id, second.id], { mode: "any", timeoutMs: 100 });
runner.starts[1].events.completed("two done", "agent_settled");
const result = await waiting;
assert.equal(result.timedOut, false);
assert.equal(result.ready, true);
assert.deepEqual(result.results.map((item) => item.state), ["running", "completed"]);
assert.deepEqual(result.pending.map((item) => item.id), [first.id]);
});
test("wait rejects unknown and empty id sets", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
await assert.rejects(() => supervisor.wait([]), /at least one subagent id is required/);
await assert.rejects(() => supervisor.wait(["missing"]), /unknown subagent id: missing/);
});
test("wait abort rejects without cancelling child", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp");
const accepted = await spawnStarted(supervisor, "one");
const controller = new AbortController();
const waiting = supervisor.wait([accepted.id], { signal: controller.signal });
controller.abort();
await assert.rejects(waiting, /subagent wait aborted/);
assert.equal(runner.starts[0].handle.cancelCalls, 0);
});
test("wait follows queued subagents through queue start and completion", async () => {
const runner = new FakeRunner();
const supervisor = new Supervisor(runner, "/tmp", { maxConcurrent: 1 });
const batch = supervisor.spawnBatch([{ prompt: "one" }, { prompt: "two" }]);
await sleep(0);
const waiting = supervisor.wait([batch.accepted[1].id], { timeoutMs: 100 });
assert.equal(await Promise.race([waiting.then(() => "done"), sleep(10).then(() => "pending")]), "pending");
runner.starts[0].events.completed("one done", "agent_settled");
await sleep(0);
runner.starts[1].events.completed("two done", "agent_settled");
const result = await waiting;
assert.equal(result.timedOut, false);
assert.equal(result.ready, true);
assert.deepEqual(result.results.map((item) => item.result), ["two done"]);
});

View File

@@ -1,558 +0,0 @@
import type {
ChildHandle,
ChildRecord,
ChildRunner,
ContextMode,
RunnerActivity,
RunnerEvents,
SpawnAccepted,
SpawnRequest,
SubagentResult,
SubagentStatus,
SubagentWaitMode,
SubagentWaitResult,
} from "./types.ts";
import { cloneResult, cloneStatus, isTerminalState, toAccepted } from "./status.ts";
interface RunningChild {
record: ChildRecord;
request: SpawnRequest;
handle?: ChildHandle;
startTimer?: ReturnType<typeof setTimeout>;
runTimer?: ReturnType<typeof setTimeout>;
expiryTimer?: ReturnType<typeof setTimeout>;
}
interface SupervisorOptions {
maxConcurrent?: number;
recentTerminalLimit?: number;
recentTerminalTtlMs?: number;
timeouts?: {
startMs?: number;
runMs?: number;
};
onMilestone?: (status: SubagentStatus, event: string) => void;
onChange?: (statuses: SubagentStatus[]) => void;
}
export interface BatchSpawnResult {
accepted: SpawnAccepted[];
failed: Array<{ index: number; error: string }>;
}
const DEFAULT_TIMEOUTS = {
startMs: 30_000,
runMs: 0,
};
const MAX_ACTIVITY_HISTORY = 100;
export class Supervisor {
private nextChild = 0;
private readonly children = new Map<string, RunningChild>();
private readonly queue: RunningChild[] = [];
private readonly waiters = new Set<() => void>();
constructor(
private readonly runner: ChildRunner,
private readonly cwd: string,
private readonly options: SupervisorOptions = {},
) {}
spawn(request: SpawnRequest): SpawnAccepted {
return this.createChild(request);
}
spawnBatch(requests: SpawnRequest[]): BatchSpawnResult {
const accepted: SpawnAccepted[] = [];
const failed: Array<{ index: number; error: string }> = [];
requests.forEach((request, index) => {
try {
accepted.push(this.createChild(request));
} catch (error) {
failed.push({ index, error: error instanceof Error ? error.message : String(error) });
}
});
return { accepted, failed };
}
list(): SubagentStatus[] {
const statuses = [...this.children.values()].map((child) => cloneStatus(child.record.status));
const active = statuses.filter((status) => !isTerminal(status.state));
const terminal = statuses
.filter((status) => isTerminal(status.state))
.sort((a, b) => Date.parse(b.completedAt ?? b.startedAt) - Date.parse(a.completedAt ?? a.startedAt));
return [...active, ...terminal];
}
status(id: string): SubagentStatus {
return cloneStatus(this.require(id).record.status);
}
result(id: string): SubagentResult {
return cloneResult(this.require(id).record);
}
clearTerminal(ids?: string[]): string[] {
const selectedIds = ids ? [...new Set(ids.map((id) => id.trim()).filter(Boolean))] : undefined;
if (selectedIds) for (const id of selectedIds) this.require(id);
const cleared: string[] = [];
for (const [id, child] of this.children) {
if (selectedIds && !selectedIds.includes(id)) continue;
if (!isTerminal(child.record.status.state)) continue;
this.clearTimer(child, "expiryTimer");
cleared.push(id);
this.children.delete(id);
}
if (cleared.length > 0) this.emitChange();
return cleared;
}
async wait(
ids: string[],
options: { timeoutMs?: number; signal?: AbortSignal; mode?: SubagentWaitMode } = {},
): Promise<SubagentWaitResult> {
const uniqueIds = [...new Set(ids.map((id) => id.trim()).filter(Boolean))];
if (uniqueIds.length === 0) throw new Error("at least one subagent id is required");
for (const id of uniqueIds) this.require(id);
const startedAt = Date.now();
const mode = options.mode ?? "all";
if (mode !== "all" && mode !== "any") throw new Error(`unknown wait mode: ${mode}`);
const deadline = options.timeoutMs && options.timeoutMs > 0 ? startedAt + options.timeoutMs : undefined;
let timedOut = false;
while (!this.waitReady(uniqueIds, mode)) {
if (options.signal?.aborted) throw new Error("subagent wait aborted");
const remainingMs = deadline === undefined ? undefined : deadline - Date.now();
if (remainingMs !== undefined && remainingMs <= 0) {
timedOut = true;
break;
}
await this.nextChange(remainingMs, options.signal).catch((error) => {
if (error instanceof Error && error.message === "subagent wait timed out") timedOut = true;
else throw error;
});
if (timedOut) break;
}
const results = uniqueIds.map((id) => this.result(id));
const pending = uniqueIds
.map((id) => this.status(id))
.filter((status) => !isTerminal(status.state));
return { ids: uniqueIds, mode, ready: this.waitReady(uniqueIds, mode), results, pending, timedOut, elapsedMs: Date.now() - startedAt };
}
async cancel(id: string): Promise<SubagentStatus> {
const child = this.require(id);
if (isTerminal(child.record.status.state)) return cloneStatus(child.record.status);
await child.handle?.cancel();
this.completeWithoutResult(child, "cancelled", "cancelled");
this.pumpQueue();
return cloneStatus(child.record.status);
}
async shutdown(): Promise<void> {
await Promise.allSettled(
[...this.children.values()].map(async (child) => {
if (!isTerminal(child.record.status.state)) {
await child.handle?.cancel();
this.completeWithoutResult(child, "cancelled", "shutdown");
}
}),
);
for (const child of this.children.values()) this.clearTimer(child, "expiryTimer");
}
private createChild(request: SpawnRequest): SpawnAccepted {
const prompt = typeof request.prompt === "string" ? request.prompt.trim() : "";
if (!prompt) throw new Error("prompt is required");
const id = this.allocateId();
const now = new Date().toISOString();
const status: SubagentStatus = {
id,
label: deriveLabel(request, id),
agent: request.agent,
adHoc: !request.agent,
context: this.resolveContext(request.context),
state: "queued",
cwd: this.cwd,
model: request.model,
thinking: request.thinking,
tools: request.tools ?? "read-only",
startedAt: now,
elapsedMs: 0,
lastEvent: "queued",
lastEventAt: now,
currentActivity: { type: "queued", summary: "queued", at: now },
activityHistory: [{ type: "queued", summary: "queued", at: now }],
resultAvailable: false,
};
const child: RunningChild = { record: { status, activityEvents: [{ type: "queued", summary: "queued", at: now }] }, request: { ...request, prompt, label: status.label, context: status.context, tools: status.tools } };
this.children.set(id, child);
this.emitMilestone(child, "accepted");
this.queue.push(child);
this.pumpQueue();
return toAccepted(cloneStatus(status));
}
private pumpQueue() {
while (this.runningCount() < this.maxConcurrent()) {
const child = this.queue.shift();
if (!child) break;
if (isTerminal(child.record.status.state)) continue;
this.start(child);
}
this.emitChange();
}
private start(child: RunningChild) {
this.setState(child.record.status, "starting", "starting");
this.armStartTimer(child);
setTimeout(() => {
if (isTerminal(child.record.status.state)) return;
void this.runner
.start(child.record.status.id, child.request, this.cwd, this.eventsFor(child.record))
.then((handle) => {
child.handle = handle;
if (isTerminal(child.record.status.state)) void handle.cancel();
})
.catch((error) => {
this.fail(child.record, error instanceof Error ? error.message : String(error));
});
}, 0);
}
private eventsFor(record: ChildRecord): RunnerEvents {
return {
accepted: (childSession) => {
const child = this.findChild(record);
if (child) {
this.clearTimer(child, "startTimer");
this.armRunTimer(child);
}
if (childSession) record.status.childSession = childSession;
this.setState(record.status, "running", "prompt accepted");
},
running: (event) => {
if (!isTerminal(record.status.state)) this.setState(record.status, "running", event);
},
settling: () => {
if (!isTerminal(record.status.state)) this.setState(record.status, "settling", "agent_settled");
},
completed: (result, stopReason) => {
const now = new Date().toISOString();
const child = this.findChild(record);
if (child) this.clearTimers(child);
record.result = result;
record.status.state = "completed";
record.status.completedAt = now;
record.status.lastEvent = "completed";
record.status.lastEventAt = now;
this.recordActivity(record, "completed", now);
record.status.stopReason = stopReason;
record.status.resultAvailable = true;
if (child) {
this.armTerminalExpiry(child);
this.emitMilestone(child, "completed");
}
this.pumpQueue();
},
failed: (error) => this.fail(record, error),
};
}
private fail(record: ChildRecord, error: string) {
if (isTerminal(record.status.state)) return;
const child = this.findChild(record);
if (child) this.clearTimers(child);
const now = new Date().toISOString();
record.status.state = "failed";
record.status.completedAt = now;
record.status.lastEvent = "failed";
record.status.lastEventAt = now;
this.recordActivity(record, "failed", now);
record.status.error = error;
record.status.stopReason = "failed";
if (child) {
this.armTerminalExpiry(child);
this.emitMilestone(child, "failed");
}
this.pumpQueue();
}
private completeWithoutResult(child: RunningChild, state: "cancelled" | "timed_out", reason: string) {
if (isTerminal(child.record.status.state)) return;
this.clearTimers(child);
const now = new Date().toISOString();
child.record.status.state = state;
child.record.status.completedAt = now;
child.record.status.lastEvent = state;
child.record.status.lastEventAt = now;
this.recordActivity(child.record, state, now);
child.record.status.stopReason = reason;
this.armTerminalExpiry(child);
this.emitMilestone(child, state);
}
private armStartTimer(child: RunningChild) {
const timeout = this.options.timeouts?.startMs ?? DEFAULT_TIMEOUTS.startMs;
if (timeout <= 0) return;
child.startTimer = setTimeout(() => {
this.timeout(child, "start_timeout");
}, timeout);
}
private armRunTimer(child: RunningChild) {
const timeout = this.options.timeouts?.runMs ?? DEFAULT_TIMEOUTS.runMs;
if (timeout <= 0) return;
child.runTimer = setTimeout(() => {
this.timeout(child, "run_timeout");
}, timeout);
}
private timeout(child: RunningChild, reason: string) {
if (isTerminal(child.record.status.state)) return;
void child.handle?.cancel();
this.completeWithoutResult(child, "timed_out", reason);
this.pumpQueue();
}
private armTerminalExpiry(child: RunningChild) {
const ttl = this.options.recentTerminalTtlMs;
if (ttl === undefined || ttl <= 0) return;
this.clearTimer(child, "expiryTimer");
child.expiryTimer = setTimeout(() => {
child.expiryTimer = undefined;
const id = child.record.status.id;
if (this.children.get(id) !== child || !isTerminal(child.record.status.state)) return;
this.children.delete(id);
this.emitChange();
}, ttl);
child.expiryTimer.unref?.();
}
private clearTimers(child: RunningChild) {
this.clearTimer(child, "startTimer");
this.clearTimer(child, "runTimer");
}
private clearTimer(child: RunningChild, key: "startTimer" | "runTimer" | "expiryTimer") {
const timer = child[key];
if (!timer) return;
clearTimeout(timer);
child[key] = undefined;
}
private findChild(record: ChildRecord): RunningChild | undefined {
return [...this.children.values()].find((child) => child.record === record);
}
activity(id: string) {
return this.require(id).record.activityEvents.map((event) => ({ ...event }));
}
private setState(status: SubagentStatus, state: SubagentStatus["state"], event: RunnerActivity) {
if (isTerminal(status.state)) return;
const record = this.require(status.id).record;
const now = new Date().toISOString();
const activity = this.recordActivity(record, event, now);
status.state = state;
status.lastEvent = activity.type;
status.lastEventAt = now;
this.emitChange();
}
private recordActivity(record: ChildRecord, event: RunnerActivity, at: string) {
const activity = normalizeActivity(event, at);
record.activityEvents.push(activity);
const summary = summarizeActivity(activity);
record.status.currentActivity = summary;
record.status.activityHistory.push(summary);
if (record.status.activityHistory.length > MAX_ACTIVITY_HISTORY) {
record.status.activityHistory.splice(0, record.status.activityHistory.length - MAX_ACTIVITY_HISTORY);
}
return activity;
}
private require(id: string): RunningChild {
const child = this.children.get(id);
if (!child) throw new Error(`unknown subagent id: ${id}`);
return child;
}
private resolveContext(context: ContextMode | undefined): ContextMode {
if (context === undefined) return "independent";
if (context !== "independent" && context !== "fork") throw new Error(`unknown context: ${context}`);
return context;
}
private maxConcurrent(): number {
return Math.max(1, this.options.maxConcurrent ?? 3);
}
private runningCount(): number {
return [...this.children.values()].filter((child) => ["starting", "running", "settling"].includes(child.record.status.state)).length;
}
private emitMilestone(child: RunningChild, event: string) {
this.options.onMilestone?.(cloneStatus(child.record.status), event);
this.emitChange();
}
private emitChange() {
this.options.onChange?.(this.list());
for (const waiter of this.waiters) waiter();
}
private waitReady(ids: string[], mode: SubagentWaitMode): boolean {
const terminal = (id: string) => isTerminal(this.require(id).record.status.state);
return mode === "all" ? ids.every(terminal) : ids.some(terminal);
}
private nextChange(timeoutMs: number | undefined, signal: AbortSignal | undefined): Promise<void> {
return new Promise((resolve, reject) => {
let timer: ReturnType<typeof setTimeout> | undefined;
const cleanup = () => {
this.waiters.delete(resolveOnce);
if (timer) clearTimeout(timer);
signal?.removeEventListener("abort", abort);
};
const resolveOnce = () => {
cleanup();
resolve();
};
const abort = () => {
cleanup();
reject(new Error("subagent wait aborted"));
};
this.waiters.add(resolveOnce);
signal?.addEventListener("abort", abort, { once: true });
if (timeoutMs !== undefined) {
timer = setTimeout(() => {
cleanup();
reject(new Error("subagent wait timed out"));
}, timeoutMs);
}
});
}
private allocateId(): string {
this.nextChild += 1;
return `sg-${Date.now().toString(36)}-${this.nextChild.toString(36)}`;
}
}
function deriveLabel(request: SpawnRequest, id: string): string {
const explicit = normalizeLabel(request.label);
if (explicit) return explicit;
const agent = normalizeLabel(request.agent);
if (agent) return agent;
return promptLabel(request.prompt) ?? `ad-hoc ${id}`;
}
function promptLabel(prompt: string): string | undefined {
const normalized = normalizeLabel(prompt);
if (!normalized) return undefined;
return truncateLabel(normalized);
}
function normalizeLabel(value: unknown): string | undefined {
if (typeof value !== "string") return undefined;
const normalized = value.replace(/\s+/gu, " ").trim();
return normalized || undefined;
}
function truncateLabel(label: string): string {
const maxLength = 80;
if (label.length <= maxLength) return label;
return `${label.slice(0, maxLength - 1).trimEnd()}…`;
}
function isTerminal(state: SubagentStatus["state"]): boolean {
return isTerminalState(state);
}
function normalizeActivity(event: RunnerActivity, at: string) {
if (typeof event === "string") return { type: event, summary: event, at };
const type = typeof event.type === "string" ? event.type : "activity";
const role = typeof event.role === "string" ? event.role : undefined;
const tool = toolFromActivity(event);
const phase = typeof event.phase === "string" ? event.phase : phaseFromType(type, event);
const text = textFromActivity(event);
const input = inputFromActivity(event);
const output = "output" in event ? event.output : "result" in event ? event.result : "partialResult" in event ? event.partialResult : undefined;
const error = typeof event.error === "string" ? event.error : undefined;
return { type, summary: summaryFor({ type, role, tool, phase, input, output, error }), at, role, tool, phase, text, input, output, error, payload: { ...event } };
}
function summarizeActivity(activity: ReturnType<typeof normalizeActivity>) {
const { type, summary, at, role, tool, phase } = activity;
return { type, summary, at, role, tool, phase };
}
function toolFromActivity(event: Record<string, unknown>): string | undefined {
for (const key of ["tool", "toolName", "name"]) {
const value = event[key];
if (typeof value === "string") return value;
}
return undefined;
}
function phaseFromType(type: string, event: Record<string, unknown>): string | undefined {
const assistantEvent = event.assistantMessageEvent;
if (assistantEvent && typeof assistantEvent === "object" && !Array.isArray(assistantEvent)) {
const assistantType = (assistantEvent as { type?: unknown }).type;
if (typeof assistantType === "string") return assistantType;
}
if (type.endsWith("_start")) return "started";
if (type.endsWith("_started")) return "started";
if (type.endsWith("_update")) return "update";
if (type.endsWith("_delta")) return "delta";
if (type.endsWith("_end")) return "completed";
if (type.endsWith("_completed")) return "completed";
if (type.endsWith("_failed")) return "failed";
return undefined;
}
function textFromActivity(event: Record<string, unknown>): string | undefined {
for (const key of ["text", "body", "content", "delta"]) {
const value = event[key];
if (typeof value === "string") return value;
}
const assistantEvent = event.assistantMessageEvent;
if (assistantEvent && typeof assistantEvent === "object" && !Array.isArray(assistantEvent)) {
for (const key of ["delta", "content"]) {
const value = (assistantEvent as Record<string, unknown>)[key];
if (typeof value === "string") return value;
}
}
return undefined;
}
function inputFromActivity(event: Record<string, unknown>): unknown {
if ("input" in event) return event.input;
if ("args" in event) return event.args;
return undefined;
}
function summaryFor(activity: { type: string; role?: string; tool?: string; phase?: string; input?: unknown; output?: unknown; error?: string }): string {
if (activity.error) return `${activity.tool ?? activity.type} failed: ${activity.error}`;
if (activity.tool) return `${activity.tool}${inputHint(activity.input)}`;
if (activity.type.startsWith("message")) return `${activity.role ?? "assistant"} message${activity.phase ? ` ${activity.phase}` : ""}`;
return activity.type;
}
function inputHint(input: unknown): string {
if (!input || typeof input !== "object" || Array.isArray(input)) return "";
const path = (input as { path?: unknown }).path;
if (typeof path === "string" && path.trim()) return ` ${path.trim()}`;
const command = (input as { command?: unknown }).command;
if (typeof command === "string" && command.trim()) return ` ${truncateActivityHint(command.trim())}`;
return "";
}
function truncateActivityHint(value: string): string {
return value.length <= 80 ? value : `${value.slice(0, 79).trimEnd()}…`;
}

View File

@@ -1,123 +0,0 @@
export type ContextMode = "independent" | "fork";
export const SUBAGENT_STATES = ["queued", "starting", "running", "settling", "completed", "failed", "cancelled", "timed_out", "orphaned"] as const;
export const SUBAGENT_TERMINAL_STATES = ["completed", "failed", "cancelled", "timed_out", "orphaned"] as const;
export type SubagentState = (typeof SUBAGENT_STATES)[number];
export interface ToolProfile {
activeTools: string[] | null;
}
export interface SpawnRequest {
prompt: string;
label?: string;
context?: ContextMode;
agent?: string;
model?: string;
thinking?: string;
tools?: string;
toolProfile?: ToolProfile;
agentBody?: string;
parentSessionFile?: string;
}
export interface SpawnAccepted {
id: string;
label: string;
context: ContextMode;
tools: string;
state: SubagentState;
hint: string;
}
export interface SubagentActivitySummary {
type: string;
summary: string;
at: string;
role?: string;
tool?: string;
phase?: string;
}
export interface SubagentActivityEvent extends SubagentActivitySummary {
text?: string;
input?: unknown;
output?: unknown;
error?: string;
payload?: Record<string, unknown>;
}
export interface SubagentCurrentActivity extends SubagentActivitySummary {}
export type RunnerActivity = string | Record<string, unknown>;
export interface SubagentStatus {
id: string;
label: string;
agent?: string;
adHoc: boolean;
context: ContextMode;
state: SubagentState;
cwd: string;
model?: string;
thinking?: string;
tools: string;
startedAt: string;
completedAt?: string;
elapsedMs: number;
lastEvent?: string;
lastEventAt?: string;
currentActivity?: SubagentCurrentActivity;
activityHistory: SubagentActivitySummary[];
stopReason?: string;
resultAvailable: boolean;
childSession?: string;
error?: string;
}
export interface SubagentResult {
id: string;
label: string;
state: SubagentState;
running: boolean;
resultAvailable: boolean;
result?: string;
error?: string;
completedAt?: string;
elapsedMs: number;
}
export type SubagentWaitMode = "all" | "any";
export interface SubagentWaitResult {
ids: string[];
mode: SubagentWaitMode;
ready: boolean;
results: SubagentResult[];
pending: SubagentStatus[];
timedOut: boolean;
elapsedMs: number;
}
export interface ChildRecord {
status: SubagentStatus;
activityEvents: SubagentActivityEvent[];
result?: string;
}
export interface RunnerEvents {
accepted(childSession?: string): void;
running(event: RunnerActivity): void;
settling(): void;
completed(result: string, stopReason?: string): void;
failed(error: string): void;
}
export interface ChildHandle {
cancel(): Promise<void>;
}
export interface ChildRunner {
start(id: string, request: SpawnRequest, cwd: string, events: RunnerEvents): Promise<ChildHandle>;
}

View File

@@ -1,89 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { SubagentState, SubagentStatus } from "./types.ts";
import { renderInspector, renderSummary, widget } from "./ui.ts";
function status(overrides: Partial<SubagentStatus> & { id: string; label: string; state: SubagentState }): SubagentStatus {
return {
adHoc: true,
context: "independent",
cwd: "/tmp",
elapsedMs: 0,
activityHistory: [],
resultAvailable: false,
startedAt: "2026-08-01T00:00:00.000Z",
tools: "inherit",
...overrides,
};
}
test("compact monitor aggregates visible children by actionable lifecycle group", () => {
assert.deepEqual(renderSummary([]), []);
assert.deepEqual(
renderSummary([
status({ id: "queued", label: "Queued", state: "queued" }),
status({ id: "starting", label: "Starting", state: "starting" }),
status({ id: "running", label: "Running", state: "running" }),
status({ id: "settling", label: "Settling", state: "settling" }),
status({ id: "completed", label: "Completed", state: "completed", resultAvailable: true }),
status({ id: "failed", label: "Failed", state: "failed", error: "boom" }),
status({ id: "timed-out", label: "Timed out", state: "timed_out" }),
status({ id: "cancelled", label: "Cancelled", state: "cancelled" }),
]),
["subagents: queued 1 · running 2 · settling 1 · completed 1 · failed 1 · timed out 1 · cancelled 1"],
);
});
test("expanded monitor shows concise current activity summaries instead of raw event types", () => {
const rendered = widget([
status({
id: "sg-reading",
label: "Audit guest enablement plan",
state: "running",
elapsedMs: 12_000,
lastEvent: "message_update",
currentActivity: {
type: "message_update",
summary: "read secret-notes.md",
at: "2026-08-01T00:00:12.000Z",
},
}),
], true)().render(240);
assert.deepEqual(rendered, ["▶ running 12s Audit guest enablement plan last: read secret-notes.md"]);
assert.doesNotMatch(rendered.join("\n"), /message_update|private transcript body/u);
});
test("expanded monitor renders one truncated row per child with state, elapsed time, and activity marker", () => {
const lines = renderInspector([
status({
id: "sg-running",
label: "Audit unusually verbose guest enablement migration plan",
state: "running",
elapsedMs: 65_000,
lastEvent: "message_update",
}),
status({
id: "sg-completed",
label: "Summarize review",
state: "completed",
elapsedMs: 3_600_000,
lastEvent: "completed",
resultAvailable: true,
}),
status({ id: "sg-failed", label: "Run risky test", state: "failed", elapsedMs: 2_000, error: "exit 1" }),
]);
assert.equal(lines.length, 3);
assert.match(lines[0], /^▶ running +1m05s +Audit unusually verbose guest enablement migration plan +last: message_update$/u);
assert.equal(lines[1], "✓ completed 1h00m00s Summarize review result: available");
assert.equal(lines[2], "✗ failed 2s Run risky test error: exit 1");
const rendered = widget([
status({ id: "sg-running", label: "Audit unusually verbose guest enablement migration plan", state: "running", elapsedMs: 65_000, lastEvent: "message_update" }),
], true)().render(32);
assert.deepEqual(rendered, ["▶ running 1m05s Audit unusual…"]);
assert.ok(rendered.every((line) => line.length <= 32));
});

View File

@@ -1,81 +0,0 @@
import type { SubagentState, SubagentStatus } from "./types.ts";
const COMPACT_GROUPS: Array<{ label: string; states: SubagentState[] }> = [
{ label: "queued", states: ["queued"] },
{ label: "running", states: ["starting", "running"] },
{ label: "settling", states: ["settling"] },
{ label: "completed", states: ["completed"] },
{ label: "failed", states: ["failed"] },
{ label: "timed out", states: ["timed_out"] },
{ label: "cancelled", states: ["cancelled"] },
{ label: "orphaned", states: ["orphaned"] },
];
const STATE_PRESENTATION: Record<SubagentState, { icon: string; label: string }> = {
queued: { icon: "…", label: "queued" },
starting: { icon: "◌", label: "starting" },
running: { icon: "▶", label: "running" },
settling: { icon: "◒", label: "settling" },
completed: { icon: "✓", label: "completed" },
failed: { icon: "✗", label: "failed" },
cancelled: { icon: "■", label: "cancelled" },
timed_out: { icon: "⏱", label: "timed out" },
orphaned: { icon: "?", label: "orphaned" },
};
export function renderSummary(statuses: SubagentStatus[]): string[] {
const groups = COMPACT_GROUPS.map((group) => ({
label: group.label,
count: statuses.filter((status) => group.states.includes(status.state)).length,
})).filter((group) => group.count > 0);
if (groups.length === 0) return [];
return [`subagents: ${groups.map((group) => `${group.label} ${group.count}`).join(" · ")}`];
}
export function renderInspector(statuses: SubagentStatus[]): string[] {
return statuses.map((status) => renderStatusRow(status));
}
export function widget(statuses: SubagentStatus[], expanded: boolean) {
return () => ({
invalidate() {},
render(width: number) {
return (expanded ? renderInspector(statuses) : renderSummary(statuses)).map((line) => truncateLine(line, width));
},
});
}
function renderStatusRow(status: SubagentStatus): string {
const presentation = STATE_PRESENTATION[status.state];
const marker = statusMarker(status);
return `${presentation.icon} ${presentation.label.padEnd(9)} ${formatDuration(status.elapsedMs)} ${status.label}${marker ? ` ${marker}` : ""}`;
}
function statusMarker(status: SubagentStatus): string | undefined {
if (status.error) return `error: ${status.error}`;
if (status.resultAvailable) return "result: available";
if (status.currentActivity) return `last: ${status.currentActivity.summary}`;
if (status.lastEvent) return `last: ${status.lastEvent}`;
if (status.state === "queued") return "waiting";
if (status.state === "settling") return "settling";
return undefined;
}
function formatDuration(elapsedMs: number): string {
const totalSeconds = Math.max(0, Math.round(elapsedMs / 1000));
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
if (hours > 0) return `${hours}h${String(minutes).padStart(2, "0")}m${String(seconds).padStart(2, "0")}s`;
if (minutes > 0) return `${minutes}m${String(seconds).padStart(2, "0")}s`;
return `${seconds}s`;
}
function truncateLine(line: string, width: number): string {
if (width <= 0) return "";
if (line.length <= width) return line;
if (width === 1) return "…";
return `${line.slice(0, width - 1)}…`;
}

View File

@@ -1,12 +1,13 @@
diff --git a/packages/coding-agent/src/utils/tools-manager.ts b/packages/coding-agent/src/utils/tools-manager.ts diff --git a/packages/coding-agent/src/utils/tools-manager.ts b/packages/coding-agent/src/utils/tools-manager.ts
--- a/packages/coding-agent/src/utils/tools-manager.ts 2026-08-01 18:41:36.970496010 -0400 --- a/packages/coding-agent/src/utils/tools-manager.ts 2026-08-01 18:41:36.970496010 -0400
+++ b/packages/coding-agent/src/utils/tools-manager.ts 2026-08-01 18:41:37.028186009 -0400 +++ b/packages/coding-agent/src/utils/tools-manager.ts 2026-08-01 18:41:37.028186009 -0400
@@ -74,8 +74,7 @@ @@ -74,8 +74,8 @@
function commandExists(cmd: string): boolean { function commandExists(cmd: string): boolean {
try { try {
const result = spawnSync(cmd, ["--version"], { stdio: "pipe" }); const result = spawnSync(cmd, ["--version"], { stdio: "pipe" });
- // Check for ENOENT error (command not found) - // Check for ENOENT error (command not found)
- return result.error === undefined || result.error === null; - return result.error === undefined || result.error === null;
+ // Downloaded generic Linux binaries can exist but fail on NixOS before they print a version.
+ return (result.error === undefined || result.error === null) && result.status === 0; + return (result.error === undefined || result.error === null) && result.status === 0;
} catch { } catch {
return false; return false;

View File

@@ -11,40 +11,6 @@ let
cfg = config.modules.agents.pi; cfg = config.modules.agents.pi;
user = config.user.name; user = config.user.name;
piDir = "${config.users.users.${user}.home}/.pi/agent"; piDir = "${config.users.users.${user}.home}/.pi/agent";
reservedToolProfiles = [
"none"
"read-only"
"read-only-with-safe-bash"
"full-tools"
];
subagentsConfig =
lib.optionalAttrs (cfg.subagents.defaultContext != null) {
defaultContext = cfg.subagents.defaultContext;
}
// lib.optionalAttrs (cfg.subagents.defaultTools != null) {
defaultTools = cfg.subagents.defaultTools;
}
// lib.optionalAttrs (cfg.subagents.maxConcurrent != null) {
maxConcurrent = cfg.subagents.maxConcurrent;
}
// lib.optionalAttrs (cfg.subagents.recentTerminalTtlMs != null) {
recentTerminalTtlMs = cfg.subagents.recentTerminalTtlMs;
}
// lib.optionalAttrs (
cfg.subagents.ui.enabled != null || cfg.subagents.ui.defaultExpanded != null
) {
ui =
lib.optionalAttrs (cfg.subagents.ui.enabled != null) {
enabled = cfg.subagents.ui.enabled;
}
// lib.optionalAttrs (cfg.subagents.ui.defaultExpanded != null) {
defaultExpanded = cfg.subagents.ui.defaultExpanded;
};
}
// lib.optionalAttrs (cfg.subagents.toolProfiles != { }) {
toolProfiles = cfg.subagents.toolProfiles;
};
subagentsJson = (pkgs.formats.json { }).generate "pi-subagents.json" subagentsConfig;
patchedPi = pkgs.pi-coding-agent.overrideAttrs (old: { patchedPi = pkgs.pi-coding-agent.overrideAttrs (old: {
patches = (old.patches or [ ]) ++ [ patches = (old.patches or [ ]) ++ [
./patches/pi-flex-spacer.patch ./patches/pi-flex-spacer.patch
@@ -76,109 +42,9 @@ in
options.modules.agents.pi = { options.modules.agents.pi = {
enable = lib.mkEnableOption '' enable = lib.mkEnableOption ''
Pi, a terminal coding agent, configured via home-manager''; Pi, a terminal coding agent, configured via home-manager'';
subagents = {
defaultContext = lib.mkOption {
type = lib.types.nullOr (lib.types.enum [
"independent"
"fork"
]);
default = null;
description = ''
Default context mode for subagents.
Left null, the extension keeps its in-code default.
'';
};
defaultTools = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "read-only-with-safe-bash";
description = ''
Default tool profile for subagents.
Left null, the extension keeps its in-code default.
'';
};
maxConcurrent = lib.mkOption {
type = lib.types.nullOr lib.types.ints.positive;
default = null;
example = 4;
description = ''
Maximum number of child processes allowed to run concurrently.
Left null, the extension keeps its in-code default.
'';
};
recentTerminalTtlMs = lib.mkOption {
type = lib.types.nullOr lib.types.ints.unsigned;
default = null;
example = 600000;
description = ''
Milliseconds to retain terminal subagents in the recent work set.
Zero disables time-based retention.
Left null, the extension keeps its in-code default.
'';
};
ui = {
enabled = lib.mkOption {
type = lib.types.nullOr lib.types.bool;
default = null;
description = ''
Whether the extension renders its built-in subagent monitor.
Left null, the extension keeps its in-code default.
'';
};
defaultExpanded = lib.mkOption {
type = lib.types.nullOr lib.types.bool;
default = null;
description = ''
Whether the built-in subagent monitor starts expanded.
Left null, the extension keeps its in-code default.
'';
};
};
toolProfiles = lib.mkOption {
type = lib.types.attrsOf (
lib.types.submodule {
options.activeTools = lib.mkOption {
type = lib.types.listOf lib.types.str;
description = "Pi tools made available to a child using this profile.";
};
}
);
default = { };
example = {
review = {
activeTools = [
"read"
"grep"
"find"
"ls"
];
};
};
description = ''
Custom named tool profiles for subagents.
The extension's reserved built-in profile names cannot be redefined.
'';
};
};
}; };
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
assertions = [
{
assertion = lib.intersectLists reservedToolProfiles (
builtins.attrNames cfg.subagents.toolProfiles
) == [ ];
message = "modules.agents.pi.subagents.toolProfiles may not redefine the reserved profiles: ${lib.concatStringsSep ", " reservedToolProfiles}.";
}
];
home-manager.users.${user} = { home-manager.users.${user} = {
programs.pi-coding-agent = { programs.pi-coding-agent = {
enable = true; enable = true;
@@ -209,13 +75,6 @@ in
source = ./prompts; source = ./prompts;
recursive = true; recursive = true;
}; };
}
// lib.optionalAttrs (subagentsConfig != { }) {
# Declaring any global override makes Nix the owner of the runtime file.
"${piDir}/subagents.json" = {
source = subagentsJson;
force = true;
};
}; };
}; };
}; };

View File

@@ -10,22 +10,7 @@ let
user = config.user.name; user = config.user.name;
# The skills installed globally, as derivations from the skills flake. # The skills installed globally, as derivations from the skills flake.
# grill interviews the operator relentlessly to resolve a plan before building. skills = with inputs.skills.packages.${pkgs.stdenv.hostPlatform.system}; [ ];
# design-skill drafts and audits Agent Skills for structural predictability.
# wayfinder, research, prototype, slice, and subagents guide work from exploration through implementation tickets and delegation.
# implement, test-driven-development, and review guide execution and validation once tickets are ready.
skills = with inputs.skills.packages.${pkgs.stdenv.hostPlatform.system}; [
grill
design-skill
wayfinder
research
prototype
slice
subagents
implement
test-driven-development
review
];
in in
{ {
home-manager.sharedModules = [ inputs.skills.homeModules.default ]; home-manager.sharedModules = [ inputs.skills.homeModules.default ];

126
modules/default.nix Normal file
View File

@@ -0,0 +1,126 @@
{
config,
lib,
pkgs,
inputs,
...
}:
# The shared foundation for every host and guest.
let
inherit (lib) mkOption types;
user = config.user;
pinArgs = prev: {
inherit (prev.stdenv.hostPlatform) system;
config.allowUnfree = true;
};
in
{
imports = [ inputs.home-manager.nixosModules.home-manager ];
options.user = {
name = mkOption {
type = types.str;
default = "alexion";
description = ''
Primary interactive user for this system.
This drives the system account and Home Manager user together.
'';
};
description = mkOption {
type = types.str;
default = "Alexion";
description = "Human-readable description for the primary user.";
};
};
config = {
nixpkgs.overlays = [
(_final: prev: {
unstable = import inputs.nixpkgs-unstable (pinArgs prev);
stable = import inputs.nixpkgs-stable (pinArgs prev);
})
];
nixpkgs.config.allowUnfree = true;
nix.settings.experimental-features = [
"nix-command"
"flakes"
];
users.users.${user.name} = {
isNormalUser = true;
description = user.description;
extraGroups = [
"wheel"
"storage"
];
};
users.groups.storage.gid = 10000;
home-manager = {
useGlobalPkgs = true;
useUserPackages = true;
extraSpecialArgs = {
inherit inputs;
};
users.${user.name} = {
home.username = user.name;
home.homeDirectory = "/home/${user.name}";
home.stateVersion = "26.05";
home.packages = with pkgs; [
eza
wget
];
};
};
registry.shell-shortcut.${config.networking.hostName} = {
ls = {
command = "eza -alg --color=always --group-directories-first --icons=always";
abbreviation = false;
};
la = {
command = "eza -a --color=always --group-directories-first --icons=always";
abbreviation = false;
};
ll = {
command = "eza -lg --color=always --group-directories-first --icons=always";
abbreviation = false;
};
lt = {
command = "eza -aT -I '.git' --color=always --group-directories-first --icons=always";
abbreviation = false;
};
"l." = {
command = "eza -a | grep -e '^\\.'";
abbreviation = false;
};
".." = "cd ..";
"..." = "cd ../..";
"...." = "cd ../../..";
cp = "cp -v";
tarnow = "tar -acf ";
untar = "tar -zxvf ";
wget = "wget -c ";
grep = "grep --color=auto";
fgrep = "fgrep --color=auto";
egrep = "egrep --color=auto";
jctl = "journalctl -p 3 -xb";
update = "sudo nixos-rebuild switch --flake .#${config.networking.hostName}";
cleanup = "sudo nix-collect-garbage -d";
};
modules.shell.fish.enable = lib.mkDefault true;
modules.shell.fish.defaultShell = lib.mkDefault true;
modules.shell.tmux.enable = lib.mkDefault true;
modules.shell.nvim.enable = lib.mkDefault true;
modules.shell.git.enable = lib.mkDefault true;
modules.shell.direnv.enable = lib.mkDefault true;
modules.shell.yazi.enable = lib.mkDefault true;
};
}

View File

@@ -6,11 +6,11 @@
}: }:
# Alacritty as the desktop terminal. # Alacritty as the desktop terminal.
let let
cfg = config.modules.desktop.terminal; cfg = config.modules.desktop.apps.alacritty;
user = config.user.name; user = config.user.name;
in in
{ {
options.modules.desktop.terminal.enable = lib.mkEnableOption "Alacritty as the desktop terminal"; options.modules.desktop.apps.alacritty.enable = lib.mkEnableOption "Alacritty as the desktop terminal";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
home-manager.users.${user}.home.packages = [ pkgs.alacritty ]; home-manager.users.${user}.home.packages = [ pkgs.alacritty ];

View File

@@ -7,12 +7,12 @@
}: }:
# Firefox as the desktop browser: stock mainline, hardened and de-monetized by policy. # Firefox as the desktop browser: stock mainline, hardened and de-monetized by policy.
let let
cfg = config.modules.desktop.firefox; cfg = config.modules.desktop.apps.firefox;
user = config.user.name; user = config.user.name;
firefoxAddons = inputs.firefox-addons.packages.${pkgs.stdenv.hostPlatform.system}; firefoxAddons = inputs.firefox-addons.packages.${pkgs.stdenv.hostPlatform.system};
in in
{ {
options.modules.desktop.firefox.enable = lib.mkEnableOption "Firefox as the desktop browser"; options.modules.desktop.apps.firefox.enable = lib.mkEnableOption "Firefox as the desktop browser";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
home-manager.users.${user} = hm: { home-manager.users.${user} = hm: {

View File

@@ -0,0 +1,18 @@
{
config,
lib,
pkgs,
...
}:
# Ghostty as the desktop terminal.
let
cfg = config.modules.desktop.apps.ghostty;
user = config.user.name;
in
{
options.modules.desktop.apps.ghostty.enable = lib.mkEnableOption "Ghostty as the desktop terminal";
config = lib.mkIf cfg.enable {
home-manager.users.${user}.home.packages = [ pkgs.ghostty ];
};
}

View File

@@ -6,11 +6,11 @@
}: }:
# Obsidian as the desktop note-taking vault. # Obsidian as the desktop note-taking vault.
let let
cfg = config.modules.desktop.obsidian; cfg = config.modules.desktop.apps.obsidian;
user = config.user.name; user = config.user.name;
in in
{ {
options.modules.desktop.obsidian.enable = lib.mkEnableOption "Obsidian as the desktop note-taking vault"; options.modules.desktop.apps.obsidian.enable = lib.mkEnableOption "Obsidian as the desktop note-taking vault";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
home-manager.users.${user}.home.packages = [ pkgs.obsidian ]; home-manager.users.${user}.home.packages = [ pkgs.obsidian ];

View File

@@ -6,10 +6,10 @@
}: }:
# Steam game launcher and runtime integration. # Steam game launcher and runtime integration.
let let
cfg = config.modules.desktop.steam; cfg = config.modules.desktop.apps.steam;
in in
{ {
options.modules.desktop.steam.enable = lib.mkEnableOption "Steam game launcher"; options.modules.desktop.apps.steam.enable = lib.mkEnableOption "Steam game launcher";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
programs.steam = { programs.steam = {

View File

@@ -0,0 +1,30 @@
{ config, lib, ... }:
# The desktop aggregator: one flag brings up the whole graphical session.
let
cfg = config.modules.desktop;
in
{
options.modules.desktop.enable = lib.mkEnableOption "the keyboard-driven Hyprland desktop";
# Each piece is turned on at default priority, so a host can still override
# any one of them while the single flag above enables the whole desktop.
config = lib.mkIf cfg.enable {
modules.desktop.apps.firefox.enable = lib.mkDefault true;
modules.desktop.apps.ghostty.enable = lib.mkDefault true;
modules.desktop.session.hyprland.enable = lib.mkDefault true;
modules.desktop.session.hyprland.hypridle.enable = lib.mkDefault true;
modules.desktop.session.hyprland.hyprlock.enable = lib.mkDefault true;
modules.desktop.session.login.enable = lib.mkDefault true;
modules.desktop.session.mako.enable = lib.mkDefault true;
modules.desktop.session.portals.enable = lib.mkDefault true;
modules.desktop.session.rofi.enable = lib.mkDefault true;
modules.desktop.session.waybar.enable = lib.mkDefault true;
modules.desktop.utilities.audio.enable = lib.mkDefault true;
modules.desktop.utilities.clipboard.enable = lib.mkDefault true;
modules.desktop.utilities.osd.enable = lib.mkDefault true;
modules.desktop.utilities.recording.enable = lib.mkDefault true;
modules.desktop.utilities.screenshot.enable = lib.mkDefault true;
modules.desktop.utilities.theming.enable = lib.mkDefault true;
modules.desktop.utilities.userdirs.enable = lib.mkDefault true;
};
}

View File

@@ -1,30 +0,0 @@
{ config, lib, ... }:
# The desktop aggregator: one flag brings up the whole graphical session.
let
cfg = config.modules.desktop;
in
{
options.modules.desktop.enable = lib.mkEnableOption "the keyboard-driven Hyprland desktop";
# Each piece is turned on at default priority, so a host can still override
# any one of them while the single flag above enables the whole desktop.
config = lib.mkIf cfg.enable {
modules.desktop.clipboard.enable = lib.mkDefault true;
modules.desktop.firefox.enable = lib.mkDefault true;
modules.desktop.hyprland.enable = lib.mkDefault true;
modules.desktop.hyprland.hyprlock.enable = lib.mkDefault true;
modules.desktop.hyprland.hypridle.enable = lib.mkDefault true;
modules.desktop.login.enable = lib.mkDefault true;
modules.desktop.mako.enable = lib.mkDefault true;
modules.desktop.portals.enable = lib.mkDefault true;
modules.desktop.recording.enable = lib.mkDefault true;
modules.desktop.rofi.enable = lib.mkDefault true;
modules.desktop.screenshot.enable = lib.mkDefault true;
modules.desktop.terminal.enable = lib.mkDefault true;
modules.desktop.userdirs.enable = lib.mkDefault true;
modules.desktop.theming.enable = lib.mkDefault true;
modules.desktop.waybar.enable = lib.mkDefault true;
modules.desktop.audio.enable = lib.mkDefault true;
modules.desktop.osd.enable = lib.mkDefault true;
};
}

View File

@@ -6,7 +6,7 @@
}: }:
# The Hyprland compositor. # The Hyprland compositor.
let let
cfg = config.modules.desktop.hyprland; cfg = config.modules.desktop.session.hyprland;
user = config.user.name; user = config.user.name;
cursor = config.stylix.cursor; cursor = config.stylix.cursor;
@@ -27,7 +27,7 @@ let
''; '';
in in
{ {
options.modules.desktop.hyprland = { options.modules.desktop.session.hyprland = {
enable = lib.mkEnableOption "the Hyprland compositor"; enable = lib.mkEnableOption "the Hyprland compositor";
blur = lib.mkEnableOption '' blur = lib.mkEnableOption ''
@@ -61,7 +61,7 @@ in
settings = { settings = {
"$mod" = "SUPER"; "$mod" = "SUPER";
"$terminal" = "alacritty"; "$terminal" = "ghostty";
# Session variables handed to the compositor directly. # Session variables handed to the compositor directly.
# UWSM launches the session without the shell profile that would carry # UWSM launches the session without the shell profile that would carry

View File

@@ -6,7 +6,7 @@
}: }:
# hypridle: idle-triggered locking and display power management. # hypridle: idle-triggered locking and display power management.
let let
cfg = config.modules.desktop.hyprland.hypridle; cfg = config.modules.desktop.session.hyprland.hypridle;
user = config.user.name; user = config.user.name;
hyprctl = "${config.programs.hyprland.package}/bin/hyprctl"; hyprctl = "${config.programs.hyprland.package}/bin/hyprctl";
@@ -17,7 +17,7 @@ let
lockCmd = "${pkgs.procps}/bin/pidof hyprlock || ${hyprlock}"; lockCmd = "${pkgs.procps}/bin/pidof hyprlock || ${hyprlock}";
in in
{ {
options.modules.desktop.hyprland.hypridle = { options.modules.desktop.session.hyprland.hypridle = {
enable = lib.mkEnableOption "hypridle idle management"; enable = lib.mkEnableOption "hypridle idle management";
lockTimeout = lib.mkOption { lockTimeout = lib.mkOption {

View File

@@ -6,7 +6,7 @@
}: }:
# The lock screen: a hyprlock session-lock surface the compositor owns. # The lock screen: a hyprlock session-lock surface the compositor owns.
let let
cfg = config.modules.desktop.hyprland.hyprlock; cfg = config.modules.desktop.session.hyprland.hyprlock;
user = config.user.name; user = config.user.name;
# The hyprlock this module installs, used by the lock keybind below. # The hyprlock this module installs, used by the lock keybind below.
@@ -45,7 +45,7 @@ let
''; '';
in in
{ {
options.modules.desktop.hyprland.hyprlock.enable = lib.mkEnableOption "the hyprlock lock screen"; options.modules.desktop.session.hyprland.hyprlock.enable = lib.mkEnableOption "the hyprlock lock screen";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
home-manager.users.${user} = { home-manager.users.${user} = {

View File

@@ -7,10 +7,10 @@
# Text login: greetd running the tuigreet greeter, which starts the session # Text login: greetd running the tuigreet greeter, which starts the session
# through the universal Wayland session manager. # through the universal Wayland session manager.
let let
cfg = config.modules.desktop.login; cfg = config.modules.desktop.session.login;
in in
{ {
options.modules.desktop.login.enable = lib.mkEnableOption "greetd with the tuigreet text greeter"; options.modules.desktop.session.login.enable = lib.mkEnableOption "greetd with the tuigreet text greeter";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
services.greetd = { services.greetd = {

View File

@@ -6,13 +6,13 @@
}: }:
# mako as the notification daemon: toasts, a do-not-disturb mode, and history recall. # mako as the notification daemon: toasts, a do-not-disturb mode, and history recall.
let let
cfg = config.modules.desktop.mako; cfg = config.modules.desktop.session.mako;
user = config.user.name; user = config.user.name;
makoctl = "${pkgs.mako}/bin/makoctl"; makoctl = "${pkgs.mako}/bin/makoctl";
in in
{ {
options.modules.desktop.mako.enable = lib.mkEnableOption "the mako notification daemon"; options.modules.desktop.session.mako.enable = lib.mkEnableOption "the mako notification daemon";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
home-manager.users.${user} = { home-manager.users.${user} = {

View File

@@ -1,10 +1,10 @@
{ config, lib, ... }: { config, lib, ... }:
# XDG desktop portal routing for in-app screen sharing and file dialogs. # XDG desktop portal routing for in-app screen sharing and file dialogs.
let let
cfg = config.modules.desktop.portals; cfg = config.modules.desktop.session.portals;
in in
{ {
options.modules.desktop.portals.enable = options.modules.desktop.session.portals.enable =
lib.mkEnableOption "XDG desktop portals for in-app screen sharing and file dialogs"; lib.mkEnableOption "XDG desktop portals for in-app screen sharing and file dialogs";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {

View File

@@ -6,7 +6,7 @@
}: }:
# rofi as the desktop launcher and dmenu-style menu frontend. # rofi as the desktop launcher and dmenu-style menu frontend.
let let
cfg = config.modules.desktop.rofi; cfg = config.modules.desktop.session.rofi;
user = config.user.name; user = config.user.name;
# A session menu built on the same themed rofi, so the power actions look # A session menu built on the same themed rofi, so the power actions look
@@ -24,7 +24,7 @@ let
''; '';
in in
{ {
options.modules.desktop.rofi.enable = lib.mkEnableOption "the rofi launcher"; options.modules.desktop.session.rofi.enable = lib.mkEnableOption "the rofi launcher";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
home-manager.users.${user} = { home-manager.users.${user} = {

View File

@@ -6,7 +6,7 @@
}: }:
# Waybar: a top status bar reading system state at a glance. # Waybar: a top status bar reading system state at a glance.
let let
cfg = config.modules.desktop.waybar; cfg = config.modules.desktop.session.waybar;
user = config.user.name; user = config.user.name;
# A Nerd Font Private-Use-Area codepoint as a literal character, decoded # A Nerd Font Private-Use-Area codepoint as a literal character, decoded
@@ -49,7 +49,7 @@ let
''; '';
in in
{ {
options.modules.desktop.waybar.enable = lib.mkEnableOption "the Waybar status bar"; options.modules.desktop.session.waybar.enable = lib.mkEnableOption "the Waybar status bar";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
# A symbols font backs the module glyphs, so pango falls back to it for the # A symbols font backs the module glyphs, so pango falls back to it for the
@@ -89,6 +89,7 @@ in
window-rewrite-default = g "f2d0"; window-rewrite-default = g "f2d0";
window-rewrite = { window-rewrite = {
"class<Alacritty>" = g "f120"; "class<Alacritty>" = g "f120";
"class<com.mitchellh.ghostty>" = g "f120";
"class<.*[Ff]irefox.*>" = g "f269"; "class<.*[Ff]irefox.*>" = g "f269";
"class<chromium.*>" = g "f268"; "class<chromium.*>" = g "f268";
"class<[Cc]ode>" = g "f121"; "class<[Cc]ode>" = g "f121";

View File

@@ -1,10 +1,10 @@
{ config, lib, ... }: { config, lib, ... }:
# PipeWire as the desktop audio server. # PipeWire as the desktop audio server.
let let
cfg = config.modules.desktop.audio; cfg = config.modules.desktop.utilities.audio;
in in
{ {
options.modules.desktop.audio.enable = lib.mkEnableOption "the PipeWire audio server"; options.modules.desktop.utilities.audio.enable = lib.mkEnableOption "the PipeWire audio server";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
# Realtime scheduling for the audio threads, so playback survives load. # Realtime scheduling for the audio threads, so playback survives load.

View File

@@ -6,7 +6,7 @@
}: }:
# Clipboard history: cliphist records every copy, picked back through rofi. # Clipboard history: cliphist records every copy, picked back through rofi.
let let
cfg = config.modules.desktop.clipboard; cfg = config.modules.desktop.utilities.clipboard;
user = config.user.name; user = config.user.name;
cliphist = "${pkgs.cliphist}/bin/cliphist"; cliphist = "${pkgs.cliphist}/bin/cliphist";
@@ -25,7 +25,7 @@ let
''; '';
in in
{ {
options.modules.desktop.clipboard.enable = lib.mkEnableOption "cliphist clipboard history"; options.modules.desktop.utilities.clipboard.enable = lib.mkEnableOption "cliphist clipboard history";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
home-manager.users.${user} = { home-manager.users.${user} = {

View File

@@ -6,11 +6,11 @@
}: }:
# SwayOSD: a transient on-screen popup for volume and brightness changes. # SwayOSD: a transient on-screen popup for volume and brightness changes.
let let
cfg = config.modules.desktop.osd; cfg = config.modules.desktop.utilities.osd;
user = config.user.name; user = config.user.name;
in in
{ {
options.modules.desktop.osd.enable = lib.mkEnableOption "the SwayOSD volume and brightness popup"; options.modules.desktop.utilities.osd.enable = lib.mkEnableOption "the SwayOSD volume and brightness popup";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
environment.systemPackages = [ pkgs.swayosd ]; environment.systemPackages = [ pkgs.swayosd ];

View File

@@ -6,7 +6,7 @@
}: }:
# Keybound screen recording: pick a region, then toggle a video-only capture. # Keybound screen recording: pick a region, then toggle a video-only capture.
let let
cfg = config.modules.desktop.recording; cfg = config.modules.desktop.utilities.recording;
user = config.user.name; user = config.user.name;
slurp = "${pkgs.slurp}/bin/slurp"; slurp = "${pkgs.slurp}/bin/slurp";
@@ -41,7 +41,7 @@ let
''; '';
in in
{ {
options.modules.desktop.recording.enable = lib.mkEnableOption "wf-recorder screen recording"; options.modules.desktop.utilities.recording.enable = lib.mkEnableOption "wf-recorder screen recording";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
home-manager.users.${user} = { home-manager.users.${user} = {

View File

@@ -7,7 +7,7 @@
# Keyboard-driven screenshots that open in satty for annotation, then land in # Keyboard-driven screenshots that open in satty for annotation, then land in
# both the clipboard and a dated file. # both the clipboard and a dated file.
let let
cfg = config.modules.desktop.screenshot; cfg = config.modules.desktop.utilities.screenshot;
user = config.user.name; user = config.user.name;
grimblast = "${pkgs.grimblast}/bin/grimblast"; grimblast = "${pkgs.grimblast}/bin/grimblast";
@@ -32,7 +32,7 @@ let
''; '';
in in
{ {
options.modules.desktop.screenshot.enable = lib.mkEnableOption "screenshots via grimblast and satty"; options.modules.desktop.utilities.screenshot.enable = lib.mkEnableOption "screenshots via grimblast and satty";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
home-manager.users.${user} = { home-manager.users.${user} = {

View File

@@ -6,7 +6,7 @@
}: }:
# Nord theming for the graphical layer, driven from one base16 scheme by Stylix. # Nord theming for the graphical layer, driven from one base16 scheme by Stylix.
let let
cfg = config.modules.desktop.theming; cfg = config.modules.desktop.utilities.theming;
user = config.user.name; user = config.user.name;
# A single static Nord wallpaper, drawn as a vertical gradient across the # A single static Nord wallpaper, drawn as a vertical gradient across the
@@ -18,7 +18,7 @@ let
''; '';
in in
{ {
options.modules.desktop.theming.enable = options.modules.desktop.utilities.theming.enable =
lib.mkEnableOption "Nord theming of the graphical layer via Stylix"; lib.mkEnableOption "Nord theming of the graphical layer via Stylix";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {

View File

@@ -2,11 +2,11 @@
# Declares the XDG user directories, so a tool that queries them lands in a # Declares the XDG user directories, so a tool that queries them lands in a
# well-known folder a host can relocate from one place. # well-known folder a host can relocate from one place.
let let
cfg = config.modules.desktop.userdirs; cfg = config.modules.desktop.utilities.userdirs;
user = config.user.name; user = config.user.name;
in in
{ {
options.modules.desktop.userdirs.enable = lib.mkEnableOption "XDG user directories"; options.modules.desktop.utilities.userdirs.enable = lib.mkEnableOption "XDG user directories";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
# Write ~/.config/user-dirs.dirs from the option defaults. # Write ~/.config/user-dirs.dirs from the option defaults.

14
modules/guest.nix Normal file
View File

@@ -0,0 +1,14 @@
{ config, lib, ... }:
let
cfg = config.modules.guest;
in
{
options.modules.guest.enable = lib.mkEnableOption "nested-guest base configuration";
config = lib.mkIf cfg.enable {
system.stateVersion = "26.05";
modules.network.ssh.enable = lib.mkDefault true;
modules.network.ssh.hostKeys.restore = lib.mkDefault false;
};
}

42
modules/host.nix Normal file
View File

@@ -0,0 +1,42 @@
{
config,
lib,
...
}:
let
cfg = config.modules.host;
user = config.user;
passwordSecret = "${user.name}-password";
in
{
options.modules.host.enable = lib.mkEnableOption "physical-host base configuration";
config = lib.mkIf cfg.enable {
nix.settings.extra-substituters = [ "https://nyx-cache.chaotic.cx/" ];
nix.settings.extra-trusted-public-keys = [
"nyx-cache.chaotic.cx:dJxTrgMC3V3cFfyIiBQDQorG6k1LsqurH/srpMSq7qk="
];
nix.gc.automatic = true;
nix.gc.dates = "Mon 03:15";
nix.gc.options = "--delete-older-than 30d";
nix.optimise.automatic = true;
nix.optimise.dates = [ "Thu 03:45" ];
boot.loader.systemd-boot.configurationLimit = 15;
services.xserver.xkb.layout = "us";
services.xserver.xkb.options = "caps:escape_shifted_capslock";
console.useXkbConfig = true;
sops.defaultSopsFile = ../secrets/shared.yaml;
sops.age.keyFile = "/var/lib/sops-nix/key.txt";
sops.age.sshKeyPaths = [ ];
sops.gnupg.sshKeyPaths = [ ];
users.mutableUsers = false;
sops.secrets.${passwordSecret}.neededForUsers = true;
users.users.${user.name}.hashedPasswordFile = config.sops.secrets.${passwordSecret}.path;
};
}

View File

@@ -1,169 +0,0 @@
{
config,
lib,
my,
...
}:
# The host networking foundation: per-VLAN bridges over a tagged trunk.
let
cfg = config.modules.network;
# Each tagged VLAN materializes as a bridge named for its id, by the shared
# convention.
inherit (my) bridgeName;
# The tagged sub-interface stacked on the trunk that feeds one bridge.
vlanName = id: "${cfg.trunk}.${toString id}";
in
{
options.modules.network = {
enable =
lib.mkEnableOption "the host trunk, its tagged-VLAN bridges, and the host management address";
trunk = lib.mkOption {
type = lib.types.str;
example = "enp1s0";
description = ''
The physical interface carrying 802.1Q-tagged traffic for every VLAN.
Each declared VLAN is stacked on it and enslaved to its own bridge.
'';
};
vlans = lib.mkOption {
type = lib.types.listOf (lib.types.ints.between 1 4094);
default = [ ];
example = [
10
20
30
];
description = ''
The tagged VLAN ids to materialize. Each id N emits exactly one bridge
named `br-vlanN`, and guests on VLAN N attach to it.
'';
};
endpoint = {
address = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "10.23.50.146";
description = ''
Expected IP address assigned outside NixOS for this host's network
endpoint. Left null, this host contributes no host endpoint to the
fleet endpoint registry.
'';
};
};
endpoints = lib.mkOption {
type = lib.types.attrsOf my.networkEndpoints.endpointType;
default = { };
description = ''
Network endpoint declarations contributed by placed workloads on this
host, keyed by their local stable endpoint name.
'';
};
management = {
vlan = lib.mkOption {
type = lib.types.nullOr (lib.types.ints.between 1 4094);
default = null;
description = ''
The VLAN whose bridge carries the host's own management address; must
be one of `vlans`. Left null, the host takes no address on any bridge
and the bridges serve guests alone.
'';
};
address = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "10.0.10.2/24";
description = ''
The host's static management address, in CIDR form, on the management
VLAN's bridge. Left null, the host takes its address there by DHCP.
'';
};
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.management.vlan == null || lib.elem cfg.management.vlan cfg.vlans;
message = "modules.network.management.vlan (${toString cfg.management.vlan}) must name one of modules.network.vlans.";
}
{
assertion = cfg.management.address == null || cfg.management.vlan != null;
message = "modules.network.management.address needs modules.network.management.vlan to say which bridge carries it.";
}
];
# networkd owns the trunk, its VLAN sub-interfaces, and the bridges, so a host
# also running NetworkManager leaves them to networkd rather than contending.
networking.networkmanager.unmanaged =
[ "interface-name:${cfg.trunk}" ]
++ map (id: "interface-name:${bridgeName id}") cfg.vlans
++ map (id: "interface-name:${vlanName id}") cfg.vlans;
systemd.network = {
enable = true;
netdevs = lib.mkMerge (
map (id: {
"40-${bridgeName id}" = {
netdevConfig = {
Name = bridgeName id;
Kind = "bridge";
};
};
"40-${vlanName id}" = {
netdevConfig = {
Name = vlanName id;
Kind = "vlan";
};
vlanConfig.Id = id;
};
}) cfg.vlans
);
networks = lib.mkMerge (
[
# The trunk carries only tagged frames up to the sub-interfaces and
# takes no address of its own.
{
"30-${cfg.trunk}" = {
matchConfig.Name = cfg.trunk;
networkConfig.LinkLocalAddressing = "no";
linkConfig.RequiredForOnline = "no";
vlan = map vlanName cfg.vlans;
};
}
]
++ map (id: {
# Enslaved to its bridge, carrying no address itself.
"40-${vlanName id}" = {
matchConfig.Name = vlanName id;
networkConfig.Bridge = bridgeName id;
linkConfig.RequiredForOnline = "no";
};
# The management VLAN's bridge carries the host address; every other
# bridge is a plain L2 segment for guests.
"40-${bridgeName id}" = lib.mkMerge [
{
matchConfig.Name = bridgeName id;
linkConfig.RequiredForOnline = "no";
}
(lib.mkIf (cfg.management.vlan == id) (
if cfg.management.address == null then
{ networkConfig.DHCP = "yes"; }
else
{ address = [ cfg.management.address ]; }
))
];
}) cfg.vlans
);
};
};
}

View File

@@ -1,11 +1,12 @@
{ {
config, config,
lib, lib,
registry,
... ...
}: }:
# SSH on this machine, in both directions. # SSH on this machine, in both directions.
let let
cfg = config.modules.ssh; cfg = config.modules.network.ssh;
user = config.user.name; user = config.user.name;
inherit (lib) inherit (lib)
@@ -152,7 +153,7 @@ let
); );
in in
{ {
options.modules.ssh = { options.modules.network.ssh = {
enable = lib.mkEnableOption "the OpenSSH daemon, with host keys restored from secrets"; enable = lib.mkEnableOption "the OpenSSH daemon, with host keys restored from secrets";
hosts = { hosts = {
@@ -189,7 +190,7 @@ in
}; };
neogaia = { neogaia = {
hostName = "10.23.50.146"; hostName = registry.address.neogaia.self;
clientKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGxQ4kWsBo2OGYIPOkFe0vNEcB3yoJwAu0y9wrdQzALE alexion@neogaia"; clientKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGxQ4kWsBo2OGYIPOkFe0vNEcB3yoJwAu0y9wrdQzALE alexion@neogaia";
hostKeys = [ hostKeys = [
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJS+wp7K123+4BT6G4f954R6WyrbWveY7VlpoBUf6I5p neogaia" "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJS+wp7K123+4BT6G4f954R6WyrbWveY7VlpoBUf6I5p neogaia"
@@ -198,7 +199,7 @@ in
}; };
pikachu = { pikachu = {
hostName = "10.23.10.102"; hostName = registry.address.pikachu.self;
clientKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINNqJIC6VRXyvrNf3n9su9KdPCikC3CjK/QrCK2reHdB alexion@pikachu"; clientKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINNqJIC6VRXyvrNf3n9su9KdPCikC3CjK/QrCK2reHdB alexion@pikachu";
hostKeys = [ hostKeys = [
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKljRf4pJO+pqEqjpPz08gOYq3g1PpxvE66xVw7uMEnA root@pikachu" "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKljRf4pJO+pqEqjpPz08gOYq3g1PpxvE66xVw7uMEnA root@pikachu"
@@ -225,7 +226,7 @@ in
default = null; default = null;
description = '' description = ''
Complete override for client public keys admitted by this host. Complete override for client public keys admitted by this host.
Leave null to derive access from `modules.ssh.hosts` and `modules.ssh.targets`. Leave null to derive access from `modules.network.ssh.hosts` and `modules.network.ssh.targets`.
''; '';
}; };
@@ -303,7 +304,7 @@ in
assertions = [ assertions = [
{ {
assertion = cfg.hostKeys.sopsFile != null; assertion = cfg.hostKeys.sopsFile != null;
message = "modules.ssh.hostKeys.restore requires modules.ssh.hostKeys.sopsFile to name the encrypted host keys."; message = "modules.network.ssh.hostKeys.restore requires modules.network.ssh.hostKeys.sopsFile to name the encrypted host keys.";
} }
]; ];

141
modules/network/vlans.nix Normal file
View File

@@ -0,0 +1,141 @@
{
config,
lib,
util,
...
}:
# The host networking foundation: per-VLAN bridges over a tagged trunk.
let
cfg = config.modules.network.vlans;
inherit (util) bridgeName;
vlanName = id: "${cfg.trunk}.${toString id}";
in
{
options.modules.network.vlans = {
enable = lib.mkEnableOption "host VLAN bridges over a tagged trunk";
trunk = lib.mkOption {
type = lib.types.str;
example = "enp1s0";
description = ''
Physical interface that carries 802.1Q-tagged traffic for every VLAN.
Each declared VLAN attaches to its own bridge.
'';
};
ids = lib.mkOption {
type = lib.types.listOf (lib.types.ints.between 1 4094);
default = [ ];
example = [
10
20
30
];
description = ''
Tagged VLAN ids to materialize.
Each id N creates one bridge named `br-vlanN`.
'';
};
management = {
vlan = lib.mkOption {
type = lib.types.nullOr (lib.types.ints.between 1 4094);
default = null;
description = ''
VLAN whose bridge carries the host's own management address.
The value must be one of `ids`.
Left null, the host takes no address on any bridge.
'';
};
address = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
example = "10.0.10.2/24";
description = ''
Host static management address in CIDR form.
Left null, the host takes its management address by DHCP.
'';
};
};
};
config = lib.mkIf cfg.enable {
assertions = [
{
assertion = cfg.management.vlan == null || lib.elem cfg.management.vlan cfg.ids;
message = "modules.network.vlans.management.vlan (${toString cfg.management.vlan}) must name one of modules.network.vlans.ids.";
}
{
assertion = cfg.management.address == null || cfg.management.vlan != null;
message = "modules.network.vlans.management.address needs modules.network.vlans.management.vlan to say which bridge carries it.";
}
];
# networkd owns these interfaces so NetworkManager does not contend for them.
networking.networkmanager.unmanaged =
[ "interface-name:${cfg.trunk}" ]
++ map (id: "interface-name:${bridgeName id}") cfg.ids
++ map (id: "interface-name:${vlanName id}") cfg.ids;
systemd.network = {
enable = true;
netdevs = lib.mkMerge (
map (id: {
"40-${bridgeName id}" = {
netdevConfig = {
Name = bridgeName id;
Kind = "bridge";
};
};
"40-${vlanName id}" = {
netdevConfig = {
Name = vlanName id;
Kind = "vlan";
};
vlanConfig.Id = id;
};
}) cfg.ids
);
networks = lib.mkMerge (
[
# The trunk carries only tagged frames and takes no address.
{
"30-${cfg.trunk}" = {
matchConfig.Name = cfg.trunk;
networkConfig.LinkLocalAddressing = "no";
linkConfig.RequiredForOnline = "no";
vlan = map vlanName cfg.ids;
};
}
]
++ map (id: {
# Enslaved to its bridge, carrying no address itself.
"40-${vlanName id}" = {
matchConfig.Name = vlanName id;
networkConfig.Bridge = bridgeName id;
linkConfig.RequiredForOnline = "no";
};
# The management bridge carries the host address.
# Other bridges provide L2 segments for guests.
"40-${bridgeName id}" = lib.mkMerge [
{
matchConfig.Name = bridgeName id;
linkConfig.RequiredForOnline = "no";
}
(lib.mkIf (cfg.management.vlan == id) (
if cfg.management.address == null then
{ networkConfig.DHCP = "yes"; }
else
{ address = [ cfg.management.address ]; }
))
];
}) cfg.ids
);
};
};
}

View File

@@ -1,97 +0,0 @@
{ config, lib, my, ... }:
let
cfg = config.modules.reverse-proxy;
inherit (my) reverseProxyRoutes;
enabledRoutes = lib.filterAttrs (_: route: route.enable) cfg.routes;
routesByHost = lib.groupBy (route: route.host) (lib.attrValues enabledRoutes);
rootRoutesByHost = lib.mapAttrs (
host: routes:
let
roots = builtins.filter (route: route.path == "/") routes;
in
if roots == [ ] then null else builtins.head roots
) routesByHost;
hasDuplicatePaths = routes:
let
paths = map (route: route.path) routes;
in
lib.length paths != lib.length (lib.unique paths);
hasUnresolvedBackend = route: route.backend == null;
mkLocation = route: {
proxyPass = route.backend;
proxyWebsockets = route.websockets;
};
mkVirtualHost = host: routes:
let
rootRoute = rootRoutesByHost.${host};
in
lib.mkIf (rootRoute != null) {
forceSSL = rootRoute.tls;
enableACME = rootRoute.tls;
serverAliases = rootRoute.aliases;
locations = lib.listToAttrs (
map (route: lib.nameValuePair route.path (mkLocation route)) (
builtins.filter (route: route.backend != null) routes
)
);
};
in
{
options.modules.reverse-proxy = {
enable = lib.mkEnableOption "the Nginx reverse proxy route realizer";
routes = lib.mkOption {
type = lib.types.attrsOf reverseProxyRoutes.routeType;
default = { };
description = "Reverse-proxy route declarations keyed by stable route name.";
};
};
config = lib.mkIf cfg.enable {
assertions =
lib.mapAttrsToList (host: rootRoute: {
assertion = rootRoute != null;
message = "modules.reverse-proxy.routes for ${host} must include a primary / route.";
}) rootRoutesByHost
++ lib.mapAttrsToList (host: routes: {
assertion = !hasDuplicatePaths routes;
message = "modules.reverse-proxy.routes for ${host} must not declare the same path more than once.";
}) routesByHost
++ map (route: {
assertion = !hasUnresolvedBackend route;
message = "modules.reverse-proxy.routes for ${route.host}${route.path} must resolve to a backend URL before actualization.";
}) (builtins.filter hasUnresolvedBackend (lib.attrValues enabledRoutes));
networking.firewall.allowedTCPPorts = [
80
443
];
security.acme = {
acceptTerms = true;
defaults.email = "contact@alexion.dev";
};
services.nginx = {
enable = true;
commonHttpConfig = ''
server {
listen 0.0.0.0:443 ssl default_server;
listen [::0]:443 ssl default_server;
ssl_reject_handshake on;
}
'';
recommendedGzipSettings = true;
recommendedOptimisation = true;
recommendedProxySettings = true;
recommendedTlsSettings = true;
virtualHosts = lib.mapAttrs mkVirtualHost routesByHost;
};
};
}

View File

@@ -1,7 +1,6 @@
{ {
config, config,
lib, lib,
my,
... ...
}: }:
let let
@@ -29,12 +28,6 @@ in
description = "User account that runs Actual Budget."; description = "User account that runs Actual Budget.";
}; };
uid = lib.mkOption {
type = lib.types.ints.positive;
default = my.serviceUid "actualbudget";
description = "Stable uid for the Actual Budget service user.";
};
group = lib.mkOption { group = lib.mkOption {
type = lib.types.str; type = lib.types.str;
default = "storage"; default = "storage";
@@ -43,21 +36,27 @@ in
}; };
config = lib.mkIf cfg.enable { config = lib.mkMerge [
users.users.${cfg.user} = { {
isSystemUser = true; registry."stable-uid".${config.networking.hostName}.actualbudget = 20001;
uid = cfg.uid; }
group = cfg.group;
};
services.actual = { (lib.mkIf cfg.enable {
enable = true; users.users.${cfg.user} = {
openFirewall = true; isSystemUser = true;
user = cfg.user; uid = config.registry."stable-uid".${config.networking.hostName}.actualbudget;
group = cfg.group; group = cfg.group;
settings = {
inherit (cfg) port dataDir;
}; };
};
}; services.actual = {
enable = true;
openFirewall = true;
user = cfg.user;
group = cfg.group;
settings = {
inherit (cfg) port dataDir;
};
};
})
];
} }

View File

@@ -1,7 +1,6 @@
{ {
config, config,
lib, lib,
my,
pkgs, pkgs,
... ...
}: }:
@@ -102,12 +101,6 @@ in
description = "User account that runs Copyparty."; description = "User account that runs Copyparty.";
}; };
uid = lib.mkOption {
type = lib.types.ints.positive;
default = my.serviceUid "copyparty";
description = "Stable uid for the Copyparty service user.";
};
group = lib.mkOption { group = lib.mkOption {
type = lib.types.str; type = lib.types.str;
default = "storage"; default = "storage";
@@ -148,54 +141,60 @@ in
}; };
}; };
config = lib.mkIf cfg.enable { config = lib.mkMerge [
assertions = [ {
{ registry."stable-uid".${config.networking.hostName}.copyparty = 20002;
assertion = cfg.volumes != { }; }
message = "modules.services.copyparty.volumes must declare at least one served volume.";
}
{
assertion = !cfg.reverseProxy.enable || cfg.reverseProxy.trustedSources != [ ];
message = "modules.services.copyparty.reverseProxy.trustedSources must name at least one trusted proxy source when reverse-proxy support is enabled.";
}
];
users.users.${cfg.user} = { (lib.mkIf cfg.enable {
isSystemUser = true; assertions = [
uid = cfg.uid; {
group = cfg.group; assertion = cfg.volumes != { };
home = cfg.stateDir; message = "modules.services.copyparty.volumes must declare at least one served volume.";
}; }
{
assertion = !cfg.reverseProxy.enable || cfg.reverseProxy.trustedSources != [ ];
message = "modules.services.copyparty.reverseProxy.trustedSources must name at least one trusted proxy source when reverse-proxy support is enabled.";
}
];
systemd.services.copyparty = { users.users.${cfg.user} = {
description = "Copyparty file server"; isSystemUser = true;
after = [ "network.target" ]; uid = config.registry."stable-uid".${config.networking.hostName}.copyparty;
wantedBy = [ "multi-user.target" ]; group = cfg.group;
serviceConfig = { home = cfg.stateDir;
ReloadSignal = "SIGUSR1";
Type = "simple";
User = cfg.user;
Group = cfg.group;
WorkingDirectory = cfg.stateDir;
Environment = [
"HOME=${cfg.stateDir}"
"XDG_CONFIG_HOME=${cfg.stateDir}"
];
StateDirectory = "copyparty";
RuntimeDirectory = "copyparty";
RuntimeDirectoryMode = "0700";
LoadCredential = [ "password:${cfg.passwordFile}" ];
ExecStartPre = configScript;
ExecStart = "${lib.getExe cfg.package} -c /run/copyparty/copyparty.conf";
Restart = "on-failure";
NoNewPrivileges = true;
PrivateTmp = true;
ProtectSystem = "strict";
ProtectHome = true;
ReadWritePaths = [ cfg.stateDir ] ++ map (volume: volume.path) (lib.attrValues cfg.volumes);
}; };
};
networking.firewall.allowedTCPPorts = [ cfg.port ]; systemd.services.copyparty = {
}; description = "Copyparty file server";
after = [ "network.target" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
ReloadSignal = "SIGUSR1";
Type = "simple";
User = cfg.user;
Group = cfg.group;
WorkingDirectory = cfg.stateDir;
Environment = [
"HOME=${cfg.stateDir}"
"XDG_CONFIG_HOME=${cfg.stateDir}"
];
StateDirectory = "copyparty";
RuntimeDirectory = "copyparty";
RuntimeDirectoryMode = "0700";
LoadCredential = [ "password:${cfg.passwordFile}" ];
ExecStartPre = configScript;
ExecStart = "${lib.getExe cfg.package} -c /run/copyparty/copyparty.conf";
Restart = "on-failure";
NoNewPrivileges = true;
PrivateTmp = true;
ProtectSystem = "strict";
ProtectHome = true;
ReadWritePaths = [ cfg.stateDir ] ++ map (volume: volume.path) (lib.attrValues cfg.volumes);
};
};
networking.firewall.allowedTCPPorts = [ cfg.port ];
})
];
} }

View File

@@ -0,0 +1,95 @@
{
config,
lib,
registry,
...
}:
let
cfg = config.modules.services.reverse-proxy;
mkRegistryPath = registryName: host: entry: "registry.${registryName}.${host}.${entry}";
mkBackend = address: route: "http://${address}:${toString route.port}";
mkVirtualHost = host: entry:
let
compositeEntry = registry.join host entry;
route = compositeEntry.route;
address = compositeEntry.address or (throw "no matching entry in registry.address for ${mkRegistryPath "route" host entry}");
in
{
inherit host entry;
name = route.domain;
value = {
forceSSL = true;
enableACME = true;
locations."/".proxyPass = mkBackend address route;
};
};
generatedVirtualHostList = lib.concatLists (
lib.mapAttrsToList (
host: routes:
lib.mapAttrsToList (entry: _route: mkVirtualHost host entry) routes
) registry.route
);
virtualHostsByDomain = lib.foldl' (
acc: virtualHost:
acc
// {
${virtualHost.name} = (acc.${virtualHost.name} or [ ]) ++ [ virtualHost ];
}
) { } generatedVirtualHostList;
duplicateDomainMessages = lib.concatLists (
lib.mapAttrsToList (
domain: virtualHosts:
if lib.length virtualHosts > 1 then
[
"duplicate route domain ${domain} in ${lib.concatMapStringsSep " and " (virtualHost: mkRegistryPath "route" virtualHost.host virtualHost.entry) virtualHosts}"
]
else
[ ]
) virtualHostsByDomain
);
generatedVirtualHosts =
if duplicateDomainMessages != [ ] then
throw (builtins.head duplicateDomainMessages)
else
lib.listToAttrs generatedVirtualHostList;
in
{
options.modules.services.reverse-proxy = {
enable = lib.mkEnableOption "the public edge reverse proxy";
};
config = lib.mkIf cfg.enable {
networking.firewall.allowedTCPPorts = [
80
443
];
security.acme = {
acceptTerms = true;
defaults.email = "contact@alexion.dev";
};
services.nginx = {
enable = true;
commonHttpConfig = ''
server {
listen 0.0.0.0:443 ssl default_server;
listen [::0]:443 ssl default_server;
ssl_reject_handshake on;
}
'';
recommendedGzipSettings = true;
recommendedOptimisation = true;
recommendedProxySettings = true;
recommendedTlsSettings = true;
virtualHosts = generatedVirtualHosts;
};
};
}

View File

@@ -5,11 +5,11 @@
}: }:
# direnv for the primary user, configured through home-manager. # direnv for the primary user, configured through home-manager.
let let
cfg = config.modules.direnv; cfg = config.modules.shell.direnv;
user = config.user.name; user = config.user.name;
in in
{ {
options.modules.direnv.enable = options.modules.shell.direnv.enable =
lib.mkEnableOption "direnv for the primary user, with nix-direnv shell caching"; lib.mkEnableOption "direnv for the primary user, with nix-direnv shell caching";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
@@ -20,6 +20,7 @@ in
# nix-direnv caches the evaluated shell so re-entering a directory is instant # nix-direnv caches the evaluated shell so re-entering a directory is instant
# instead of re-running `nix develop`, and adds the `use flake` stdlib helper. # instead of re-running `nix develop`, and adds the `use flake` stdlib helper.
nix-direnv.enable = true; nix-direnv.enable = true;
stdlib = builtins.readFile ./repo-flake.sh;
}; };
}; };
} }

View File

@@ -0,0 +1,33 @@
if declare -f use_flake >/dev/null; then
__dotfiles_use_flake_definition="$(declare -f use_flake)"
eval "${__dotfiles_use_flake_definition/use_flake/__dotfiles_nix_direnv_use_flake}"
unset __dotfiles_use_flake_definition
use_flake() {
local flake_expr="${1:-.}"
if [[ "$flake_expr" == //* ]]; then
local git_root
if ! git_root="$(git rev-parse --show-toplevel 2>/dev/null)"; then
log_error 'use flake // requires a Git repository'
return 1
fi
local flake_suffix="${flake_expr#//}"
if [[ -n "$flake_suffix" && "$flake_suffix" != \#* && "$flake_suffix" != /* ]]; then
flake_expr="path:${git_root}/${flake_suffix}"
else
flake_expr="path:${git_root}${flake_suffix}"
fi
shift
__dotfiles_nix_direnv_use_flake "$flake_expr" "$@"
return
fi
__dotfiles_nix_direnv_use_flake "$@"
}
else
log_error 'nix-direnv must define use_flake before the // wrapper loads'
return 1
fi

View File

@@ -6,11 +6,13 @@
}: }:
# fish for the primary user, configured through home-manager. # fish for the primary user, configured through home-manager.
let let
cfg = config.modules.fish; cfg = config.modules.shell.fish;
user = config.user.name; user = config.user.name;
shortcuts = config.registry.shell-shortcut.${config.networking.hostName};
commandsOf = shortcuts: lib.mapAttrs (_name: shortcut: shortcut.command) shortcuts;
in in
{ {
options.modules.fish = { options.modules.shell.fish = {
enable = lib.mkEnableOption "fish as the user's shell, configured via home-manager"; enable = lib.mkEnableOption "fish as the user's shell, configured via home-manager";
defaultShell = lib.mkOption { defaultShell = lib.mkOption {
@@ -27,10 +29,8 @@ in
home-manager.users.${user} = { home-manager.users.${user} = {
home.packages = with pkgs; [ home.packages = with pkgs; [
eza # backs the ls/la/ll aliases
bat # backs the manpager bat # backs the manpager
fastfetch # the shell greeting fastfetch # the shell greeting
wget # backs the wget abbreviation
]; ];
programs.fish = { programs.fish = {
@@ -51,38 +51,8 @@ in
} }
]; ];
shellAliases = { shellAliases = commandsOf (lib.filterAttrs (_name: shortcut: !shortcut.abbreviation) shortcuts);
ls = "eza -alg --color=always --group-directories-first --icons=always"; shellAbbrs = commandsOf (lib.filterAttrs (_name: shortcut: shortcut.abbreviation) shortcuts);
la = "eza -a --color=always --group-directories-first --icons=always";
ll = "eza -lg --color=always --group-directories-first --icons=always";
lt = "eza -aT -I '.git' --color=always --group-directories-first --icons=always";
"l." = "eza -a | grep -e '^\\.'";
};
shellAbbrs = {
# Walk up the tree.
".." = "cd ..";
"..." = "cd ../..";
"...." = "cd ../../..";
vi = "nvim";
vim = "nvim";
cp = "cp -v";
tmx = "tmux new-session -A -s";
hs = "herdr --session";
tarnow = "tar -acf ";
untar = "tar -zxvf ";
wget = "wget -c ";
grep = "grep --color=auto";
fgrep = "fgrep --color=auto";
egrep = "egrep --color=auto";
jctl = "journalctl -p 3 -xb";
# Rebuild the system, and reclaim disk from old generations.
update = "sudo nixos-rebuild switch --flake .#${config.networking.hostName}";
cleanup = "sudo nix-collect-garbage -d";
};
functions = { functions = {
# Pick the logo that fits the terminal so the greeting never wraps. # Pick the logo that fits the terminal so the greeting never wraps.

View File

@@ -5,11 +5,11 @@
}: }:
# git for the primary user, configured through home-manager. # git for the primary user, configured through home-manager.
let let
cfg = config.modules.git; cfg = config.modules.shell.git;
user = config.user.name; user = config.user.name;
in in
{ {
options.modules.git.enable = options.modules.shell.git.enable =
lib.mkEnableOption "git for the primary user, carrying the operator's commit identity"; lib.mkEnableOption "git for the primary user, carrying the operator's commit identity";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {

View File

@@ -6,13 +6,15 @@
}: }:
# Herdr, a terminal multiplexer for coding agents. # Herdr, a terminal multiplexer for coding agents.
let let
cfg = config.modules.agents.herdr; cfg = config.modules.shell.herdr;
user = config.user.name; user = config.user.name;
in in
{ {
options.modules.agents.herdr.enable = lib.mkEnableOption "Herdr, a terminal multiplexer for coding agents"; options.modules.shell.herdr.enable = lib.mkEnableOption "Herdr, a terminal multiplexer for coding agents";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
registry.shell-shortcut.${config.networking.hostName}.hs = "herdr --session";
home-manager.users.${user} = { home-manager.users.${user} = {
home.packages = [ pkgs.herdr ]; home.packages = [ pkgs.herdr ];
@@ -36,6 +38,9 @@ in
[ui] [ui]
prompt_new_tab_name = false prompt_new_tab_name = false
[experimental]
kitty_graphics = true
''; '';
}; };
}; };

View File

@@ -16,6 +16,16 @@ vim.api.nvim_create_autocmd("FileType", {
end, end,
}) })
-- Soft-wrap prose buffers without inserting line breaks.
vim.api.nvim_create_autocmd("FileType", {
pattern = { "gitcommit", "markdown", "text" },
callback = function()
vim.opt_local.wrap = true
vim.opt_local.linebreak = true
vim.opt_local.breakindent = true
end,
})
-- Turn line blame off again once the Neogit status buffer is closed. -- Turn line blame off again once the Neogit status buffer is closed.
vim.api.nvim_create_autocmd("BufUnload", { vim.api.nvim_create_autocmd("BufUnload", {
callback = function(args) callback = function(args)

View File

@@ -7,13 +7,18 @@
}: }:
# Neovim for the primary user, configured declaratively through nixvim. # Neovim for the primary user, configured declaratively through nixvim.
let let
cfg = config.modules.nvim; cfg = config.modules.shell.nvim;
user = config.user.name; user = config.user.name;
in in
{ {
options.modules.nvim.enable = lib.mkEnableOption "Neovim, configured declaratively via nixvim"; options.modules.shell.nvim.enable = lib.mkEnableOption "Neovim, configured declaratively via nixvim";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
registry.shell-shortcut.${config.networking.hostName} = {
vi = "nvim";
vim = "nvim";
};
home-manager.sharedModules = [ inputs.nixvim.homeModules.nixvim ]; home-manager.sharedModules = [ inputs.nixvim.homeModules.nixvim ];
home-manager.users.${user} = hm: { home-manager.users.${user} = hm: {
@@ -87,6 +92,18 @@ in
action = "<cmd>nohlsearch<CR>"; action = "<cmd>nohlsearch<CR>";
options.desc = "Clear search highlight"; options.desc = "Clear search highlight";
} }
{
mode = "n";
key = "j";
action = "gj";
options.desc = "Move down by display line";
}
{
mode = "n";
key = "k";
action = "gk";
options.desc = "Move up by display line";
}
{ {
mode = "n"; mode = "n";
key = "<leader>e"; key = "<leader>e";
@@ -176,8 +193,8 @@ in
}; };
}; };
# gbprod/nord.nvim, set up in ./config.lua. # `gbprod-nord` provides the `require("nord").setup()` API used in `./config.lua`.
# nixvim's colorschemes.nord is a different plugin. # nixpkgs packages `shaunsingh/nord.nvim` as `nord-nvim`, which is a different plugin.
extraPlugins = [ pkgs.vimPlugins.gbprod-nord ]; extraPlugins = [ pkgs.vimPlugins.gbprod-nord ];
extraConfigLua = builtins.readFile ./config.lua; extraConfigLua = builtins.readFile ./config.lua;

View File

@@ -6,13 +6,15 @@
# tmux for the primary user, configured through home-manager. # tmux for the primary user, configured through home-manager.
# Settings without a home-manager option are read from ./extra.conf. # Settings without a home-manager option are read from ./extra.conf.
let let
cfg = config.modules.tmux; cfg = config.modules.shell.tmux;
user = config.user.name; user = config.user.name;
in in
{ {
options.modules.tmux.enable = lib.mkEnableOption "tmux, configured via home-manager"; options.modules.shell.tmux.enable = lib.mkEnableOption "tmux, configured via home-manager";
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
registry.shell-shortcut.${config.networking.hostName}.tmx = "tmux new-session -A -s";
home-manager.users.${user}.programs.tmux = { home-manager.users.${user}.programs.tmux = {
enable = true; enable = true;

32
modules/shell/yazi.nix Normal file
View File

@@ -0,0 +1,32 @@
{
config,
lib,
pkgs,
...
}:
# Yazi, a terminal file manager.
let
cfg = config.modules.shell.yazi;
user = config.user.name;
in
{
options.modules.shell.yazi.enable = lib.mkEnableOption "Yazi, a terminal file manager";
config = lib.mkIf cfg.enable {
home-manager.users.${user}.programs.yazi = {
enable = true;
enableFishIntegration = true;
extraPackages = with pkgs; [
fd
ffmpegthumbnailer
fzf
imagemagick
jq
poppler
ripgrep
unar
zoxide
];
};
};
}

View File

@@ -1,20 +0,0 @@
{ config, lib, ... }:
# The baseline interactive toolset as one deliberate bundle.
let
cfg = config.modules.toolkit;
in
{
options.modules.toolkit.enable =
lib.mkEnableOption "the baseline interactive environment — fish, tmux, nvim, git, and direnv — as one unit";
# Each piece is turned on at default priority, so a host can still override any one of them.
config = lib.mkIf cfg.enable {
modules.fish.enable = lib.mkDefault true;
# fish is also the login shell, so the bundled environment is what a shell drops into.
modules.fish.defaultShell = lib.mkDefault true;
modules.tmux.enable = lib.mkDefault true;
modules.nvim.enable = lib.mkDefault true;
modules.git.enable = lib.mkDefault true;
modules.direnv.enable = lib.mkDefault true;
};
}

View File

@@ -1,4 +1,11 @@
{ lib }: { lib, ... }:
{ {
type = lib.types.str; type = lib.types.str;
checks = [
{
assertion = lib.registry.predicates.uniqueValue (entry: entry.value);
message = "Address registry values must be unique.";
}
];
} }

25
registry/route.nix Normal file
View File

@@ -0,0 +1,25 @@
{ lib, ... }:
{
checks = [
{
assertion = lib.registry.predicates.uniqueValue (entry: entry.value.domain);
message = "Route domains must be unique.";
}
];
type = lib.types.submodule {
options = {
domain = lib.mkOption {
type = lib.types.str;
example = "files.alexion.dev";
description = "Public domain served by this reverse-proxy route entry.";
};
port = lib.mkOption {
type = lib.types.ints.between 1 65535;
example = 3923;
description = "Backend TCP port served by the matching address registry entry.";
};
};
};
}

View File

@@ -0,0 +1,21 @@
{ lib, ... }:
let
entryType = lib.types.submodule {
options = {
command = lib.mkOption {
type = lib.types.str;
example = "nvim";
description = "Command expanded by this shell shortcut.";
};
abbreviation = lib.mkOption {
type = lib.types.bool;
default = true;
description = "Whether fish realizes this shell shortcut as an abbreviation instead of an alias.";
};
};
};
in
{
type = lib.types.coercedTo lib.types.str (command: { inherit command; }) entryType;
}

31
registry/stable-uid.nix Normal file
View File

@@ -0,0 +1,31 @@
{ lib, ... }:
let
inherit (lib)
filterAttrs
groupBy
mapAttrs
unique
;
serviceNamesByUid = entries:
mapAttrs (_uid: uidEntries: unique (map (entry: entry.entry) uidEntries)) (
groupBy (entry: toString entry.value) entries
);
duplicateUids = entries:
filterAttrs (_uid: serviceNames: builtins.length serviceNames > 1) (serviceNamesByUid entries);
in
{
# Next stable UID: 20003
replicate = true;
type = lib.types.ints.positive;
checks = [
{
assertion = entries: duplicateUids entries == { };
message = "Stable UID allocations must be unique.";
}
];
}

View File

@@ -1,75 +0,0 @@
{
config,
lib,
pkgs,
...
}:
# The host base: the host-only machinery a physical machine needs on top of the
# shared base — bootloader, secret decryption, and the maintenance timers.
let
user = config.user;
passwordSecret = "${user.name}-password";
in
{
imports = [ ./base.nix ];
# chaotic's binary cache, so the CachyOS kernel is fetched rather than compiled.
# The `extra-` prefix keeps cache.nixos.org alongside it.
nix.settings.extra-substituters = [ "https://nyx-cache.chaotic.cx/" ];
nix.settings.extra-trusted-public-keys = [
"nyx-cache.chaotic.cx:dJxTrgMC3V3cFfyIiBQDQorG6k1LsqurH/srpMSq7qk="
];
# A month of generations is kept, because on a rolling channel with a
# third-party kernel an old generation is a known-good system to boot when
# an update breaks something.
nix.gc.automatic = true;
nix.gc.dates = "Mon 03:15";
nix.gc.options = "--delete-older-than 30d";
# Deduplication runs on a timer, off the rebuild path, so it never adds
# latency to a `nixos-rebuild switch`.
# It falls on a different day from collection, so the two never contend.
nix.optimise.automatic = true;
nix.optimise.dates = [ "Thu 03:45" ];
# The EFI system partition holds a kernel and an initrd per entry at roughly
# 70 MiB apiece, and is fixed in size.
# An exhausted one fails at bootloader installation, after the build has
# already succeeded.
boot.loader.systemd-boot.configurationLimit = 15;
environment.systemPackages = [ pkgs.git ];
# Caps Lock is a second Escape.
# Shift+Caps Lock still toggles Caps Lock.
services.xserver.xkb.layout = "us";
services.xserver.xkb.options = "caps:escape_shifted_capslock";
# Compile the console keymap from the layout above, so the remap holds on a
# bare TTY and not only under a graphical session.
console.useXkbConfig = true;
# Decryption machinery every host depends on.
# The identity sits on the encrypted root, which is mounted early enough to
# satisfy the secret below.
# Clearing both `sshKeyPaths` defaults keeps the SSH host keys out of the
# decryption path.
sops.defaultSopsFile = ./secrets/shared.yaml;
sops.age.keyFile = "/var/lib/sops-nix/key.txt";
sops.age.sshKeyPaths = [ ];
sops.gnupg.sshKeyPaths = [ ];
# A password set by hand on a running machine otherwise takes precedence.
# That leaves the declared `hashedPasswordFile` below silently inert.
# Root has no declared password and is therefore locked.
# `sudo` from the wheel group is the way in.
users.mutableUsers = false;
# Decrypted in an earlier activation stage than ordinary secrets.
# That is early enough to precede the account that reads it.
sops.secrets.${passwordSecret}.neededForUsers = true;
users.users.${user.name}.hashedPasswordFile = config.sops.secrets.${passwordSecret}.path;
}