diff --git a/.gitea/workflows/llm-agents.yaml b/.gitea/workflows/llm-agents.yaml new file mode 100644 index 0000000..25501f4 --- /dev/null +++ b/.gitea/workflows/llm-agents.yaml @@ -0,0 +1,39 @@ +name: Build llm-agents + +on: + pull_request: + branches: [master] + types: [opened, synchronize, reopened] + workflow_dispatch: + +jobs: + build: + if: >- + (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/automation/llm-agents') || + (github.event.pull_request.head.repo.full_name == github.repository && + github.event.pull_request.head.ref == 'automation/llm-agents') + runs-on: ubuntu-26.04 + permissions: + contents: read + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + - uses: DeterminateSystems/determinate-nix-action@v3 + with: + github-token: ${{ secrets.GH_PULL_TOKEN }} + extra-conf: | + sandbox-fallback = false + lazy-trees = true + eval-cores = 0 + - name: Build installed agent packages + shell: bash + run: | + attrs="$(nix eval --accept-flake-config --no-update-lock-file --raw \ + .#llmAgentPackages.x86_64-linux \ + --apply 'packages: builtins.concatStringsSep "\n" (builtins.attrNames packages)')" + if [[ -n "$attrs" ]]; then + mapfile -t packages <<< "$attrs" + nix build --accept-flake-config --no-update-lock-file --no-link \ + "${packages[@]/#/.#llmAgentPackages.x86_64-linux.}" + fi diff --git a/.gitea/workflows/update-llm-agents.yaml b/.gitea/workflows/update-llm-agents.yaml new file mode 100644 index 0000000..7b26581 --- /dev/null +++ b/.gitea/workflows/update-llm-agents.yaml @@ -0,0 +1,32 @@ +name: Update llm-agents + +on: + schedule: + - cron: '19 */4 * * *' + workflow_dispatch: + +concurrency: + group: update-llm-agents + +jobs: + update: + if: github.ref == 'refs/heads/master' + runs-on: ubuntu-26.04 + permissions: + contents: write + pull-requests: write + actions: write + steps: + - uses: actions/checkout@v6 + with: + ref: master + persist-credentials: false + - uses: DeterminateSystems/determinate-nix-action@v3 + with: + github-token: ${{ secrets.GH_PULL_TOKEN }} + - name: Update the dependency PR + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + run: >- + nix shell --accept-flake-config .#nixpkgs.unstable.x86_64-linux.python3 + --command python3 ci/update-llm-agents.py diff --git a/ci/llm-agent-packages.nix b/ci/llm-agent-packages.nix new file mode 100644 index 0000000..4daba7c --- /dev/null +++ b/ci/llm-agent-packages.nix @@ -0,0 +1,29 @@ +{ lib, inputs, nixfiles, system }: +let + inherit (builtins) any attrValues filter tryEval; + inherit (lib) concatMap filterAttrs getName groupBy isDerivation; + inherit (nixfiles.config) nixos home-manager; + + systems = filter (box: box.system == system) (attrValues nixos.systems); + homes = filter (home: home.system == system) (attrValues home-manager.homes); + + installedPackages = + concatMap + (box: + let cfg = box.rendered.config; + in cfg.environment.systemPackages + ++ concatMap (home: home.home.packages) (attrValues cfg.home-manager.users)) + systems + ++ concatMap (home: home.configuration.config.home.packages) homes; + + installedByName = groupBy getName installedPackages; +in +filterAttrs + (_: package: + # Check names before forcing output paths. Some unrelated upstream exports + # are helpers or packages that cannot be evaluated on this platform. + let name = tryEval (if isDerivation package then getName package else null); + in name.success && name.value != null + && any (installed: installed.drvPath == package.drvPath) + (installedByName.${name.value} or [ ])) + (inputs.llm-agents.packages.${system} or { }) diff --git a/ci/update-llm-agents.py b/ci/update-llm-agents.py new file mode 100755 index 0000000..b33b29b --- /dev/null +++ b/ci/update-llm-agents.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +"""Keep the llm-agents update PR and its package build current.""" + +import base64 +import json +import os +import subprocess +from itertools import count +from pathlib import Path +from tempfile import TemporaryDirectory +from urllib.error import HTTPError +from urllib.parse import urlencode +from urllib.request import Request, urlopen + + +BASE = "master" +BRANCH = "automation/llm-agents" +REF = f"refs/heads/{BRANCH}" +TITLE = "flake: Update llm-agents" +LOCK = Path("flake.lock") +BUILD_WORKFLOW = "actions/workflows/llm-agents.yaml" + + +def git_output(*args: str) -> bytes: + return subprocess.check_output(["git", *args]) + + +def versions(lock_file: Path | None = None) -> dict[str, str]: + command = [ + "nix", "eval", "--accept-flake-config", "--no-update-lock-file", "--json", + ".#llmAgentPackages.x86_64-linux", + "--apply", "builtins.mapAttrs (_: package: package.version)", + ] + if lock_file is not None: + command.extend(["--reference-lock-file", str(lock_file)]) + + return json.loads(subprocess.check_output(command)) + + +def api(path: str, *, query=None, data=None): + server = os.environ["GITHUB_SERVER_URL"].rstrip("/") + repo = os.environ["GITHUB_REPOSITORY"] + url = f"{server}/api/v1/repos/{repo}/{path}" + if query is not None: + url += "?" + urlencode(query) + + headers = {"Authorization": f"token {os.environ['GITEA_TOKEN']}"} + payload = None + if data is not None: + headers["Content-Type"] = "application/json" + payload = json.dumps(data).encode() + + request = Request(url, data=payload, headers=headers) + try: + with urlopen(request, timeout=30) as response: + body = response.read() + except HTTPError as error: + message = error.read(4096).decode(errors="replace") + raise RuntimeError( + f"{request.get_method()} {path} returned HTTP {error.code}: {message}" + ) from None + + return json.loads(body) if body else None + + +def ensure_pull_request() -> str: + repo = os.environ["GITHUB_REPOSITORY"] + for page in count(1): + pulls = api("pulls", query={ + "state": "open", "base_branch": BASE, "limit": 50, "page": page, + }) + if not pulls: + break + + for pull in pulls: + head = pull["head"] + if head["ref"] == BRANCH and (head["repo"] or {}).get("full_name") == repo: + return pull["html_url"] + + pull = api("pulls", data={ + "base": BASE, + "head": BRANCH, + "title": TITLE, + "body": ( + "Updates the llm-agents pin when an installed package changes version. " + "See the commit message for the version changes." + ), + }) + return pull["html_url"] + + +def publish(previous: str, before: dict[str, str], after: dict[str, str]) -> str: + changes = "\n".join( + f"{name} {before.get(name, 'absent')} -> {after.get(name, 'absent')}" + for name in sorted(before.keys() | after.keys()) + if before.get(name) != after.get(name) + ) + subprocess.run(["git", "add", "--", str(LOCK)], check=True) + subprocess.run([ + "git", "-c", "user.name=github-actions[bot]", + "-c", "user.email=github-actions[bot]@users.noreply.github.com", + "commit", "-m", TITLE, "-m", changes, + ], check=True) + + # Pass the credential to Git without putting it in the remote URL. + auth = base64.b64encode(f"oauth2:{os.environ['GITEA_TOKEN']}".encode()).decode() + subprocess.run([ + "git", "push", f"--force-with-lease={REF}:{previous}", "origin", f"HEAD:{REF}", + ], check=True, env=os.environ | { + "GIT_CONFIG_COUNT": "1", + "GIT_CONFIG_KEY_0": "http.extraHeader", + "GIT_CONFIG_VALUE_0": f"Authorization: Basic {auth}", + }) + return git_output("rev-parse", "HEAD").decode().strip() + + +def main() -> None: + # Capture the tip before evaluating so the lease protects concurrent updates. + previous = git_output("ls-remote", "origin", REF).decode().partition("\t")[0] + if previous: + subprocess.run(["git", "fetch", "--no-tags", "--depth=2", "origin", REF], check=True) + + base_lock = git_output("show", f"HEAD:{LOCK}") + subprocess.run(["nix", "flake", "update", "--accept-flake-config", "llm-agents"], check=True) + candidate_lock = LOCK.read_bytes() + if candidate_lock == base_lock: + print("The llm-agents pin is current.") + return + + with TemporaryDirectory() as temp: + reference = Path(temp) / LOCK.name + reference.write_bytes(base_lock) + before = versions(reference) + after = versions() + if before == after: + print("Installed llm-agents package versions are unchanged.") + return + + pending = None + if previous and git_output("show", f"{previous}^:{LOCK}") == base_lock: + pending_lock = git_output("show", f"{previous}:{LOCK}") + reference.write_bytes(pending_lock) + pending = after if pending_lock == candidate_lock else versions(reference) + + head = previous if pending == after else publish(previous, before, after) + print(f"Update PR {ensure_pull_request()}") + + # Gitea suppresses events from the Actions token. Dispatch explicitly and + # recover on the next poll if there is still no build for this commit. + runs = api(f"{BUILD_WORKFLOW}/runs", query={"head_sha": head, "limit": 1}) + if runs["total_count"] == 0: + api(f"{BUILD_WORKFLOW}/dispatches", data={"ref": BRANCH}) + print(f"Queued the llm-agents build for {head[:12]}.") + + +if __name__ == "__main__": + main() diff --git a/docs/deployment.md b/docs/deployment.md index 9ffc6d1..f2f7662 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -84,9 +84,10 @@ Boxes default to `fish`, so pipe multi-statement remote scripts through `bash`, ## Coding agents -The shared GUI home-manager module installs Codex and Claude Code from the `llm-agents` input, retaining -that input's tested nixpkgs pin. Run `nix flake update llm-agents`, then switch the system -or home configuration to use the updated package. +The shared GUI home-manager module installs Codex and Claude Code from the `llm-agents` input, +retaining that input's tested nixpkgs pin. [CI proposes version updates](#llm-agents-updates). +To refresh the pin manually, run `nix flake update llm-agents`, then switch the system or home +configuration to use the updated packages. The shared cache settings in `lib.my.c.nix.cache` and the flake's `nixConfig` include the [Numtide binary cache](https://github.com/numtide/llm-agents.nix#binary-cache), so @@ -327,6 +328,23 @@ It then builds `.#ciDrv.x86_64-linux`, a `linkFarm` of all CI attributes, and pu Pushing the `installer` tag (refreshed by `update-installer`) builds `my.buildAs.iso` and `my.buildAs.netbootArchive`, then attaches both to a release. +### llm-agents updates + +[`update-llm-agents.yaml`](../.gitea/workflows/update-llm-agents.yaml) checks for updates every +four hours and can also be run manually on `master`. It matches packages directly installed +by the x86_64 Linux NixOS and home-manager configurations to derivations exported by +`llm-agents`. This discovers the tracked packages without building a whole system. + +When an installed version changes, CI commits the updated lockfile on the dedicated +`automation/llm-agents` branch. The commit message lists the version changes. New versions +refresh the branch behind the existing open PR. Upstream revisions with the same package +versions leave that branch alone. + +[`llm-agents.yaml`](../.gitea/workflows/llm-agents.yaml) builds the discovered packages for +the update commit using the flake's caches. The updater dispatches the build explicitly +because Gitea suppresses automatic workflow events from its job token. The updater needs +the repository's Actions token limits to allow writes to code, pull requests and Actions. + ### `update-docs.yaml` On pushes to `master`, excluding its own commits, this runs the assignment, option and DNS diff --git a/flake.nix b/flake.nix index 8bfbedd..18f7ede 100644 --- a/flake.nix +++ b/flake.nix @@ -287,6 +287,8 @@ (import ./pkgs { inherit lib pkgs; }) // (import ./openwrt { inherit pkgs inputs; })); + llmAgentPackages = import ./ci/llm-agent-packages.nix { inherit lib inputs nixfiles system; }; + devShells.default = shell; ci =