From 68068d363a2de58414c322af0046fc4e1bc4a4cf Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Sun, 8 Nov 2026 22:58:43 -0500 Subject: [PATCH] feat(nix): declare mutable global settings with home-manager --- docs/home-manager.md | 67 +++++++++++++++++++++++++++++ nix/home-manager/check-home.sh | 74 +++++++++++++++++++++++++++++++++ nix/home-manager/check.nix | 5 +++ nix/home-manager/evaluation.nix | 52 +++++++++++++++++++++++ nix/home-manager/module.nix | 59 ++++++++++++++++++++++++++ robot-docs/settings.md | 2 + 6 files changed, 259 insertions(+) diff --git a/docs/home-manager.md b/docs/home-manager.md index bb333beb0..feaceffa1 100644 --- a/docs/home-manager.md +++ b/docs/home-manager.md @@ -31,6 +31,73 @@ does not change this module's `${home.homeDirectory}/.albedo` declaration. The module creates a missing daemon directory with mode 0700, preserves an existing directory, and keeps data when you disable the service. +## Declare global settings + +Set `services.albedo.settings` to native JSON objects for your global settings: + +```nix +{ + services.albedo = { + enable = true; + settings = { + config.active = "local"; + config.providers.local = { + extension = "openai"; + baseUrl = "http://127.0.0.1:8000/v1"; + protocol = "chat_completions"; + model = "your-served-model"; + }; + extensions.enabled.mcp = true; + extensions.subagents.maxOpenChildren = 8; + capabilities.global.skills."example-skill" = false; + picker.thinking = true; + }; + }; +} +``` + +| Key | File under `${home.homeDirectory}/.albedo` | Native fields | +| --- | --- | --- | +| `config` | `config.json` | `active`, `providers..baseUrl`, `model`, `protocol` | +| `extensions` | `extensions.json` | `enabled`, `subagents`, `mcp.servers`, extension sections | +| `capabilities` | `capabilities.json` | `global.skills`, `global.instructions`, `global.mcp` | +| `picker` | `picker.json` | `thinking`, `tools`, global UI preferences | + +These native keys differ from the HTTP API. Session preferences stay in SQLite. +The option checks JSON types, not Albedo's schema, so Albedo can still reject a +valid JSON value when it reads the file. All declared values enter the +world-readable Nix store. Keep credentials in Albedo's credential store. + +Declared nested values win, undeclared keys survive, and arrays replace existing +arrays. Removing a declared key keeps its last stored value. An empty document or +a disabled service stops managing the file and leaves it in place. New files use +mode 0600. Existing files keep their modes, even permissive ones. + +### Activate with the daemon stopped + +Activation merges into files the daemon also writes, and it does not stop the +daemon itself. A running daemon can overwrite the merge, including by replaying +its settings journal. To apply settings reliably: + +1. Stop the daemon with `albedo daemon --stop`, and stop every other Albedo + process that uses this home. +2. Activate your home-manager configuration. +3. If the daemon is not running afterwards, start it with `albedo daemon`. + +If `${home.homeDirectory}/.albedo/.settings-recovery` exists, activation refuses +before it changes anything. Start Albedo so it finishes recovery, stop it, then +activate again. Activation merges one file at a time in alphabetical order. If a +later file fails, for example because it holds malformed JSON, the earlier files +stay merged and activation stops. Fix the file and activate again. + +When declarations change, home-manager normally restarts a running service. +Reapplying unchanged declarations over interactive edits does not request a +restart, so a running daemon can keep cached settings. +Restart it with `albedo daemon --stop` and `albedo daemon`. With +`systemd.user.startServices = "suggest"` or `false`, run the suggested commands +yourself. See [Daemon service](daemon-lifecycle.md#daemon-service) for lifecycle +limits. + ## Tools available to the daemon The service PATH includes `home.profileDirectory` and `nix.package` when set. diff --git a/nix/home-manager/check-home.sh b/nix/home-manager/check-home.sh index 093fc2854..2572c6923 100644 --- a/nix/home-manager/check-home.sh +++ b/nix/home-manager/check-home.sh @@ -38,3 +38,77 @@ if (source ./entry); then exit 1 fi test -L "$TMPDIR/private/.albedo" + +# Run the generated merge with activation's errexit, including expected failures. +merge_settings() { + bash -e -c 'source "$homeManagerHelper"; source ./settings-entry' +} +rm "$TMPDIR/private/.albedo" +source ./entry +settings_home="$TMPDIR/private/.albedo" +source ./settings-preflight +DRY_RUN=1 merge_settings +test -z "$(find "$settings_home" -mindepth 1)" +merge_settings +for document in capabilities config extensions picker; do + test "$(stat -c %a "$settings_home/$document.json")" = 600 +done +jq -e '.global.skills.example == false' "$settings_home/capabilities.json" +jq -e '.subagents.maxOpenChildren == 8' "$settings_home/extensions.json" +jq -e '.thinking == true' "$settings_home/picker.json" + +cat >"$settings_home/config.json" <<'JSON' +{ + "active": "interactive", + "providers": { + "local": {"model": "old", "keep": true} + }, + "models": ["old", "extra"], + "keep": 1 +} +JSON +chmod 640 "$settings_home/config.json" +merge_settings +jq -e ' + .active == "local" + and .providers.local == {"model": "declared", "keep": true} + and .models == ["declared"] + and .keep == 1 +' "$settings_home/config.json" +jq '.providers.local.model = "edited" | .keep = 2' "$settings_home/config.json" >edited +cat edited >"$settings_home/config.json" +merge_settings +jq -e ' + .providers.local.model == "declared" + and .keep == 2 +' "$settings_home/config.json" +test "$(stat -c %a "$settings_home/config.json")" = 640 + +cp -r "$settings_home" before-journal +for journal_kind in file symlink; do + if [[ $journal_kind == file ]]; then + printf '%s\n' 'leave unread' >"$settings_home/.settings-recovery" + chmod 000 "$settings_home/.settings-recovery" + else + ln -s "$TMPDIR/absent-journal" "$settings_home/.settings-recovery" + fi + if (source ./settings-preflight); then + echo 'Accepted pending recovery' >&2 + exit 1 + fi + test -e "$settings_home/.settings-recovery" || test -L "$settings_home/.settings-recovery" + rm "$settings_home/.settings-recovery" + diff -r before-journal "$settings_home" +done + +rm "$settings_home/"*.json +printf '%s\n' '{"broken":' >"$settings_home/extensions.json" +cp "$settings_home/extensions.json" malformed +if merge_settings; then + echo 'Accepted malformed settings' >&2 + exit 1 +fi +cmp malformed "$settings_home/extensions.json" +jq -e '.global.skills.example == false' "$settings_home/capabilities.json" +jq -e '.active == "local"' "$settings_home/config.json" +test ! -e "$settings_home/picker.json" diff --git a/nix/home-manager/check.nix b/nix/home-manager/check.nix index c6f9b0360..763914a96 100644 --- a/nix/home-manager/check.nix +++ b/nix/home-manager/check.nix @@ -41,6 +41,8 @@ specialSource = specialConfiguration.xdg.configFile."systemd/user/albedo.service".source; directoryEntry = pkgs.writeText "albedo-home-entry" configuration.home.activation.albedoHome.data; preflightEntry = pkgs.writeText "albedo-home-preflight" configuration.home.activation.checkAlbedoHome.data; + settingsEntry = pkgs.writeText "albedo-settings-entry" native.cases.settings.config.home.activation.albedoSettings.data; + settingsPreflight = pkgs.writeText "albedo-settings-preflight" native.cases.settings.config.home.activation.checkAlbedoSettings.data; executable = lib.getExe' configuration.services.albedo.package "albedo"; specialExecutable = lib.getExe' specialConfiguration.services.albedo.package "albedo"; specialHome = "${native.specialHomeDirectory}/.albedo"; @@ -48,6 +50,7 @@ in assert native.passed && lib.all (platform: platform.passed) otherPlatforms; pkgs.runCommand "albedo-home-manager-check" { + nativeBuildInputs = [pkgs.jq]; homeManagerHelper = "${inputs.home-manager}/lib/bash/home-manager.sh"; } '' substitute ${source} normalized \ @@ -61,6 +64,8 @@ in substitute ${directoryEntry} entry --replace-fail ${lib.escapeShellArg native.homeDirectory} "$TMPDIR/private" substitute ${preflightEntry} preflight --replace-fail ${lib.escapeShellArg native.homeDirectory} "$TMPDIR/private" + substitute ${settingsEntry} settings-entry --replace-fail ${lib.escapeShellArg native.homeDirectory} "$TMPDIR/private" + substitute ${settingsPreflight} settings-preflight --replace-fail ${lib.escapeShellArg native.homeDirectory} "$TMPDIR/private" source ${./check-home.sh} mkdir "$out" diff --git a/nix/home-manager/evaluation.nix b/nix/home-manager/evaluation.nix index 8d99883c4..f47562851 100644 --- a/nix/home-manager/evaluation.nix +++ b/nix/home-manager/evaluation.nix @@ -33,6 +33,30 @@ {config = settings;} ]; }; + settings = { + capabilities.global.skills.example = false; + config = { + active = "local"; + providers.local.model = "declared"; + models = ["declared"]; + }; + extensions.subagents.maxOpenChildren = 8; + picker.thinking = true; + }; + settingsCase = declarations: + evaluate { + services.albedo = { + enable = true; + package = samplePackage; + settings = declarations; + }; + }; + triggers = evaluated: + map toString ( + if isLinux + then evaluated.config.systemd.user.services.albedo.Unit.X-Restart-Triggers or [] + else evaluated.config.launchd.agents.albedo-daemon.restartTriggers or [] + ); cases = { disabled = evaluate {}; client = evaluate {programs.albedo.enable = true;}; @@ -40,6 +64,13 @@ services.albedo.enable = true; services.albedo.package = samplePackage; }; + settings = settingsCase settings; + emptySettings = settingsCase { + config = {}; + picker = {}; + }; + filteredSettings = settingsCase (settings // {picker = {};}); + disabledSettings = evaluate {services.albedo.settings = settings;}; both = evaluate { home.homeDirectory = lib.mkForce specialHomeDirectory; programs.albedo.enable = true; @@ -72,6 +103,11 @@ if isLinux then configuration.systemd.user.services != {} else configuration.launchd.agents.albedo-daemon.enable or false; + documents = lib.filterAttrs (_: value: value != {}) configuration.services.albedo.settings; + managesSettings = serviceEnabled && documents != {}; + expectedTriggers = lib.optionals managesSettings (lib.mapAttrsToList + (name: value: toString ((pkgs.formats.json {}).generate "albedo-${name}.json" value)) + documents); activationOrder = map (entry: entry.name) (inputs.home-manager.lib.hm.dag.topoSort configuration.home.activation).result; position = name: lib.lists.findFirstIndex (entry: entry == name) @@ -82,6 +118,12 @@ if isLinux then "reloadSystemd" else "setupLaunchAgents"; + settingsOrdered = + !(configuration.home.activation ? albedoSettings) + || (runsBefore "checkAlbedoSettings" "writeBoundary" + && runsBefore "albedoHome" "albedoSettings" + && runsBefore "linkGeneration" "albedoSettings" + && runsBefore "albedoSettings" nativeActivation); activationOrdered = !serviceEnabled || ( @@ -94,6 +136,11 @@ assert lib.assertMsg (lib.elem configuration.programs.albedo.package configuration.home.packages == clientEnabled) "Client enable does not match package installation"; assert lib.assertMsg (serviceDeclared == serviceEnabled) "Service enable does not match its declaration"; assert lib.assertMsg (clientEnabled || !serviceEnabled || !(lib.elem configuration.services.albedo.package configuration.home.packages)) "Service-only enable installed a client"; + assert lib.assertMsg ((configuration.home.activation ? albedoSettings) + == managesSettings + && (configuration.home.activation ? checkAlbedoSettings) == managesSettings) "Settings activation enable mismatch"; + assert lib.assertMsg (triggers evaluated == expectedTriggers) "Settings restart triggers mismatch"; + assert lib.assertMsg settingsOrdered "Settings activation order changed"; assert lib.assertMsg activationOrdered "Albedo activation order changed"; evaluated.activationPackage.drvPath; rejectsHome = home: let @@ -104,6 +151,8 @@ result = builtins.tryEval (builtins.deepSeq evaluated.activationPackage.drvPath true); in !result.success; + rejectsSettings = declarations: + !(builtins.tryEval (builtins.deepSeq (settingsCase declarations).activationPackage.drvPath true)).success; invalidHomes = ["/tmp/invalid\nhome"] ++ lib.optional (!isLinux) "/tmp/invalid{home}"; pathOverrideWorks = if isLinux @@ -111,6 +160,9 @@ else pathOverride.config.launchd.agents.albedo-daemon.config.EnvironmentVariables.PATH == customPath; in assert lib.assertMsg (lib.all rejectsHome invalidHomes) "Unsupported home path was accepted"; + assert lib.assertMsg (lib.all rejectsSettings [{sessions.value = true;} {config = 1;} {config = [];}]) "Invalid settings accepted"; + assert triggers cases.settings == triggers (settingsCase settings); + assert triggers cases.settings != triggers (settingsCase (settings // {picker.thinking = false;})); assert lib.assertMsg pathOverrideWorks "Native service PATH override was ignored"; assert lib.assertMsg configuredNixAvailable "Configured Nix package is missing from the service PATH"; assert cases.service.config.programs.albedo.package == self.packages.${system}.albedo; diff --git a/nix/home-manager/module.nix b/nix/home-manager/module.nix index 5f9310e49..517fedfab 100644 --- a/nix/home-manager/module.nix +++ b/nix/home-manager/module.nix @@ -6,6 +6,22 @@ }: let client = config.programs.albedo; service = config.services.albedo; + jsonFormat = pkgs.formats.json {}; + allowedDocuments = ["config" "extensions" "capabilities" "picker"]; + unsupportedDocuments = lib.filter (name: !(lib.elem name allowedDocuments)) (lib.attrNames service.settings); + documents = lib.filterAttrs (_: value: value != {}) service.settings; + staticSettings = lib.mapAttrs (name: value: jsonFormat.generate "albedo-${name}.json" value) documents; + settingsMergeScript = lib.concatStrings (lib.mapAttrsToList (name: file: + lib.hm.generators.mkImpureConfigMerger { + inherit pkgs; + staticSettings = file; + format = "json"; + empty = "{}"; + jqOperation = "$dynamic * $static"; + path = "${albedoHome}/${name}.json"; + mode = "600"; + }) + staticSettings); albedoHome = "${config.home.homeDirectory}/.albedo"; defaultServicePath = lib.makeBinPath ( [config.home.profileDirectory] ++ lib.optional (config.nix.package != null) config.nix.package @@ -40,6 +56,32 @@ in { }; options.services.albedo = { enable = lib.mkEnableOption "the albedo daemon as a login user service"; + settings = lib.mkOption { + type = lib.types.attrsOf (lib.types.attrsOf jsonFormat.type); + default = {}; + example = lib.literalExpression '' + { + config.active = "local"; + config.providers.local = { + extension = "openai"; + baseUrl = "http://127.0.0.1:8000/v1"; + protocol = "chat_completions"; + model = "your-served-model"; + }; + extensions.enabled.mcp = true; + picker.thinking = true; + } + ''; + description = '' + Native JSON objects for config.json, extensions.json, capabilities.json, + and picker.json under ~/.albedo, keyed by basename without .json. + Activation merges declared values recursively over the existing files. + Undeclared keys survive, arrays are replaced, and removing a declaration + leaves its last stored value. Values enter the world-readable Nix store, + so never put secrets here. Stop the daemon and other Albedo writers + before activating. See docs/home-manager.md for details. + ''; + }; package = lib.mkOption { type = lib.types.package; default = client.package; @@ -52,6 +94,10 @@ in { (lib.mkIf client.enable {home.packages = [client.package];}) (lib.mkIf service.enable { assertions = [ + { + assertion = unsupportedDocuments == []; + message = "Unsupported Albedo settings documents: ${lib.concatStringsSep ", " unsupportedDocuments}. Allowed: ${lib.concatStringsSep ", " allowedDocuments}."; + } { assertion = !homeHasControlCharacters; message = "The albedo service home must not contain control characters."; @@ -80,12 +126,24 @@ in { fi ''; }) + (lib.mkIf (service.enable && documents != {}) { + home.activation.checkAlbedoSettings = lib.hm.dag.entryBefore ["writeBoundary"] '' + journal=${lib.escapeShellArg "${albedoHome}/.settings-recovery"} + # Recovery contents may contain credentials; check only existence. + if [[ -e "$journal" || -L "$journal" ]]; then + errorEcho "Pending Albedo settings recovery at $journal; let Albedo finish recovery, stop it, then activate again." + exit 1 + fi + ''; + home.activation.albedoSettings = lib.hm.dag.entryBetween [nativeActivation] ["linkGeneration" "albedoHome"] settingsMergeScript; + }) (lib.mkIf (service.enable && pkgs.stdenv.hostPlatform.isLinux) { systemd.user.services.albedo = { Unit = { Description = "albedo daemon"; StartLimitIntervalSec = 60; StartLimitBurst = 5; + X-Restart-Triggers = lib.mkIf (documents != {}) (lib.attrValues staticSettings); }; Service = { Type = "exec"; @@ -105,6 +163,7 @@ in { (lib.mkIf (service.enable && pkgs.stdenv.hostPlatform.isDarwin) { launchd.agents.albedo-daemon = { enable = true; + restartTriggers = lib.mkIf (documents != {}) (lib.attrValues staticSettings); config = { Label = "systems.albedo.daemon"; ProgramArguments = [executable "daemon" "--serve"]; diff --git a/robot-docs/settings.md b/robot-docs/settings.md index 24b0aa04d..81a89b77e 100644 --- a/robot-docs/settings.md +++ b/robot-docs/settings.md @@ -62,6 +62,8 @@ Workspace edits are standalone patches with the observed family revision. The na ## Persistence and recovery +home-manager's `services.albedo.settings` merges native documents at activation, one file at a time, outside `albedo_settings_lock` and the settings journal. It requires the daemon and every other writer of the home to be stopped, and it refuses when `.settings-recovery` exists. See [Manage albedo with home-manager](../docs/home-manager.md#declare-global-settings) for merge rules and recovery steps. + Global settings remain in `config.json`, `extensions.json`, `capabilities.json`, `picker.json`, and `creds.json`. `settings-revisions.json` stores group publication counters, including secret-only changes. The settings journal publishes affected files atomically under one home lock. Every lock holder first completes a journal left behind (`.settings-recovery`); until that succeeds, every settings operation fails with the step and POSIX reason that stopped it (never the record's bytes, which can hold credentials), and over HTTP that is a 503 `settings_unavailable`, including on `GET /server`. Malformed or unreadable documents fail operations. Writes retain unrelated fields and use sealed, synced temporary files. `daemon/settings.gleam` exposes group operations. `harness/settings/projection.gleam` owns read-only views, secret-presence projections, and cache priors; it returns native JSON maps so the publication owner retains the existing encoder and validators. `harness/settings/declared.gleam` projects and patches the `extension_settings` group from the declared sections, the daemon's own (`daemon/core_settings.gleam`) and the installed extensions', whose types `harness/settings.gleam` defines. `albedo_settings_http.erl` owns locks, conditional publication, and MCP probing outside the lock followed by locked revalidation. Provider validation and saved-profile normalization belong to `daemon/configuration`; MCP validation belongs to its extension. OAuth refresh, profile settings, and credential writes share the home lock. -- knotmirror 0.0.1