Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278{albedoPackage}: { config, lib, pkgs, ...}: 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);
# programs.mcp.servers in Albedo's native MCP server shape. home-manager's helpers set # `type` and wrap file-backed env entries in a script that reads them when # the server starts. Albedo has no templating, so only a whole "{env:VAR}" # value becomes a native environment reference. importsMcpServers = service.enable && service.enableMcpIntegration && config.programs.mcp.enable; toNativeValue = value: let placeholder = if lib.isString value then builtins.match "[{]env:([A-Za-z_][A-Za-z0-9_]*)[}]" value else null; in if placeholder == null then value else {env = lib.head placeholder;}; importMcpServer = name: server: let transformed = lib.hm.mcp.transformMcpServer { inherit server; extraTransforms = [ lib.hm.mcp.addType (lib.hm.mcp.wrapEnvFilesCommand {inherit pkgs name;}) ]; }; valueMaps = lib.filterAttrs (field: _: field == "env" || field == "headers") transformed; in transformed // lib.mapAttrs (_: lib.mapAttrs (_: toNativeValue)) valueMaps; importedMcpServers = lib.optionalAttrs importsMcpServers (lib.mapAttrs importMcpServer config.programs.mcp.servers); declaredExtensions = service.settings.extensions or {}; declaredMcpServers = declaredExtensions.mcp.servers or {}; # A server declared in services.albedo.settings replaces the imported one # of the same name as a whole, so checks only see imports that survive. survivingMcpImports = removeAttrs importedMcpServers (lib.attrNames declaredMcpServers); # Importing into an extension that is off would do nothing, so a non-empty # import turns `mcp` on unless the declaration says otherwise. extensionsWithMcpImports = declaredExtensions // { enabled = {mcp = true;} // declaredExtensions.enabled or {}; mcp = declaredExtensions.mcp or {} // {servers = importedMcpServers // declaredMcpServers;}; }; effectiveSettings = if importedMcpServers == {} then service.settings else service.settings // {extensions = extensionsWithMcpImports;};
# Albedo fails the whole `mcp` section for a bad name or type, and would send # any other "{env:...}" or "{file:...}" text as a literal credential. validMcpServerName = name: builtins.match "[A-Za-z0-9][A-Za-z0-9_-]{0,63}" name != null; unresolvedPlaceholders = server: lib.concatMap (field: lib.mapAttrsToList (key: _: "${field}.${key}") (lib.filterAttrs (_: value: lib.isString value && (lib.hasInfix "{env:" value || lib.hasInfix "{file:" value)) server.${field} or {})) ["env" "headers"]; mcpImportProblems = lib.concatLists (lib.mapAttrsToList (name: server: lib.optional (!validMcpServerName name) "programs.mcp.servers.${name}: Albedo server names start with a letter or digit, use only letters, digits, '_' and '-', and have at most 64 characters." ++ lib.optional (!lib.elem (server.type or null) ["stdio" "http"]) "programs.mcp.servers.${name}: Albedo supports only type \"stdio\" or \"http\", not ${builtins.toJSON (server.type or null)}." ++ map (path: "programs.mcp.servers.${name}.${path}: Albedo would send this placeholder as text. Use a whole \"{env:NAME}\" value with a valid variable name.") (unresolvedPlaceholders server)) survivingMcpImports);
documents = lib.filterAttrs (_: value: value != {}) effectiveSettings; 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 ); servicePath = if pkgs.stdenv.hostPlatform.isLinux then config.systemd.user.sessionVariables.PATH or defaultServicePath else defaultServicePath; environment = { ALBEDO_HOME = albedoHome; PATH = servicePath; }; # systemd and the CLI's unit renderer reject newlines and NUL in service values. homeHasControlCharacters = builtins.match ".*[[:cntrl:]].*" albedoHome != null; logPath = "${albedoHome}/daemon.log"; executable = lib.getExe' service.package "albedo"; escapeSystemdSpecifiers = lib.replaceStrings ["%"] ["%%"]; quoteSystemdWord = value: "\"${lib.escape ["\\" "\""] (escapeSystemdSpecifiers value)}\""; nativeActivation = if pkgs.stdenv.hostPlatform.isLinux then "reloadSystemd" else "setupLaunchAgents";in { options.programs.albedo = { enable = lib.mkEnableOption "the albedo terminal client"; skills = lib.mkOption { type = lib.types.attrsOf lib.types.path; default = {}; example = lib.literalExpression "{ review = ./skills/review; }"; description = '' Skill directories to link under ~/.albedo/skills when the client or service is enabled. Each directory must contain SKILL.md, whose frontmatter name matches the attribute name. Resources and scripts stay with the skill. Use pkgs.writeTextDir "SKILL.md" for inline content. Skill contents enter the world-readable Nix store, so do not include secrets. ''; }; package = lib.mkOption { type = lib.types.package; default = albedoPackage; defaultText = lib.literalMD "The albedo package from this flake."; description = "Package providing the albedo terminal client."; }; }; options.services.albedo = { enable = lib.mkEnableOption "the albedo daemon as a login user service"; enableMcpIntegration = lib.mkOption { type = lib.types.bool; default = false; description = '' Whether to add the servers in {option}`programs.mcp.servers` to extensions.json `mcp.servers` when {option}`programs.mcp.enable` is set. A server of the same name in {option}`services.albedo.settings` replaces the imported one entirely. A non-empty import also sets `enabled.mcp` unless the settings declare it. See docs/home-manager.md for details. ''; }; 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; defaultText = lib.literalExpression "config.programs.albedo.package"; description = "Package providing bin/albedo daemon --serve."; }; };
config = lib.mkMerge [ (lib.mkIf client.enable {home.packages = [client.package];}) (lib.mkIf (client.enable || service.enable) { home.file = lib.mapAttrs' (name: source: lib.nameValuePair ".albedo/skills/${name}" {inherit source;}) client.skills; }) (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."; } { assertion = !pkgs.stdenv.hostPlatform.isDarwin || builtins.match ".*[{}].*" albedoHome == null; message = "The albedo service home must not contain braces on macOS."; } { assertion = mcpImportProblems == []; message = lib.concatStringsSep "\n" mcpImportProblems; } ]; home.activation.checkAlbedoHome = lib.hm.dag.entryBefore ["writeBoundary"] '' albedoHome=${lib.escapeShellArg albedoHome} if [[ ! -d "$albedoHome" && ( -e "$albedoHome" || -L "$albedoHome" ) ]]; then errorEcho "Cannot create albedo home: $albedoHome is not a directory" exit 1 fi ''; home.activation.albedoHome = lib.hm.dag.entryBetween [nativeActivation] ["writeBoundary"] '' albedoHome=${lib.escapeShellArg albedoHome} if [[ -d "$albedoHome" ]]; then : elif [[ -e "$albedoHome" || -L "$albedoHome" ]]; then errorEcho "Cannot create albedo home: $albedoHome is not a directory" exit 1 else run ${pkgs.coreutils}/bin/install -d -m 700 -- "$albedoHome" 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"; ExecStart = ":${quoteSystemdWord executable} daemon --serve"; Environment = lib.mapAttrsToList (name: value: quoteSystemdWord "${name}=${value}") environment; KillMode = "process"; Restart = "on-failure"; RestartSec = 3; RestartPreventExitStatus = 75; TimeoutStopSec = 45; StandardOutput = "append:${escapeSystemdSpecifiers logPath}"; StandardError = "append:${escapeSystemdSpecifiers logPath}"; }; Install.WantedBy = ["default.target"]; }; }) (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"]; EnvironmentVariables = environment; RunAtLoad = true; KeepAlive.SuccessfulExit = false; AbandonProcessGroup = true; ExitTimeOut = 45; StandardOutPath = logPath; StandardErrorPath = logPath; }; }; }) ];}