ci/llm-agents: Propose and build version updates #5
No files matched your search
@@ -0,0 +1,47 @@
|
||||
name: Build llm-agents
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [master]
|
||||
types: [opened, synchronize, reopened]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
# Only the update branch, whether dispatched by the updater or pushed by hand
|
||||
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
|
||||
@@ -0,0 +1,36 @@
|
||||
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
|
||||
@@ -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 { })
|
||||
Executable
+205
@@ -0,0 +1,205 @@
|
||||
#!/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, *, method: str | None = None, 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, method=method)
|
||||
|
||||
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 find_pull_request(state: str, sort: str | None = None):
|
||||
"""Return the first update PR in the listing, or None."""
|
||||
repo = os.environ["GITHUB_REPOSITORY"]
|
||||
query = {"state": state, "base_branch": BASE, "limit": 50}
|
||||
if sort is not None:
|
||||
query["sort"] = sort
|
||||
|
||||
for page in count(1):
|
||||
pulls = api("pulls", query=query | {"page": page})
|
||||
if not pulls:
|
||||
return None
|
||||
|
||||
for pull in pulls:
|
||||
head = pull["head"]
|
||||
if head["ref"] == BRANCH and (head["repo"] or {}).get("full_name") == repo:
|
||||
return pull
|
||||
|
||||
|
||||
def create_pull_request():
|
||||
return 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. Close this PR to skip "
|
||||
"these versions; a later release opens a new one."
|
||||
),
|
||||
})
|
||||
|
||||
|
||||
def close_obsolete(pull) -> None:
|
||||
if pull is None:
|
||||
return
|
||||
|
||||
api(f"issues/{pull['number']}/comments", data={
|
||||
"body": f"`{BASE}` already has the latest installed llm-agents versions.",
|
||||
})
|
||||
api(f"pulls/{pull['number']}", method="PATCH", data={"state": "closed"})
|
||||
print(f"Closed the obsolete update PR {pull['html_url']}.")
|
||||
|
||||
|
||||
def declined(after: dict[str, str], reference: Path) -> bool:
|
||||
"""Check whether the most recently closed update PR rejected these versions."""
|
||||
pull = find_pull_request("closed", sort="recentclose")
|
||||
if pull is None or pull["merged"]:
|
||||
return False
|
||||
|
||||
# Gitea keeps the PR's head at close time even if the branch moves on.
|
||||
subprocess.run([
|
||||
"git", "fetch", "--no-tags", "--depth=1", "origin", f"refs/pull/{pull['number']}/head",
|
||||
], check=True)
|
||||
reference.write_bytes(git_output("show", f"FETCH_HEAD:{LOCK}"))
|
||||
if versions(reference) != after:
|
||||
return False
|
||||
|
||||
print(f"Skipping the versions declined in {pull['html_url']}.")
|
||||
return True
|
||||
|
||||
|
||||
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()
|
||||
|
||||
pull = find_pull_request("open")
|
||||
if candidate_lock == base_lock:
|
||||
print("The llm-agents pin is current.")
|
||||
close_obsolete(pull)
|
||||
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.")
|
||||
close_obsolete(pull)
|
||||
return
|
||||
|
||||
if pull is None and declined(after, reference):
|
||||
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)
|
||||
|
||||
if pull is None:
|
||||
pull = create_pull_request()
|
||||
print(f"Update PR {pull['html_url']}")
|
||||
|
||||
# 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()
|
||||
+26
-3
@@ -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,28 @@ 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.
|
||||
|
||||
- **Declining:** close the PR without merging. CI won't propose the same versions again, and
|
||||
opens a new PR once a later version appears.
|
||||
- **Obsolete PRs:** if `master` already has the latest installed versions, for example after a
|
||||
manual update, CI comments on the open PR and closes it.
|
||||
|
||||
[`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
|
||||
|
||||
Reference in new issue
Block a user