The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): stable lookup failures travel as exceptions and name the quota the failed request spent
Tekniumcb80675ab3c2
diff --git a/hermes_cli/source_check.py b/hermes_cli/source_check.pyindex 37ffacae49b..4f7fd1c0340 100644--- a/hermes_cli/source_check.py+++ b/hermes_cli/source_check.py@@ -123,9 +123,14 @@ def _request(url: str, accept: str = "application/vnd.github+json") -> str:return _request_with(url, accept, token)except urllib.error.HTTPError as exc:if token is None or exc.code != 401:+ exc.hermes_authenticated = token is not None # which quota a 403/429 spentraiselogger.debug("GitHub rejected the configured token; retrying anonymously")+ try:return _request_with(url, accept, None)+ except urllib.error.HTTPError as exc:+ exc.hermes_authenticated = False+ raisedef _request_with(url: str, accept: str, token: str | None) -> str:diff --git a/hermes_cli/source_releases.py b/hermes_cli/source_releases.pyindex 67abd990867..b9b0acb8fdb 100644--- a/hermes_cli/source_releases.py+++ b/hermes_cli/source_releases.py@@ -159,18 +159,14 @@ def _resolve_source_target(channel: str, git_cmd=None, cwd=None, *, repository=Nversion=request["sourceVersion"], build_id=request["buildId"])-# Why the last release lookup returned nothing, so callers name the real cause-# (a rate limit is not "no release").-_last_release_failure: dict[str, BaseException] = {}---def _describe_release_failure(failure: BaseException | None) -> str:+def _describe_release_failure(failure: BaseException) -> str:+ """A transport failure names its cause (a rate limit is not "no release")."""if isinstance(failure, (urllib.error.URLError, TimeoutError)):- from hermes_cli.github_api import describe_github_failure, github_token+ from hermes_cli.github_api import describe_github_failure- return describe_github_failure(failure, authenticated=github_token() is not None)- return f"No published stable release could be verified: {failure}" if failure else (- "No published stable release could be verified")+ # The request that failed, not the configuration: a rejected token retries anonymously.+ return describe_github_failure(failure, authenticated=getattr(failure, "hermes_authenticated", False))+ return f"No published stable release could be verified: {failure}"def _resolve_stable(repository: str, git_cmd=None, cwd=None) -> SourceTarget:@@ -178,11 +174,11 @@ def _resolve_stable(repository: str, git_cmd=None, cwd=None) -> SourceTarget:publishes (non-draft, non-prerelease, strict vX.Y.Z), verified against origin.No R2 record or pointer is consulted; publishing the release is the only promotion."""- _last_release_failure.pop("stable", None)- tag, commit = resolve_source_release("stable", git_cmd, cwd, repository=repository, pointer=False)- if commit is None:- failure = _last_release_failure.pop("stable", None)- raise ValueError(_describe_release_failure(failure))+ try:+ tag, commit = _resolve_release("stable", git_cmd, cwd, repository=repository, pointer=False)+ except (OSError, ValueError, subprocess.SubprocessError) as exc:+ logger.warning("Could not resolve the stable source release: %s", exc)+ raise ValueError(_describe_release_failure(exc)) from excreturn SourceTarget("stable", "stable", repository, commit=commit, version=str(tag).removeprefix("v"))@@ -321,6 +317,45 @@ def _release_pointer(channel: str) -> tuple[str | None, str | None]:return page.tags[0], None+def _resolve_release(channel: str, git_cmd=None, cwd=None, *, repository=None,+ pointer: bool = True) -> tuple[str, str]:+ """``resolve_source_release`` that raises the failure instead of returning ``(None, None)``."""+ if channel not in ("stable", "canary"):+ raise ValueError(f"Not a release channel: {channel}")+ repository = repository or source_repository(git_cmd, cwd)+ base = f"https://api.github.com/repos/{repository}"+ tag, pinned_sha = (_release_pointer(channel)+ if pointer and repository.lower() == OFFICIAL_REPOSITORY.lower() else (None, None))+ if tag is None:+ release = _published_fallback(channel, base)+ tag = release["tag_name"]+ else:+ release = _json(f"{base}/releases/tags/{tag}")+ if not _published(release, channel) or release["tag_name"] != tag:+ raise ValueError(f"{tag} is not a published {channel} release")+ commit = _json(f"{base}/commits/{tag}")+ sha = commit.get("sha") if isinstance(commit, dict) else None+ if not isinstance(sha, str) or not _SHA.fullmatch(sha):+ raise ValueError(f"No published commit for release {tag}")+ if git_cmd is not None:+ from hermes_cli.source_check import source_git_env++ ref = f"refs/tags/{tag}"+ result = subprocess.run(+ [*git_cmd, "ls-remote", "--tags", "origin", ref, ref + "^{}"],+ cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace",+ check=True, timeout=60, stdin=subprocess.DEVNULL,+ env=source_git_env(),+ )+ refs = dict((parts[1], parts[0]) for line in result.stdout.splitlines()+ if len(parts := line.split()) == 2)+ if refs.get(ref + "^{}", refs.get(ref)) != sha:+ raise ValueError(f"Origin tag {tag} does not match the published release commit")+ if pinned_sha is not None and sha != pinned_sha:+ raise ValueError(f"Release {tag} no longer matches its published commit")+ return tag, sha++def resolve_source_release(channel: str, git_cmd=None, cwd=None, *, repository=None,pointer: bool = True) -> tuple[str | None, str | None]:"""Read published stable/canary release metadata (not channel discovery).@@ -332,42 +367,8 @@ def resolve_source_release(channel: str, git_cmd=None, cwd=None, *, repository=N``git_cmd`` resolves the selected tag on origin; ZIP callers omit it andresolve the same tag through GitHub's commit endpoint."""- if channel not in ("stable", "canary"):- raise ValueError(f"Not a release channel: {channel}")try:- repository = repository or source_repository(git_cmd, cwd)- base = f"https://api.github.com/repos/{repository}"- tag, pinned_sha = (_release_pointer(channel)- if pointer and repository.lower() == OFFICIAL_REPOSITORY.lower() else (None, None))- if tag is None:- release = _published_fallback(channel, base)- tag = release["tag_name"]- else:- release = _json(f"{base}/releases/tags/{tag}")- if not _published(release, channel) or release["tag_name"] != tag:- raise ValueError(f"{tag} is not a published {channel} release")- commit = _json(f"{base}/commits/{tag}")- sha = commit.get("sha") if isinstance(commit, dict) else None- if not isinstance(sha, str) or not _SHA.fullmatch(sha):- raise ValueError(f"No published commit for release {tag}")- if git_cmd is not None:- from hermes_cli.source_check import source_git_env-- ref = f"refs/tags/{tag}"- result = subprocess.run(- [*git_cmd, "ls-remote", "--tags", "origin", ref, ref + "^{}"],- cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace",- check=True, timeout=60, stdin=subprocess.DEVNULL,- env=source_git_env(),- )- refs = dict((parts[1], parts[0]) for line in result.stdout.splitlines()- if len(parts := line.split()) == 2)- if refs.get(ref + "^{}", refs.get(ref)) != sha:- raise ValueError(f"Origin tag {tag} does not match the published release commit")- if pinned_sha is not None and sha != pinned_sha:- raise ValueError(f"Release {tag} no longer matches its published commit")- return tag, sha+ return _resolve_release(channel, git_cmd, cwd, repository=repository, pointer=pointer)except (OSError, ValueError, subprocess.SubprocessError) as exc:logger.warning("Could not resolve the %s source release: %s", channel, exc)- _last_release_failure[channel] = excreturn None, Nonediff --git a/tests/hermes_cli/test_stable_lookup_github_auth.py b/tests/hermes_cli/test_stable_lookup_github_auth.pyindex 64fed2bff76..42ee9bc524c 100644--- a/tests/hermes_cli/test_stable_lookup_github_auth.py+++ b/tests/hermes_cli/test_stable_lookup_github_auth.py@@ -17,12 +17,16 @@ SHA = "818c13be1dc4fd28987e1e881a9408224afd4535"def github(monkeypatch):"""A local api.github.com: answers releases/latest + commits/<tag>, or 403s the quota."""seen: list[tuple[str, str | None]] = []- state = {"limited": False}+ state = {"limited": False, "reject_token": False}class Handler(BaseHTTPRequestHandler):def do_GET(self):- seen.append((self.path, self.headers.get("Authorization")))- if state["limited"]:+ auth = self.headers.get("Authorization")+ seen.append((self.path, auth))+ if state["reject_token"] and auth:+ body = b'{"message":"Bad credentials"}'+ self.send_response(401)+ elif state["limited"]:body = b'{"message":"API rate limit exceeded"}'self.send_response(403)self.send_header("x-ratelimit-remaining", "0")@@ -43,7 +47,8 @@ def github(monkeypatch):passserver = ThreadingHTTPServer(("127.0.0.1", 0), Handler)- threading.Thread(target=server.serve_forever, daemon=True).start()+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()real = urllib.request.urlopendef local(request, *args, **kwargs):@@ -59,6 +64,8 @@ def github(monkeypatch):monkeypatch.delenv("GITHUB_TOKEN", raising=False)yield seen, stateserver.shutdown()+ server.server_close()+ thread.join()def test_stable_lookup_sends_the_configured_token(github, monkeypatch):@@ -82,3 +89,15 @@ def test_a_rate_limit_is_reported_as_one_not_as_a_missing_release(github, monkeymessage = str(caught.value)assert "rate limit" in message and "No published stable release" not in messageassert ("GITHUB_TOKEN in the environment" in message) is (token is None)+++def test_a_rejected_token_then_anonymous_limit_names_the_anonymous_quota(github, monkeypatch):+ seen, state = github+ state["limited"] = state["reject_token"] = True+ monkeypatch.setenv("GH_TOKEN", "ghp_revoked")+ with pytest.raises(ValueError) as caught:+ source_releases._resolve_stable("NousResearch/hermes-agent")+ # The 403 came from the anonymous retry, so the user's token quota is not the one to wait on.+ assert [auth for _, auth in seen] == ["Bearer ghp_revoked", None]+ assert "anonymous requests are limited" in str(caught.value)+ assert "for your GITHUB_TOKEN" not in str(caught.value)