Compare commits
37 Commits
throwaway/
...
dc74538cfe
| Author | SHA1 | Date | |
|---|---|---|---|
| dc74538cfe | |||
| 28d8eb7ca9 | |||
| 42b1578efa | |||
| 4f105c81c2 | |||
| 0abd3121fb | |||
| d88ee49aaf | |||
| 647b20b934 | |||
| 6f0f586fb6 | |||
| be4a060e94 | |||
| 1ba3bdf8d6 | |||
| abac67afb4 | |||
| f767b613a0 | |||
| 105960ea3b | |||
| 200930035a | |||
| 64c1db71e4 | |||
| 17326fa65b | |||
| 09d8e72065 | |||
| 32ef8edbed | |||
| a0604c708e | |||
| 8eb873f57b | |||
| 48d9d3280f | |||
| f45aa44ead | |||
| 622d09818f | |||
| cb59b18703 | |||
| 45c6d01b1f | |||
| c267a2ec5c | |||
| 6f963920ec | |||
| 21fa48d93d | |||
| cd602b74b6 | |||
| 34bf1c7c22 | |||
| 932dad911f | |||
| 2c6d586cf5 | |||
| 0781c7cb30 | |||
| 8838472001 | |||
| bd2c1583da | |||
| 4677dbe591 | |||
| c50e996851 |
191
AGENTS.md
191
AGENTS.md
@@ -1,103 +1,110 @@
|
||||
# dotfiles-nixos
|
||||
|
||||
One flake that builds every machine the user owns.
|
||||
The domain model (Host, Module, Skeleton, Auto-loader, Enable convention, overlays) lives in `~/Documents/ai-artifacts/projects/dotfiles/003-dotfiles-context.md`.
|
||||
One flake builds every machine I own.
|
||||
|
||||
## 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.
|
||||
End the comment with a `— Claude` sign-off.
|
||||
(A dedicated bot account may replace this later.
|
||||
Until then, the sign-off is the only marker.)
|
||||
- Commit messages follow Conventional Commits, specified in `docs/conventional-commits.md`.
|
||||
Scope is the module or host the change belongs to (`fish`, `nvim`, `neogaia`), omitted for repo-wide changes.
|
||||
Keep messages free of Gitea-specific references: this repository is mirrored to GitHub, where issue and pull-request numbers resolve to unrelated things.
|
||||
- When a graphical application is added, give it a `window-rewrite` icon mapping in `modules/desktop/waybar.nix`.
|
||||
Without one its windows fall back to the generic default glyph on the workspace indicator instead of showing a recognisable per-application icon.
|
||||
Match on the window class, which `hyprctl clients -j | jq -r '.[].class' | sort -u` lists for the running session.
|
||||
- Use `docs/technical-writing.md` and `docs/dictionary.md` while authoring any file.
|
||||
Apply them to comments, user-facing descriptions, commit prose, pull-request prose, and Markdown documentation.
|
||||
- Comments posted to the forge under the operator's account must end with `— Pi`.
|
||||
The sign-off identifies the agent as the author instead of the operator.
|
||||
- Commit messages follow Conventional Commits, defined in `docs/conventional-commits.md`.
|
||||
Use a scope for the changed module or host, such as `fish`, `nvim`, or `neogaia`.
|
||||
- Keep commit messages about the Git history, not the forge workflow.
|
||||
Do not reference issue or pull-request numbers unless the commit itself requires a stable external reference.
|
||||
- During pull-request development, add follow-up commits instead of amending existing commits.
|
||||
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
|
||||
|
||||
- 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.
|
||||
- `sops.secrets.<name>.owner` must name a user known on the decrypting host.
|
||||
For guest-only service users, do not set the owner to the guest uid unless the host also declares that user.
|
||||
Use a host-visible owner plus a shared group mode when an identity-mapped guest service can read through its group.
|
||||
- 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.
|
||||
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.
|
||||
- Subagent completion delivery is non-blocking through immediate spawn, milestone notifications, retained terminal entries, and `subagent_list` or `subagent_result` retrieval.
|
||||
`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.
|
||||
- Nixvim's flake input following the root nixpkgs source does not make its Home Manager module reuse the host's `pkgs` instance.
|
||||
Keep `programs.nixvim.nixpkgs.useGlobalPackages = true` so Nixvim uses the shared package set without warning that its source default was affected.
|
||||
Guest addresses and routes are host-level configuration because a guest module can be used on multiple hosts.
|
||||
- The registry collector reads only top-level host `config.registry` declarations.
|
||||
Registry declarations inside guest interiors live under `config.containers.<guest>.config.registry`.
|
||||
The collected registry does not include those guest-interior declarations.
|
||||
Publish guest values from host-side code, or extend the collector to recurse into guests.
|
||||
See http://git.alexion.dev/alexion/dotfiles/issues/65.
|
||||
- A NixOS module function argument default such as `registry ? config.registry` does not safely handle an unprovided module argument.
|
||||
The module system still queries `_module.args.registry`.
|
||||
Evaluation fails when that argument is absent.
|
||||
For an optional special-argument fallback, bind module arguments through `@args`.
|
||||
Test `args ? <name>` inside the module body.
|
||||
|
||||
- `chaotic-nyx` must **not** follow this flake's `nixpkgs`.
|
||||
Chaotic builds its packages against its own pinned `nixpkgs`.
|
||||
Its overlay defaults to `onTopOf = "flake-nixpkgs"`, the cache-friendly path.
|
||||
That setup lets `nyx-cache.chaotic.cx` serve the CachyOS kernel instead of building it from source.
|
||||
Chaotic packages do not see this flake's `unstable` or `stable` overlays.
|
||||
|
||||
- Remote deploy helpers that run target-side `sudo` over SSH need a TTY.
|
||||
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 ad hoc Python, use Nix explicitly, such as `nix shell nixpkgs#python3 -c python3 <script>`.
|
||||
- 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.
|
||||
Filename migrations preserve references in immutable bodies through frontmatter aliases rather than rewriting those bodies.
|
||||
- This repo pins no Nix formatter, and its committed `.nix` files are not clean under current `nixfmt-rfc-style`.
|
||||
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.
|
||||
Format only the lines being written or changed, matching the surrounding style by hand.
|
||||
- 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.
|
||||
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.
|
||||
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.
|
||||
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.
|
||||
|
||||
91
base.nix
91
base.nix
@@ -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
59
docs/dictionary.md
Normal 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. |
|
||||
@@ -171,7 +171,7 @@ Then populate that file, which needs no existing identity because encrypting onl
|
||||
$ 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.
|
||||
Commit the matching public halves beside the host's configuration in plaintext, since publishing them is their purpose.
|
||||
|
||||
|
||||
270
docs/nix.md
Normal file
270
docs/nix.md
Normal 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
109
docs/technical-writing.md
Normal 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.`
|
||||
8
flake.lock
generated
8
flake.lock
generated
@@ -562,11 +562,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1785695024,
|
||||
"narHash": "sha256-DLLk6X5zu3cRT50p18uHVdwjGVtiS0t/661M34q02zU=",
|
||||
"lastModified": 1787455371,
|
||||
"narHash": "sha256-MJ0bX4/cksSbGl7v9o0l+Wy1xAEa3BgzG7Hs8EEGde0=",
|
||||
"ref": "refs/heads/main",
|
||||
"rev": "9b2a6bcd583d7d6bf7e5377c3632f601692df209",
|
||||
"revCount": 54,
|
||||
"rev": "9a1d21da4d3e70165ff772967d639df244dcc2ea",
|
||||
"revCount": 55,
|
||||
"type": "git",
|
||||
"url": "https://git.alexion.dev/alexion/skills"
|
||||
},
|
||||
|
||||
121
flake.nix
121
flake.nix
@@ -76,14 +76,9 @@
|
||||
{ self, nixpkgs, ... }@inputs:
|
||||
let
|
||||
inherit (nixpkgs) lib;
|
||||
my = import ./lib { inherit lib inputs self; };
|
||||
in
|
||||
{
|
||||
# Helper functions for discovering and building hosts.
|
||||
lib = my;
|
||||
|
||||
# Every host under hosts/ is discovered and built.
|
||||
nixosConfigurations = my.mkHosts (self + "/hosts");
|
||||
inherit (import ./flake { inherit lib inputs self; }) nixosConfigurations;
|
||||
|
||||
# A project shell for agent-local resources that should travel with this
|
||||
# checkout rather than the operator's global profile.
|
||||
@@ -98,111 +93,13 @@
|
||||
];
|
||||
};
|
||||
|
||||
# `nix flake check` builds host toplevels and project-level checks.
|
||||
checks.x86_64-linux =
|
||||
let
|
||||
pkgs = nixpkgs.legacyPackages.x86_64-linux;
|
||||
serviceIdentities = import ./lib/service-identities.nix { inherit lib; };
|
||||
serviceIdentityTestsPass = lib.all (result: result) (lib.attrValues serviceIdentities.tests);
|
||||
in
|
||||
(lib.mapAttrs (
|
||||
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
|
||||
'';
|
||||
|
||||
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.extendModules {
|
||||
modules = [
|
||||
{
|
||||
guests.actualbudget.reverseProxy = {
|
||||
enable = true;
|
||||
host = "budget.alexion.dev";
|
||||
backend = "http://10.23.20.42:5006";
|
||||
};
|
||||
}
|
||||
];
|
||||
}).config;
|
||||
route = testConfig.modules.reverse-proxy.routes.actualbudget;
|
||||
in
|
||||
pkgs.runCommand "reverse-proxy-actualbudget-guest-route-check" { } ''
|
||||
${
|
||||
lib.optionalString (
|
||||
!(route.host == "budget.alexion.dev" && route.backend == "http://10.23.20.42:5006")
|
||||
) "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
|
||||
'';
|
||||
};
|
||||
# `nix flake check` builds every discovered host toplevel.
|
||||
checks.x86_64-linux = lib.mapAttrs (
|
||||
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;
|
||||
};
|
||||
}
|
||||
|
||||
53
flake/default.nix
Normal file
53
flake/default.nix
Normal 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
279
flake/guest.nix
Normal 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
45
flake/host.nix
Normal 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
7
flake/module.nix
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
root,
|
||||
util,
|
||||
}:
|
||||
{
|
||||
imports = util.collectNixFiles root;
|
||||
}
|
||||
197
flake/registry.nix
Normal file
197
flake/registry.nix
Normal 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; });
|
||||
}
|
||||
31
guest.nix
31
guest.nix
@@ -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;
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
my,
|
||||
...
|
||||
}:
|
||||
let
|
||||
@@ -9,18 +8,6 @@ let
|
||||
dataDir = "/data";
|
||||
in
|
||||
{
|
||||
imports = [
|
||||
(my.guest {
|
||||
name = "actualbudget";
|
||||
interior = {
|
||||
modules.services.actualbudget = {
|
||||
enable = true;
|
||||
inherit dataDir;
|
||||
};
|
||||
};
|
||||
})
|
||||
];
|
||||
|
||||
options.guests.actualbudget = {
|
||||
dataPath = lib.mkOption {
|
||||
type = lib.types.nullOr lib.types.str;
|
||||
@@ -39,7 +26,13 @@ in
|
||||
];
|
||||
|
||||
guests.actualbudget = {
|
||||
mounts.${dataDir}.hostPath = cfg.dataPath;
|
||||
interior = {
|
||||
modules.services.actualbudget = {
|
||||
enable = true;
|
||||
inherit dataDir;
|
||||
};
|
||||
};
|
||||
mounts.${dataDir}.directory = cfg.dataPath;
|
||||
limits = {
|
||||
memory = lib.mkDefault "2G";
|
||||
cpu = lib.mkDefault "200%";
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
my,
|
||||
...
|
||||
}:
|
||||
let
|
||||
cfg = config.guests.copyparty;
|
||||
serviceUid = my.serviceUid "copyparty";
|
||||
|
||||
volumeType = lib.types.submodule {
|
||||
options = {
|
||||
@@ -35,22 +33,6 @@ let
|
||||
};
|
||||
in
|
||||
{
|
||||
imports = [
|
||||
(my.guest {
|
||||
name = "copyparty";
|
||||
interior = {
|
||||
modules.services.copyparty = {
|
||||
enable = true;
|
||||
inherit (cfg) accountName stateDir;
|
||||
passwordFile = "/run/secrets/${cfg.passwordSecret}";
|
||||
volumes = lib.mapAttrs (_urlPath: volume: {
|
||||
inherit (volume) path access flags;
|
||||
}) cfg.volumes;
|
||||
};
|
||||
};
|
||||
})
|
||||
];
|
||||
|
||||
options.guests.copyparty = {
|
||||
accountName = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
@@ -77,6 +59,12 @@ in
|
||||
description = "Host path bind-mounted as Copyparty's state directory.";
|
||||
};
|
||||
|
||||
reverseProxy.trustedSources = lib.mkOption {
|
||||
type = lib.types.listOf lib.types.str;
|
||||
default = [ ];
|
||||
description = "IP ranges that may supply Copyparty's forwarded client IP header.";
|
||||
};
|
||||
|
||||
volumes = lib.mkOption {
|
||||
type = lib.types.attrsOf volumeType;
|
||||
default = { };
|
||||
@@ -97,19 +85,33 @@ in
|
||||
];
|
||||
|
||||
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 =
|
||||
{
|
||||
${cfg.stateDir} = {
|
||||
hostPath = cfg.statePath;
|
||||
create = {
|
||||
owner = serviceUid;
|
||||
group = "storage";
|
||||
mode = "0770";
|
||||
};
|
||||
directory = cfg.statePath;
|
||||
owner = config.registry."stable-uid".${config.networking.hostName}.copyparty;
|
||||
group = "storage";
|
||||
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 = {
|
||||
memory = lib.mkDefault "2G";
|
||||
cpu = lib.mkDefault "200%";
|
||||
|
||||
@@ -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
|
||||
@@ -1,40 +1,58 @@
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
my,
|
||||
...
|
||||
}:
|
||||
let
|
||||
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
|
||||
{
|
||||
imports = [
|
||||
(my.guest {
|
||||
name = "reverse-proxy";
|
||||
config = lib.mkIf config.guests.reverse-proxy.enable {
|
||||
guests.reverse-proxy = {
|
||||
interior = {
|
||||
modules.reverse-proxy = {
|
||||
enable = true;
|
||||
routes = config.modules.reverse-proxy.routes // legacyRoutes;
|
||||
modules.services.reverse-proxy.enable = true;
|
||||
|
||||
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 ];
|
||||
@@ -46,11 +64,7 @@ in
|
||||
}
|
||||
'';
|
||||
};
|
||||
})
|
||||
];
|
||||
|
||||
config = lib.mkIf config.guests.reverse-proxy.enable {
|
||||
guests.reverse-proxy = {
|
||||
limits = {
|
||||
memory = lib.mkDefault "1G";
|
||||
cpu = lib.mkDefault "100%";
|
||||
|
||||
@@ -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
|
||||
@@ -31,45 +31,22 @@
|
||||
# So wifi can be joined from the console.
|
||||
networking.networkmanager.enable = true;
|
||||
|
||||
registry.address.neogaia.self = "10.23.50.146";
|
||||
|
||||
# So setup can be driven over the network.
|
||||
# The matching host public keys sit beside this file in plaintext, since
|
||||
# publishing them is their purpose.
|
||||
modules.ssh.enable = true;
|
||||
modules.ssh.hostKeys.sopsFile = ../../secrets/neogaia.yaml;
|
||||
modules.ssh.userKey.sopsFile = ../../secrets/neogaia.yaml;
|
||||
modules.network.ssh.enable = true;
|
||||
modules.network.ssh.hostKeys.sopsFile = ../../secrets/neogaia.yaml;
|
||||
modules.network.ssh.userKey.sopsFile = ../../secrets/neogaia.yaml;
|
||||
|
||||
modules.toolkit.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.shell.herdr.enable = true;
|
||||
modules.agents.tools.gitea-axi.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.obsidian.enable = true;
|
||||
modules.desktop.steam.enable = true;
|
||||
modules.desktop.apps.obsidian.enable = true;
|
||||
modules.desktop.apps.steam.enable = true;
|
||||
|
||||
time.timeZone = "America/New_York";
|
||||
i18n.defaultLocale = "en_GB.UTF-8";
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
{ pkgs, ... }:
|
||||
{
|
||||
config,
|
||||
pkgs,
|
||||
registry,
|
||||
...
|
||||
}:
|
||||
# pikachu — AZW ME Pro server.
|
||||
# Disk layout is in ./disk.nix.
|
||||
# `fileSystems` for the root disk are derived from it.
|
||||
@@ -57,7 +62,7 @@
|
||||
};
|
||||
networking.useDHCP = false;
|
||||
|
||||
modules.network.vlans = [ 20 ];
|
||||
modules.network.vlans.ids = [ 20 ];
|
||||
|
||||
boot.zfs.forceImportRoot = false;
|
||||
|
||||
@@ -67,22 +72,24 @@
|
||||
pools.pikachu = { };
|
||||
};
|
||||
|
||||
modules.ssh.enable = true;
|
||||
modules.ssh.hostKeys.sopsFile = ../../secrets/pikachu.yaml;
|
||||
modules.ssh.userKey.sopsFile = ../../secrets/pikachu.yaml;
|
||||
registry.address.pikachu.self = "10.23.10.102";
|
||||
|
||||
modules.git.enable = true;
|
||||
modules.toolkit.enable = true;
|
||||
modules.network.ssh.enable = true;
|
||||
modules.network.ssh.hostKeys.sopsFile = ../../secrets/pikachu.yaml;
|
||||
modules.network.ssh.userKey.sopsFile = ../../secrets/pikachu.yaml;
|
||||
|
||||
guests.actualbudget = {
|
||||
enable = true;
|
||||
vlan = 20;
|
||||
mac = "BC:24:11:C1:CD:28";
|
||||
dataPath = "/pikachu/data/actualbudget";
|
||||
address = "10.23.20.42";
|
||||
reverseProxy = {
|
||||
enable = true;
|
||||
host = "budget.alexion.dev";
|
||||
backend = "http://10.23.20.42:5006";
|
||||
route = {
|
||||
domain = "budget.alexion.dev";
|
||||
port = 5006;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
@@ -90,6 +97,7 @@
|
||||
enable = true;
|
||||
vlan = 20;
|
||||
mac = "02:98:64:5a:07:4f";
|
||||
address = "10.23.20.109";
|
||||
};
|
||||
|
||||
guests.copyparty = {
|
||||
@@ -97,10 +105,14 @@
|
||||
vlan = 20;
|
||||
mac = "02:23:20:39:23:01";
|
||||
statePath = "/pikachu/data/copyparty";
|
||||
address = "10.23.20.126";
|
||||
reverseProxy = {
|
||||
enable = true;
|
||||
host = "files.alexion.dev";
|
||||
backend = "http://10.23.20.126:3923";
|
||||
route = {
|
||||
domain = "files.alexion.dev";
|
||||
port = 3923;
|
||||
};
|
||||
trustedSources = [ "${registry.address.${config.networking.hostName}."reverse-proxy"}/32" ];
|
||||
};
|
||||
volumes = {
|
||||
"/inbox" = {
|
||||
|
||||
@@ -1,94 +1,9 @@
|
||||
{
|
||||
lib,
|
||||
inputs,
|
||||
self,
|
||||
}:
|
||||
{ lib }:
|
||||
let
|
||||
inherit (lib)
|
||||
attrNames
|
||||
filterAttrs
|
||||
genAttrs
|
||||
flatten
|
||||
hasSuffix
|
||||
mapAttrsToList
|
||||
;
|
||||
|
||||
serviceIdentityRegistry = import ./service-identities.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 = {
|
||||
inherit inputs;
|
||||
my = self.lib;
|
||||
};
|
||||
|
||||
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
|
||||
(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; });
|
||||
files = import ./files.nix { inherit lib; };
|
||||
network = import ./network.nix { inherit lib; };
|
||||
in
|
||||
{
|
||||
inherit
|
||||
collectNixFiles
|
||||
mkHost
|
||||
mkHosts
|
||||
bridgeName
|
||||
reverseProxyRoutes
|
||||
;
|
||||
|
||||
inherit (guests) deriveMac guest;
|
||||
|
||||
inherit (serviceIdentityRegistry) serviceUid;
|
||||
serviceIdentities = serviceIdentityRegistry.identities;
|
||||
inherit (files) collectNixFiles;
|
||||
inherit (network) bridgeName deriveMac;
|
||||
}
|
||||
|
||||
22
lib/files.nix
Normal file
22
lib/files.nix
Normal 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;
|
||||
}
|
||||
358
lib/guests.nix
358
lib/guests.nix
@@ -1,358 +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.
|
||||
'';
|
||||
};
|
||||
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.reverse-proxy.routes.${machineName} = lib.mkIf cfg.reverseProxy.enable (
|
||||
reverseProxyRoutes.routeFields cfg.reverseProxy
|
||||
);
|
||||
|
||||
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;
|
||||
}
|
||||
12
lib/network.nix
Normal file
12
lib/network.nix
Normal 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 ]);
|
||||
}
|
||||
@@ -1,77 +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.str;
|
||||
description = "Full HTTP backend URL that receives proxied traffic.";
|
||||
};
|
||||
|
||||
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
|
||||
tls
|
||||
websockets
|
||||
;
|
||||
};
|
||||
in
|
||||
{
|
||||
inherit mkRouteOptions routeFields;
|
||||
|
||||
routeType = lib.types.submodule (
|
||||
{ name, ... }:
|
||||
{
|
||||
options = mkRouteOptions { inherit name; };
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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.
|
||||
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.
|
||||
- Never manually modify CHANGELOG.md files or any files that are 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`).
|
||||
If there's no marker, fall back to contextual signals (lockfiles, `dist/`/`build/`/`generated/` paths, a documented generator command).
|
||||
If it's still ambiguous, ask before editing rather than guessing.
|
||||
- When writing or substantially editing long Markdown files, put each full sentence in its own line.
|
||||
Preserve normal Markdown structure, but avoid wrapping multiple sentences onto one physical line.
|
||||
Apply this to any prose you author, regardless of file length; "long" is not a real threshold.
|
||||
Only format what you're actually writing or changing.
|
||||
Never reflow an entire pre-existing paragraph or file just because you touched something nearby.
|
||||
- When making technical decisions, do not give much weight to development cost.
|
||||
Instead, prefer quality, simplicity, robustness, scalability and long term maintainability.
|
||||
This is specifically about 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.
|
||||
This is not a license to override standard anti-overengineering guardrails (avoid premature abstraction, no speculative config, etc.); those still apply to unnecessary complexity.
|
||||
It means: don't discount a more robust or maintainable approach just because it would take a human a long time to build.
|
||||
- File names should always be lower case, unless there's a valid reason.
|
||||
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.
|
||||
- Never manually modify `CHANGELOG.md` files or files marked as auto-generated.
|
||||
Detect auto-generated files with a layered check.
|
||||
Trust an explicit in-file marker first, for example `AUTO-GENERATED, DO NOT EDIT`.
|
||||
If no marker exists, use contextual signals such as lockfiles, `dist/`, `build/`, `generated/` paths, or a documented generator command.
|
||||
If the answer stays ambiguous, ask before editing.
|
||||
- In authored prose, do not put multiple sentences on one physical line.
|
||||
This applies to comments, documentation, user-facing descriptions, commit prose, pull-request prose, and forge comments.
|
||||
A sentence can wrap across multiple physical lines when needed.
|
||||
- Keep Markdown formatting changes local.
|
||||
Only format prose you write or change.
|
||||
Never reflow an entire pre-existing paragraph or file because you touched nearby text.
|
||||
- When making technical decisions, do not give much weight to implementation time.
|
||||
Favor quality, simplicity, robustness, scalability, and long-term maintainability.
|
||||
Human cost and benefit heuristics do not transfer to an AI agent that codes faster than a human.
|
||||
Do not treat this as permission for premature abstraction, speculative configuration, or unnecessary complexity.
|
||||
Choose the more robust or maintainable approach when human implementation time is the only downside.
|
||||
- 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.
|
||||
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".
|
||||
- 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.
|
||||
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 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).
|
||||
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.
|
||||
Append to an existing AGENTS.md immediately, without asking; if no AGENTS.md exists yet for the project, ask before creating one.
|
||||
Briefly mention the edit in your response rather than making it silently.
|
||||
If an existing entry is later found to be wrong or stale, correct or remove it the same way.
|
||||
- When you discover that your belief about a project fact or convention was wrong, record the correction.
|
||||
Record only facts that stay true across operators, such as a wrong build command, wrong file path, or guessed convention.
|
||||
Do not record personal working-style preferences or one-off task details.
|
||||
Record the correction in the nearest project `AGENTS.md`, not this global file.
|
||||
Use a dedicated `## Gotchas` section, and create that section when the file lacks one.
|
||||
If no project `AGENTS.md` exists, ask before creating one.
|
||||
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
|
||||
|
||||
- Write comments only where they earn their place, and keep them concise.
|
||||
Assume the reader can read code: comment the "why", not the "what", and explain "what" only when it is genuinely non-obvious.
|
||||
A comment must be self-contained to its file — accurate to a reader looking at that file alone.
|
||||
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.
|
||||
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.
|
||||
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.
|
||||
Never reference agent-facing state (anything under `.agents/`, `.claude/`, `AGENTS.md`, or `CLAUDE.md`).
|
||||
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.
|
||||
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>".
|
||||
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.
|
||||
- Start each sentence of a comment on its own line, as with Markdown prose.
|
||||
A sentence needing more than one line is first a prompt to ask whether it should be two sentences.
|
||||
Only when it genuinely cannot be split does it wrap, and then it wraps normally at the right margin.
|
||||
Never break a line early at a comma or clause boundary to make it read as a unit.
|
||||
Never use a semicolon, in a comment or in authored prose.
|
||||
Recast as two sentences instead.
|
||||
Only reformat comments you are actually writing or changing.
|
||||
- Write comments only where they earn their place.
|
||||
Keep comments concise.
|
||||
Assume the reader can read code.
|
||||
Explain why, not what.
|
||||
Explain what only when it is genuinely non-obvious.
|
||||
- Keep comments self-contained to their file.
|
||||
Write comments for a reader who sees only that file.
|
||||
Do not explain how another file or tool consumes a value.
|
||||
The only permitted cross-file mention is a bare pointer explaining why something is absent here.
|
||||
- Do not narrate history or future state in comments.
|
||||
Avoid phrases such as "used to be", "now moved here", and "will be".
|
||||
State the present reason a thing exists.
|
||||
- Do not justify a choice against alternatives in comments.
|
||||
State the positive reason the choice exists.
|
||||
Include present consequences when they matter.
|
||||
- Do not reference agent-facing state in comments.
|
||||
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.
|
||||
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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'")));
|
||||
});
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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}`;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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"]);
|
||||
});
|
||||
@@ -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()}…`;
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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));
|
||||
});
|
||||
@@ -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)}…`;
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
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
|
||||
+++ 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 {
|
||||
try {
|
||||
const result = spawnSync(cmd, ["--version"], { stdio: "pipe" });
|
||||
- // Check for ENOENT error (command not found)
|
||||
- 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;
|
||||
} catch {
|
||||
return false;
|
||||
|
||||
@@ -11,40 +11,6 @@ let
|
||||
cfg = config.modules.agents.pi;
|
||||
user = config.user.name;
|
||||
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: {
|
||||
patches = (old.patches or [ ]) ++ [
|
||||
./patches/pi-flex-spacer.patch
|
||||
@@ -76,109 +42,9 @@ in
|
||||
options.modules.agents.pi = {
|
||||
enable = lib.mkEnableOption ''
|
||||
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 {
|
||||
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} = {
|
||||
programs.pi-coding-agent = {
|
||||
enable = true;
|
||||
@@ -209,13 +75,6 @@ in
|
||||
source = ./prompts;
|
||||
recursive = true;
|
||||
};
|
||||
}
|
||||
// lib.optionalAttrs (subagentsConfig != { }) {
|
||||
# Declaring any global override makes Nix the owner of the runtime file.
|
||||
"${piDir}/subagents.json" = {
|
||||
source = subagentsJson;
|
||||
force = true;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
@@ -10,22 +10,7 @@ let
|
||||
user = config.user.name;
|
||||
|
||||
# The skills installed globally, as derivations from the skills flake.
|
||||
# grill interviews the operator relentlessly to resolve a plan before building.
|
||||
# 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
|
||||
];
|
||||
skills = with inputs.skills.packages.${pkgs.stdenv.hostPlatform.system}; [ ];
|
||||
in
|
||||
{
|
||||
home-manager.sharedModules = [ inputs.skills.homeModules.default ];
|
||||
|
||||
125
modules/default.nix
Normal file
125
modules/default.nix
Normal file
@@ -0,0 +1,125 @@
|
||||
{
|
||||
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;
|
||||
};
|
||||
}
|
||||
@@ -6,11 +6,11 @@
|
||||
}:
|
||||
# Alacritty as the desktop terminal.
|
||||
let
|
||||
cfg = config.modules.desktop.terminal;
|
||||
cfg = config.modules.desktop.apps.alacritty;
|
||||
user = config.user.name;
|
||||
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 {
|
||||
home-manager.users.${user}.home.packages = [ pkgs.alacritty ];
|
||||
@@ -7,12 +7,12 @@
|
||||
}:
|
||||
# Firefox as the desktop browser: stock mainline, hardened and de-monetized by policy.
|
||||
let
|
||||
cfg = config.modules.desktop.firefox;
|
||||
cfg = config.modules.desktop.apps.firefox;
|
||||
user = config.user.name;
|
||||
firefoxAddons = inputs.firefox-addons.packages.${pkgs.stdenv.hostPlatform.system};
|
||||
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 {
|
||||
home-manager.users.${user} = hm: {
|
||||
@@ -6,11 +6,11 @@
|
||||
}:
|
||||
# Obsidian as the desktop note-taking vault.
|
||||
let
|
||||
cfg = config.modules.desktop.obsidian;
|
||||
cfg = config.modules.desktop.apps.obsidian;
|
||||
user = config.user.name;
|
||||
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 {
|
||||
home-manager.users.${user}.home.packages = [ pkgs.obsidian ];
|
||||
@@ -6,10 +6,10 @@
|
||||
}:
|
||||
# Steam game launcher and runtime integration.
|
||||
let
|
||||
cfg = config.modules.desktop.steam;
|
||||
cfg = config.modules.desktop.apps.steam;
|
||||
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 {
|
||||
programs.steam = {
|
||||
30
modules/desktop/default.nix
Normal file
30
modules/desktop/default.nix
Normal 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.alacritty.enable = lib.mkDefault true;
|
||||
modules.desktop.apps.firefox.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;
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
};
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
}:
|
||||
# The Hyprland compositor.
|
||||
let
|
||||
cfg = config.modules.desktop.hyprland;
|
||||
cfg = config.modules.desktop.session.hyprland;
|
||||
user = config.user.name;
|
||||
cursor = config.stylix.cursor;
|
||||
|
||||
@@ -27,7 +27,7 @@ let
|
||||
'';
|
||||
in
|
||||
{
|
||||
options.modules.desktop.hyprland = {
|
||||
options.modules.desktop.session.hyprland = {
|
||||
enable = lib.mkEnableOption "the Hyprland compositor";
|
||||
|
||||
blur = lib.mkEnableOption ''
|
||||
@@ -6,7 +6,7 @@
|
||||
}:
|
||||
# hypridle: idle-triggered locking and display power management.
|
||||
let
|
||||
cfg = config.modules.desktop.hyprland.hypridle;
|
||||
cfg = config.modules.desktop.session.hyprland.hypridle;
|
||||
user = config.user.name;
|
||||
|
||||
hyprctl = "${config.programs.hyprland.package}/bin/hyprctl";
|
||||
@@ -17,7 +17,7 @@ let
|
||||
lockCmd = "${pkgs.procps}/bin/pidof hyprlock || ${hyprlock}";
|
||||
in
|
||||
{
|
||||
options.modules.desktop.hyprland.hypridle = {
|
||||
options.modules.desktop.session.hyprland.hypridle = {
|
||||
enable = lib.mkEnableOption "hypridle idle management";
|
||||
|
||||
lockTimeout = lib.mkOption {
|
||||
@@ -6,14 +6,46 @@
|
||||
}:
|
||||
# The lock screen: a hyprlock session-lock surface the compositor owns.
|
||||
let
|
||||
cfg = config.modules.desktop.hyprland.hyprlock;
|
||||
cfg = config.modules.desktop.session.hyprland.hyprlock;
|
||||
user = config.user.name;
|
||||
|
||||
# The hyprlock this module installs, used by the lock keybind below.
|
||||
hyprlock = "${config.home-manager.users.${user}.programs.hyprlock.package}/bin/hyprlock";
|
||||
|
||||
sleepIcon = builtins.fromJSON ''"\udb81\udcb2"'';
|
||||
sleepOffIcon = builtins.fromJSON ''"\udb81\udcb3"'';
|
||||
|
||||
idleLockToggle = pkgs.writeShellScript "lockscreen-idle-inhibit-toggle" ''
|
||||
unit=lockscreen-idle-inhibit.service
|
||||
|
||||
refresh_waybar() {
|
||||
${pkgs.procps}/bin/pkill -RTMIN+9 waybar >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
if ${pkgs.systemd}/bin/systemctl --user is-active --quiet "$unit"; then
|
||||
${pkgs.systemd}/bin/systemctl --user stop "$unit"
|
||||
refresh_waybar
|
||||
${pkgs.swayosd}/bin/swayosd-client --custom-message "${sleepIcon}"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ${pkgs.systemd}/bin/systemd-run \
|
||||
--user \
|
||||
--collect \
|
||||
--unit=lockscreen-idle-inhibit \
|
||||
--description="Disable idle-triggered screen locking" \
|
||||
${pkgs.systemd}/bin/systemd-inhibit \
|
||||
--what=idle \
|
||||
--who=lockscreen-hotkey \
|
||||
--why="lock screen disabled by hotkey" \
|
||||
${pkgs.coreutils}/bin/sleep infinity >/dev/null; then
|
||||
refresh_waybar
|
||||
${pkgs.swayosd}/bin/swayosd-client --custom-message "${sleepOffIcon}"
|
||||
fi
|
||||
'';
|
||||
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 {
|
||||
home-manager.users.${user} = {
|
||||
@@ -55,6 +87,7 @@ in
|
||||
# hyprlock never stacks over the first.
|
||||
wayland.windowManager.hyprland.settings.bind = [
|
||||
"$mod, X, exec, ${pkgs.procps}/bin/pidof hyprlock || ${hyprlock}"
|
||||
"$mod CTRL, X, exec, ${idleLockToggle}"
|
||||
];
|
||||
};
|
||||
};
|
||||
@@ -7,10 +7,10 @@
|
||||
# Text login: greetd running the tuigreet greeter, which starts the session
|
||||
# through the universal Wayland session manager.
|
||||
let
|
||||
cfg = config.modules.desktop.login;
|
||||
cfg = config.modules.desktop.session.login;
|
||||
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 {
|
||||
services.greetd = {
|
||||
@@ -6,13 +6,13 @@
|
||||
}:
|
||||
# mako as the notification daemon: toasts, a do-not-disturb mode, and history recall.
|
||||
let
|
||||
cfg = config.modules.desktop.mako;
|
||||
cfg = config.modules.desktop.session.mako;
|
||||
user = config.user.name;
|
||||
|
||||
makoctl = "${pkgs.mako}/bin/makoctl";
|
||||
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 {
|
||||
home-manager.users.${user} = {
|
||||
@@ -1,10 +1,10 @@
|
||||
{ config, lib, ... }:
|
||||
# XDG desktop portal routing for in-app screen sharing and file dialogs.
|
||||
let
|
||||
cfg = config.modules.desktop.portals;
|
||||
cfg = config.modules.desktop.session.portals;
|
||||
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";
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
@@ -6,7 +6,7 @@
|
||||
}:
|
||||
# rofi as the desktop launcher and dmenu-style menu frontend.
|
||||
let
|
||||
cfg = config.modules.desktop.rofi;
|
||||
cfg = config.modules.desktop.session.rofi;
|
||||
user = config.user.name;
|
||||
|
||||
# A session menu built on the same themed rofi, so the power actions look
|
||||
@@ -24,7 +24,7 @@ let
|
||||
'';
|
||||
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 {
|
||||
home-manager.users.${user} = {
|
||||
@@ -6,12 +6,13 @@
|
||||
}:
|
||||
# Waybar: a top status bar reading system state at a glance.
|
||||
let
|
||||
cfg = config.modules.desktop.waybar;
|
||||
cfg = config.modules.desktop.session.waybar;
|
||||
user = config.user.name;
|
||||
|
||||
# A Nerd Font Private-Use-Area codepoint as a literal character, decoded
|
||||
# through JSON so the glyph survives as bytes rather than an editor paste.
|
||||
g = code: builtins.fromJSON ''"\u${code}"'';
|
||||
sleepOffIcon = builtins.fromJSON ''"\udb81\udcb3"'';
|
||||
|
||||
# Renders and toggles mako's do-not-disturb mode.
|
||||
# With no mako daemon answering, the status reads "notifications on", keeping
|
||||
@@ -38,9 +39,17 @@ let
|
||||
printf '{"text":"","class":"idle"}\n'
|
||||
fi
|
||||
'';
|
||||
|
||||
idleLockStatus = pkgs.writeShellScript "waybar-idle-lock-status" ''
|
||||
if ${pkgs.systemd}/bin/systemctl --user is-active --quiet lockscreen-idle-inhibit.service; then
|
||||
printf '{"text":"${sleepOffIcon}","tooltip":"Idle locking inhibited","class":"inhibited"}\n'
|
||||
else
|
||||
printf '{"text":"","class":"idle"}\n'
|
||||
fi
|
||||
'';
|
||||
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 {
|
||||
# A symbols font backs the module glyphs, so pango falls back to it for the
|
||||
@@ -63,6 +72,7 @@ in
|
||||
modules-center = [ "clock" ];
|
||||
modules-right = [
|
||||
"custom/recording"
|
||||
"custom/idle-lock"
|
||||
"mpris"
|
||||
"wireplumber"
|
||||
"network"
|
||||
@@ -155,6 +165,13 @@ in
|
||||
exec = "${recStatus}";
|
||||
interval = 1;
|
||||
};
|
||||
|
||||
"custom/idle-lock" = {
|
||||
return-type = "json";
|
||||
exec = "${idleLockStatus}";
|
||||
interval = "once";
|
||||
signal = 9;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
@@ -1,10 +1,10 @@
|
||||
{ config, lib, ... }:
|
||||
# PipeWire as the desktop audio server.
|
||||
let
|
||||
cfg = config.modules.desktop.audio;
|
||||
cfg = config.modules.desktop.utilities.audio;
|
||||
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 {
|
||||
# Realtime scheduling for the audio threads, so playback survives load.
|
||||
@@ -6,7 +6,7 @@
|
||||
}:
|
||||
# Clipboard history: cliphist records every copy, picked back through rofi.
|
||||
let
|
||||
cfg = config.modules.desktop.clipboard;
|
||||
cfg = config.modules.desktop.utilities.clipboard;
|
||||
user = config.user.name;
|
||||
|
||||
cliphist = "${pkgs.cliphist}/bin/cliphist";
|
||||
@@ -25,7 +25,7 @@ let
|
||||
'';
|
||||
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 {
|
||||
home-manager.users.${user} = {
|
||||
@@ -6,11 +6,11 @@
|
||||
}:
|
||||
# SwayOSD: a transient on-screen popup for volume and brightness changes.
|
||||
let
|
||||
cfg = config.modules.desktop.osd;
|
||||
cfg = config.modules.desktop.utilities.osd;
|
||||
user = config.user.name;
|
||||
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 {
|
||||
environment.systemPackages = [ pkgs.swayosd ];
|
||||
@@ -6,7 +6,7 @@
|
||||
}:
|
||||
# Keybound screen recording: pick a region, then toggle a video-only capture.
|
||||
let
|
||||
cfg = config.modules.desktop.recording;
|
||||
cfg = config.modules.desktop.utilities.recording;
|
||||
user = config.user.name;
|
||||
|
||||
slurp = "${pkgs.slurp}/bin/slurp";
|
||||
@@ -41,7 +41,7 @@ let
|
||||
'';
|
||||
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 {
|
||||
home-manager.users.${user} = {
|
||||
@@ -7,7 +7,7 @@
|
||||
# Keyboard-driven screenshots that open in satty for annotation, then land in
|
||||
# both the clipboard and a dated file.
|
||||
let
|
||||
cfg = config.modules.desktop.screenshot;
|
||||
cfg = config.modules.desktop.utilities.screenshot;
|
||||
user = config.user.name;
|
||||
|
||||
grimblast = "${pkgs.grimblast}/bin/grimblast";
|
||||
@@ -32,7 +32,7 @@ let
|
||||
'';
|
||||
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 {
|
||||
home-manager.users.${user} = {
|
||||
@@ -6,7 +6,7 @@
|
||||
}:
|
||||
# Nord theming for the graphical layer, driven from one base16 scheme by Stylix.
|
||||
let
|
||||
cfg = config.modules.desktop.theming;
|
||||
cfg = config.modules.desktop.utilities.theming;
|
||||
user = config.user.name;
|
||||
|
||||
# A single static Nord wallpaper, drawn as a vertical gradient across the
|
||||
@@ -18,7 +18,7 @@ let
|
||||
'';
|
||||
in
|
||||
{
|
||||
options.modules.desktop.theming.enable =
|
||||
options.modules.desktop.utilities.theming.enable =
|
||||
lib.mkEnableOption "Nord theming of the graphical layer via Stylix";
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
@@ -2,11 +2,11 @@
|
||||
# Declares the XDG user directories, so a tool that queries them lands in a
|
||||
# well-known folder a host can relocate from one place.
|
||||
let
|
||||
cfg = config.modules.desktop.userdirs;
|
||||
cfg = config.modules.desktop.utilities.userdirs;
|
||||
user = config.user.name;
|
||||
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 {
|
||||
# Write ~/.config/user-dirs.dirs from the option defaults.
|
||||
14
modules/guest.nix
Normal file
14
modules/guest.nix
Normal 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
42
modules/host.nix
Normal 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;
|
||||
};
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
registry,
|
||||
...
|
||||
}:
|
||||
# SSH on this machine, in both directions.
|
||||
let
|
||||
cfg = config.modules.ssh;
|
||||
cfg = config.modules.network.ssh;
|
||||
user = config.user.name;
|
||||
|
||||
inherit (lib)
|
||||
@@ -152,7 +153,7 @@ let
|
||||
);
|
||||
in
|
||||
{
|
||||
options.modules.ssh = {
|
||||
options.modules.network.ssh = {
|
||||
enable = lib.mkEnableOption "the OpenSSH daemon, with host keys restored from secrets";
|
||||
|
||||
hosts = {
|
||||
@@ -189,7 +190,7 @@ in
|
||||
};
|
||||
|
||||
neogaia = {
|
||||
hostName = "10.23.50.146";
|
||||
hostName = registry.address.neogaia.self;
|
||||
clientKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGxQ4kWsBo2OGYIPOkFe0vNEcB3yoJwAu0y9wrdQzALE alexion@neogaia";
|
||||
hostKeys = [
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIJS+wp7K123+4BT6G4f954R6WyrbWveY7VlpoBUf6I5p neogaia"
|
||||
@@ -198,7 +199,7 @@ in
|
||||
};
|
||||
|
||||
pikachu = {
|
||||
hostName = "10.23.10.102";
|
||||
hostName = registry.address.pikachu.self;
|
||||
clientKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINNqJIC6VRXyvrNf3n9su9KdPCikC3CjK/QrCK2reHdB alexion@pikachu";
|
||||
hostKeys = [
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKljRf4pJO+pqEqjpPz08gOYq3g1PpxvE66xVw7uMEnA root@pikachu"
|
||||
@@ -225,7 +226,7 @@ in
|
||||
default = null;
|
||||
description = ''
|
||||
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 = [
|
||||
{
|
||||
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.";
|
||||
}
|
||||
];
|
||||
|
||||
@@ -1,35 +1,31 @@
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
my,
|
||||
util,
|
||||
...
|
||||
}:
|
||||
# The host networking foundation: per-VLAN bridges over a tagged trunk.
|
||||
let
|
||||
cfg = config.modules.network;
|
||||
cfg = config.modules.network.vlans;
|
||||
|
||||
# Each tagged VLAN materializes as a bridge named for its id, by the shared
|
||||
# convention.
|
||||
inherit (my) bridgeName;
|
||||
inherit (util) 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";
|
||||
options.modules.network.vlans = {
|
||||
enable = lib.mkEnableOption "host VLAN bridges over a tagged trunk";
|
||||
|
||||
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.
|
||||
Physical interface that carries 802.1Q-tagged traffic for every VLAN.
|
||||
Each declared VLAN attaches to its own bridge.
|
||||
'';
|
||||
};
|
||||
|
||||
vlans = lib.mkOption {
|
||||
ids = lib.mkOption {
|
||||
type = lib.types.listOf (lib.types.ints.between 1 4094);
|
||||
default = [ ];
|
||||
example = [
|
||||
@@ -38,8 +34,8 @@ in
|
||||
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.
|
||||
Tagged VLAN ids to materialize.
|
||||
Each id N creates one bridge named `br-vlanN`.
|
||||
'';
|
||||
};
|
||||
|
||||
@@ -48,9 +44,9 @@ in
|
||||
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.
|
||||
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.
|
||||
'';
|
||||
};
|
||||
|
||||
@@ -59,8 +55,8 @@ in
|
||||
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.
|
||||
Host static management address in CIDR form.
|
||||
Left null, the host takes its management address by DHCP.
|
||||
'';
|
||||
};
|
||||
};
|
||||
@@ -69,21 +65,20 @@ in
|
||||
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.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.management.address needs modules.network.management.vlan to say which bridge carries it.";
|
||||
message = "modules.network.vlans.management.address needs modules.network.vlans.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.
|
||||
# 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.vlans
|
||||
++ map (id: "interface-name:${vlanName id}") cfg.vlans;
|
||||
++ map (id: "interface-name:${bridgeName id}") cfg.ids
|
||||
++ map (id: "interface-name:${vlanName id}") cfg.ids;
|
||||
|
||||
systemd.network = {
|
||||
enable = true;
|
||||
@@ -103,19 +98,18 @@ in
|
||||
};
|
||||
vlanConfig.Id = id;
|
||||
};
|
||||
}) cfg.vlans
|
||||
}) cfg.ids
|
||||
);
|
||||
|
||||
networks = lib.mkMerge (
|
||||
[
|
||||
# The trunk carries only tagged frames up to the sub-interfaces and
|
||||
# takes no address of its own.
|
||||
# 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.vlans;
|
||||
vlan = map vlanName cfg.ids;
|
||||
};
|
||||
}
|
||||
]
|
||||
@@ -126,8 +120,8 @@ in
|
||||
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.
|
||||
# The management bridge carries the host address.
|
||||
# Other bridges provide L2 segments for guests.
|
||||
"40-${bridgeName id}" = lib.mkMerge [
|
||||
{
|
||||
matchConfig.Name = bridgeName id;
|
||||
@@ -140,7 +134,7 @@ in
|
||||
{ address = [ cfg.management.address ]; }
|
||||
))
|
||||
];
|
||||
}) cfg.vlans
|
||||
}) cfg.ids
|
||||
);
|
||||
};
|
||||
};
|
||||
@@ -1,82 +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);
|
||||
|
||||
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)) 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;
|
||||
|
||||
networking.firewall.allowedTCPPorts = [
|
||||
80
|
||||
443
|
||||
];
|
||||
|
||||
security.acme = {
|
||||
acceptTerms = true;
|
||||
defaults.email = "contact@alexion.dev";
|
||||
};
|
||||
|
||||
services.nginx = {
|
||||
enable = true;
|
||||
recommendedGzipSettings = true;
|
||||
recommendedOptimisation = true;
|
||||
recommendedProxySettings = true;
|
||||
recommendedTlsSettings = true;
|
||||
virtualHosts = lib.mapAttrs mkVirtualHost routesByHost;
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
my,
|
||||
...
|
||||
}:
|
||||
let
|
||||
@@ -29,12 +28,6 @@ in
|
||||
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 {
|
||||
type = lib.types.str;
|
||||
default = "storage";
|
||||
@@ -43,21 +36,27 @@ in
|
||||
|
||||
};
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
users.users.${cfg.user} = {
|
||||
isSystemUser = true;
|
||||
uid = cfg.uid;
|
||||
group = cfg.group;
|
||||
};
|
||||
config = lib.mkMerge [
|
||||
{
|
||||
registry."stable-uid".${config.networking.hostName}.actualbudget = 20001;
|
||||
}
|
||||
|
||||
services.actual = {
|
||||
enable = true;
|
||||
openFirewall = true;
|
||||
user = cfg.user;
|
||||
group = cfg.group;
|
||||
settings = {
|
||||
inherit (cfg) port dataDir;
|
||||
(lib.mkIf cfg.enable {
|
||||
users.users.${cfg.user} = {
|
||||
isSystemUser = true;
|
||||
uid = config.registry."stable-uid".${config.networking.hostName}.actualbudget;
|
||||
group = cfg.group;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
services.actual = {
|
||||
enable = true;
|
||||
openFirewall = true;
|
||||
user = cfg.user;
|
||||
group = cfg.group;
|
||||
settings = {
|
||||
inherit (cfg) port dataDir;
|
||||
};
|
||||
};
|
||||
})
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
my,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
@@ -48,6 +47,14 @@ let
|
||||
''}
|
||||
'';
|
||||
|
||||
renderTrustedSource = source: " xff-src: ${source}";
|
||||
|
||||
renderedReverseProxy = lib.optionalString cfg.reverseProxy.enable ''
|
||||
rproxy: 1
|
||||
xff-hdr: x-forwarded-for
|
||||
${lib.concatStringsSep "\n" (map renderTrustedSource cfg.reverseProxy.trustedSources)}
|
||||
'';
|
||||
|
||||
renderedVolumes = lib.concatStringsSep "\n" (lib.mapAttrsToList renderVolume cfg.volumes);
|
||||
|
||||
configScript = pkgs.writeShellScript "copyparty-config" ''
|
||||
@@ -68,7 +75,7 @@ let
|
||||
ses-db: ${cfg.stateDir}/sessions.db
|
||||
chpw-db: ${cfg.stateDir}/chpw.json
|
||||
shr-db: ${cfg.stateDir}/shares.db
|
||||
|
||||
${renderedReverseProxy}
|
||||
[accounts]
|
||||
${cfg.accountName}: $password
|
||||
|
||||
@@ -94,12 +101,6 @@ in
|
||||
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 {
|
||||
type = lib.types.str;
|
||||
default = "storage";
|
||||
@@ -128,52 +129,72 @@ in
|
||||
default = { };
|
||||
description = "Copyparty volumes keyed by their URL path.";
|
||||
};
|
||||
};
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
assertions = [
|
||||
{
|
||||
assertion = cfg.volumes != { };
|
||||
message = "modules.services.copyparty.volumes must declare at least one served volume.";
|
||||
}
|
||||
];
|
||||
reverseProxy = {
|
||||
enable = lib.mkEnableOption "reverse-proxy trust settings for Copyparty";
|
||||
|
||||
users.users.${cfg.user} = {
|
||||
isSystemUser = true;
|
||||
uid = cfg.uid;
|
||||
group = cfg.group;
|
||||
home = cfg.stateDir;
|
||||
};
|
||||
|
||||
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);
|
||||
trustedSources = lib.mkOption {
|
||||
type = lib.types.listOf lib.types.str;
|
||||
default = [ ];
|
||||
description = "IP ranges that may supply Copyparty's forwarded client IP header.";
|
||||
};
|
||||
};
|
||||
|
||||
networking.firewall.allowedTCPPorts = [ cfg.port ];
|
||||
};
|
||||
|
||||
config = lib.mkMerge [
|
||||
{
|
||||
registry."stable-uid".${config.networking.hostName}.copyparty = 20002;
|
||||
}
|
||||
|
||||
(lib.mkIf cfg.enable {
|
||||
assertions = [
|
||||
{
|
||||
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} = {
|
||||
isSystemUser = true;
|
||||
uid = config.registry."stable-uid".${config.networking.hostName}.copyparty;
|
||||
group = cfg.group;
|
||||
home = cfg.stateDir;
|
||||
};
|
||||
|
||||
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 ];
|
||||
})
|
||||
];
|
||||
}
|
||||
|
||||
95
modules/services/reverse-proxy.nix
Normal file
95
modules/services/reverse-proxy.nix
Normal 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;
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -5,11 +5,11 @@
|
||||
}:
|
||||
# direnv for the primary user, configured through home-manager.
|
||||
let
|
||||
cfg = config.modules.direnv;
|
||||
cfg = config.modules.shell.direnv;
|
||||
user = config.user.name;
|
||||
in
|
||||
{
|
||||
options.modules.direnv.enable =
|
||||
options.modules.shell.direnv.enable =
|
||||
lib.mkEnableOption "direnv for the primary user, with nix-direnv shell caching";
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
@@ -6,11 +6,13 @@
|
||||
}:
|
||||
# fish for the primary user, configured through home-manager.
|
||||
let
|
||||
cfg = config.modules.fish;
|
||||
cfg = config.modules.shell.fish;
|
||||
user = config.user.name;
|
||||
shortcuts = config.registry.shell-shortcut.${config.networking.hostName};
|
||||
commandsOf = shortcuts: lib.mapAttrs (_name: shortcut: shortcut.command) shortcuts;
|
||||
in
|
||||
{
|
||||
options.modules.fish = {
|
||||
options.modules.shell.fish = {
|
||||
enable = lib.mkEnableOption "fish as the user's shell, configured via home-manager";
|
||||
|
||||
defaultShell = lib.mkOption {
|
||||
@@ -27,10 +29,8 @@ in
|
||||
|
||||
home-manager.users.${user} = {
|
||||
home.packages = with pkgs; [
|
||||
eza # backs the ls/la/ll aliases
|
||||
bat # backs the manpager
|
||||
fastfetch # the shell greeting
|
||||
wget # backs the wget abbreviation
|
||||
];
|
||||
|
||||
programs.fish = {
|
||||
@@ -51,37 +51,8 @@ in
|
||||
}
|
||||
];
|
||||
|
||||
shellAliases = {
|
||||
ls = "eza -alg --color=always --group-directories-first --icons=always";
|
||||
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";
|
||||
|
||||
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";
|
||||
};
|
||||
shellAliases = commandsOf (lib.filterAttrs (_name: shortcut: !shortcut.abbreviation) shortcuts);
|
||||
shellAbbrs = commandsOf (lib.filterAttrs (_name: shortcut: shortcut.abbreviation) shortcuts);
|
||||
|
||||
functions = {
|
||||
# Pick the logo that fits the terminal so the greeting never wraps.
|
||||
@@ -120,6 +91,11 @@ in
|
||||
description = "Copy a file, or recursively copy a source directory into a destination";
|
||||
body = builtins.readFile ./functions/copy.fish;
|
||||
};
|
||||
|
||||
deploy-to = {
|
||||
description = "Deploy the current dotfiles branch to a host through target-local nixos-rebuild";
|
||||
body = builtins.readFile ./functions/deploy-to.fish;
|
||||
};
|
||||
};
|
||||
|
||||
# Rendered by home-manager into ~/.config/fish/config.fish.
|
||||
53
modules/shell/fish/functions/deploy-to.fish
Normal file
53
modules/shell/fish/functions/deploy-to.fish
Normal file
@@ -0,0 +1,53 @@
|
||||
if test (count $argv) -lt 1; or test (count $argv) -gt 2
|
||||
echo "usage: deploy-to <host> [branch]" >&2
|
||||
return 2
|
||||
end
|
||||
|
||||
set host $argv[1]
|
||||
set branch $argv[2]
|
||||
|
||||
if test -z "$branch"
|
||||
set branch (git branch --show-current)
|
||||
end
|
||||
|
||||
if test -z "$branch"
|
||||
echo "deploy-to: could not determine the current branch" >&2
|
||||
return 2
|
||||
end
|
||||
|
||||
git rev-parse --show-toplevel >/dev/null 2>&1
|
||||
or begin
|
||||
echo "deploy-to: run this from a git checkout" >&2
|
||||
return 2
|
||||
end
|
||||
|
||||
set dirty_lines (git status --porcelain)
|
||||
if test (count $dirty_lines) -gt 0
|
||||
echo "deploy-to: refusing to deploy with a dirty local worktree" >&2
|
||||
return 1
|
||||
end
|
||||
|
||||
git fetch origin
|
||||
or return $status
|
||||
|
||||
set remote_ref refs/remotes/origin/$branch
|
||||
git rev-parse --verify --quiet $remote_ref >/dev/null
|
||||
or begin
|
||||
echo "deploy-to: origin/$branch does not exist" >&2
|
||||
return 1
|
||||
end
|
||||
|
||||
set local_head (git rev-parse HEAD)
|
||||
set remote_head (git rev-parse $remote_ref)
|
||||
|
||||
if test "$local_head" != "$remote_head"
|
||||
echo "deploy-to: local HEAD differs from origin/$branch" >&2
|
||||
echo "deploy-to: push or reset the branch before deploying" >&2
|
||||
return 1
|
||||
end
|
||||
|
||||
set escaped_branch (string escape -- $branch)
|
||||
set escaped_host (string escape -- $host)
|
||||
set remote_command "cd ~/wrk/dotfiles && git fetch origin && git switch -- $escaped_branch && git reset --hard origin/$escaped_branch && sudo nixos-rebuild switch --flake .#$escaped_host --print-build-logs"
|
||||
|
||||
ssh -t $host $remote_command
|
||||
@@ -5,11 +5,11 @@
|
||||
}:
|
||||
# git for the primary user, configured through home-manager.
|
||||
let
|
||||
cfg = config.modules.git;
|
||||
cfg = config.modules.shell.git;
|
||||
user = config.user.name;
|
||||
in
|
||||
{
|
||||
options.modules.git.enable =
|
||||
options.modules.shell.git.enable =
|
||||
lib.mkEnableOption "git for the primary user, carrying the operator's commit identity";
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
@@ -6,13 +6,15 @@
|
||||
}:
|
||||
# Herdr, a terminal multiplexer for coding agents.
|
||||
let
|
||||
cfg = config.modules.agents.herdr;
|
||||
cfg = config.modules.shell.herdr;
|
||||
user = config.user.name;
|
||||
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 {
|
||||
registry.shell-shortcut.${config.networking.hostName}.hs = "herdr --session";
|
||||
|
||||
home-manager.users.${user} = {
|
||||
home.packages = [ pkgs.herdr ];
|
||||
|
||||
@@ -7,13 +7,18 @@
|
||||
}:
|
||||
# Neovim for the primary user, configured declaratively through nixvim.
|
||||
let
|
||||
cfg = config.modules.nvim;
|
||||
cfg = config.modules.shell.nvim;
|
||||
user = config.user.name;
|
||||
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 {
|
||||
registry.shell-shortcut.${config.networking.hostName} = {
|
||||
vi = "nvim";
|
||||
vim = "nvim";
|
||||
};
|
||||
|
||||
home-manager.sharedModules = [ inputs.nixvim.homeModules.nixvim ];
|
||||
|
||||
home-manager.users.${user} = hm: {
|
||||
@@ -176,8 +181,8 @@ in
|
||||
};
|
||||
};
|
||||
|
||||
# gbprod/nord.nvim, set up in ./config.lua.
|
||||
# nixvim's colorschemes.nord is a different plugin.
|
||||
# `gbprod-nord` provides the `require("nord").setup()` API used in `./config.lua`.
|
||||
# nixpkgs packages `shaunsingh/nord.nvim` as `nord-nvim`, which is a different plugin.
|
||||
extraPlugins = [ pkgs.vimPlugins.gbprod-nord ];
|
||||
|
||||
extraConfigLua = builtins.readFile ./config.lua;
|
||||
@@ -6,13 +6,15 @@
|
||||
# tmux for the primary user, configured through home-manager.
|
||||
# Settings without a home-manager option are read from ./extra.conf.
|
||||
let
|
||||
cfg = config.modules.tmux;
|
||||
cfg = config.modules.shell.tmux;
|
||||
user = config.user.name;
|
||||
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 {
|
||||
registry.shell-shortcut.${config.networking.hostName}.tmx = "tmux new-session -A -s";
|
||||
|
||||
home-manager.users.${user}.programs.tmux = {
|
||||
enable = true;
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
}
|
||||
11
registry/address.nix
Normal file
11
registry/address.nix
Normal file
@@ -0,0 +1,11 @@
|
||||
{ lib, ... }:
|
||||
{
|
||||
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
25
registry/route.nix
Normal 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.";
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
21
registry/shell-shortcut.nix
Normal file
21
registry/shell-shortcut.nix
Normal 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
31
registry/stable-uid.nix
Normal 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.";
|
||||
}
|
||||
];
|
||||
}
|
||||
75
system.nix
75
system.nix
@@ -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;
|
||||
}
|
||||
Reference in New Issue
Block a user